[ prog / sol / mona ]

prog


How to learn Scheme's continuations

3 2021-09-14 07:10

Think of the Scheme program as a tree. Imagine that it is evaluated by replacing each node with its value, starting from the leafs. So if you have (/ (+ 1 2) 3), evaluating (+ 1 2) will give you (/ 3 3), etc. Now if you consider any node in the original tree, its continuation will be this replacement. For example, for (+ 1 2) the continuation will be (lambda (v) (/ v 3)), for the 3 it will be (lambda (v) (/ (+ 1 2) v)), and so on.

call/cc will work in this as a "shortcut". It gives you a continuation, something like a function, that also replaces the whole tree. Consider the following example:

(+ 1
   (call/cc
    (lambda (k)
      (+ 5 (k (+ 1 2))))))

First, we evaluate (+ 1 2):

(+ 1
   (call/cc
    (lambda (k)
      (+ 5 (k 3)))))

Now k, the continuation, is invoked, and instead of just replacing it with a value, we replace the whole tree with the value passed to it!

(+ 1 3)

You can see that it skipped the whole (+ 5 ...) thing.

Or something like this, I hope this gives you a general idea. I cheated and ignored a few things (evaluating 1==, ==+, etc., plus first we should evaluate (call/cc λ) to (λ k) and so on), but I am already late from work so I hope at least this will be of some help and it doesn't just confuse you further.

7


VIP:

do not edit these