foreach vs. iterators

David Gileadi foo at bar.com
Mon Nov 6 09:10:21 PST 2006


Bill Baxter wrote:
> Sean Kelly 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()) )
>>> {
>>> }
>>
>>
>> Yup, but this seems confusing with the presence of val() methods.
> 
> I'm not sold on val() yet.  :-)
> 
> --bb

For what it's worth, C# implements it like this:

     public interface IEnumerator
     {
	public bool MoveNext();
	public object Current { get; }
	public void Reset();
     }

It seems that MoveNext() must be called before Current becomes valid 
(assuming that there are any items in the collection).  If Current is 
accessed without having an object to return, it throws an exception.  So 
a while loop might look like:

     while (e.MoveNext())
     {
         object obj = e.Current;
         Console.WriteLine(obj);
     }

C#'s foreach loop also works with IEnumerator, as:

     foreach (object obj in c)
     {
         Console.WriteLine(obj);
     }

where c is an object that implements the IEnumerable interface, which 
has a single GetEnumerator() method.

I'm not suggesting that D do the same thing as C#, but I thought that 
some of the above might be relevant to this discussion.

-Dave



More information about the Digitalmars-d-announce mailing list