www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Less typed ranges

reply bearophile <bearophileHUGS lycos.com> writes:
You can't write this:


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'


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
Feb 04 2012
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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 

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 

 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
Feb 04 2012
parent bearophile <bearophileHUGS lycos.com> writes:
Ali:

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

Thank you, I did miss them :-) Bye, bearophile
Feb 04 2012