Passing iterators into functions

Max Haughton maxhaton at gmail.com
Thu Jun 25 04:26:22 UTC 2020


On Thursday, 25 June 2020 at 03:35:00 UTC, repr-man wrote:
> I have the code:
>
> int[5] a = [0, 1, 2, 3, 4];
> int[5] b = [5, 6, 7, 8, 9];
> auto x = chain(a[], b[]).chunks(5);
> writeln(x);
>
> It produces a range of slices as is expected: [[0, 1, 2, 3, 4], 
> [5, 6, 7, 8, 9]]
>
> However, when I define a function as follows and pass in the 
> result of the chain iterator:
>
> auto func(R)(R r, size_t width)
> if(isRandomAccessRange!R)
> {
>     return r.chunks(width);
> }
>
> void main()
> {
>     int[5] a = [0, 1, 2, 3, 4];
>     int[5] b = [5, 6, 7, 8, 9];
>     auto x = func!(int[])(chain(a[], b[]), 5);
>     writeln(x);
> }
>
> It gives me an error along the lines of:
> Error: func!(int[]).func(int[] r, ulong width) is not callable 
> using argument types (Result, int)
>        cannot pass argument chain(a[], b[]) of type Result to 
> parameter int[] r
>
> I was hoping it would return the same result as the first 
> program.
>
> This seems to have to do with the fact that all iterators 
> return their own unique type.  Could someone help me understand 
> the reason behind this design and how to remedy my situation?

Chain returns a range not an int[]. You need to either convert 
the range to an array via .array or allow the compiler to infer 
the type of the parameter of func (You'll need to import 
std.range to have the range interface available)

mhh


More information about the Digitalmars-d-learn mailing list