Functor and fmap
fmap and the Functor class
map works on lists. A Functor is the class of types for which the same idea exists under another name: fmap :: (a -> b) -> f a -> f b applies a function inside a structure without changing the structure. The class has one method, and the operator <$> is the same function written infix.
class Functor f where
fmap :: (a -> b) -> f a -> f b
fmap (* 2) [1, 2, 3] -- [2,4,6]
(* 2) <$> [1, 2, 3] -- [2,4,6]
The type variable f is the structure, not the element type; the class is over type constructors such as Maybe, [] or Tree. A function that returns f b from f a cannot change the shape, only the values inside, which is the property the laws make precise.
Maybe and lists
For Maybe, fmap applies the function to the value if there is one and leaves Nothing alone. For lists it is map. The two instances together are the reason the function-to-structure pipeline of the last lessons works for both.
module Main (main) where
main :: IO ()
main = do
print (fmap (* 2) (Just (3 :: Int)))
print (fmap (* 2) (Nothing :: Maybe Int))
print (fmap show ([1, 2] :: [Int]))
print ((* 2) <$> [1, 2, 3] :: [Int])
ghc -Wall -O1 -o functor functor.hs
./functor
Just 6
Nothing
["1","2"]
[2,4,6]
The second line is the important one: the function is not applied at all, and the absence survives. That is why fmap is safe on a value that may be missing, and why a chain of fmap calls needs no case analysis until the end.
A Functor instance of your own
A recursive type is a functor as soon as the recursive positions are mapped as well. The tree of the recursion lesson becomes a Tree a with the value parameter, and the instance maps over the left subtree, the value and the right subtree:
module Main (main) where
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving (Show)
instance Functor Tree where
fmap _ Leaf = Leaf
fmap f (Node left value right) = Node (fmap f left) (f value) (fmap f right)
sample :: Tree Int
sample = Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 Leaf)
main :: IO ()
main = do
print sample
print (fmap (* 10) sample)
print (fmap (fmap (* 10)) (Just sample))
ghc -Wall -O1 -o treefmap treefmap.hs
./treefmap
Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 Leaf)
Node (Node Leaf 10 Leaf) 20 (Node Leaf 30 Leaf)
Just (Node (Node Leaf 10 Leaf) 20 (Node Leaf 30 Leaf))
The third line is the composition of two functors: Maybe (Tree Int) has an fmap that goes through the Just and then through the tree, which is what the outer fmap does in one call. That nesting is the reason the class exists: a pipeline does not have to know how many layers of structure it is mapping over.
The functor laws
An instance must satisfy two laws, and the compiler does not check them:
- fmap id == id: mapping the identity changes nothing, which rules out an instance that rebuilds or reorders the structure.
- fmap (f . g) == fmap f . fmap g: mapping a composition is mapping twice, which rules out an instance that counts calls or depends on how the function is written.
fmap id (Just 3) == Just 3 -- True
fmap ((+ 1) . (* 2)) (Just 3) == fmap (+ 1) (fmap (* 2) (Just 3)) -- True
The laws are what lets a library accept any Functor and still reason about the result. A broken instance compiles and then a function that maps twice gives a different answer from one that maps the composition, which is the kind of bug the types cannot catch. The same pattern returns in the lessons on Applicative and Monad, each with its own laws.
Exercises
- Map length over Just "abc" and over Nothing.
- Rewrite map (* 2) xs as fmap (* 2) xs and check that both compile.
- Add a Leaf value with a label to the tree type and update the Functor instance.
- Check both functor laws for Maybe with three functions of your choice.
- Write fmap (fmap (+ 1)) (Just [1, 2]) and explain the two layers.
- Explain why an instance that returns Leaf for every input breaks the first law.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is the type of fmap?
Answer
(a -> b) -> f a -> f bfmap works for any Functor f and changes the values inside without changing the structure.
-
What does
fmap (* 2) Nothingreturn?Answer
Nothing
The Maybe instance leaves Nothing alone and applies the function only to Just.
-
What does
fmap show [1, 2]produce?Answer
["1","2"]
For lists fmap is map, so show is applied to each element.
-
What is
<$>?Answer
The infix spelling of fmap
<$> is the same function as fmap, used infix for readability.
-
What does this program print?
module Main (main) where main :: IO () main = print (fmap (* 10) (Just (4 :: Int)))Answer
Just 40
The value inside Just is multiplied by ten and stays wrapped.
-
Which law must every Functor instance satisfy?
Answer
fmap id == id and fmap (f . g) == fmap f . fmap g
Identity and composition are the two functor laws.
-
What shape may a Functor instance change?
Answer
None: only the values inside, never the structure
The first law rules out rebuilding or reordering, because fmap id must be the identity.
-
What does this program print?
module Main (main) where data Tree a = Leaf | Node (Tree a) a (Tree a) deriving (Show) instance Functor Tree where fmap _ Leaf = Leaf fmap f (Node l v r) = Node (fmap f l) (f v) (fmap f r) main :: IO () main = print (fmap (+ 1) (Node Leaf 1 Leaf))Answer
Node Leaf 2 Leaf
The instance maps the value and both subtrees, so 1 becomes 2.
-
What does
fmap (fmap (+ 1)) (Just [1, 2])produce?Answer
Just [2,3]
The outer fmap goes through Maybe and the inner one through the list.
-
Why do the functor laws matter for a library?
Answer
They let the library treat any Functor uniformly, because mapping composes
The laws guarantee that a chain of mappings can be rearranged without changing the result.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev