20-CS-4003-001 Organization of Programming Languages Fall 2017
Call-with-current-continuation examples

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

Simple co-routining example

(define call/cc call-with-current-continuation)

(define env1 '())
(define env2 '())

(define main
  (lambda ()
    (begin
      (display 'In_main) (newline)
      (if (= (call/cc (lambda (k) (set! env2 k) 0)) 0)
          (begin
            (display 'Calling_f1_from_main) (newline)
            (f1))
          (begin
            (display 'Calling_f2_from_main) (newline)
            (f2))))))

(define f1
  (lambda ()
    (begin
      (display 'In_f1) (newline)
      (if (= (call/cc (lambda (k) (set! env1 k) 0)) 0)
          (begin
            (display 'Passing_control_from_f1_to_f2)
            (newline)
            (env2 1))
          (f1)))))

(define f2
  (lambda ()
    (begin
      (display 'In_f2) (newline)
      (if (= (call/cc (lambda (k) (set! env2 k) 0)) 0)
          (begin
            (display 'Passing_control_from_f2_to_f1)
            (newline)
            (env1 1))
          (f2)))))
 -  This example shows how call-with-current-continuation may be used to support co-routining. Global variable env1 is initially '() but will later hold a continuation that sends control back to f1 in the condition of the if. Similarly, env2 provides the same service for f2. When the following is invoked
   (main)
the continuation in the if of main is temporarily stored in env2. Since 0 is returned by that call/cc the if test succeeds and f1 is invoked. The continuation in the if of f2 is stored in env1 and since the call/cc returns 0 the env2 continuation is invoked. But this sends control back to the if of main, this time with call/cc returning a value of 1 (due to (env2 1)). Now the if of main fails and f2 is invoked. The continuation of f2 is saved in env2 and the contination env1 is invoked with a return value of 1. This sends control to f1 resulting in the invocation (f1). In the if of f1 a continuation is grabbed and put into env1 and f2 is invoked. In f2, (f2) is invoked and then a continuation is grabbed and placed in env2. Invoking the continuation env1 sends control back to f1. The cycle repeats forever. Observe that the computation is always forward through f1 and f2. There is no backtracking.