liveBook · Manning

Operator precedence

As explained in Learn Haskell by Example

Operator precedence is the ranking that determines which operators bind and are evaluated before others in an expression.

Operator precedence ranks infix operators so an expression groups and evaluates in the intended order. Haskell combines precedence with associativity: operators at the same precedence group from the left, right, or not at all. section 7.2.3 section 11.3.3

Use fixity declarations to control custom operators:

  • `infixl`, `infixr`, and `infix` select left associativity, right associativity, or no associativity. section 11.3.3
  • The number following the keyword sets precedence from 0 through 9; higher-precedence operators bind more strongly. section 7.2.3 section 11.3.3
  • The dollar operator is declared `infixr 0 $`, so most other operators are grouped before the function application it introduces. section 7.2.3
  • Parentheses can always make the intended grouping explicit when an operator expression becomes confusing. section 7.2.3

Precedence changes the result

With `(++)` at precedence 5 and `($)` at precedence 0, `map (*10) $ [1..5] ++ [6..10]` groups as `map (*10) ([1..5] ++ [6..10])`. Without `$`, parentheses express the same intent explicitly: `map (*10) ([1..5] ++ [6..10])`. section 7.2.3

Precedence in a music DSL

A musical composition DSL gives note construction `(.|)` precedence 4, sequencing `(<~>)` precedence 3, and grouping `(<:>)` precedence 2: `infixr 4 .|`, `infixr 3 <~>`, `infixr 2 <:>`. Thus `c 4 .| wn <~> e 4 .| wn <:> g 4 .| wn` gives sequencing tighter binding than grouping. Repetition operators use precedence 1 so they wrap larger compositions. section 11.3.2 section 11.3.3

ghci> :i ($)
($) :: (a -> b) -> a -> b
infixr 0 $

Inspect an operator’s type, associativity, and precedence directly in GHCi with `:i ($)`. section 7.2.3

How Learn Haskell by Example covers it

How deep it goes
Explains precedence, associativity, fixity declarations, and grouping examples, stopping short of parser implementation internals.
Examples
Demonstrates `$`, `(++)`, musical sequencing, grouping, note construction, and repetition operators.
What you can do after
Build custom operators and readable DSL expressions by declaring their precedence and associativity.
How it connects
Connects operator precedence with associativity, fixity declarations, function application, parentheses, and embedded domain-specific languages.

Also explained in

Compare how 7 books explain operator precedence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.