Skip to content

Instantly share code, notes, and snippets.

@pyldin601
Forked from beberlei/tailrecursion.php
Last active August 18, 2023 11:20
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pyldin601/8de8e0c7f1288676ea0e451886799833 to your computer and use it in GitHub Desktop.
Save pyldin601/8de8e0c7f1288676ea0e451886799833 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