Search code examples
haskelloperatorsdollar-signpartial-applicationoperator-sections

Haskell dollar operator application


I'm having trouble with understanding how function application works with currying in haskell. If I have following function:

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

I understand that to partially apply this function I need to provide (a -> b) function ($'s first argument).

Why then is it possible to apply a value first (i.e. reverse arguments)?

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

What am I missing here?


Solution

  • ($) is an operator. In Haskell, any operator can be written in a left-section (like (x $)) or a right-section (like ($ x)):

    (x $) = (\y -> x $ y) = ($) x
    ($ x) = (\y -> y $ x) = flip ($) x
    

    Note that the only exception to this rule is (-), in order to conveniently write negative numbers:

    \x -> (x-) :: Num a => a -> a -> a  -- equivalent to \x -> (-) x
    \x -> (-x) :: Num a => a -> a       -- equivalent to \x -> negate x
    

    In case you want to tersely write (\y -> y - x), you can use subtract:

    \x -> subtract x :: Num a => a -> a -> a  -- equivalent to \x -> flip (-) x