assignment: left-to-right or right-to-left evaluation?
Derek Parnell
derek at psych.ward
Sat May 9 16:15:59 PDT 2009
On Sat, 09 May 2009 11:43:09 -0500, Andrei Alexandrescu wrote:
> Consider:
>
> uint fun();
> int gun();
> ...
> int[] a = new int[5];
> a[fun] = gun;
>
> Which should be evaluated first, fun() or gun()? It's a rather arbitrary
> decision. C/C++ don't even define an order. Python chooses
> left-to-right, EXCEPT for assignment, which is right-hand side first.
> Lisp and C# choose consistent left-to-right. I don't like exceptions and
> I'd like everything to be left-to-right. However, this leads to some odd
> cases. Consider this example in TDPL:
>
> import std.stdio, std.string;
>
> void main() {
> uint[string] dic;
> foreach (line; stdin.byLine) {
> string[] words = split(strip(line));
> foreach (word; words) {
> if (word in dic) continue; // nothing to do
> uint newID = dic.length;
> dic[word] = newID;
> writeln(newID, '\t', word);
> }
> }
> }
>
> If we want to get rid of newID, we'd write:
>
> writeln(dic.length, '\t', word);
> dic[word] = dic.length;
>
> by the Python rule, and
>
> writeln(dic.length, '\t', word);
> dic[word] = dic.length - 1;
>
> by the C# rule.
>
> What's best?
I'm sure about 'best', but I'd prefer the Python method.
The example is similar to ...
array = array ~ array.length;
in as much as the result of the assignment is that the array length
changes, but here it more easy to see that the pre-assignment length is
being used by the RHS.
In COBOL-like syntax ...
move dic.length to dic[word].
it is also more obvious what the coder's intentions were.
In assembler-like syntax (which is what eventually gets run, of course) ...
mov regA, dic.length
mov dic[word], regA
It just seems counter-intuitive that the target expression's side-effects
should influence the source expression.
--
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell
More information about the Digitalmars-d
mailing list