Re: coroutines and continuations ( in Python? - long discussion )

Tim Peters (tim@ksr.com)
Wed, 04 May 94 23:32:55 -0400

> [steve]
> Since I'm at home on the modem, detailed response to your example
> and some of your points will have to wait until I get a hardcopy
> to study, but I'll comment on a few points now:

The terms of the discussion have changed a lot since it started, so let's
drop it & start a new one <wink>.

Two things I took from Guido's responses:

1) Your original problem (redirecting the "write" output from one
function to the "read" input of another, in pipe-like fashion) would
be easy to solve using threads (i.e., by binding stdin & stdout to a
pair of "get" and "put" methods much like the methods of that name in
Guido's Generator class).

2) General continuations may be much harder to implement than we thought,
because the state of the _C_ runtime stack is also part of the current
continuation, and that's hard to muck with short of low-level OS- and
machine-specific hacks. I can picture an elaborate scheme to worm
around that, also using threads, but ...

Disagree with either of those? The more I see of general continuations
the less I want to see them as part of Official Python, but I do think
they'd be fascinating to play with. I've been surprised before!

> ...
> As one of the less object-oriented of functional-programmers once put
> it: "Why would you ever want objects when you have closures and
> continuations."

Indeed, given those, why would anyone ever want sex.

> ...
> What I need for my read/write problem is a "save this continuation
> (insert arrow) HERE and resume that continuation THERE" syntax.

Approaching this via "simple" coroutines, a
coroutine_transfer_to THERE
in routine HERE says exactly that. General coroutines are easier to
reason about, because you can use the name of a routine as a shorthand
for "whatever continuation was in effect the last time the routine with
that name coroutine-transferred out".

> Modula has a syntax for coroutine call, though I can't recall it
> offhand. ( Guido? ) I suspect that it does the sort of 'swap'
> that I require, but hides the continuation as you would like.

In Modula-2 it's

PROCEDURE TRANSFER(VAR p1,p2: PROCESS)

Saves the state of the current process into p1, and resumes process p2.
Chase it back far enough and p2 must initially have been created by a
call to NEWPROCESS, which creates a "process" out of a top-level
parameterless procedure and a chunk of "workspace" memory.

In an OO language, or any language that took coroutines very seriously,
it would be more natural for the transfer to name only p2.

> ...
> So maybe I *will* have to give up the idea of passing, assigning,
> handling, poking and otherwise prodding continuation explicitly.

Heck no! It's fun <smile>.

although-given-whiskey-i'm-not-sure-why-anyone-would-want-continuations-
ly y'rs - tim

Tim Peters tim@ksr.com
not speaking for Kendall Square Research Corp