CODE: Continuations, closures, concurrency

A blogger recently posted a challenge for programmers of languages with first-class continuations: use them to construct a Prolog-like constraint satisfaction construct that works by saving choice points. Of course, I can't resist this kind of thing…

My Nickle solution is checked into the examples directory in the distribution. I'll leave you to meditate there over the actual implementation, but here's the style of programming it enables:

import Search;
void right_triangles(bool all_solutions)
    /* Find an integer right triangle
       with sides in the range 1..10. */
{
    init_search();
    int x = in_range(1, 10);
    int y = in_range(1, 10);
    int z = in_range(1, 10);
    if (x ** 2 + y ** 2 == z ** 2)
        printf("%d + %d == %d\n",
               x ** 2, y ** 2, z ** 2);
    else
        fail();
}

I think it's pretty cool that this can be made to work.

When I showed this to one of my students, Josh, he showed me the Nickle problem he'd been having trouble with: getting voluntary coroutines to work using continuations. That led to more code in the examples directory, which is used like this:

import Channel;
channel c;

void generate() {
    for (int i = 0; i < 10; i++) {
        printf("sent %d\n", i);
        send(&c, i);
    }
}

void test() {
    int i;
    do {
        i = recv(&c, generate);
        printf("got %d\n", i);
    } while (i != 7);
}

test();

More coolness.

This brought back an old project I'd tried in the past: implementing Scheme-style promise with delay/force using closures to facilitate lazy evaluation in Nickle. This seems harder, and I can't quite see how to do it yet. I'm sure I'll figure it out eventually. For now, I'm calling it a night. It's a night.