Unexpected behaviour of foreach statement

bauss jj_1337 at live.dk
Fri Mar 2 10:34:31 UTC 2018


On Friday, 2 March 2018 at 10:21:39 UTC, Arredondo wrote:
> Hi,
>
> The following works as expected:
>
> auto range = [1, 2, 3, 4, 5];
> foreach (i, el; range) {
> 	writeln(i, ": ", el);
> }
>
> but this slight modification doesn't:
>
> auto range = iota(5);
> foreach (i, el; range) {
> 	writeln(i, ": ", el);
> }
>
> DMD 2.078.3 says:
> Error: cannot infer argument types, expected 1 argument, not 2
>
> The error message is not helpful either, because indicating the 
> types, as in:
>
> foreach (int i, int el; range) { ... }
>
> throws the same error.
> What's going on here?
>
> Arredondo

What you want to do is call "enumerate" from "std.range".

     auto range = iota(5).enumerate;

     foreach (i, el; range) {
         writeln(i, ": ", el);
     }

You can also call "array" from "std.array".

     auto range = iota(5).array;

     foreach (i, el; range) {
         writeln(i, ": ", el);
     }



More information about the Digitalmars-d-learn mailing list