foreach vs. iterators

Oskar Linde oskar.lindeREM at OVEgmail.com
Fri Nov 3 09:41:11 PST 2006


Sean Kelly wrote:

>  From this it seems clear that foreach is not sufficiently adaptable to 
> meet the needs of all sequential algorithms and opIndex is not a 
> reasonable substitute for all cases where foreach may not be used.  What 
> alternatives do we have?  So far, iterator variants are all I've been 
> able to come up with.

I agree, and I have been saying this countless times. :)

Why don't we come up with a standard iterator concept for D?
For a forward iterator, C++ has:

*i
i++ / ++i
i != end

In the post "Iterators (Was: Re: Lazy eval -- an example issue)" in 
digitalmars.D ( 
news://news.digitalmars.com:119/ecmvec$ksl$1@digitaldaemon.com ) I 
suggested a simple java-style variant:

*i.next()
i.hasNext()

A generic opApply could then be implemented as:

template opApplyMixin() {
   int opApply(int delegate(inout ValueType v) dg) {
     ValueType *t;
     while(hasNext()) {
       t = next();
       if (auto status = dg(*t))
         return status;
     }
     return 0;
   }
}

And a simple array iterator wrapper (Could of course be more efficiently 
implemented):

struct ArrayForwardIterator(T) {
   T[] arr;
   alias T ValueType;

   T* next() { arr = arr[1..$]; return arr.ptr-1; }
   bool hasNext() { return arr.length > 0; }
   mixin opApplyMixin;
}

If pointers should be avoided, and since D doesn't have an opDeref, but 
has lhs/rhs overloads for indexing, another iterator variant could be to use

i[]
i[]=

for rhs, and lhs iterator dereferencing.

i++ / ++i could be used instead of .next() if it is any clearer, and so 
on...

It doesn't really matter what convention we pick. For better rather than 
worse, D doesn't allow us to do as C++ does, make iterators 
interchangeable with pointers. We may as well pick anything we like as 
long as the compiler is able to make reasonable efficient code out of it.

As I said in the above referenced post, I have been toying with making a 
template iterator/array algorithm library. I've got a quite substantial 
proof of concept working, but have not had much time lately. I do love 
discussions about this though. :)

/Oskar



More information about the Digitalmars-d-announce mailing list