foreach, an analogy
Reiner Pope
reiner.pope at REMOVE.THIS.gmail.com
Thu Oct 19 15:14:25 PDT 2006
Walter Bright wrote:
> Bruno Medeiros wrote:
>> As of DMD now, the only advantage in 'foreach_reverse' is ephemerous:
>> it allows efficient reverse iteration of arrays.
>
> That's the most important use case.
>
>> But couldn't the compiler easily detect this:
>> foreach(Foo f; &fooarray.opApplyReverse) { ...
>> and and compile it as if it were a:
>> foreach_reverse(Foo f; fooarray) { ...
>
> Yes, it could. But it looks like a hack. A little syntactic sugar makes
> a big difference.
Here's a better solution: allow trailing delegates, and define iteration
according to them, making user iteration first-class. Then, mandate that
arrays support forwards and backwards iteration using, eg, 'each' and
'each_r' and the compiler can optimize such calls away:
[0,1,2].each (i) writefln(i); // Prints 0 1 2
[0,1,2].each_r (i) writefln(i); // Prints 2 1 0
void random(int[] array, void print(int i, out IterationStatus v), inout
IterationStatus s) { /* define my own random iterator */ }
[0,1,2].random (i) writefln(i); // Prints 0 2 1
You get the efficiency and an even nicer syntax.
Cheers,
Reiner
More information about the Digitalmars-d-announce
mailing list