🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Fmap over Maybe

Fmap over Maybe is the use of fmap to change the value inside a Maybe value. It changes a Just value and leaves Nothing unchanged.

fmap multiplies the value inside Just by ten

fmap applies times ten inside Just. The output shows 3 changed to 30.

main :: IO ()
main = print (fmap (*10) (Just 3))

fmap over Nothing gives Nothing

There is no value to change. The output shows Nothing unchanged.

main :: IO ()
main = print (fmap (+1) (Nothing :: Maybe Int))

fmap finds the length of the string inside Just

fmap length measures the held string. The output shows Just 5 for a five-letter string.

main :: IO ()
main = print (fmap length (Just "hello"))

Example

import Data.Char (toUpper)
main :: IO ()
main = do
  print (fmap (map toUpper) (Just "hi"))
  print (fmap (map toUpper) (Nothing :: Maybe String))

Key points

  • Maybe: a type that holds either a value in Just or nothing in Nothing.
  • fmap: a function that applies a function to the value inside Just.
  • Just: the case where fmap changes the held value.
  • Nothing: the case where fmap gives Nothing back unchanged.
  • Function: any function that fits the held type can be used with fmap.

In this example, fmap applies map toUpper to the value inside Maybe. The first line turns the string inside Just into capitals. The second line leaves Nothing unchanged.

Note

fmap over Maybe never turns Nothing into a Just value.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is fmap (+1) (Nothing :: Maybe Int)?