Ranges and indexes with foreach
kenji hara
k.hara.pg at gmail.com
Mon Jan 23 16:40:41 PST 2012
2012/1/24 bearophile <bearophileHUGS at lycos.com>:
> Jonathan M Davis:
>
>> The lack of indexing for foreach and ranges is a bit of problem (not a huge
>> one but definitely an annoying one - it's one of the few reasons to still use
>> opApply instead of ranges). The obvious solution is to just have the compiler
>> provide a counter.
>> ...
>> Thoughts? Is there anything obvious (or non-obvious) that I'm missing here?
>
> Time ago I have proposed this, I think this is a tidier solution, that requires no compiler changes:
> http://d.puremagic.com/issues/show_bug.cgi?id=5550
>
> (and then the front-end is free to recognize the usage of this Phobos range enumerate(), and optimize it much better).
>
> Usage example (this also uses the tuple unpacking syntax):
>
> foreach ((i, e); enumerate(range)) {
> // code that uses i and e
> }
>
>
> Until the tuple unpacking syntax is not present you use:
>
> foreach (ie; enumerate(range)) {
> const i = ie[0];
> const e = ie[1];
> // code that uses i and e
> }
>
> Bye,
> bearophile
Today, foreach can expand the front tuple automatically.
foreach (i, e; zip(sequence!"n", range))
{
// i = 0, 1, 2, ...
// e = elements of range
}
So extra unpacking syntax is not need.
Kenji Hara
More information about the Digitalmars-d
mailing list