Course map
Haskell // 23

Functors and monads

Read

Functor

map works on lists. fmap works on anything that is a Functor: lists, Maybe, Either e, IO. It applies a function inside without changing the shape.

main :: IO ()
main = do
  print (fmap (+ 1) [1, 2, 3])       -- [2,3,4]
  print (fmap (+ 1) (Just 5))        -- Just 6
  print (fmap (+ 1) Nothing)         -- Nothing
  print ((+ 1) <$> Right 5 :: Either String Int)   -- Right 6

<$> is fmap as an operator. The point: code that uses fmap does not care whether the value is missing, failed or a list; the container handles that.

01 / 05