Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to understand this continuation?

(let ([x (call/cc (lambda (k) k))])
    (x (lambda (ignore) "hi")))  => "hi"

How can I write the executing steps of this continuation?

like image 874
abelard2008 Avatar asked Dec 20 '22 19:12

abelard2008


2 Answers

The call/cc operator is used to call a given procedure with the current continuation (hence the name call-with-current-continuation). So to understand how it works, we need to know what the current continuation is.

In your program, at the point that the call/cc is executed, the continuation looks like this:

CONT = (let ([x HOLE])
         (x (lambda (ignore) "hi")))

where HOLE is a placeholder for a value to plug in. In other words, the continuation is the remaining computation. You can stick a value into the continuation if you want to progress.

Now, call/cc captures this continuation and passes it to the procedure (lambda (k) k). You can see that this procedure just immediately returns the continuation. So the program reduces to:

(let ([x CONT])
  (x (lambda (ignore) "hi")))

Applying a continuation captured by call/cc replaces the current computation with that continuation plugged with the value you give it. So the application (x (lambda (ignore) "hi")) turns into:

(let ([x (lambda (ignore) "hi")])
  (x (lambda (ignore) "hi")))

and the rest should follow from what you already know about lambdas and application.

like image 186
Asumu Takikawa Avatar answered Jan 09 '23 01:01

Asumu Takikawa


In the first line [x (call/cc (lambda (k) k))] we're creating a new continuation which is bound to the k parameter in the received lambda. That k is returned and in turn bound to the x local variable - therefore, x is a continuation.

In the second line, x is called with a single-argument lambda; the argument is ignored and the result of invoking (lambda (ignore) "hi") is "hi", which is finally returned as the result of the continuation. This is equivalent to simply calling:

(call/cc
 (lambda (k)
   (k "hi")))
like image 36
Óscar López Avatar answered Jan 08 '23 23:01

Óscar López