is there a common type?

Ali Çehreli acehreli at yahoo.com
Tue May 15 11:14:51 PDT 2012


On 05/15/2012 10:29 AM, Christian Köstlin wrote:
> for [1, 2, 3] and iota(2, 10)?
>
> thanks in advance
>
> christian

When it comes to compile-time polymorphism or duck typing, they are both 
RandomAccessRanges. (Pedantically, [1, 2, 3] is not a range (I think 
:P), but a container. Although, any slice of it is a RandomAccessRange.)

import std.range;
import std.stdio;

void foo(R)(R r)
     if (isRandomAccessRange!R)
{
     if (!r.empty) {
         writeln(r[0]);
     }
}

void main()
{
     foo([1, 2, 3]);
     foo(iota(2, 10));
}

When it comes to runtime polymorphism, they can be both 
RandomAccessFinite!int:

import std.range;
import std.stdio;

void foo(RandomAccessFinite!int r)
{
     if (!r.empty) {
         writeln(r[0]);
     }
}

void main()
{
     RandomAccessFinite!int r;

     r = inputRangeObject([1, 2, 3]);
     foo(r);

     r = inputRangeObject(iota(2, 10));
     foo(r);
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html


More information about the Digitalmars-d-learn mailing list