Differing levels of type-inference: Can D do this?

Chad J chadjoan at __spam.is.bad__gmail.com
Sun Jul 29 10:22:10 PDT 2012


On 07/29/2012 11:54 AM, Ali Çehreli wrote:
> On 07/28/2012 01:47 PM, Chad J wrote:
>
>  > What I want to do is constrain that the type of r3 is some kind of
>  > range. I don't care what kind of range, it could be a range of integers,
>  > a range of floats, an input range, a forward range, and so on. I don't
>  > care which, but it has to be a range.
>
> It does exist in Phobos as inputRangeObject() (and ouputRangeObject).
> Although the name sounds limiting, inputRangeObject() can present any
> non-output range as a dynamically-typed range object.
>
> This example demonstrates how the programmer wanted an array of
> ForwardRange!int objects and inputRangeObject supported the need:
>
> import std.algorithm;
> import std.range;
> import std.stdio;
>
> void main() {
> int[] a1 = [1, 2, 3];
>
> ForwardRange!int r1 = inputRangeObject(map!"2 * a"(a1));
> ForwardRange!int r2 = inputRangeObject(map!"a ^^ 2"(a1));
>
> auto a2 = [r1, r2];
>
> writeln(a2);
> }
>
> That works because inputRangeObject uses 'static if' internally to
> determine what functionality the input range has.
>
> Note that r1 and r2 are based on two different original range types as
> the string delegate that the map() template takes makes the return type
> unique.
>
> The example can be changed like this to add any other ForwardRange!int
> to the existing ranges collection:
>
> auto a2 = [r1, r2];
> a2 ~= inputRangeObject([10, 20]);
> writeln(a2);
>
> Ali
>

IIRC, these are classes that come with all the typical runtime overhead, 
right?

I intend to try and keep the awesome mix of potentially optimal code 
that's also completely generalized.  Introducing hard-to-inline vtable 
calls into the mix would run against that goal.

If not for that, it would be close to what I'm looking for, minus the 
extraneous function call tacked onto every expression (which also makes 
it less discoverable).


More information about the Digitalmars-d-learn mailing list