The Expressiveness of D

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Nov 2 08:00:12 PDT 2010


On 11/2/10 9:07 AM, Simen kjaeraas wrote:
> %u <user at web.news> wrote:
>
>> class A {}
>> class B : A {}
>> class C : A {}
>>
>> template T(A...) { alias A T; }
>>
>> void main() {
>> auto a = true ? new B : new C;
>> // these don't work - why?
>> // auto b = [new B, new C];
>> // auto c = { return [1: new B,2: new C]; };
>
> "The type of the first element is taken to be the type of all the
> elements, and all elements are implicitly converted to that type."
> (http://digitalmars.com/d/2.0/expression.html#ArrayLiteral)
>
> I believe it has been discussed numerous times before that the ?:
> test should be used to find the element type - not sure why it
> isn't.

Looks like outdated documentation to me.

>> T!(int,int) e = (1,2);
>> e = T!(3,4);
>>
>> // ah - so (1,2) syntax on initialization, T!(1,2) when assigning!
>> T!(int,int) d = T!(1,2);
>>
>> e = d;
>>
>> // tuples aren't first class, why?
>> // auto f = { return e; };
>> }
>
> Compile-time argument tuples are something of a strange beast. They
> behave not very unlike tuples, but due to their ability to hold
> types, literals, expressions and aliases to whatever, they are not
> a very good match for what you'd expect tuples to be. (e.g, what do
> you expect T!(3,T) to be?)
>
> For tuples, you should instead look into std.typecons' Tuple struct
> and tuple function:
>
> Tuple!( int, "n", string, "s" ) tup;
> tup.n = 4;
> tup.s = "A string! My kingdom for a string!";
>
> auto tup2 = tuple( 1, 2 );
> assert( is( typeof( tup2 ) == Tuple!( int, int ) ) );
>
>
> For even better support of tuples, you should have a look-see at
> Philippe Sigaud's dranges.tuple and dranges.reftuple
> (http://svn.dsource.org/projects/dranges/trunk/dranges/docs/tuple.html
> and
> http://svn.dsource.org/projects/dranges/trunk/dranges/docs/reftuple.html)
>
> The latter is absolutely awesome, and should be made part of
> phobos ASAP, IMO (though according to the documentation, it
> is not in tip-top shape).
>
> Examples from the reftuple page:
>
>
> int a, b;
> _(a,b) = tuple(b,a); // swap
> _(a,b) = tuple(b,a+b); // fibonacci
>
> int[] arr = [0,1,2,3,4];
> int [] c;
> _(a,b,c) = arr; // a = 0, b = 1, c = [2,3,4]

This was already contributed to in Phobos (under a different syntax) but 
I rejected it on grounds of safety: the value built by "_" must escape 
addresses of all of its arguments, so it's not safe.

My suggestion to address this issue was (and is) to make the assigned 
part of the function call:

int a, b;
scatter(tuple(b, a), a, b);
scatter(tuple(b, a + b), a, b);
int[] arr = [0, 1, 2, 3, 4];
int[] c;
scatter(arr, a, b, c);


Andrei


More information about the Digitalmars-d mailing list