Less typed ranges

Ali Çehreli acehreli at yahoo.com
Sat Feb 4 08:09:27 PST 2012


On 02/04/2012 07:49 AM, bearophile wrote:
 > You can't write this:

Because the => syntax is not in dmd 2.057 yet! :p j/k

 > import std.algorithm;
 > void main() {
 >      int[] a1 = [1, 2, 3];
 >      auto r1 = map!(x =>  2 * x)(a1);
 >      auto r2 = map!(x =>  x ^^ 2)(a1);
 >      auto a2 = [r1, r2];
 > }
 >
 >
 > because the types of r1 and r2 aren't compatibile:
 > test.d(6): Error: incompatible types for ((r1) ? (r2)): 'Result' and 
'Result'

That used to include the template parameter of Range as well. The 
message used to make more sense. (But actually the delegates would make 
it very complicated.)

 > So is it good to have something like this in Phobos that uses some 
type erasure?
 >
 >
 > import std.algorithm, std.range;
 > void main() {
 >      int[] a1 = [1, 2, 3];
 >      ForwardRange!int r1 = forwardRange(map!(x =>  2 * x)(a1));
 >      ForwardRange!int r2 = forwardRange(map!(x =>  x ^^ 2)(a1));
 >      ForwardRange!int[] a2 = [r1, r2];
 > }
 >
 > Bye,
 > bearophile

It already exists: inputRangeObject() supports the "accessing ranges" 
and outputRangeObject takes care of output ranges.

I will use the string delegate format:

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);
}

inputRangeObject() uses coditional compilation to return a ForwardRange 
if its parameter is a ForwardRange. Because inputRangeObject() now 
changes the game into runtime polymorphism, we must spell out what 
interface we want to use. That's why we can't leave the left hand side 
to type inference, as it picks Object.

Ali



More information about the Digitalmars-d-learn mailing list