foreach automoatic counter?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Sep 21 15:49:46 PDT 2015


On Monday, September 21, 2015 15:38:38 French Football via Digitalmars-d-learn wrote:
> Going through a book on coding in D,
> http://ddili.org/ders/d.en/foreach.html , I find the following
> very useful feature:
>
> When two names are specified in the names section [with a plain
> array], they represent an automatic counter and the value of the
> element, respectively:
>      foreach (i, element; array) {
>          writeln(i, ": ", element);
>      }
>
> I understand that foreach is built on top of a for loop... I'm
> just wondering why I can't access the automatic counter from a
> doubly linked list, or an associative array, or some range? It's
> pretty common for me to have to rewrite foreach loops to be for
> loops when I get to the bottom and realize I need to know where
> in the sequence I am...

It's an index, not a counter. In the case of an array, it's what's used to
access each element. In the case of an AA, it has no index. It's a set of
unordered key-value pairs. So, if you did

foreach(i, element; aa) {}

what you're really getting is the key and value, not an index and its
corresponding element.

foreach(key, value; aa) {}

would make more sense in that case, but it's merely a change in name. The
types and what they represent are the same regardless.

In the case of an input range, it doesn't have any kind of index. It's just
a list of elements that keep getting popped off in order to iterate through
them.  And whether any kind of index would even make sense would depend on
what the range represents. In the cases where it would make sense, the range
is probably a random-access range, in which case, you can use indices
explicitly if you want. In general though, if you want a counter for the
range that you're indexing, then you can use lockstep to wrap the range, and
then when you use it in foreach, you get the count and the element:

http://dlang.org/phobos/std_range.html#.lockstep

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list