Search⌘ K
AI Features

Operator Association and Precedence

Explore how operator associativity and precedence influence the evaluation of expressions in Haskell. Understand the built-in rules for predefined operators and how to use fixity declarations to control associativity and precedence when defining custom operators.

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 ...