码迷,mamicode.com
首页 > 其他好文 > 详细

递归——CPS(三)

时间:2016-07-02 00:30:53      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

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/

递归——CPS(三)

标签:

原文地址:http://www.cnblogs.com/sjjsxl/p/5634602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!