/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Anonymous Recursion?

Can someone show me some examples of anonymous recursion in PHP (if possible)?

I suppose factorial would be a good example to work with:

This is just a peck of code I created really quickly, but maybe it can help you see where I am stuck.

[code=php]
$int = 10;
$x = function($i) {
return function($i) use ($i) {
return $i != 0 ? $this($i) + $i * ($i – 1) : 0;
}
}
[/code]

I can’t figure out how to do it without using an identifier (variable). Since a closure allows you to refrence $this, should I be returning

return $i != 0 ? $this($i) + $i * ($i – 1) : $i;

Don’t take my code too seriously. It doesn’t necessarily make any sense (at least, in terms of computing factorial).

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@eval_BadCode_authorFeb 24.2012 — Here's an example I fixed up, showing the fibonaci sequence. This is a better example:

[code=php]
<?php
function fib_private($n) {
$f = __FUNCTION__;
return ($n < 2) ? 1 : $f($n-1) + $f($n-2);
}
function fib($n) {
return $n < 0 ? NULL : fib_private($n);
}

for($i = 1; $i < 10; $i++) echo fib($i), " ";[/code]


Output:
[CODE]1 2 3 5 8 13 21 34 55[/CODE]

Is there any way to put fib_private inside of fib?
Copy linkTweet thisAlerts:
@gvreFeb 24.2012 — Check this
Copy linkTweet thisAlerts:
@eval_BadCode_authorFeb 25.2012 — [SIZE="5"][B][ RESOLVED ][/B][/SIZE]

You sir, are a scholar, hacker, and gentleman ?

Check this[/QUOTE]

I don't post new thread often, but when I do- it's for awesome answers like this. ?

Edit: I will post to code the sort of "complete" this thread. That way someone else looking for examples of anonymouse recursion can see it here:
[code=php]
<?php
$fib = function($n) use (&$fib) {
if($n == 0 || $n == 1) return 1;
return $fib($n - 1) + $fib($n - 2); };
for($i = 1; $i < 10; $i++) echo fib($i), " ";
[/code]


Output:
[CODE]1 2 3 5 8 13 21 34 55[/CODE]
×

Success!

Help @eval_BadCode_ spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...