CS2112: Exercises + Answers from $2 Expressions 1: Operators

* List the operators of any other programming language that you know and write down their number of operands, precedence, associativity etc. If you don't know another language well enough, go into the library and pick any book describing a language. How easy is it to find this information in the book?

It is usually a lot harder to find this information than it should be. I managed fairly easily for C (although it wasn't trivial), but I had a lot of trouble for SML, and I suspect I still have not got it right.

Take pity on your users if you ever design a computer language, and make sure this sort of information is easy to locate. It may be best to put it into an appendix. I rather like the layout of the original definition of Pascal; the first half was a tutorial introduction to the language, the last half a stricter but (nearly) complete definition.

* Does it make sense to have two operators of the same precedence but different associativity? What happens when you use them in the same expression?

It doesn't make sense. X-associativity means that, a series of operators of the same precedence are evaluated from the X (where X can be left, right or not at all).

e.g. using two imaginary operators "#" and "$" of equal precedence, if "#" is left associative and "$" is right associative,
then: "a # b # c" means "(a # b) # c"
and: "a $ b $ c" means "a $ (b $ c)"
so: "a # b $ c" means both "(a # b) $ c" and "a # (b $ c)"
which is ridiculous. (Similar contradictions happen with non-associative operators.) This can only make sense if any one expression cannot contain both "#" and "$" operators, but in that case they don't need to have the same precedence anyway.

Many parser-generators, like Yacc, can be explicitly told the precedence and associativity of operators, but the method used cannot give different associativities to operators of equal precedence.
(see $5.4 of the lecture notes)