我想在创建类似于function advice或method combination的系统时避免乱吹。这涉及树遍历(在我的实现中),条件递归等。可用于将递归转换为循环的极少数方法之一是蹦床。我试过这个然后发现我需要实现例如。短路布尔表达式评估。简而言之,我已经实施了蹦床与延续的组合,现在我试图找出这种结构是否存在以及它的名称是什么 - 因为我一直找不到任何这样已经存在的构造。
我的实施 - 手动堆栈处理的反弹评估:
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 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);
}
}
并且,作为示例,短路和实现(即在JavaScript first(args) && second(args)
中)。 $first
和$second
也是可以返回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
);
}
);
这允许一般递归,每个正常函数调用大约有3个函数调用的开销(尽管在一般情况下,对于变量迭代计数,写入并且需要“懒惰递归”)非常麻烦。
有没有人见过这样的结构?