Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

operator precedence in Haskell

Tags:

haskell

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
like image 707
גלעד ברקן Avatar asked Feb 26 '13 02:02

גלעד ברקן


People also ask

Is Haskell right or left associative?

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.

What is precedence of an operator in TCL?

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.

What is Haskell 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).

How precedence work?

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


2 Answers

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
like image 163
Pubby Avatar answered Sep 18 '22 06:09

Pubby


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.

like image 40
eazar001 Avatar answered Sep 21 '22 06:09

eazar001