Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Haskell: Operator precedence, associativity rules

The value of an expression depends on the order of evaluation of operators, which is determined by the Precedence, and associativity of operators. By using associativity, we can specify whether an operator is evaluated from left to right or right to left.

*Main> 1 + 4 * 5
21

Since ‘*’ has higher precedence than ‘+ operator, then 1 + 4 * 5 = 1 + 20 = 21. If you want to evaluate ‘1+4’ first use parenthesis.

*Main> (1 + 4) * 5
25

Following table summarizes the operator precedence and Associativity Rules. Haskell maintains 10 precedence levels from 0 to 9 (inclusive). Level 9 represents high precedence and level 0 represents low precedence.

There are three kinds of associativity.
a.   Non-Associative (Represented by identifier infix)
b.   Left associative (Represented by identifier infixl)
c.    Right associative (Represented by identifier infixr)

Precedence Level
Left associative operators
Non-associative
Operators
Right associative operators
0


$, $!, ‘seq‘
1
>>, >>=


2


||
3


&&
4

==, /=, <, <=, >, >=,       
‘elem‘, ‘notElem

5


:, ++
6
+, -


7
, /, ‘div‘,   
‘mod‘, ‘rem‘, ‘quot‘        


8


^ , ^^ , ⋆⋆
9
!!

.


By using ‘:info’ command, you can get the precedence levels of operators.
*Main> :info +
class Num a where
(+) :: a -> a -> a
...
-- Defined in ‘GHC.Num’
infixl 6 +
*Main>
*Main> :info ++
(++) :: [a] -> [a] -> [a] -- Defined in ‘GHC.Base’
infixr 5 ++
*Main>
*Main> :info ==
class Eq a where
(==) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 ==

References
https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-820004.4.2




Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell: Operator precedence, associativity rules

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×