-
-
Save beberlei/4145442 to your computer and use it in GitHub Desktop.
PHP Tail Recursion
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 | |
class TailRecursion | |
{ | |
public $func; | |
public $acc; | |
public $recursing; | |
public function tail() | |
{ | |
return call_user_func_array($this->func, func_get_args()); | |
} | |
public function getClosure($fn) | |
{ | |
$this->acc = array(); | |
$this->recursing = false; | |
$fn = $fn->bindTo($this); | |
return $this->func = function() use ($fn) { | |
$this->acc[] = func_get_args(); | |
if ( ! $this->recursing) { | |
$this->recursing = true; | |
while ($this->acc) { | |
$ret = call_user_func_array($fn, array_shift($this->acc)); | |
} | |
$this->recursing = false; | |
return $ret; | |
} | |
}; | |
} | |
} | |
function tailrec($func) | |
{ | |
$tail = new TailRecursion(); | |
return $tail->getClosure($func); | |
} | |
$fac = tailrec(function($n, $acc = 1) { | |
if ($n == 1) { | |
return $acc; | |
} | |
return $this->tail($n - 1, $acc * $n); | |
}); | |
echo $fac(4); // 1 * 2 * 3 * 4 = 24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I optimized your version and done it without classes:
https://gist.github.com/pldin601/8de8e0c7f1288676ea0e451886799833
Just function that decorates other function. Works awasome.