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
开发者_Python百科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?
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.)
You have a typo:
function continuationtest(a) {
}
*use a*
*part 2*
}
This may be what you wanted:
function continuationtest(a) {
*use a*
*part 2*
}
Other than that, it will be hard to help with so little information, such as what will happen in the continuationtest
, as that could be critical if you are still having problems.
精彩评论