Created
December 30, 2012 16:49
-
-
Save igorw/4413758 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$factorial = call_user_func( | |
function ($le) { | |
return call_user_func( | |
function ($f) { | |
return $f($f); | |
}, | |
function ($f) use ($le) { | |
return $le(function ($x) use ($f) { | |
return call_user_func($f($f), $x); | |
}); | |
} | |
); | |
}, | |
function ($factorial) { | |
return function ($x) use ($factorial) { | |
if ($x > 0) { | |
return $x * $factorial($x - 1); | |
} | |
return 1; | |
}; | |
} | |
); | |
var_dump($factorial(1)); | |
var_dump($factorial(2)); | |
var_dump($factorial(3)); | |
var_dump($factorial(4)); |
Who needs recursion for a factorial though:
function factorial($number)
{
$factorial = 1;
while ($number > 1) {
$factorial *= $number--;
}
return $factorial ;
}
@MarkBaker we can find an iterative solution to almost any problem that we can solve with recursion. The point was to illustrate that it is possible to make a closure recursive in PHP. Which is not a straight forward conclusion, as there is no keyword to refer to the closure itself from within the closure.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I suppose I could use the y combinator, but this is simpler:
:)