One way to look at foreach as not so bad

BCS BCS at pathlink.com
Fri Oct 20 10:15:07 PDT 2006


Bill Baxter wrote:

> Maybe I can get used to this version that works now:
>     obj.each( (int i) {
>       wrietfln(i);
>     })
> 
> But it just looks weird to have my loop body inside the parens, and will 
> look even weirder if nested
>     obj.each( (Obj c) {
>       c.each( (int i) {
>         writefln(i);
>       })
>     })
> 
> It sort of looks like nested loops, but I just can't get excited about 
> all those })'s screaming out "I'm a not a loop! I'm a function call!".

I'm not to happy about foreach_reverse (more neutral than anything) but 
I do see a major advantage of both foreaches over the form mentioned above:

outer: foreach(Obj c; &obj.each)
    foreach(int i; &c.each)
    {
       break outer;
       continue outer;
       break;
       continue;
       return;
    }

any of the lines in the inner loop quickly become an ugly hack when the 
user is writing the blocks as delegates.

> 
> All that's just about plain 'foreach'.  I still can't see a good 
> justification for foreach_reverse.  Reverse iteration just isn't common 
> enough to justify a special case like that.
> 

A templateized reverse iterator would be good enough for me.

int delegate(int delegate(T)) reverse(T)(T[]){...}

foreach(int i; reverse([1,2,3,4,5,6,7,8,9]))
{
}

> --bb



More information about the Digitalmars-d-announce mailing list