[squeak-dev] Re: Generators in Smalltalk?

Andreas Raab andreas.raab at gmx.de
Wed Feb 10 07:49:27 UTC 2010


Lukas Renggli wrote:
> http://source.lukas-renggli.ch/continuations/Generator-lr.3.mcz

Interesting, thanks. I notice you have Generator>>reset and 
Generator>>fork which are definitely useful, but no Generator>>close? 
The latter allowing to execute any unwind blocks associated with the 
generator, say:

gen := Generator on:[:yield| | fs |
	[fs := FileStream readOnlyFileNamed: 'foo.bar'.
	[fs atEnd] whileFalse:[yield value: fs nextLine]]
		ensure:[fs close]
].

Unless a close operation is provided, the file in the above will not be 
closed properly.

Cheers,
   - Andreas

> On 10 February 2010 06:49, Colin Putney <cputney at wiresong.ca> wrote:
>> On 2010-02-09, at 9:27 PM, Andreas Raab wrote:
>>
>>> Folks -
>>>
>>> One thing I really like about Python is Generators (http://docs.python.org/tutorial/classes.html#generators). They allow code to provide a stream (iterator) interface where it's not easy to provide the interface explicitly. I.e., it would allow one to provide a stream interface to an arbitrary computation like:
>>>
>>> gen := Generator on: [:yield| 3 to: 1 by: -1 do:[:i| yield value: i]].
>>> gen next. "=>3"
>>> gen next. "=>2"
>>> gen next. "=>1"
>>> gen next. "=>nil"
>>>
>>> This *ought* to be really simple to do in Smalltalk by using blocks and some voodoo in the execution engine. Has anyone ever done that?
>> Generators are essentially coroutines, which makes them pretty easy to implement in Smalltalk - thisContext is all you need. They've been implemented a few times to my knowledge. GST has an implementation that is pretty similar to what Python provides:
>>
>> http://smalltalk.gnu.org/faq/47
>>
>> Also, Stephen Pair posted an implementation here in December:
>>
>> http://n4.nabble.com/ANN-CoroutineReadStream-tt963004.html#a963004
>>
>> I've done stuff like this for testing. My MockLibrary package provides a class called Mocket ("mock socket") that uses coroutines to make it easier to test network code. It's not a "generator" exactly, but it does simulate reading data off a socket by jumping back into the test case and letting it generate the data.
>>
>> Colin
>>
> 
> 
> 




More information about the Squeak-dev mailing list