Assignment Expression Idea

Ben Hinkle Ben_member at pathlink.com
Thu Jun 8 21:12:40 PDT 2006


In article <e69bni$2jr$1 at digitaldaemon.com>, Wolfgang Draxinger says...
>
>Lastly I was writing a huge buck of Python code and then came
>back to D and unintentionally used a nice syntax sugar (getting
>a compile error), that's possible in a lot of cool languages,
>among them Python and Lua (maybe one of the next D versions?).
>
>Say you got a bunch of variables:
>
>int a1, a2;
>char b1, b2;
>float d1, d2;
>class T{...}; T t1, t2;
>
>Then in Python you can perfectly write
>
>a1, b1, c1, t1 = a2, b2, c2, t2;
>
>but also such fancy stuff like swapping
>
>a1, a2 = a2, a1;
>
>and if the types are compatible or there have been conversion
>operators been introduced
>
>d1, t1 = a1, b1;
>d2, t2 = a2, a2; // a2 get's assigned to both d2 and t2
>
>I don't think that this would introduce ambiguties. The semantics
>of the ','-operator could be changed, that the result is a tuple
>and that tuples get read and assigned right to left (making
>tuples a L value).

Changing the , operator to make tuples is a pretty big change. In particular it
would have to change precedence. In my Cx extensions I implemented multiple
return values using the syntax
[a,b,c] = foo();
where the brackets [] indicate the new behavior. The behavior of multiple return
functions is exactly like MATLAB (where is it very handy). If you're curious
about how it works in Cx surf around starting at
http://tinycx.sourceforge.net/multival.html, for example. If you do poke around
I'd appreciate any feedback you have.

> If for example one writes 
>
>a1, a2, d1 = b1, b2;
>
>This would evaluate
>
>d1 = b2;
>a2 = b1;
>a1 = nil;
>
>Well, nil is not defined this way in D and thus I'd let raise
>this a syntax error, but
>
>a1, a2 = b1, b2, b3;
>
>would be safe
>
>a2 = b3;
>a1 = b2;

This is backwards from how MATLAB (and Cx) does it. The assignment goes left to
right. If you return more values that destinations then unused values are
discarded (much like you can discard the return value of a regular one-output
function).
In terms of D I would expect that it would end up getting a library tuple
support much like C++ has planned. But we'll see.

>No assignment of b1, which is consistent with the old syntax.
>An implementation must take care, that in assignments like
>
>a1, a2 = a2, a1;
>
>temporary registers are used.
>
>-- 
>Wolfgang Draxinger
>

-Ben





More information about the Digitalmars-d mailing list