Tuple assignment

Russel Winder russel at russel.org.uk
Wed Oct 6 23:43:18 PDT 2010


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
        >>> 


-- 
Russel.
=============================================================================
Dr Russel Winder      t: +44 20 7585 2200   voip: sip:russel.winder at ekiga.net
41 Buckmaster Road    m: +44 7770 465 077   xmpp: russel at russel.org.uk
London SW11 1EN, UK   w: www.russel.org.uk  skype: russel_winder
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: This is a digitally signed message part
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20101007/566d172f/attachment.pgp>


More information about the Digitalmars-d mailing list