Empowering foreach with multiple aggregates

Daniel Keep daniel.keep.lists at gmail.com
Sun Sep 9 02:53:59 PDT 2007



Janice Caron wrote:
> [snip]
> 
>  void tweak(int[] dst, int[] src)
>  {
>      foreach (d; dst; s; src)
>      {
>          d = s + 1;
>      }
>  }

I believe Walter and Andrei have talked about this before.  The syntax
they proposed at the time was something like:

foreach(ref d ; dst)(s ; src)
{
    d = s + 1
}

I think the main problem with doing this is related to how foreach is
actually implemented.  If we assume that dst and src are actually user
types, then this loop:

foreach(ref T d ; dst)
  d = 1;

Becomes:

dst.opApply((ref T d) {
  d = 1;
  return 0;
});

This is a problem if you want to do iteration over multiple aggregates;
you'd essentially need to call two functions simultaneously, then have
those call into a third function passing half of the arguments each.

Adding this to D would probably require completely rethinking how custom
aggregates are created, which isn't necessarily a bad thing, but
certainly a difficult thing.

	-- Daniel



More information about the Digitalmars-d mailing list