[Haskell-cafe] Continuations and coroutines
paul at cogito.org.uk
Sat Jun 19 06:07:40 EDT 2010
On 19/06/10 10:36, Yves Parès wrote:
> I saw on the haskell wikibook that coroutines could be implemented by
> using continuations :
> (unhappily, the section is empty)
> Since I'm actually learning the wonders of continuations, I just
> wonder : how ?
Coroutines depend on the ability to suspend and resume execution. A
continuation acts as the "resume point" in the current function. The
"callCC" function in the continuation monad takes a function that
expects the continuation as an argument (which is how you get access to
it). So you say something like:
> yield = callCC $ \continuation -> ....
Then you would typically store the continuation somewhere and call some
other previously stored continuation to switch contexts.
Continuations can be used to pass data back into the continuation: you
call the continuation with an argument, and that argument becomes the
return value of the "callCC". In this case you probably just want to
You typically have a queue for continuations, so the new continuation
goes on the back of the queue and then you call the head of the queue.
Obvious modifications for priority, simulated time, real time or
whatever else you are trying to schedule. This implies some kind of
monadic state to store the queue in, so you will probably make your
monad of type "ContT (State Queue)"
If you want a thread to wait, say on a semaphore, then you have a queue
of continuations in the semaphore data structure.
Is this any help?
More information about the Haskell-Cafe