Open DrDub opened 1 year ago
moving the recursive call to tail_recursion
doesn't work either:
function fac($n, $acc = 1) {
if ($n == 1) {
echo (new Exception())->getTraceAsString()."\n";
return $acc;
}
return tail_recursion('fac')($n - 1, $acc * $n);
}
Hmm, looking at https://github.com/functional-php/trampoline, a full solution might need two functions.
The code in https://gist.github.com/beberlei/4145442 changes the recursive call in line 49 to be a call to the instance variable
$func
, which in turn is changed in the line 19. Through that then the recursive calls return immediately, storing the arguments in the$acc
instance variable. The re-implementation in functional-php does not do that, rendering thetail_recursion
a noop.Compare the output of these two scripts:
functional-php code
The output is:
highlighting 10 stack frames are used.
While the gist linked:
produces:
Maybe a solution can be implemented using reflection and renaming the function?