🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Functor Class

The Functor class is a typeclass for types that can be mapped over. It gives one operation named fmap for changing the value held inside.

fmap changes the value inside Just

fmap applies plus one inside Just. The output shows 3 changed to 4.

main :: IO ()
main = print (fmap (+1) (Just 3))

fmap changes every element of a list

fmap applies plus one to each element. The output shows both elements changed.

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

fmap changes the Right value of Either

fmap applies plus one to the Right value. The output shows 5 changed to 6.

main :: IO ()
main = print (fmap (+1) (Right 5 :: Either String Int))

Example

main :: IO ()
main = do
  print (fmap (*2) [1,2,3])
  print (fmap (*2) (Just 5))
  print (fmap (*2) (Right 5 :: Either String Int))

Key points

  • Functor: a typeclass for types that can be mapped over.
  • fmap: a function that applies a function to the value held inside.
  • List: a Functor whose fmap changes every element.
  • Maybe: a Functor whose fmap changes the value in Just and leaves Nothing alone.
  • Either: a Functor whose fmap changes the Right value and leaves a Left value alone.
  • Operator: (<$>) is the operator form of fmap.

In this example, fmap doubles the value in each case. The first line doubles every element of a list. The second line doubles the value inside Just. The third line doubles the Right value.

Note

fmap changes the value inside and keeps the outer shape.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What is fmap (+1) (Just 3)?