Tuple literal syntax

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Oct 7 07:46:59 PDT 2010


On 10/7/10 5:39 CDT, retard wrote:
> Thu, 07 Oct 2010 03:20:23 -0500, Andrei Alexandrescu wrote:
>
>> Sorry for being Debbie Downer in this thread, but I'm not seeing a lot
>> of progress here. This is nothing but a syntax cutesy that helps
>> Tuple!(A, B) and tuple(a, b) and leaves all other issues related to
>> tuples unresolved (I'm actually afraid that it exacerbates them).
>>
>> One good thing about Tuple is that it allows names of fields, so
>> functions can return tuples with conveniently named fields, e.g.
>> Tuple!(bool, "found", size_t, "position") etc. without having to define
>> little structs everywhere and fostering simple, clear code on the caller
>> side.
>
> Why do tuple fields need a name?

They don't always need, but oftentimes names are better than numeric 
constants.

> Isn't this a new ad-hoc way to introduce
> structural typing in D?

Well what is the old ad-hoc way? Anyhow, tuples are a prime candidate 
for structural typing. Currently Tuple does not support it.

> I often start with tuples, but if it turns out
> that the value is used in many places, it will be eventually replaced
> with a struct (e.g. coordinates in a gui / gamedev) for better type
> safety.

I don't see

struct Coord
{
     int x, y, z;
}

one iota typesafer than

alias Tuple!(int, "x", int, "y", int, "z") Coord;

Clearly if you want to introduce protection, methods etc. then 
struct/class is the way to go. Tuples have their charter.

> Even with structs the need for field names is very rare.

I don't know how to define a struct without naming its fields in C, C++, 
C#, or D. If I could, I'd seldom want to use magic indexes instead of 
descriptive names.

> The real
> need for tuples is in very special cases where the syntax needs to be
> light.

auto r = fun(42);
writeln(r.foo, ": ", r.bar);

On the client side the syntax is very light. The definition of the 
function would need to specify the type name:

Tuple!(int, "foo", string, "bar") fun(int) {
     ...
}

I think much of the list of grievances against tuple limitations stems 
from a feeling that doing tuples without special syntax is "cheating". 
For my money, library tuples are eminently usable, and once we fix a 
couple of compiler bugs, they will be as good as (if not simpler, 
richer, and clearer than) a built-in facility. I do want to introduce 
syntax for expansion a la

auto (a, b) = foo(42);

because that's a common need that's not satisfiable via a library. But 
then I want to define the syntax in a general way so it works not only 
with tuples, but also with arrays and types that implement opIndex.


Andrei


More information about the Digitalmars-d mailing list