I would like to avoid stack inflating when creating a system similar to a feature recommendation or a combination of methods . This includes tree traversal (in my implementation), conditional recursion, etc. One of the few methods available for converting recursion into loops is springboard. I tried this and then figured out what I need to implement, for example. evaluation of Boolean short circuit expressions. In short, I implemented a combination of a trampoline with a sequel, and now I'm trying to find out if this structure exists and what its name is, because I could not find such an existing structure.
My implementation is a failure assessment with manual stack handling:
function immediate($bounce, $args) { $stack = array($bounce->run($args)); while ($stack[0] instanceof Bounce) { $current = array_pop($stack); if ($current instanceof Bounce) { $stack[] = $current; $stack[] = $current->current(); } else { $next = array_pop($stack); $stack[] = $next->next($current); } } return $stack[0]; }
Bounce Class:
class Bounce { protected $current; protected $next; public function __construct($current, $next) { $this->current = $current; $this->next = $next; } public function current() { $fn = $this->current; return $fn(); } public function next($arg) { $fn = $this->next; return $fn($arg); } }
And, as an example, the implementation of the AND short circuit (i.e., in JavaScript first(args) && second(args) ). $first and $second are functions that can return a Bounce .
return new Bounce( function () use ($first, $args) { return $first($args); }, function ($return) use ($second, $args) { if (!$return) { return $return; } return new Bounce( function () use ($second, $args) { return $second($args); }, null ); } );
This allows you to use general recursion with an overhead of about 3 function calls per regular function call (although in the general case, for a variable number of iterations, this is rather cumbersome to write and requires "lazy recursion").
Has anyone seen such a structure before?