Question

I am trying to learn continuations and use them to implement coroutines in Scheme.

I have two procedures (coroutines) a and b, and I switch between them in the following way:

;; c is a continuation.
(define (a c)
   ...
   ;; Switch to the other coroutine.
   (call/cc c)
   ...


(define (b c)
   ...
   ;; Switch to the other coroutine.
   (call/cc c)
   ...

I start the execution with

(a b)

I have tested a small example and, indeed, the execution switches back and forth between the two procedures until one of the two terminates without calling the continuation it was given as an argument.

I have two questions:

  1. Is my example an appropriate / idiomatic implementation of coroutines using continuations?
  2. Is tail-call optimization mandatory for implementing coroutines with continuations? In my solution, switching too often between the two coroutines might cause a stack overflow if Scheme did not provide TCO. Are there other solutions that do not require TCO?

EDIT

Basile's comment seems to be sufficient to answer my question. The background of the question is that I would like this approach to implement coroutines in Python, where I do not have TCO.

Was it helpful?

Solution

As I commented:

  • yes, your example is an appropriate implementation of coroutines using continuations.

  • yes, tail-call optimization is mandatory for implementing coroutines with continuations.

Licensed under: CC-BY-SA with attribution
scroll top