jastrachan | 21 Apr 13:49 2004

Re: Generators take 2 (was Generator Expressions)

On 21 Apr 2004, at 12:22, jastrachan@... wrote:
> I just took a look at how generators are designed in C# 2.0 which seem 
> quite nice. Basically the trick is that a generator could return a new 
> java.util.Iterator instance which maintains its own state.
> e.g.
> myGenerator() {
>   yield 1
>   for (x in 3..6) {
>     yield x
>   }
> }

BTW some background might help for those unaware of what all this 
generators thing is. While its a big field and touches on various 
topics like generators, coroutines, continuations, backtracking, tail 
recursion along the way.

The main aim in this use case (and similarly in the C# 2.0 spec)  is to 
offer a simple way to write iterators over data in a simple way, where 
rather than having isNext() / next() methods, you can just 'yield' each 
value when you're ready.

Its a bit like the difference between pull and push based XML parsing, 
kinda. Writing iterators is inside out and this generators idea helps 
to write them the way our brains think about them rather than the way 
we must structure them to conform to java.util.Iterator.

I think generators-as-iterators is fairly easily doable without any 
wacky Thread stuff or support for full continuations etc.