Skip to content

Instantly share code, notes, and snippets.

@danilopinotti
Forked from pyldin601/tailrecursion.php
Created June 19, 2021 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danilopinotti/57fc85b15a217266ff789faac48c2696 to your computer and use it in GitHub Desktop.
Save danilopinotti/57fc85b15a217266ff789faac48c2696 to your computer and use it in GitHub Desktop.
PHP Tail Recursion
<?php
function tail($fn)
{
$underCall = false;
$pool = [];
return function (...$args) use (&$fn, &$underCall, &$pool) {
$result = null;
$pool[] = $args;
if (!$underCall) {
$underCall = true;
while ($pool) {
$head = array_shift($pool);
$result = $fn(...$head);
}
$underCall = false;
}
return $result;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment