I'm trying to understand continuations and continuation passing style better. They're supposed to be good for writing generators, iterators, coroutines, and the like.
I know Javascript already has builtin generators, but I thought building a generator by hand in continuation passing style would be a good exercise. This blog post has some code samples of traversing an array,
function logArray(arr) {
forEachCps(arr, function (elem, index, next) { // (*)
console.log(elem);
next();
}, function () {
console.log("### Done");
});
}
function forEachCps(arr, visitor, done) { // (**)
forEachCpsRec(0, arr, visitor, done)
}
function forEachCpsRec(index, arr, visitor, done) {
if (index < arr.length) {
visitor(arr[index], index, function () {
forEachCpsRec(index+1, arr, visitor, done);
});
} else {
done();
}
}
but I was hoping for an infinite list type generator, rather than one that traverses a fixed array. I was also hoping for the caller to have control over how often to take numbers (this is the difference between iterator and generator, right?). Can this be done in Javascript? (Or if not, what would be a good language to do this language in? Only Scheme??)