What does $ mean / do mean in Haskell?

When you write somewhat more complex functions, I notice that $ used a lot, but I don’t know what it does?

+45
operators syntax haskell dollar-sign
Oct 22 '13 at 14:51
source share
2 answers

$ is an infix "application". It is defined as

 ($) :: (a -> b) -> (a -> b) f $ x = fx -- or ($) fx = fx -- or ($) = id 

It is useful to avoid extra parentheses: f (gx) == f $ gx .

A particularly useful place for it is the β€œback lambda body,” for example

 forM_ [1..10] $ \i -> do l <- readLine replicateM_ i $ print l 

compared with

 forM_ [1..10] (\i -> do l <- readLine replicateM_ i (print l) ) 

Or, oddly enough, it sometimes appears in sections when it says "apply this argument to any function"

 applyArg :: a -> (a -> b) -> b applyArg x = ($ x) >>> map ($ 10) [(+1), (+2), (+3)] [11, 12, 13] 
+57
Oct. 22 '13 at 14:56
source share

I like to think of the $ sign as a replacement for brackets.

For example, the following expression:

 take 1 $ filter even [1..10] -- = [2] 

What happens if we do not put $? Then it would turn out

 take 1 filter even [1..10] 

and the compiler will now complain because it would think that we are trying to apply 4 arguments to the take function with arguments 1 :: Int , filter :: (a -> Bool) -> [a] -> [a] , even :: Integral a => a -> Bool , [1..10] :: [Int] .

This is obviously not true. So what can we do instead? Well, we could put parentheses around our expression:

(take 1) (filter even [1..10])

This will not decrease to:

(take 1) ([2,4,6,8,10])

which then becomes:

take 1 [2,4,6,8,10]

But we do not always want to write brackets, especially since we begin to enter each other. An alternative is to place the $ sign between where the pair of brackets will go, which in this case will be:

take 1 $ filter even [1..10]

+7
May 14 '16 at 3:25 pm
source share



All Articles