Skip to content

Instantly share code, notes, and snippets.

@pkriete
Created April 20, 2012 03:52
Show Gist options
  • Save pkriete/2425817 to your computer and use it in GitHub Desktop.
Save pkriete/2425817 to your computer and use it in GitHub Desktop.
PHP Tail Recursion
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";
@beberlei
Copy link

I optimized on your code to avoid the use(&$sumrand) part with a 5.4 only example:

https://gist.github.com/4145442

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment