Tuple basics

downs default_357-line at yahoo.de
Fri Sep 12 20:38:17 PDT 2008


downs wrote:
> downs wrote:
>> Sam Hu wrote:
>>> Hi downs,
>>>
>>>  A Tuple [...] is a sequence of any mix of types, expressions or symbols.
>>>
>>> So is it a class or a type or a variable or something else?The examples in the D Spec. is used inside a template,so is it just limited to use inside  the template or can use in a common function or anywhere else?
>>> Thanks,
>>> Sam
>> It's a tuple; i.e. neither of the above.
>>
>> And now you'll ask "What is a tuple?"
>>
>> And the answer is still, a sequence of types, expressions or symbols.
>>
>> :p
> 
> To pre-empt further questions; they appear in relation with templates because that's one of the most common ways to form type tuples:
> 
> template Tuple(T...) { alias T Tuple; }
> 
> In this case, most tuples formed this way will be type tuples, i.e. sequences of types.
> 
> For another example, the ".tupleof" expression of, say, a struct or a class evaluates to a tuple (sequence) of the values of the tuple's members.

Er, the struct's members.

> 
> The typeof([struct tuple]) is again a type tuple.
> 
> Look at it like this: a [X] tuple is a list, or sequence, of [X].
> 
> A type tuple is a list of types. A value tuple is a list of values.
> 
> Example (untested):
> 
> template Tuple(T...) { alias T Tuple; }
> 
> int add(int a, int b) { return a + b; }
> 
> struct Pair(T) { T a, b; }
> 
> void main() {
>   Pair!(int) p; p.a = 2; p.b = 2;
>   static assert(is(typeof(p.tupleof) == Tuple!(int, int)));
>   // and a value tuple is a list of values
>   assert(4 == add(p.tupleof)); // == assert(4 == add(/* just a list of values */ 2, 2))
> }

Something else to keep in mind:

A tuple has no "binding power" of its own.

Some people get confused when they compare LISP tuples and D tuples. It is important to keep in mind that a tuple is not a single expression.

For instance:

Tuple!(Tuple!(int, int), int)

is _EXACTLY_ the same thing as Tuple!(int, int, int)

I actually think this might be why the D specs use the term "sequence", and not "list". A list suggests a distinct element. A sequence is just some things following one another.


More information about the Digitalmars-d-learn mailing list