infinnie / infinnie.github.io

https://infinnie.github.io/
Apache License 2.0
0 stars 1 forks source link

JavaScript: simple call/cc #2

Closed infinnie closed 7 years ago

infinnie commented 8 years ago

Call/cc: https://en.wikipedia.org/wiki/Call-with-current-continuation

var callCC = function (g) {
    "use strict";
    var tempVal, done = false, tempFun = function (x) {
        if (!done) {
            done = true;
            tempVal = x;
        }
    };
    tempFun(g(tempFun));
    return tempVal;
};

Use:

callCC(function (f) {
    f(1);
    f(2);
    return 3;
}); // returns 1

callCC(function (f) {
    return 233;
}); // returns 233

To better support premature termination, instead of running to complete regardless of the intention, I’ve come up with an updated version of call/cc:

var callCC = function (g) {
    "use strict";
    var tempVal, done = false, tempFun = function (x) {
        if (!done) {
            done = true;
            tempVal = x;
            throw new Error("callCC");
        }
    };
    try {
        tempFun(g(tempFun));
    }
    catch (x) {
        if (x.message !== "callCC")
            throw x;
    }
    return tempVal;
};

Arguments support yet to be added.