Created
October 27, 2017 14:15
-
-
Save pwm/e4f60274a37a86d9652b69d1ab0146bd to your computer and use it in GitHub Desktop.
Trampolining tail-recursive functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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