Iterators for D

Dave Dave_member at pathlink.com
Sun Nov 12 21:30:04 PST 2006


Walter Bright wrote:
>>
>> 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.

For arrays, we already have arr.ptr, what if array.end was simply added?

auto slice = array[50..100];
for(auto i = slice.ptr; i != slice.end; i++) { ... }

Then for UDT custom iterators, ptr, end and op[Pre|Post][Inc|Dec] could be overloaded?

Just a thought..



More information about the Digitalmars-d mailing list