2

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??)

ziggurism
  • 2,264
  • 2
  • 16
  • 23
  • 1
    I doubt it, because CPS requires passing a callback down, which does not conform to how iterators/generators are required to be structured. – CertainPerformance Nov 11 '20 at 23:11
  • It's *possible* to create a *similar* mechanism, but honestly once you "get" the new feature in the language it's extremely easy to use and it opens up a surprising number of fundamental architectural possibilities. – Pointy Nov 11 '20 at 23:12
  • @Pointy generators are great and easy to use, but at the moment I'm trying to understand continuations better, which are not as easy, – ziggurism Nov 11 '20 at 23:17
  • The excellent self answer by Aadit M Shah explains that you can't fully implement `callcc` in Javascript, but you can make a facsimile of it, which he shows. Could I use that to write generators in Javascript? – ziggurism Nov 11 '20 at 23:24
  • [What's in a Continuation](https://jlongster.com/Whats-in-a-Continuation) talks about them in the context of javascript and has some interactive demonstrations. – Ouroborus Nov 12 '20 at 08:20

0 Answers0