foreach syntax, std.mixin

Philippe Sigaud philippe.sigaud at gmail.com
Sun Nov 8 12:43:16 PST 2009


On Sun, Nov 8, 2009 at 21:14, dsimcha wrote:

> > function like in python. Which does something like
> > zip(iota(1,bar.length),bar).
>
> > I think the index variant would better be done as an enumerate()
> Enumerate is a great idea.  It's probably much better than requiring every
> range
> struct to mix something in to enable this behavior.  Thanks.
>
> FWIW, I coded enumerate and such for D2, and will post them on dsource as
soon as I can get my hands on svn. In a few days at most, I hope.

Personally, I then use a 'tuplify' template which takes a standard function
and transforms it into a tuple-accepting one:
so if I have:

int foo(int a, double b, string c) {...}
tuplify!foo is :
int tfoo(Tuple!(int, double, string) t) { /* extracts a,b & c from t, and
returns foo(a,b,c) */  }


so, as I can't unpack the tuple:

foreach(a,b,c ; zip(range1, range2, range3) {
      /* do something with foo on (a,b,c) */
}

I tuplify foo and do:

foreach (tup; zip(range1, range2, range3) {
   /* do something with tuplify!foo(tup) */
}
There is no real limit on the number of ranges that can be acted upon in
parallel that way, though I admit the syntax is a bit cumbersome.

I also use unzip!index( someZip) to get back the original range from inside
zip.



> I guess the same thing could be applied to unpack().  Instead of making the
> range
> implementer mixin something to enable this (he/she will probably forget and
> it
> could lead to ambiguities), do it on the caller end.
>
> Makes me wonder why noone thought of this until now, or maybe someone did
> and I
> forgot.  How's:
>
> foreach(fooElem, barElem; unpack(zip(foo, bar))) {}, or:
>
> foreach(i, elem; enumerate(chain(foo, bar))) {} ?
>
>
Can that be done for more than two ranges? The syntax is so nice, I'd be
deligthed to have that.


  Philippe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20091108/081533e3/attachment.html>


More information about the Digitalmars-d mailing list