Operator Association and Precedence

Learn about association and precedence behavior of operators.

We'll cover the following

Ambiguity in operator expressions

Expressions that contain several applications of infix operators without parentheses can carry some ambiguity regarding the evaluation of the expression.

The first source of ambiguity is association. It occurs in chained applications of the same operator. For example, the expression

16 / 4 / 4


could in principle be evaluated in two ways.

(16 / 4) / 4 = 1
16 / (4 / 4) = 16


The first bracketing corresponds to the / operator being left associative, while the second bracketing corresponds to / being right associative.

In this case, we want / to be left associative. But there are also operators (like the function arrow -> in type annotations), which should be right associative.

There are also operators which are non associative and cannot be chained. One example is the comparison operator ==. The expression 1 == 2 == 3 would be a type error in either way of bracketing, as the comparison of two numbers results in a Bool, which cannot be compared to the third number.

The second source of ambiguity is precedence. It occurs in unbracketed expressions involving multiple different operators. For example, the expression

3 + 5 * 7


allows the evaluation orders

(3 + 5) * 7
3 + (5 * 7)


In the first version, addition has higher precedence, while in the second version, multiplication has higher precedence (which is what we are used to).

Get hands-on with 1200+ tech skills courses.