Search code examples
functional-programmingschemeracketcontinuations

Can I have a co-routine of three functions using continuations in Scheme?


Is it possible to add another function procC in here so that the sequence of evaluation is procA->procB->procC->procA ... ?

(define (procA another-fun)
  (let loop ((n 5))
    (display "In Proc A \n")
    (set! another-fun (call/cc another-fun))
    (when (> n 0)
      (loop (- n 1)))))

(define (procB another-fun)
  (let loop ((n 5))
    (display "In Proc B  \n")
    (set! another-fun (call/cc another-fun))
    (when (> n 0)
      (loop (- n 1)))))

Solution

  • From "The Scheme Programming Language"

    http://www.scheme.com/tspl4/further.html#./further:h3

    (define lwp-list '()) ; SO's highlighter gets confused
    (define lwp
      (lambda (thunk)
        (set! lwp-list (append lwp-list (list thunk)))))
    
    (define start
      (lambda ()
        (let ([p (car lwp-list)])
          (set! lwp-list (cdr lwp-list))
          (p))))
    
    (define pause
      (lambda ()
        (call/cc
          (lambda (k)
            (lwp (lambda () (k #f)))
            (start)))))
    
    
    (lwp (lambda () (let f () (pause) (display "h") (f))))
    (lwp (lambda () (let f () (pause) (display "e") (f))))
    (lwp (lambda () (let f () (pause) (display "y") (f))))
    (lwp (lambda () (let f () (pause) (display "!") (f))))
    (lwp (lambda () (let f () (pause) (newline) (f))))
    (start)  hey!
             hey!
             hey!
             hey!