Tuple assignment

Denis Koroskin 2korden at gmail.com
Thu Oct 7 00:28:57 PDT 2010


On Thu, 07 Oct 2010 10:43:18 +0400, Russel Winder <russel at russel.org.uk>  
wrote:

> On Wed, 2010-10-06 at 23:08 -0700, Walter Bright wrote:
>> If expr represents a tuple, we (Andrei and I) were thinking about the  
>> syntax:
>>
>>      auto (a, b, c, d) = expr;
>>
>> being equivalent to:
>>
>>      auto t = expr; auto a = t[0]; auto b = t[1]; auto c = t[2 .. $];
>>
>> You can also do this with arrays, such that:
>>
>>      float[3] xyz;
>>      auto (x, y, z) = xyz;
>>
>> The Lithpers among you will notice that this essentially provides a  
>> handy
>> car,cdr shortcut for tuples and arrays:
>>
>>      auto (car, cdr) = expr;
>
>
> Python may be the best base to compare things to as tuple assignment has
> been in there for years.
>
> Pythons choice is not a car/cdr approach but an exact match approach.
> so if t represents a tuple datum or a function returning a tuple:
>
>         x = t
>
> then x is a tuple -- remembering that variables are all just references
> to objects implemented via keys in a dictionary, and:
>
>         a , b , c = t
> or
>         ( a , b , c ) = t
>
> is tuple assignment where now t is required to be a tuple of length 3.
> cf.
>
>
>         |> python
>         Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
>         [GCC 4.4.3] on linux2
>         Type "help", "copyright", "credits" or "license" for more  
> information.
>         >>> t = ( 1 , 'fred' , 2.0 )
>         >>> x = t
>         >>> print x
>         (1, 'fred', 2.0)
>         >>> a , b , c = t
>         >>> print a , b , c
>         1 fred 2.0
>         >>> a , b = t
>         Traceback (most recent call last):
>           File "<stdin>", line 1, in <module>
>         ValueError: too many values to unpack
>         >>> a , b , c , d = t
>         Traceback (most recent call last):
>           File "<stdin>", line 1, in <module>
>         ValueError: need more than 3 values to unpack
>         >>>
>
>

That's because Python is not a strictly typed language. With proper type  
propagation compiler helps you writing code the way in meant to be. E.g.  
the following:

(a, b, c, d) = ('tuple', 'of', 'three')

could be statically disabled, but there is nothing wrong with allowing it  
either: d would be just a no-op, you will know it for sure the moment you  
try using it.


More information about the Digitalmars-d mailing list