Tuesday, 27 November 2007

Wrapping my head around continuations

I am pretty clueless in general. But to my credit, I relentlessly pursue knowledge, some of it being useful! As you may know, I have been looking at Weblocks as I feel I would eventually reinvent it badly.

Anyway, one of the things that the author recently added was support for continuations. A very simple example was demonstrated, and lo and behold it worked! So I went off, confident that I understood what a continuation was. I created an app skeleton and started using with-flow. And it didn't work. I fixed some parentheses. It still didn't work. "Hmm," I thought, "perhaps continuations aren't just things to gloss over." So I went back and read Continuations-Based Web Applications in CL with Weblocks again. Still didn't get it. I finally ended up at Wikipedia's continuation entry. And it all made sense. I even understood what a delimited continuation was.

I went back to my code, moved a couple of more parentheses, added a couple of functions, and lo and behold, it worked!

Thank you Slava Akhmechet for making this useful feature available. Note, neither he or I are claiming that Weblocks is the first system to use continuations.

The use of continuations for Web applications should be more popular. I would assume the main reason it is unheard of is because most languages don't support it. To Java's credit however, this article discusses using continuations. However, true to Java form, the third listing uses XML. Sigh...

2 comments:

Anonymous said...

Can you explain delimited continuation?

Sohail Somani said...

Sure. If you Google for delimited continuations, it ain't gonna help :-) I will give my layman's understanding.

Normal continuations represent all of a remaining computation and therefore(?) you never return from a continuation. Delimited continuations only represent part of the remaining computation and therefore(?) can have a return value. I believe the word "delimited" comes from the fact that you specify which parts of the computation are to become a continuation.

The simplest use of what I comfortably say can create a delimited continuation is the yield statement in Python. This allows you to write code like this:
def yield_123():
yield 1
yield 2
yield 3

for i in yield_123():
print i

# Output:
# 1
# 2
# 3

The yield statement creates a generator object which is really the implementation of the continuation. The yield statements store/reset the continuation which is what leads to the delimited continuation. In general, you can think of delimited continuations as coroutines and I think you will still be more correct than most people.