Created
April 20, 2012 03:52
-
-
Save pkriete/2425817 to your computer and use it in GitHub Desktop.
PHP Tail Recursion
This file contains 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
function tailrec($func) | |
{ | |
$acc = array(); | |
$recursing = FALSE; | |
$func = new ReflectionFunction($func); | |
return function() use ($func, &$acc, &$recursing) { | |
$acc[] = func_get_args(); | |
if ( ! $recursing) | |
{ | |
$recursing = TRUE; | |
while ( ! empty($acc)) | |
{ | |
$ret = $func->invokeArgs(array_shift($acc)); | |
} | |
$recursing = FALSE; | |
return $ret; | |
} | |
}; | |
} | |
// in order to recurse on a closure in php you need to | |
// pass a reference to the assigned variable. | |
$sumrand = tailrec(function($n, $sum) use (&$sumrand) { | |
if ($n == 0) | |
{ | |
return $sum; | |
} | |
return $sumrand($n - 1, $sum + rand(0, 1)); | |
}); | |
echo $sumrand(500000, 0) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I optimized on your code to avoid the
use(&$sumrand)
part with a 5.4 only example:https://gist.github.com/4145442