foreach and retro
kenji hara
k.hara.pg at gmail.com
Mon Jul 2 09:57:16 PDT 2012
D does not provide index for the range iteration.
Instead, you can create 'zipped' range.
void main() {
auto intr = sequence!"n"(); // 0, 1, 2, ...
double[] a = [ 0, 1, 2, 3, 4, 5 ];
foreach(i, x; zip(intr, retro(a)))
writeln(i, "\t", x);
}
zip(intr, retro(a)) is a range of Tuple!(size_t, double), and foreach
automatically expand the tow fields of zip front into i and x like
follows.
foreach(__e; zip(intr, retro(a))) {
auto i = __elem[0], x = __elem[1]; // inserted by the compiler
writeln(i, "\t", x);
}
After all, you can get 'index' for range iteration.
Kenji Hara
2012/7/3 Joseph Rushton Wakeling <joseph.wakeling at webdrake.net>:
> On 02/07/12 17:48, Timon Gehr wrote:
>>
>> What would be your expected output?
>
>
> I'd expect to see
>
> 0 5
> 1 4
> 2 3
> 3 2
> 4 1
> 5 0
>
> i.e. as if I was foreach-ing over an array with the same values in inverted
> order.
More information about the Digitalmars-d
mailing list