Ranges and indexes with foreach

bearophile bearophileHUGS at lycos.com
Mon Jan 23 16:50:07 PST 2012


kenji hara:

> Today, foreach can expand the front tuple automatically.
> 
> foreach (i, e; zip(sequence!"n", range))
> {
>     // i = 0, 1, 2, ...
>     // e = elements of range
> }
> 
> So extra unpacking syntax is not need.

Very good, I didn't know it. This works:

import std.stdio, std.range, std.algorithm;
void main() {
    auto range = [1, 2, 3, 4];
    foreach (i, e; zip(sequence!"n"(), range))
        writeln(i, " ", e);
}


So it's better to update the zip usage example in the docs:
http://www.dlang.org/phobos/std_range.html#zip

That currently is (plus newlines that don't get copied in copying&pasting from the site pages):
int[] a = [ 1, 2, 3 ]; string[] b = [ "a", "b", "c" ]; // prints 1:a 2:b 3:c foreach (e; zip(a, b)) { write(e[0], ':', e[1], ' '); }


But going against what Walter usually says, some shallow higher order functions are not useless in Phobos, so:
enumerate(range)
is quite better than this for programmers:
zip(sequence!"n"(), range)
(And maybe it's simpler for a D front-end to recognize the enumerate() and optimize it better).

Bye,
bearophile


More information about the Digitalmars-d mailing list