The future of foreach

Jascha Wetzel firstname at mainia.de
Sun Dec 23 07:52:02 PST 2007


Janice Caron wrote:
> Walter has stated many times that foreach is a good thing because it
> expresses the programmer's intent, and leaves the optimisation down to
> the compiler. (Should it use pointers? Should it use indeces? etc.)
...
> Thoughts?

Induction variable analysis and reduction in strength also work for
foreach ( i; arr1 )
   arr2 = arr1[i] + arr3[i]*arr4[i];
no need for special syntax.
Instead,
foreach ( i; arr1 ) ( j; arr3 ) ( k; arr4 )
   arr2 = arr1[i]+arr3[j]*arr4[k];
is ambiguous wrt. the loop condition, since i.g. arr1.length != 
arr3.length, etc.
"Recursing" into multidim. arrays is in fact nesting foreach loops. 
There is no generality gained. IVA and Loop Invariant Code Motion will 
behave equally well with manually nested foreach loops.
The syntactic effect can be achieved with opApply.

Generalizing iteration to any type providing opIndex, etc. won't work 
because the mere existence of these operators won't tell the compiler 
how to generate indices. That's what opApply is for.
It would work for continuous iterators (like .ptr() and .end()), but 
then again, that's what opApply is for.



More information about the Digitalmars-d mailing list