Javascript CPS execution (continued)

Due to an article in IBM Developer Works about CPS (Continuation Walkthrough Style) , I try not to use "return".

without CPS

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

transition

rest of 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*
}

problem

The loop ends in the rest of the function.

What solution?

+5
source share
2 answers

Continuation style does not mix with JavaScript loops. You need to find another way to do the loop.

Please note that your code is interpreted as follows:

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

, . getter() continuationtest(), , , , continuationtest() .

CPS .

CPS

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

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

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); });
    }
}

( CPS , setTimeout() " script" . )

+6

:

function continuationtest(a) {
    }
    *use a*
    *part 2*
}

, :

function continuationtest(a) {
    *use a*
    *part 2*
}

, , , continuationtest, , .

0

All Articles