Haskell Composition & ($)
Two tiny operators appear in almost every Haskell file: . (function composition) and $ (function application). Neither adds new power; they exist to remove parentheses and to let you build pipelines out of small functions.
Function composition: .
In mathematics, (f ∘ g)(x) = f(g(x)). Haskell writes the ∘ as a dot:
(.) :: (b -> c) -> (a -> b) -> (a -> c)
(f . g) x = f (g x)f . g is a new function that first applies g, then applies f to the result. Read it from right to left:
import Data.Char (toUpper)
shout :: String -> String
shout = map toUpper . reverse
countWords :: String -> Int
countWords = length . words
main :: IO ()
main = do
putStrLn (shout "olleh")
print (countWords "composition glues small functions together")
print ((negate . abs) 7, (negate . abs) (-7))
print (map (show . (* 2)) [1, 2, 3])
print (filter (odd . length) ["a", "bb", "ccc"])HELLO
5
(-7,-7)
["2","4","6"]
["a","ccc"]
Composition is most useful for passing a combined function to map or filter, as in map (show . (* 2)), without writing a lambda.
A pipeline of transformations
Chaining several functions with . describes a data pipeline. This one normalises a list of tags:
import Data.Char (toLower, isSpace)
import Data.List (nub, sort)
trim :: String -> String
trim = dropWhileEnd' isSpace . dropWhile isSpace
where
dropWhileEnd' p = reverse . dropWhile p . reverse
normaliseTags :: [String] -> [String]
normaliseTags = sort . nub . filter (not . null) . map (map toLower . trim)
main :: IO ()
main = print (normaliseTags [" Haskell", "FP ", "haskell", "", " ", "Types", "fp"])["fp","haskell","types"]
Read normaliseTags from right to left: trim and lowercase each tag, drop the empty ones, remove duplicates (nub), sort. (Data.List already has dropWhileEnd; the local version shows how it can be built by composition.)
Application: $
$ is plain function application with the lowest precedence and right associativity:
($) :: (a -> b) -> a -> b
f $ x = f xThat sounds useless, but low precedence means "everything to the right of $ is evaluated first and becomes the argument". It replaces a pair of parentheses that would otherwise close at the end of the line:
main :: IO ()
main = do
print (sum (filter even (map (* 3) [1 .. 10])))
print $ sum $ filter even $ map (* 3) [1 .. 10]
print . sum . filter even . map (* 3) $ [1 .. 10]
putStrLn $ "Total: " ++ show (2 + 3)90
90
90
Total: 5
All three versions of the first computation are equivalent. The last one composes the pipeline with . and applies it to the data with $, a very common idiom.
| Write | Instead of |
|---|---|
f $ g $ h x |
f (g (h x)) |
f . g . h $ x |
f (g (h x)) |
putStrLn $ "a" ++ b |
putStrLn ("a" ++ b) |
$ as a function
Since $ is an ordinary operator, it can be partially applied. ($ 3) means "apply to 3", which lets you run a list of functions on one value:
main :: IO ()
main = do
let checks = [(> 0), even, (< 100)]
print (map ($ 42) checks)
print (map ($ 5) [(+ 1), (* 2), (^ 2)])
print (zipWith ($) [succ, pred, negate] [10, 20, 30])[True,True,True]
[6,10,25]
[11,19,-30]
&: left-to-right application
If you prefer pipelines that read left to right, like Unix pipes or F#'s |>, Data.Function exports &, which is $ with the arguments flipped:
import Data.Function ((&))
import Data.Char (isAlpha, toUpper)
main :: IO ()
main = do
let result =
" ship it, then measure! "
& filter isAlpha
& map toUpper
& take 8
putStrLn result
print ([1 .. 10] & filter odd & map (* 10) & sum)SHIPITTH
250
Both styles are idiomatic. Choose one per codebase and stay consistent.
Common mistakes
main :: IO ()
main = print . length "hello"<source>:2:8: error: [GHC-83865]
* Couldn't match expected type: IO ()
with actual type: a0 -> IO ()
* Probable cause: `(.)' is applied to too few arguments
In the expression: print . length "hello"
In an equation for `main': main = print . length "hello"
|
2 | main = print . length "hello"
| ^^^^^^^^^^^^^^^^^^^^^^
<source>:2:16: error: [GHC-83865]
* Couldn't match expected type `a0 -> b0' with actual type `Int'
* Possible cause: `length' is applied to too many arguments
In the second argument of `(.)', namely `length "hello"'
In the expression: print . length "hello"
In an equation for `main': main = print . length "hello"
|
2 | main = print . length "hello"
| ^^^^^^^^^^^^^^
GHC reports two errors for one mistake. Function application binds tighter than ., so this composes print with the number length "hello", which is not a function (the second error), and the result of the composition would be a function instead of an IO () (the first). Fix it with print . length $ "hello" or print (length "hello"). In general: use . between functions and $ before the final argument.
Test yourself
What does (show . (+ 1)) 4 evaluate to?
5"5""41"- A type error
Which expression equals f (g (h x))?
f . g . h xf $ g $ h xf g h x(f $ g) . h x
What is map ($ 2) [(* 10), (+ 1)]?
[20,3][12,3][2,2]- A type error