sna*_*ter 5 php recursion functional-programming trampolines
我想在创建类似于功能建议或方法组合的系统时避免吹掉堆栈.这涉及树遍历(在我的实现中),条件递归等.可用于将递归转换为循环的极少数方法之一是蹦床.我试过这个然后发现我需要实现例如.短路布尔表达式评估.简而言之,我已经实现了蹦床与延续的组合,现在我试图找出这种结构是否存在以及它的名称是什么 - 因为我一直无法找到任何这样的现有结构.
我的实现 - 手动堆栈处理的反弹评估:
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];
}
Run Code Online (Sandbox Code Playgroud)
Bounce类:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
并且,作为示例,短路和实现(即在JavaScript中first(args) && second(args)).$first并且$second是可以返回Bounces的函数.
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
);
}
);
Run Code Online (Sandbox Code Playgroud)
这允许一般递归,每个正常函数调用大约有3个函数调用的开销(尽管在一般情况下,对于变量迭代计数,编写并且需要'延迟递归')非常麻烦.
有没有人见过这样的结构?