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

Ali Çehreli acehreli at yahoo.com
Sun Jul 29 08:54:13 PDT 2012


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



More information about the Digitalmars-d-learn mailing list