Iterators for D

Benji Smith dlanguage at benjismith.net
Tue Nov 7 12:20:15 PST 2006


Sean Kelly wrote:
> Since D has slicing, the argument for using iterators to define the 
> boundaries of a range of randomly accessible elements seems kind of 
> small to me.  ie.
>
>     sort( a.begin, a.begin + 5 ); // sort the first 5 elements
> or
>     sort( a[0 .. 5] );
>
> I find the second to be cleaner to look at.  But I'm undecided whether 
> we'd lose any power or flexibility by not bothering with random access 
> iterators.

I agree completely. As someone with a background in Java, C#, and Python 
(among others), but without significant C++ experience, my concept of an 
iterator is: "an object with methods for getting the current element, 
determining whether a 'next' element exists, and for advancing the 
cursor to the next element".

The C++ iterators look very weird (and very very wrong) to me.

Search and sort routines should use opIndex, opIndexAssign, and opSlice. 
If an object doesn't implement opIndex or opIndexAssign, it's not 
sortable using generic sorting algorithms. Tough luck.

Iteration, though, is completely distinct from sorting and searching, 
and should use a different mechanism.

Walter Bright wrote:
 > Hmm, instead of 'pointers as iterators', have 'arrays as iterators'.
 > That definitely sounds like a good area to explore.

Perhaps an iterator always steps through an array (or an object 
implementing a List or Iterable interface), and in order for an object 
to be foreach-able, you'll need to first transform an object into an 
array (or construct a List or an Iterable wrapping the object).

Arrays could still get their own special-case implementation of foreach, 
avoiding interfaces for maximum speed. And, if a class supports opIndex, 
then you could avoid making a virtual method call through the Iterable 
interface.

But I think it's also desirable, in many many cases, to implement an 
Iterator class, without supporting opIndex. The only methods in the 
iterator would be hasNext() and next().

Foreach should support real arrays, classes with opIndex, and Java-style 
iterators. Searching and sorting should only use opIndex, opIndex, 
opCmp, and opEquals. Iterators should only be used for iteration.

Anyhoo, those are my two cents.

--Benji Smith



More information about the Digitalmars-d mailing list