[squeak-dev] Re: Generators in Smalltalk??

Andreas Raab andreas.raab at gmx.de
Wed Feb 10 22:30:39 UTC 2010


Ralph Boland wrote:
> I do not understand all the commotion over generators.

Generators transform a push model (#do:) into a pull model (#next). 
Let's say you have two algorithms one that produces values via a push 
model and one that consumes values via a pull model:

producer := SomeAlgorithm new.
producer do:[:value| "produces the value from the algorithm"].

consumer := AnotherAlgoritm new.
consumer process: inputStream. "consumes the value from inputStream"

Plugging these two together can be a royal pain. You basically have the 
following three options:

1) Preproduce all the values from the producer and create a stream that 
holds them:

values := Array streamContents:[:s| producer do:[:each| s nextPut: each]].
consumer process: values readStream.

This can work very well if the number of values is limited and if you 
know you're going to consume all the produced values (doesn't work that 
well with infinite sequences of numbers).

2) Rewrite either one of the algorithms. Can work very well if it's your 
own code and reasonably simple, and can be extremely painful if it's 
complex.

3) Use a Generator. With a generator, the solution becomes simply:

consumer process: (Generator on:[:yield| producer do: yield]).

When you can neither use solution 1) or 2) generators simplify your life 
  *greatly*. In fact I'd say they are indispensable if you're dealing 
with a complex existing environment.

> If a Collection class cannot do what you want, use a Stream.
> Take a read only Stream and subclass from it a class called GenMyData.
> Inside GenMyData write code that generates the data you
> need on the fly and feeds it to the user upon request using
> the ReadStream interface.

See above. You're describing option #2. Rewriting an existing algorithm 
to "feed" the data properly can be decidedly non-trivial. You can start 
with Integer>>primesUpTo:do: which is a very simple algorithm. The point 
being that while all algorithms can be expressed either way the generic 
way in which a Generator does that replaces the need to reimplement each 
specific algorithm.

Cheers,
   - Andreas



More information about the Squeak-dev mailing list