2006-06-04
Partial Continuations and Narrative Javascript
I've been playing with Narrative Javascript and decided to have a go at porting the bshift and breset Scheme example to it. I'd previously had a go at this with Rhino.
Trying some simple examples out it turns out that the continuations provided by Narrative Javascript are really partial continuations. Here's an example demonstrating this:
var ex4cc ;
function ex4a(cont) {
ex4cc = cont;
cont();
}
function ex4() {
var x = 0;
ex4a->();
x = x +1;
print("here:" + x);
return x;
}
function callex4() {
var x = ex4cc();
print("Returned: "+ x);
}
js> ex4()
here:1
js> ex4cc()
here:2
js> ex4cc()
here:3
js> callex4()
here:4
Returned: undefined
Full continuations don't return to their caller since they effectively replace the entire call stack with the original call stack of the continuation. This example shows 'callex4' printing 'Returned...' after the original continuation was called. The partial continuation appears to be delimited by the nearest function in the call stack which was not called with the '->' operator. This makes a simple shift/reset something like this:
function reset(f) {
return f();
}
function shift(f, cont) {
f(cont);
}
The 'range' function and examples:
function range(from, to) {
return shift->(function(pcc) {
while(from < to) {
pcc(from++);
}
return to;
});
}
function test1() {
reset(function() {
print(range->(1, 5));
});
}
function test2() {
var sum = 0;
reset(function() {
sum += range->(1, 10);
});
print(sum);
}
js> test1()
1
2
3
4
5
js> test2()
55
Once compiled with Narrative Javascript's compiler the resulting code runs fine in a standard web browser.
Neil Mix, the author of Narrative Javascript, has set up a google group for discussion about it.