Working with ranges: mismatched function return type inference

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 11 11:09:26 PDT 2016


On 10/11/2016 09:55 AM, orip wrote:
> 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?

You've got some options:

1) OOP with std.range.interfaces. Ali already showed how this work. 
Comes at the cost of extra allocations and indirections.

2) std.range.choose wraps two different range types and uses forwards to 
one of them based on a condition. Should be cheap. But you need 
restructure your code a little:

----
auto foo(int[] ints) {
   import std.range: chain, choose;
   return choose(ints.length > 10,
     chain(ints[0..5], ints[8..$]),
     ints);
}
----

3) The workaround you already discovered: making a seemingly pointless 
call to `chain` to get the types to match. Possibly the most efficient 
solution. Looks a little odd.


More information about the Digitalmars-d-learn mailing list