Working with ranges: mismatched function return type inference

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Oct 11 12:20:11 PDT 2016


On Tuesday, October 11, 2016 10:42:42 Ali Çehreli via Digitalmars-d-learn 
wrote:
> Those interfaces already exist in Phobos: :)
>
>    https://dlang.org/phobos/std_range_interfaces.html
>
> auto foo(int[] ints) {
>    import std.range;
>    if (ints.length > 10) {
>        return
> cast(RandomAccessFinite!int)inputRangeObject(chain(ints[0..5], ints[8..$]));
> } else {
>        return cast(RandomAccessFinite!int)inputRangeObject(ints);
>    }
> }
>
> void main() {
>      import std.stdio;
>      import std.range;
>      import std.algorithm;
>      writeln(foo([1, 2, 3]));
>      writeln(foo(iota(20).array));
> }

And in this case, if you were considering doing that, you might as well just
concatenate the dynamic arrays rather than chaining them, because using
interfaces means allocating on the heap just like you would with
concatenating.

About the only time that using interfaces is the right solution with ranges
is when you're dealing with virtual functions (which can't be templatized),
and even then, it's not necessarily the best choice. Here, IMHO, it makes no
sense at all.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list