Ranges and indexes with foreach

kenji hara k.hara.pg at gmail.com
Mon Jan 23 18:26:27 PST 2012


Ok, I understand.

The syntax is similar to my "multiple var declaration" proposal.
http://d.puremagic.com/issues/show_bug.cgi?id=6365
https://github.com/D-Programming-Language/dmd/pull/341

If the enhancement would be accepted, I'd like to implement your
proposal to increase consistency.

Kenji Hara

2012/1/24 bearophile <bearophileHUGS at lycos.com>:
> 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