ahala
ahala

Reputation: 4803

infix operator precedence in Haskell

For the following Haskell expression

return a >>= f

Should it be read as

(return a) >>= f

or

return (a >>= f)?

what are the related rules here?

Upvotes: 2

Views: 665

Answers (1)

bheklilr
bheklilr

Reputation: 54078

The rule is always that function application has higher precedence than any operator, so

return a >>= f

Is parsed as

(return a) >>= f

no matter what functions or operators are being used instead of return, f, and >>=.


That means things like

divide :: Int -> Int -> Double
divide x y = (fromIntegral x) / (fromIntegral y)

Are equivalent to

divide :: Int -> Int -> Double
divide x y = fromIntegral x / fromIntegral y

Another example where this is even more useful is in function composition:

something :: [Int] -> [Int]
something xs = filter even . map (+1) . zipWith (*) [1..] . take 200 . cycle $ xs

As you can see here, we even have zipWith taking two arguments composed with several other functions. This is equivalent to having put parentheses around every component of the composition.

Upvotes: 12

Related Questions