[squeak-dev] Generators in Smalltalk?

Colin Putney cputney at wiresong.ca
Wed Feb 10 05:49:55 UTC 2010


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