I am confused about the rules for operator precedence in Haskell.
More specifically, why is this:
*Main> 2 * 3 `mod` 2
0
different than this?
*Main> 2 * mod 3 2
2
The makers of Haskell wanted function composition to be logically as similar as the $ operation. One of the makers of Haskell was a Japanese who found it more intuitive to make function composition right associative instead of left associative.
Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
Haskell provides special syntax to support infix notation. An operator is a function that can be applied using infix syntax (Section 3.4), or partially applied using a section (Section 3.5).
Precedence means “priority of importance,” as in “Their request takes precedence because we received it first.” Precedent means “an earlier occurrence” or “something done or said that may serve as an example.” Its plural precedents is pronounced just like precedence, so always check if you mean “priority” or “example” ...
Function calls bind the tightest, and so
2 * mod 3 2
is the same as
2 * (mod 3 2)
Keep in mind that mod
is not being used as an operator here since there are no backticks.
Now, when mod
is used in infix form it has a precedence of 7, which (*)
also has. Since they have the same precendence, and are left-associative, they are simply parsed from left to right:
(2 * 3) `mod` 2
2*3 = 6 and then mod 2
= 3 with no remainder ... so 6 mod 2 = 0
is your answer there.
In your second case you are doing 2 * the result of mod 3 2
which is 2 * 1 = 2
. Therefore your answer is 2
.... Your operator precedence remains the same, you just arranged it so the answers were expressed accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With