Skip to content
Functor — fmap and the (<$>) operator
step 1/5

Reading — step 1 of 5

Learn

~1 min readType Classes and Functors

Functor is the type class for things you can map a function over:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

The f is a type constructor (like Maybe, [], IO). fmap lifts a regular function to operate on values inside the container.

Standard instances:

fmap (+1) [1, 2, 3]            -- [2, 3, 4]
fmap (+1) (Just 5)             -- Just 6
fmap (+1) Nothing              -- Nothing
fmap (+1) (Right 5)            -- Right 6
fmap (+1) (Left "err")          -- Left "err"

The <$> operator is fmap infix — usually preferred:

(+1) <$> [1, 2, 3]              -- [2, 3, 4]
negate <$> Just 7               -- Just (-7)
length <$> getLine              -- IO Int — length of input line

Why this matters — every "context" you work with in Haskell is a Functor:

  • Maybe — "value or absence"
  • Either e — "value or typed error"
  • [] — "zero or more values"
  • IO — "value obtained from real-world effect"
  • Map k, Set (via Foldable, not directly Functor)

Once you grok Functor, the same code works on all of them. fmap show works on Just 5, [1,2,3], Right 7, anything.

Functor laws (every instance must satisfy):

  • fmap id = id
  • fmap (g . f) = fmap g . fmap f

These aren't enforced by the compiler — they're a contract the implementer must respect.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…