递归——CPS(三)

时间:2023-03-09 08:24:20
递归——CPS(三)

JScript不是天然支持CPS,但是可以写一个分发引擎使得能工作在CPS风格下。一般只有一个活动的continuation,所以可以定义规则:JScript CPS 函数允许有返回,但是它们做的最后一件事必须是将continuation告诉我们的分发引擎。

为了让事情简单化,我们令每个CPS 风格的函数拥有一个参数,当然,可以是一个包含多个字段的对象。

让我们回顾一下前面的 CPS treeDepth程序,并且将所有的 continuation 调用 替换为 这样一种调用: 这种调用告诉运行时引擎下一步 continuation 该做什么。然后,函数可以正常返回,并且让运行时引擎调用continuation。

function treeDepth(args)
{
if(args.curtree == null)
cont(args.afterDepth, 0);
else
{
function afterLeft(leftDepth)
{
function afterRight(rightDepth)
{
cont(args.afterDepth, 1+Math.max(leftDepth, rightDepth));
}
cont(treeDepth, {curtree: args.curtree.right, afterDepth: afterRight});
}
cont(treeDepth, {curtree: args.curtree.left, afterDepth: afterLeft});
}
}

分发引擎为

var continuation = null;
function cont(newfunc, newargs)
{
continuation = {func: newfunc, args : newargs};
} function run()
{
while(continuation != null)
{
var curfunc = continuation.func;
var curargs = continuation.args;
continuation = null;
curfunc(curargs);
}
}

如果下一步没有需要调用的话,就表示程序完成。为了确定一棵树的深度,我们简单地告诉continuation引擎下一步需要做什么。

cont(treeDepth, {curtree: mytree, afterDepth: print });
run();

原文:https://blogs.msdn.microsoft.com/ericlippert/2005/08/15/recursion-part-six-making-cps-work/