[plt-scheme] Fun with Unicode and delimited continuations

From: John Clements (clements at brinckerhoff.org)
Date: Thu Jun 3 13:40:39 EDT 2010

On Jun 3, 2010, at 10:19 AM, Jon Rafkind wrote:

> On 06/03/2010 11:07 AM, Eli Barzilay wrote:
>> On Jun  3, Matthias Felleisen wrote:
>>> On Jun 3, 2010, at 12:31 PM, John Clements wrote:
>>>>> Sorry, maybe this wasn't clear: I mean e.g. the python 'yield',
>>>>> which allows a function to return multiple values in a serialized
>>>>> form.
>>> If you can write a yield + create a two-element structure in Python
>>> that way, you can mimic delimited continuations.
>>>> The only problem with this mechanism is that the yield boundary is
>>>> fixed on entry to the function call.
>>> That's minor. Reset is next to the function entry point too.
>>> Go for it. Show us that Python has delimited continuations.
>> Here's some quick code:
>>   #lang scheme
>>   (require scheme/generator)
>>   (define (foo x y) (yield x) (yield (+ x y)))
>>   (define (bar a b c)
>>     (generator             ; v5 will require () after `generator'
>>       (for* ([x (in-generator (foo a b))]
>>              [y (in-generator (foo x c))])
>>         (yield y))))
>>   (define g (bar 100 10 1))
>>   (g) (g) (g) (g)
>> where `foo' is the moral equivalent of plus/minus.  Given that this
>> uses exactly the feature that scheme/generator has that python doesn't
>> (it uses a dynamic `yield' so it can be used in "helper" functions),
>> it would be interesting to see if there's a way to do that in python.
>> (I think that Jon looked for an example that shows the difference.)
> This python program behaves the same, although it would break if one of the `yield's in (foo) were moved to a helper function, like
> (define (foo1 x) (yield x))
> (define (foo x y) (yield x) (foo1 (+ x y)))
> # -- python --
> def foo(x, y):
>    yield x
>    yield x + y
> def bar(a, b, c):
>    for x in foo(a, b):
>        for y in foo(x, c):
>            yield y
> for n in bar(100, 10, 1):
>    print n
> # -- end --

Right... the problem with this is that the body of bar gets horribly mangled, and the calls to foo have to be lifted out.  This is basically the partial CPSing that would be required to implement this without generators.

I'm wondering, though: if you "capture a continuation" by using a yield in Python, and make a copy of the resulting generator, can you enter the two resulting "continuations" separately, or does the copied object contain a reference to state that gets messed up?

I just spent a few minutes on this, and I got hung up on how to pull just one value from a python generator.  It's probably easy, but I don't know how to do it.


-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 4669 bytes
Desc: not available
URL: <http://lists.racket-lang.org/users/archive/attachments/20100603/20f87c4d/attachment.p7s>

Posted on the users mailing list.