Empowering foreach with multiple aggregates

Janice Caron caron800 at googlemail.com
Sun Sep 9 02:11:09 PDT 2007


There are some things that iterators can do that foreach can't. I
/don't/ want to add iterators to D. Instead, I'd like to see foreach
enhanced, so that it can do the things it currently can't.

Here's my first example.

 void tweak(int[] dst, int[] src)
 {
     assert(dst.length == src.length);
     for (int i=0; i<dst.length; ++i)
     {
         dst[i] = src[i] + 1;
     }
 }

How much nicer it would be to be able to say

 void tweak(int[] dst, int[] src)
 {
     foreach (d; dst; s; src)
     {
         d = s + 1;
     }
 }

The ability to walk through two collections simultaneously is such a
common thing to want to do that I'm suprised there's no language
support for it. Of course, it needs some extra code if dst.length and
src.length are /not/ equal, but that would also be true of the
iterator way. Using the foreach way, you'd end up with something like:

 void tweak(int[] dst, int[] src)
 {
     int len = dst.length < src.length ? dst.length : src.length;
     foreach (d; dst[0..len]; s; src[0..len])
     {
         d = s + 1;
     }
     if (dst.length > src.length) foreach(d; dst[len..$])
     {
         d = 1;
     }
 }

There might be some array operations planned that will do something
similar, but the point is that not all collections are arrays. You
might want to iterate through any arbitrary collections, and that's
where iterators show their strength. Why not let foreach have that
additional strength?



More information about the Digitalmars-d mailing list