Skip to content

Instantly share code, notes, and snippets.

@e-kostylov
Last active September 15, 2018 04:37
Show Gist options
  • Save e-kostylov/24199e1117e3a2b91f2672321a33c353 to your computer and use it in GitHub Desktop.
Save e-kostylov/24199e1117e3a2b91f2672321a33c353 to your computer and use it in GitHub Desktop.
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