foreach vs. iterators

Sean Kelly sean at f4.ca
Sun Nov 5 11:12:32 PST 2006


Bill Baxter wrote:
> Bill Baxter wrote:
>> Sean Kelly wrote:
>>
>>> Sean Kelly wrote:
>>>
>>>> Still, I think it's useful to have in an iterator, so perhaps 
>>>> something roughly like this:
>>>>
>>>> interface Iterator(T)
>>>> {
>>>>     T val();
>>>>     T next();
>>>>     bool hasNext();
>>>> }
>>>
>>>
>>>
>>> Err... this doesn't work for an iterator returned for an empty 
>>> container.  
>>
>>
>> It's fine if you define the behavior to be that you have to call 
>> next() once to get the first value.  So for iteration idiom becomes:
>>
>> T v;
>> while(c.hasNext()) )
>> {
>> }
> 
> ....another victem of Ctrl+Enter....
> 
> while(c.hasNext())
> {
>    T v = c.next();
> }
> 
> I think an alias for T also needs to be a part of the definition of the 
> iterator.  Like  alias T value_type.

I don't think it's necessary, but it may be convenient.  For example, 
this should work:

typeof(c.next());

but that obviously requires an instance of the iterator.  And it's 
perhaps a bit confusing.

> Also would do you do a mutating iteration over collections of basic 
> value types (eg floats), structs, and classes?  I.e. if you want to do 
> something like:
> 
> while(c.hasNext())
> {
>    T v = c.next();
>    v += 2;
> }
> where T could be float, struct, or class.  Ok, class case is fine, but 
> the other two aren't clear to me.  Mutable iterator over structs could 
> maybe return a pointer to each struct.  Basic value type, I'm not sure. 
>  Just woke up though... maybe it's obvious and my head just isn't 
> working yet.

Yeah, perhaps returning a pointer is better.  The lack of reference 
types in D can make things like this a bit awkward.



More information about the Digitalmars-d-announce mailing list