[plt-scheme] Help with understanding continuations

From: Grant Rettke (grettke at acm.org)
Date: Thu Nov 29 18:39:51 EST 2007

Hi folks,

I took Matthias' example on continuations:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (generate-one-element-at-a-time a-list)
  (define (generator)
    (call/cc control-state))
  (define (control-state return)
    (for-each
     (lambda (an-element-from-a-list)
       (call/cc
        (lambda (resume-here)
          (set! control-state resume-here)
          (return an-element-from-a-list))))
     a-list)
    (return 'you-fell-off-the-end-off-the-list))
  generator)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

and attempted to modify it to generate a kind of long running
"process" that depends on some external properties to complete. If a
condition isn't true, the process will abort, and when it is continued
it will execute again immediately before the last check.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


(define cond1 #f)
(define cond2 #f)
(define (foo-process arg1 arg2)
  (define (process)
    (call/cc impl))
  (define (impl return)
    (begin
      (printf "Passed in args ~a and ~a~n" arg1 arg2)
      (let/cc resume-here (set! impl resume-here))
      (if cond1
          (printf "Condition 1 is met, going to condition 2~n")
          (return "Condition 1 not met"))
      (let/cc resume-here (set! impl resume-here))
      (if cond2
          (printf "Condition 2 is met, can finish the process")
          (return "Condition 2 not met"))
      (printf "The process has finished with values ~a and ~a~n" arg1
arg2)
      (let ([result (+ arg1 arg2)])
        (let/cc resume-here (set! impl resume-here))
        (return result))))
  process)

(define a-process (foo-process 13 29))
(a-process)
(set! cond1 #t)
(a-process)
(set! cond2 #t)
(a-process)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

So I've got two questions for you.

1. Is the runnable version of the foo process implemented in a sane
way? Is this how one may implement such a thing?

2. The notion of the current continuation is the function that would
get called after this current computation has finished being
evaluated. It is the flow, what "comes next". Is this a temporal thing
or should it be thought of some other way?


Posted on the users mailing list.