齐天大圣
齐天大圣

Reputation: 1189

(call/cc): What exactly is continuation?

This question have been asked several times on SO, but none of them solve my question. What is continuation?

Consider the following code:

( (lambda (pair)
     (begin (print (car pair))
            ((cdr pair) (cons (+ 1 (car pair)) 
                              (cdr pair)))))

  (call/cc (lambda (k) 
             (cons 0 k))))

This program loops indefinitely printing the sequence of integers starting from 0.

What I understand is:

Step 1: (call/cc (lambda (k) (cons 0 k))) is evaluated, return pair (0 . #continuation) (What is #continuation in here)

Step 2: Apply the pair from step 1 to a lambda function. The lambda function first print out the car, which is 0.

Now, I am totally lost. The program is evaluating (#continuation (1 . #continuation)), which does not really make sense to me. Is #continuation a procedure now?

What makes the program keep applying (call/cc (lambda (k) (cons 0 k))) to the lambda function? So that it can keep calling itself

Upvotes: 2

Views: 248

Answers (1)

齐天大圣
齐天大圣

Reputation: 1189

I think I have figured it out.

Continuation is the current state of the program

Given this, first we need to ask: what is the continuation, or the current state of this program?

It is a lambda function waiting for a pair.

#continuation = ( lambda-function <placeholder>)

<placeholder> would be whatever we will pass to that lambda function, but we have not done that yet.

Now our program start to run, it evaluates the lambda function, then it evaluate the pair return by call/cc, which is (0 . #continuation).

(print (car pair)) => Next the lambda function prints out 0

((cdr pair) (cons (+ 1 (car pair)) (cdr pair))))) => Here, (cdr pair) is our continuation, which is (lambda-function <placeholder>), then our program pass a new pair into it. Then the program starts its infinite loop

Upvotes: 3

Related Questions