Algorithms and slices

Ali Çehreli acehreli at yahoo.com
Fri Aug 26 13:05:18 PDT 2011


On Fri, 26 Aug 2011 20:24:43 +0200, Mafi wrote:

> The algorithms in std.algorithm are great. They operate the same on
> arrays/slices and generic ranges. But they return their own range-types.
> Often this ok but sometimes you need a T[].

I have a feeling that std.range.inputRangeObject() will be helpful here. 
It provides a polymorphic interface to different types of ranges.

It returns an InputRangeObject(R), but don't let its name give the wrong 
impression: it can be used as any non-OutputRange :), as long as the 
range R supports that interface.

Say, the element type is int and the range is a ForwardRange. Then you 
can have

    ForwardRange!int r = inputRangeObject(my_range_returning_algo());

Or, when you don't need the ForwardRange functionality, you can specify 
another type on the left hand side:

    InputRange!int r = inputRangeObject(my_range_returning_algo());

(You must specify the type explicitly.)

Then you can have arrays of interfaces to these actually unrelated ranges:

    InputRange!int[] my_input_ranges;
    my_input_ranges ~= inputRangeObject(foo_algo());
    my_input_ranges ~= inputRangeObject(bar_algo());

(Not tested. Type casting may be needed on the right hand sides as well.)

Ali


More information about the Digitalmars-d mailing list