Iterators for D

Walter Bright newshound at digitalmars.com
Tue Nov 7 23:20:03 PST 2006


Oskar Linde wrote:
> As Sean hints at, "random access iterators" are not pure iterators. The 
> random access part is orthogonal to the iterative part. In D, a perfect 
> way to implement a random access view is defining a .length property and 
> an opIndex method. A random access view doesn't need to be iterable and 
> an iterator doesn't need to provide random access. A D slice is the 
> perfect example of a random access view.

You two might be right.

> I see no reason to use operator overloading when the result isn't 
> replaceable with a pointer anyway.

Right.

> Bill Baxter's points regarding iterator as a concept vs an 
> interface/abstract class are very valid. And as Bill says, maybe both 
> should be supported. One of them could always be converted to the other.

Yes.

> Regarding efficiency, here is one sample implementation that a compiler 
> should(*) be able to make just as efficient as for/foreach loops:
> 
> struct Iterator(T) {
>     T* ptr;
>     T* end;
> 
>     bool step() { return ++ptr != end; }
>     T value() { return *ptr; }
>     T value(T x) { return *ptr = x; }
>     // mixin OpApplyMixin;
> }
> 
> Iterator!(T) iter(T)(T[] x) {
>     Iterator!(T) ret;// = {x.ptr-1, x.ptr+x.length}; // ICE
>     ret.ptr = x.ptr-1;
>     ret.end = x.ptr+x.length;
>     return ret;
> }
> 
> void main() {
>     int[] arr = [1,2,3,4,5];
> 
>     auto i = arr.iter();
> 
>     while(i.step) {
>         writefln("%s",i.value);
>         i.value = 5;
>     }
> }

It's good, but the pointer-before-the-start is problematic. This can 
cause problems on some architectures. Pointing past the end is 
explicitly supported, but before the beginning is not. I'd also prefer 
the step() get 'stuck' at the end, instead of going past it if it gets 
called again (this makes sense for input iterators). So I suggest instead:

	for (auto i = arr.iter(); !i.atEnd(); i.step())
		...

in other words, separate out the 'end' test from the 'step' operation.



More information about the Digitalmars-d mailing list