foreach range with index
Luís Marques via Digitalmars-d
digitalmars-d at puremagic.com
Tue Jun 13 10:15:36 PDT 2017
In the documentation for foreach with range concepts (not x..y
ranges)
(<http://dlang.org/spec/statement.html#foreach-with-ranges>) I
did not find anything about foreach supporting iteration
indices/tuple unpacking for ranges, such as `foreach(i, elm;
range)`. It is "documented" in an example for std.range.enumerate
though [1].
I found a bug report asking for that to be documented [2] and one
saying that it should be removed [3].
One of the things that I like in D is the plasticity of the code.
In the situation that brought me to this issue, I started with a
plain slice which I iterated with foreach(i, foo; foos). Then
`foos` became a range, and the foreach became foreach(i, foo;
foos.enumerate); Thus, I didn't have to restructure my foreach
iteration, moving the index variable outside the foreach
statement, and manually incrementing the index, making this
change less disruptive.
Some thoughts about this:
- It doesn't strike me as very realistic to remove support for
foreach(i, e; range.enumerate) now, as probably a lot of people
are relying on this. I find it very useful, especially as
currently there doesn't seem to be a good alternative.
- The plasticity was not perfect in my example; ideally I
wouldn't have to change the foreach statement at all (i.e., add
.enumerate). Consider: my range had random access, why couldn't
foreach itself generate the index, as it does for slices, instead
of relying on .enumerate and tuple unpacking? Maybe it would even
make sense for input ranges, I'm not sure.
- Whatever changes you decide for tuple unpacking and foreach,
please try to keep in mind this plasticity concern. I'm trying
some techniques to make data-oriented designs more flexible, and
this feature seems like an important tool for the approach I'm
following/devising.
- Since foreach with ranges and unpacking (i.e., indices when
using .enumerate) seems here to stay for now, please document it.
The code I was writing was supporting material for an article.
But I'm afraid to advocate an approach which relies on behavior
which is undocumented and which people are arguing should be
removed. Not exactly confidence inspiring...
Thank you for your hard work.
Cheers,
Luís
[1] <http://dlang.org/phobos/std_range.html#enumerate>
[2] <https://issues.dlang.org/show_bug.cgi?id=7361>
[3] <https://issues.dlang.org/show_bug.cgi?id=9817>
More information about the Digitalmars-d
mailing list