More powerful foreach statements

pragma pragma_member at pathlink.com
Thu Jul 20 11:51:08 PDT 2006


In article <e9ogh7$b1b$1 at digitaldaemon.com>, kris says...
>
>Ben Phillips wrote:
>> While D's foreach is a much appreciated improvement over C++'s template version,
>> I feel there are still some ways in which it can be improved. I listed two ideas
>> below,
[snipped foreach proposal]
>
>
>Both can be done right now:
>
>1)  foreach (int i, Foo f; ManyFooInstance)
>              if (i is 0)
>                  ....
>
>Or somthing like that.

Agreed.  The only variation that is missing is for AA's:

foreach(key, value; myAA){
}

Being able to get at the current iteration would be nice, but its certainly
sugar.  The only way I can see this single case being covered, is with a third
foreach arg, like so:

foreach(uint i,key,value; myAA){
}

.. as this makes a rather nice, logical extension to things IMO.  But I'm not
holding my breath for its inclusion into D. ;)

A variation would be to use a specialized iterator:

uint i;
foreach(key,value; myAA.forward(&i){
//i is incremented for each call of opApply()
}

.. or to iterate over the keys and lookup on each pass:

foreach(i,key; myAA.keys){
auto value = myAA[key];
}

I don't have a clue if doing an explicit lookup for 'value' is less efficent
than letting the compiler figure it out what 'value' is via the foreach()
expression. ::shrug::

>
>
>2) foreach (int element; collection.reverse)
>	    ...
>
>where #2 returns a type which supports foreach. Typically, this would be 
>some kind of Iterator construct. 

Also agreed.  There are simply too many kinds of variants for iteration, that
anything outside the standard "storage order" (analagous to "database order" for
SQL) iteration we have now should be left up to the developer.  Granted, having
a set of typical iterators like "reverse" would be a nice to have, but that's
probably best left to a library.

>IIRC, someone already has a framework 
>for such things? Was it Oskar?

I remember seeing a heavily templated Array library posted here, that Andrew
made a while back, could that be it?  It was drafted well before implicit
templates were available, so maybe its worth reviewing again.

- EricAnderton at yahoo



More information about the Digitalmars-d mailing list