What distinguishes a continuation from a function?

callcc, continuations, lisp, scheme

Solution

True. All programs have continuations until it halts. One continuation is usually one step in the calculation done by the underlying implementation.

Your example:

(+ (* 2 3) 5)

The combination + is dependent on the combination * to finish first. Thus `(+ result 5)` is indeed the continuation of `(* 2 3)`. It's not a procedure in this context though. The usefulness of `call/cc` is when you have an continuation you regret and want to do something else instead or you want to come back to this at a later time. Lets do the first:

(define g 0)
(call/cc 
  (lambda (exit)
    (/ 10 (if (= g 0) (exit +Inf.0) g))))

Clearly, there is a division which is the continuation when the result of the if is done, but since `exit` is run the whole thing gets short circuited to return +Inf.0.

How would you do that with a procedure without getting it to do the division afterward? In this style, you can't.

It isn't really magic since Scheme converts your code to Continuation Passing Style(=CPS) and in CPS call/cc is no special. It's not trivial writing code in CPS.

Here's the CPS definition of `call/cc`

(define (kcall/cc k consumer)
  (consumer k (lambda (ignore v) (k v))))

Problem

Continuation describes what happens next with some value, right? Isn't that just a function that takes a value and does some computation? ``` (+ (* 2 3) 5) ``` the continuation of `(* 2 3)` is `(+ _ 5)` ``` (define k (lambda (v) (+ v 5))) ``` What is the point of using `call/cc` in here and not using the function `k` ?

Original source