Skip to content

Instantly share code, notes, and snippets.

@pwm
Created October 27, 2017 14:15
Show Gist options
  • Save pwm/e4f60274a37a86d9652b69d1ab0146bd to your computer and use it in GitHub Desktop.
Save pwm/e4f60274a37a86d9652b69d1ab0146bd to your computer and use it in GitHub Desktop.
Trampolining tail-recursive functions
<?php
declare(strict_types=1);
$trampoline = function (callable $f) {
return function (...$args) use ($f) {
while (is_callable($f)) {
$f = $f(...$args);
}
return $f;
};
};
$range = function (int $s, int $e, array $res = []) use (&$range) {
$res[] = $s;
return $s === $e
? $res
: function () use ($range, $s, $e, $res) { return $range($s < $e ? ++$s : --$s, $e, $res); };
};
echo array_sum($trampoline($range)(1, 10000)); // 50005000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment