Search code examples
haskelloperator-precedence

Weird behavior for infix functions regarding precedence


I am using the bool :: a -> a -> Bool -> a function. I wanted to use the infix version, because I though it more readable, but I noticed that:

(-1) `bool` 1 True

is an error

(-1) `bool` 1 $ True

works. Even

(-1) `bool` 1 (True)

doesn't work, which I thought was an equal alternative until now (i.e. using $ versus wrapping in parentheses from this location till the end)

How can this even make a difference? In the first version there is only one single operation.


Solution

  • Infix operators bind loosely, applications bind tightly.

    (-1) `bool` 1 True
    -- means
    (-1) `bool` (1 True)
    
    
    (-1) `bool` 1 $ True
    -- means
    ((-1) `bool` 1) $ True
    
    
    (-1) `bool` 1 (True)
    -- means
    (-1) `bool` (1 (True))
    

    You might want:

    ((-1) `bool` 1) True