What does $ mean/do in Haskell?

前端 未结 2 1492
甜味超标
甜味超标 2020-11-28 07:50

When you are writing slightly more complex functions I notice that $ is used a lot but I don\'t have a clue what it does?

2条回答
  •  余生分开走
    2020-11-28 08:42

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

    For example, the following expression:

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

    What happens if we don't put the $? Then we would get

    take 1 filter even [1..10]
    

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

    This is obviously incorrect. So what can we do instead? Well, we could put parenthesis around our expression:

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

    This would now reduce to:

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

    which then becomes:

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

    But we don't always want to be writing parenthesis, especially when functions start getting nested in each other. An alternative is to place the $ sign between where the pair of parenthesis would go, which in this case would be:

    take 1 $ filter even [1..10]

提交回复
热议问题