Ranges and indexes with foreach
bearophile
bearophileHUGS at lycos.com
Mon Jan 23 15:54:26 PST 2012
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
More information about the Digitalmars-d
mailing list