Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do different operators have different associativity?

I've got to the section on operators in The Ruby Programming Language, and it's made me think about operator associativity. This isn't a Ruby question by the way - it applies to all languages.

I know that operators have to associate one way or the other, and I can see why in some cases one way would be preferable to the other, but I'm struggling to see the bigger picture. Are there some criteria that language designers use to decide what should be left-to-right and what should be right-to-left? Are there some cases where it "just makes sense" for it to be one way over the others, and other cases where it's just an arbitrary decision? Or is there some grand design behind all of this?

like image 380
Skilldrick Avatar asked Dec 22 '22 22:12

Skilldrick


1 Answers

Typically it's so the syntax is "natural":

  • Consider x - y + z. You want that to be left-to-right, so that you get (x - y) + z rather than x - (y + z).
  • Consider a = b = c. You want that to be right-to-left, so that you get a = (b = c), rather than (a = b) = c.

I can't think of an example of where the choice appears to have been made "arbitrarily".

Disclaimer: I don't know Ruby, so my examples above are based on C syntax. But I'm sure the same principles apply in Ruby.

like image 151
Oliver Charlesworth Avatar answered Jan 05 '23 15:01

Oliver Charlesworth