Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What distinguishes a continuation from a function?

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 ?

like image 546
ayhid Avatar asked Aug 29 '13 22:08

ayhid


Video Answer


2 Answers

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))))
like image 55
Sylwester Avatar answered Nov 03 '22 16:11

Sylwester


Congratulations! You've just invented continuation-passing style! The only difference between what you've done and call/cc is that call/cc does it automatically, and doesn't require you to restructure your code.

like image 40
John Clements Avatar answered Nov 03 '22 18:11

John Clements