Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 57 ยท Functors, applicatives and monads

Functors

Understand the Haskell Functor class: how fmap and <$> apply a function inside Maybe, lists and functions, and which laws every instance must obey.

You already know map: it applies a function to every element of a list. But lists are not the only things that hold values. A Maybe Int holds zero or one Int. An Either String Int holds either an error or an Int. A function r -> Int "holds" an Int that appears once you supply an r. Wouldn't it be nice to say "apply this function to whatever is inside" for all of them with one name?

That name is fmap, and the class that provides it is Functor. This lesson opens the chapter that leads to monads. Take it slowly: functors are the simplest of the three ideas, and the other two build directly on them.

Real Haskell is not installed on this site, so the Haskell blocks are read-only. The runnable examples use JavaScript stand-ins and say what is real and what is imitation.

The Functor class

Here is the class, as it appears in the standard library (slightly simplified):

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

Notice that f is not a type like Int. It is a type constructor: something that takes a type and gives a type, like Maybe, [] or Either String. In f a, the f is the container and a is what it holds. fmap turns a plain function a -> b into a function that works inside the container, f a -> f b, while leaving the container's shape alone.

One idea, many containers

List Apply to every element.
Maybe Apply if a value is there.
Either Apply to a Right, skip a Left.
Function Apply after the function runs.

The shape stays the same; only the contents change.

1 / 2

Instances you already use

For lists, fmap is map:

HASKELL
fmap (+ 1) [1, 2, 3]          -- [2,3,4]

For Maybe, the function is applied only when there is a value:

HASKELL
fmap (* 2) (Just 21)          -- Just 42
fmap (* 2) Nothing            -- Nothing

The instance is short enough to write out in full:

HASKELL
instance Functor Maybe where
  fmap _ Nothing  = Nothing
  fmap f (Just x) = Just (f x)

Either e is a functor in its second type parameter: the Right value is mapped, a Left passes through untouched. That is why Either is handy for computations that may fail with an error message.

HASKELL
fmap length (Right "hello")        -- Right 5  :: Either e Int
fmap length (Left "no input")      -- Left "no input"

IO is a functor as well: fmap transforms the result of an action once it has run. You will use that in the IO chapter, for example to uppercase a line read from the keyboard.

Functions are functors too

For a function type r -> a, the container is "a function waiting for an r". Mapping over it means post-processing its result, which is exactly composition:

HASKELL
instance Functor ((->) r) where
  fmap = (.)

fmap (+ 1) (* 2) 5            -- 11, same as ((+ 1) . (* 2)) 5

It looks odd at first, but it follows from the same rule: keep the shape (a function from r), change what comes out.

The operator form: <$>

Writing fmap in prefix form gets noisy, so there is an infix synonym:

HASKELL
(<$>) :: Functor f => (a -> b) -> f a -> f b
(<$>) = fmap

Use it to apply a function to a wrapped value, as if the wrapper were not there:

HASKELL
length <$> Just "haskell"      -- Just 7
(+ 10) <$> [1, 2, 3]           -- [11,12,13]

There is also <$, which replaces everything inside with one value, and void, which throws the contents away:

HASKELL
0 <$ [1, 2, 3]                 -- [0,0,0]

<$> is $ with a functor lifted around it. Compare f $ x with f <$> mx. The resemblance is intentional and will help in the next lesson, where <*> joins the family.

A stand-in you can run

JavaScript has Array.prototype.map, but nothing equivalent for "maybe" values. In this stand-in, a Maybe is a tagged object, and fmap dispatches on the tag. Real Haskell picks the right instance from the type automatically; here we do it by hand.

JS fmap for lists, Maybe and functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The Functor laws

An instance is only a proper functor if it obeys two laws. GHC cannot check them; it is your job.

  1. Identity: fmap id x == x. Mapping the do-nothing function changes nothing.
  2. Composition: fmap (g . f) x == fmap g (fmap f x). Mapping twice is the same as mapping the composed function once.

Together they say that fmap may change the contents but never the structure. A bogus instance, for example one that reversed a list on every fmap, would break the identity law, because fmap id [1, 2, 3] would give [3, 2, 1].

The laws are not only philosophy. The composition law lets a compiler (or you) fuse two passes over a list into one, and it lets you refactor fmap f . fmap g into fmap (f . g) without worrying.

JS Checking the laws by example

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Deriving a Functor

Any simple data type that stores values of its last type parameter can have a functor instance written for it automatically. With the DeriveFunctor extension:

HASKELL
# LANGUAGE DeriveFunctor #

data Pair a = Pair a a deriving (Show, Functor)

data Tree a = Leaf | Node (Tree a) a (Tree a)
  deriving (Show, Functor)

fmap (* 2) (Pair 3 4)     -- Pair 6 8

The derived fmap for Tree walks the whole tree and applies the function at each Node. You met such trees in Recursive Data Types and Trees; making them a Functor gives them fmap, <$> and every helper written for functors for free.

A type can only be a Functor in its last type parameter. Either e a maps over a; there is no way to fmap over the e without wrapping the type or using another class such as Bifunctor.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of fmap?

    fmap lifts a plain function a -> b into a function over any functor f. The list-only type is map; the third type is <*> and the fourth is >>=.
  2. 2. What does fmap (+ 1) (Left "oops") give for Either String Int?

    Either e is a functor in its Right side only. A Left value passes through unchanged.
  3. 3. Which law says fmap id x == x?

    Mapping the identity function must not change the structure or the contents.
  4. 4. What does fmap f g mean when g is a function?

    The Functor instance for functions is composition: fmap f g x equals f (g x).

Summary

  • A Functor is a type constructor f with fmap :: (a -> b) -> f a -> f b.
  • fmap changes the contents and keeps the shape; <$> is its infix form.
  • Lists, Maybe, Either e, IO and functions r -> a are all functors.
  • Instances must obey the identity and composition laws.
  • DeriveFunctor writes an instance for you when the last type parameter is stored in the type.

Next: Applicative Functors.