Ranges and indexes with foreach

bearophile bearophileHUGS at lycos.com
Mon Jan 23 18:04:37 PST 2012


kenji hara:

> std.range.zip makes a range of std.typecons.Tuple, not std.typetuple.TypeTuple.
> Then foreach statement supports the std.typecons.Tuple unpacking of range.front.

Ah, right.


> Therefore, follows would work.
> 
>     auto ap = [P(1,2), P(3,4), P(5,6)];
>     foreach (x, y; ap)  //
>         writeln(x, " ", y);

This program:

import std.stdio, std.range, std.algorithm, std.typecons;
alias Tuple!(int,int) P;
void main() {
    auto ap = [P(1,2), P(3,4), P(5,6)];
    foreach (x, y; ap)
        writeln(x, " ", y);
}

To me outputs:

0 Tuple!(int,int)(1, 2)
1 Tuple!(int,int)(3, 4)
2 Tuple!(int,int)(5, 6)

Instead of:

1 2
3 4
5 6

If you have an array, foreach puts the index of the items at the first variable.

To tell apart tuple unpacking from normal array indexing I have suggested a syntax like:
foreach ((x, y); ap)
If you fear programmers will miss the (), then requiring something like an auto solves the problem:
foreach (auto (x, y); ap)

Bye,
bearophile


More information about the Digitalmars-d mailing list