【问题标题】:memoize continuation passing style functionmemoize 延续传递风格函数
【发布时间】:2012-04-19 02:24:31
【问题描述】:

我想知道是否有一种方法可以实现通用的“memoize”函数(如在一个函数作为输入和一个函数作为输出的函数中,作为 python 的装饰器)能够处理 cps 样式的函数。

对于普通函数(如“结果值由返回返回,参数仅用于输入!”)memoize 函数可以像(在 javascript 中)一样简单

function memoize(fun) {
    var cache = {};
    return function () {
        var args = Array.prototype.slice.call(arguments);
        if (args in cache)
            return cache[args];
        var ret = fun.apply(this, arguments);
        cache[args] = ret;
        return ret;
    };
}

但是我的简单 memoize 函数无法记住 cps 风格的函数,因为我需要“再次”评估函数类型的参数,同时还要知道要传递给它们的参数。

例如,给定函数

function cps(param, next) {
    var ret = param + 1;

    // setTimeout for simulate async behaviour
    setTimeout(function () {
            next(ret);
    }, 0);
}

也许我可以发现next 是一个函数,但它的签名(嗯……也许,但它很棘手),绝对不是函数中使用的参数!

谁能告诉我我错了? :D

我对能够记忆半打 cps 风格的函数很感兴趣,我不想搞乱在每个函数中插入“缓存”的逻辑。

【问题讨论】:

  • 如果您将哈希表作为函数的参数传递(定义 n 对键:值),它会为您的目的简化逻辑?
  • 这不是那么简单:我正在使用 cps 样式的函数,因为我正在处理 ajax 调用: continueIfTrue / continueIfFalse 不是由我的函数直接调用的,而是注册为回调并由当响应返回时浏览器......我看不出使用哈希表如何帮助我(也许我只是瞎了:D启发我!)。

标签: javascript memoization continuation-passing


【解决方案1】:

我是 CPS 新手,但我认为您必须以特定方式构造函数。

您的 CPS 函数具有以下结构(从您的示例中概括):

function cps(param, next) {
    var ret = someFunctionOfParam(param);

    // setTimeout for simulate async behaviour
    setTimeout(function () {
        next(ret);
    }, 0);
}

因此,您可以使用标准记忆器,也可以构建 CPS 函数。首先是 CPS-maker(假设函数的最后一个参数始终是要传递给的函数):

function cpsMaker(transformFunc) {
    return function() {
               var args = Array.prototype.slice.call(arguments);
               var next = args.pop(); // assume final arg is function to call
               var ret = transformFunc.apply(this,args);
               // setTimeout for simulate async behaviour
               setTimeout(function () {
                   next(ret);
               }, 0);
           }
}

然后可以配合使用memoizer:

function plusOne(val) {
    return val+1;
}

var memoPlusOne = memoize(plusOne);
var cpsMemPlusOne = cpsMaker(memoPlusOne);

cpsMemPlusOne(3,function(n){console.log(n)});

关键是将变换的记忆与CPS构造分开。

感谢您介绍 memoized CPS 的概念;即使这个答案很垃圾,也让我大开眼界!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2011-12-16
    • 1970-01-01
    相关资源
    最近更新 更多