🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Fmap Composition

Fmap composition is the use of fmap with a composed function. It lets one fmap do the work of two fmaps in a row.

One fmap doubles and then adds one

The composed function doubles first and then adds one. The output shows 1, 2, and 3 changed to 3, 5, and 7.

main :: IO ()
main = print (fmap ((+1) . (*2)) [1,2,3])

Two fmaps in a row give the same result

The first fmap doubles and the second fmap adds one. The output matches the single composed fmap.

main :: IO ()
main = print (fmap (+1) (fmap (*2) [1,2,3]))

A composed fmap can change a value into a string

The composed function adds one and then shows the result. The output shows Just with the string 5.

main :: IO ()
main = print (fmap (show . (+1)) (Just 4))

Example

main :: IO ()
main = do
  print (fmap ((*10) . (+1)) [1,2,3])
  print (fmap (*10) (fmap (+1) [1,2,3]))

Key points

  • Composition: the (.) operator joins two functions into one function.
  • Composed function: a single function that runs the right function first and then the left function.
  • Single fmap: fmap with a composed function applies both steps at once.
  • Two fmaps: applying fmap twice in a row gives the same result as one fmap with the composed function.
  • Order: the rightmost function in a composition runs first.

In this example, the same two steps are done in two ways. The first line uses one fmap with a composed function. The second line uses two fmaps in a row. Both lines print the same list.

Note

composition keeps the code shorter without changing the result.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is fmap ((+1) . (*2)) [1,2]?