🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Fmap over Lists

Fmap over lists is the use of fmap to change every element of a list. The result is a new list with the same length and the same order.

fmap adds ten to every element

fmap applies plus ten to each element. The output shows 1, 2, and 3 changed to 11, 12, and 13.

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

fmap finds the length of every string

fmap length finds the length of each string. The output shows lengths 1, 2, and 3.

main :: IO ()
main = print (fmap length ["a","bb","ccc"])

fmap over an empty list gives an empty list

There is no element to change. The output shows an empty list.

main :: IO ()
main = print (fmap (+1) ([] :: [Int]))

Example

main :: IO ()
main = do
  print (fmap (*2) [3,5,7])
  print (length (fmap (*2) [3,5,7]))

Key points

  • fmap: a function that applies a function to every element of a list.
  • Result: a new list with the same length as the original list.
  • Order: the result keeps the original order of elements.
  • Function: any function that fits the element type can be used with fmap.
  • Empty list: fmap over an empty list gives an empty list.

In this example, fmap doubles every element of the list. The first line shows the doubled list. The second line shows that the doubled list still has length 3.

Note

fmap over a list never adds or removes elements.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

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