Why is there no range iteration with index by the language?

Seb seb at wilzba.ch
Wed Jun 10 00:53:30 UTC 2020


On Tuesday, 9 June 2020 at 23:53:16 UTC, Q. Schroll wrote:
> Is there any particular reason why std.range : enumerate is a 
> thing and
>
>     foreach (i, e; range) { ... }
>
> doesn't work from the get-go? I wouldn't have such an issue 
> with it if static foreach would work with enumerate just fine. 
> As far as I can tell,
>
>     foreach (e; range) { ... }
>
> is being lowered to
>
>     for (auto _range = range; !_range.empty; _range.popFront)
>     {
>         auto e = _range.front;
>         ...
>     }
>
> So why cant DMD rewrite
>
>     foreach (i, e; range) { ... }
>
> to
>
>     for (auto _range = range, index = size_t(0); !_range.empty; 
> _range.popFront, ++index)
>     {
>         size_t i = index;
>         auto e = _range.front;
>         ...
>     }
>
> Doesn't seem like a big deal, does it? I'm asking because I 
> suspect there's an odd reason I have no idea and I whish to be 
> educated.

It's a bit more complicated though as you need to avoid subtle 
breakage with ranges that return tuples that are auto-expanded 
like e.g. `foreach (k,v; myDict)`.
So IIRC the main reason why D's foreach magic isn't doing this is 
that it was argued that this problem is not significant enough to 
be worth fixing as there's enumerate and "there's bigger fish to 
fry".

Anyhow, I would be highly in favor of DMD doing this. It's one of 
those many things that I have on my list for D3 or a D fork.


More information about the Digitalmars-d-learn mailing list