Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript CPS (continuation passing style) implementation

Because of an article in IBM Developer Works about CPS (continuation passing style), I'm trying to not use "return".

without CPS

function getter() {
    * calculate a*
    return a;
}
function test() {
    *part 1*
    if(*condition*) {
         a = getter();
    }
    *use a*
    *part 2*
}

transition

the rest of the function

    }
    *use a*
    *part 2*

with CPS

function getter() {
    * calculate a*
    continuationtest(a);
}
function test() {
    *part 1*
    if (*condition*) {
        getter();
}
function continuationtest(a) {
    }
    *use a*
    *part 2*
}

the problem

A loop ends in the rest of the function.

What is the solution?

like image 927
Delirium tremens Avatar asked Nov 30 '09 17:11

Delirium tremens


1 Answers

Continuation-passing style doesn't mix well with JavaScript loops. You need to find another way to do the loop.

Note that your code is being interpreted like this:

function test() {
    *part 1*
    if (*condition*) {
        getter();
    }                               // <--- note indentation here
    function continuationtest(a) {  // <--- and here
    }
    *use a*
    *part 2*
}

So you are not currently using continuation-passing style at all. When getter() calls continuationtest(), it's probably failing, since continuationtest() is not in scope there.

A CPS example with a loop might look like this.

Without CPS

function doSomething(i) {
    alert("doing " + i);
}

function doLoop() {
    for (i = 0; i < 9; i++)
        doSomething(i);
}

With CPS

function doSomething(i, ctn) {
    alert("doing " + i);
    ctn();
}

function doLoop() {
    doLoopStartingAt(0);

    function doLoopStartingAt(i) {
        if (i < 9)
            doSomething(i, function ctn() { doLoopStartingAt(i + 1); });
    }
}

(The advantage of CPS is that at any point you can use setTimeout() to delay execution of the rest, or wait for user input to be processed, or avoid the browser from showing a "slow script" popup.)

like image 137
Jason Orendorff Avatar answered Oct 10 '22 03:10

Jason Orendorff