-
-
Save far-rainbow/5534c0a06bd9d310c5d00d20e85da3c3 to your computer and use it in GitHub Desktop.
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
function factorial($n) | |
{ | |
if ($n == 1) { | |
return $n; | |
} | |
return $n * factorial($n-1); | |
} | |
function tail_factorial($n, $acc = 1) | |
{ | |
if ($n == 1) { | |
return $acc; | |
} | |
return tail_factorial($n-1, $n * $acc); | |
} | |
function unrolled_factorial($n) | |
{ | |
$acc = 1; | |
while ($n > 1) { | |
$acc *= $n--; | |
} | |
return $acc; | |
} | |
function goto_factorial($n) | |
{ | |
$acc = 1; | |
f: | |
if ($n == 1) { | |
return $acc; | |
} | |
$acc *= $n--; | |
goto f; | |
} | |
function trampo_factorial($n, $acc = 1) | |
{ | |
if ($n == 1) { | |
return $acc; | |
} | |
return function() use ($n, $acc) { return trampo_factorial($n-1, $n * $acc); }; | |
} | |
function trampoline(callable $c, ...$args) | |
{ | |
while (is_callable($c)) { $c = $c(...$args); } return $c; | |
} | |
echo trampoline('trampo_factorial', 42); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment