Search code examples
haskellsyntaxoperator-keyworddollar-sign

Dollar sign inside closed parens


Websocket snippet has a statement that has dollar sign inside closed parens like this,

any ($ fst client)

Since haskellers use $ sign instead of parens, why do we need parens here?

Why is there a $ symbol between parens?

I tried to see if $ is a function by doing

Prelude>:t $

But it threw the error, parse error on input $


Solution

  • In Haskell, operators are just normal functions that have names made up of symbols and used infix by default. You can use them just like a normal identifier by wrapping them in parentheses:

    λ> :t (+)
    (+) :: Num a => a -> a -> a
    

    $ is just an operator like this itself. It represents function application and is defined as follows:

    f $ x = f x
    

    You can get its type just like (+):

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

    Haskell operators can also be partially applied like normal functions, by wrapping them in parentheses with arguments to one side. For example, (+ 1) is the same as \ x -> x + 1 and (1 +) is the same as \x -> 1 + x.

    This applies to $ too, so ($ fst client) is the same as \ f -> f $ fst client or just \ f -> f (fst client). The code snippet you have checks if any of a list of functions returns true given fst client.