Working with ranges: mismatched function return type inference

pineapple via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 11 06:06:37 PDT 2016


On Tuesday, 11 October 2016 at 07:55:36 UTC, orip wrote:
> I get "Error: mismatched function return type inference" errors 
> with choosing the return type for functions that work on ranges 
> using, e.g, std.algorithm or std.range functions, but have 
> different behavior based on runtime values. The return type is 
> always a range with the same underlying type.
>
> Here's an example:
>
> auto foo(int[] ints) {
>   import std.range;
>   if (ints.length > 10) {
>     return chain(ints[0..5], ints[8..$]);
>   } else {
>     //return ints; // Error: mismatched function return type 
> inference of int[] and Result
>     return chain(ints[0..0], ints[0..$]); // This workaround 
> compiles
>   }
> }
>
> Is there a compatible return type that can be used, or some 
> other workaround?
> I couldn't find one when searching for the error or looking at 
> the phobos source code.
>
> Thanks! orip

Rewrite `return chain(ints[0..5], ints[8..$]);` as `return 
ints[0..5] ~ ints[8..$];`

The `chain` function doesn't return an array, it returns a 
lazily-evaluated sequence of an entirely different type from 
`int[]`.


More information about the Digitalmars-d-learn mailing list