Alex Rivera | Logout

Looking for examples of "real" uses of continuations

Asked 2008-08-29T08:07:58.687
21

I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the Wikipedia article:

(define the-continuation #f)

(define (test)
  (let ((i 0))
    ; call/cc calls its first function argument, passing 
    ; a continuation variable representing this point in
    ; the program as the argument to that function. 
    ;
    ; In this case, the function argument assigns that
    ; continuation to the variable the-continuation. 
    ;
    (call/cc (lambda (k) (set! the-continuation k)))
    ;
    ; The next time the-continuation is called, we start here.
    (set! i (+ i 1))
    i))

I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate.

So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.

Cheers!

Edit
Report

3 Answers

7

@Pat

Seaside

Yes, Seaside is a great example. I browsed its code quickly and found this message illustrating passing control between components in a seemingly statefull way accross the Web.

WAComponent >> call: aComponent
    "Pass control from the receiver to aComponent. The receiver will be
    temporarily replaced with aComponent. Code can return from here later
    on by sending #answer: to aComponent."

    ^ AnswerContinuation currentDo: [ :cc |
        self show: aComponent onAnswer: cc.
        WARenderNotification raiseSignal ]

So nice!

answered 2008-08-29T10:18:18.517
7

I built my own unit testing software. Before executing the test, I store the continuation before executing the test, and then on failure, I (optionally) tell the scheme interpreter to drop into debug mode, and re-invoke the continuation. This way I can step through the problematic code really easily.

If your continuations are serializable, you can also store then on application failure, and then re-invoke them to get detailed information about variable values, stack traces, etc.

answered 2008-09-16T06:43:19.817
3

Continuations are a good alternative to thread-per-request in server programming (including web application frontends.

In this model, instead of launching a new (heavy) thread every time a request comes in, you just start some work in a function. Then, when you are ready to block on I/O (i.e. reading from the database), you pass a continuation into the networking response handler. When the response comes back, you execute the continuation. With this scheme, you can process lots of requests with just a few threads.

This makes the control flow more complex than using blocking threads, but under heavy load, it is more efficient (at least on today's hardware).

answered 2008-09-16T06:50:53.137

Your Answer