Search code examples
haskellsyntaxdollar-sign

Is '$' a function in haskell?


I am quite confused about ($) in haskell.

when I type

:t ($)

in ghci. I will get

:($) :: (a -> b) -> a -> b

but, when I type

:t ($ 3)

I will get

($ 3) :: Num a => (a -> b) -> b

so, why ($) accept the second argument without any error?


Solution

  • Well ($) is an operator, which is an infix function. It's definition is pretty straightforward (in fact the only thing that makes it interesting is its fixity, and I'm sure google has tons of resources on that):

    ($) :: (a -> b) -> a -> b
    f $ x = f x
    

    Like all operators, you can take sections of it by applying only the first or only the second argument. This might be more obvious with the addition (+) operator:

    (+ 2) -- equivalent to \x -> x + 2
    (2 +) -- equivalent to \x -> 2 + x
    

    The same holds for ($ 3) - it is equivalent to \f -> f $ 3. The type of this function should be pretty clear then: its argument f has to be itself a function that takes a number and returns something else (f :: Num a => a -> b), and the whole function returns the same type as whatever f returns. That gives

    (\f -> f $ 3) :: Num a => (a -> b) -> b
    

    And consequently ($ 3) :: Num a => (a -> b) -> b.