2

I have been reading about call-with-current-continuation particularly in Scheme and have read various articles on many websites. However, I still don't understand how does the control flow work while using call-with-current-continuation.

For example, given the below attached code, how is the continuation invoked and whenever it is invoked, how does the control flow through the body of this procedure?

 (define call/cc call-with-current-continuation)
 (define showit (lambda (a b) 
                  (begin (display a) (display b) (display " "))))

 (define f
  (lambda (n)
     (let ((p (call/cc (lambda (k) k))))
         (begin
           (showit ’f= n)
          p))))

Also, when this procedure is run using ((f 2) (f 4)) it results in infinite loop with the pattern like this:

enter image description here

Can anyone explain the reason behind the infinite loop? Note: Using Drracket with R5RS

1 Answer 1

0

Call/cc returns a function that continues the surrounding computation. When it is called, control is returned to the place where the function was taken from, with a value that is given to the function.

In the example, (let ((p (call/cc (lambda (k) k)))) ...), p is given a continuation function. If p was then called (p 3), the control would have returned to the let-form like it had been (let ((p 3)) ...).

((f 2) (f 4)) juggles the continuations from (f 2) and (f 4), which results in the infinite loop. I've tried to explain the flow below:

=> ((f 2) (f 4))
  => (f 2) ;; first (f 2)
       call/cc returns the current continuation (lets say "cc1") into p
       display f=2
       return cc1
=> (cc1 (f 4))
  => (f 4) ;; first (f 4)
       call/cc returns the current continuation cc2 into p
       display f=4
       return cc2
=> (cc1 cc2)
     cc1 goes back to the first (f 2), but call/cc returns now cc2 into p
     display f=2
     returns cc2 from the first (f 2)
=> (cc2 (f 4))
  => (f 4) ;; second (f 4)
       call/cc returns cc3 into p
       display f=4
       return cc3
=> (cc2 cc3)
     cc2 goes back to the first (f 4), but p gets cc3
     display f=4
     returns cc3 from the first (f 4)
=> (cc1 cc3)
     cc1 goes back to the first (f 2), but p gets cc3
     display f=2
     returns cc3 from the first (f 2)
=> (cc3 (f 4))
  => (f 4) ;; third (f 4)
       display f=4
  <= cc4
=> (cc3 cc4)
  => (f 4) ;; second again
       display f=4
  <= cc4
=> (cc2 cc4)
  => (f 4) ;; first again
       display f=4
  <= cc4
=> (cc1 cc4)
  => (f 2) ;; first again
       display f=2
  <= cc4
=> (cc4 (f 4))
  => (f 4) ;; fourth (f 4)
       display f=4
  <= cc5
...so on
  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.