Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"files": [
"src/Nerd/Common/Arrays.php",
"src/Nerd/Common/Classes.php",
"src/Nerd/Common/Strings.php"
"src/Nerd/Common/Strings.php",
"src/Nerd/Common/Functional.php"
]
},
"require-dev": {
Expand Down
28 changes: 28 additions & 0 deletions src/Nerd/Common/Functional.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

namespace Nerd\Common\Functional;

/**
* Optimize given function for tail recursion.
*
* @param callable $fn
* @return \Closure
*/
function tail(callable $fn)
{
$underCall = false;
$pool = [];
return function (...$args) use (&$fn, &$underCall, &$pool) {
$result = null;
$pool[] = $args;
if (!$underCall) {
$underCall = true;
while ($pool) {
$head = array_shift($pool);
$result = $fn(...$head);
}
$underCall = false;
}
return $result;
};
}
20 changes: 20 additions & 0 deletions tests/FunctionalTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace tests;

use function Nerd\Common\Functional\tail;
use PHPUnit\Framework\TestCase;

class FunctionalTest extends TestCase
{
public function testTailRecursion()
{
$func = tail(function ($max, $acc = 0) use (&$func) {
if ($max == $acc) {
return $acc;
}
return $func($max, $acc + 1);
});
$this->assertEquals(10000, $func(10000));
}
}