jastrachan | 21 Apr 15:00 2004
Picon

Re: Generators take 2 (was Generator Expressions)


On 21 Apr 2004, at 13:27, Galarneau, Neil wrote:
> I don't understand something:
>
> James said:
>> 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
>>    }
>> }
>>
>> if I then did
>>
>>      list = []
>>      for (x in myGenerator()) {
>> 	list.add(x)
>>      }
>>      assert list == [1, 3, 4, 5, 6]
>>
>> So what we'd need to do to implement these kinds of generators is...
>>
>> * reserve 'yield' as a keyword (worth doing now just in case)
>> * any method which uses 'yield' must return any type, Iterator or
>> Object. i.e. its a compile error for the return type to not support
>> Iterator
>
> Doesn't myGenerator() return an int?  Does int implement Iterator?
>
> There seem to be 2 return types:
>   - the Iterator (which seems to need some kind of constructor)
>   - the type the Iterator returns (which in myGenerator is int)

In C# 2.0 a generator is just a function which returns in Iterator 
which could be of any type.

So in the above example you'd get this...

y = myGenerator()
assert y instanceof Iterator
assert y.hasNext()
first = y.next()
assert first == 1

etc

So in this case a generator function is just a function which creates 
an iterator, which we could then use in a for loop or in list-generator 
comprehensions etc.

James
-------
http://radio.weblogs.com/0112098/

Gmane