Memoize continued motion function

I am wondering if there is a way to implement a common "memoize" function (both in a function with a function as input and as an output function, like python decorators), which can also handle cps-style functions.

for a normal function (as in "the returned result returns a result, parameters are for input only!") the memoize function can be as simple as (in 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;
    };
}

but the cps-style function cannot be stored in memory by my simple function memoize, so I need to evaluate the arguments of the type function again, knowing also that the parameter must go to them.

For example, given the function

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

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

, , next - , (... , ), , !

- , ?: D

cps-, , "" .

+5
2

CPS, , .

CPS ( ):

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

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

, memoizer 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; , !

+2

, F #.

0

All Articles