Haskell Functor
You know map, which applies a function to every element of a list. But lists are not the only "containers": a Maybe holds zero or one value, an Either e holds a result or an error, a tree holds values at its nodes, and an IO action produces a value later. Functor is the type class for all types that can be mapped over in the same way.
class Functor f where
fmap :: (a -> b) -> f a -> f bfmap takes an ordinary function a -> b and lifts it to work inside the structure f, leaving the structure itself unchanged.
fmap on familiar types
main :: IO ()
main = do
print (fmap (+ 1) [1, 2, 3]) -- list: same as map
print (fmap (+ 1) (Just 41)) -- Maybe: apply inside Just
print (fmap (+ 1) Nothing) -- Nothing stays Nothing
print (fmap length (Right "hello" :: Either String String))
print (fmap length (Left "error" :: Either String String))
print (fmap negate (10, 20)) -- pairs map the second component[2,3,4]
Just 42
Nothing
Right 5
Left "error"
(10,-20)
| Type | What fmap f does |
|---|---|
[a] |
applies f to every element |
Maybe a |
applies f to the value in Just; Nothing stays Nothing |
Either e a |
applies f to the value in Right; a Left passes through untouched |
(e, a) |
applies f to the second component |
IO a |
applies f to the result the action produces |
Map k v |
applies f to every value (keys unchanged) |
The idea for Maybe and Either is powerful: you can write the happy-path transformation and let failures flow through automatically.
The <gt; operator
<gt; is an infix synonym for fmap, chosen to look like $ ("apply"), but inside a structure:
import Data.Char (toUpper)
import Text.Read (readMaybe)
main :: IO ()
main = do
print (map toUpper <gt; Just "quiet")
print ((* 2) <gt; [1, 2, 3])
print ((+ 10) <gt; (readMaybe "5" :: Maybe Int))
print ((+ 10) <gt; (readMaybe "five" :: Maybe Int))
print (3 <$ Just "anything") -- replace the contents with a constantJust "QUIET"
[2,4,6]
Just 15
Nothing
Just 3
fmap over IO
An IO String is an action that will produce a string. fmap lets you transform that future result without running anything early:
import Data.Char (toUpper)
greeting :: IO String
greeting = return "hello, functor"
main :: IO ()
main = do
loud <- fmap (map toUpper) greeting
putStrLn loud
n <- length <gt; greeting
print nHELLO, FUNCTOR
14
In a real program greeting would be getLine or readFile "notes.txt", and length <gt; readFile path is a very common idiom.
Writing your own Functor instance
Any type with one "slot" for values can be a Functor. Here is a binary tree:
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving Show
instance Functor Tree where
fmap _ Leaf = Leaf
fmap f (Node left x right) = Node (fmap f left) (f x) (fmap f right)
sample :: Tree Int
sample = Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 Leaf)
main :: IO ()
main = do
print (fmap (* 10) sample)
print (fmap show sample)
print (fmap even sample)Node (Node Leaf 10 Leaf) 20 (Node Leaf 30 Leaf)
Node (Node Leaf "1" Leaf) "2" (Node Leaf "3" Leaf)
Node (Node Leaf False Leaf) True (Node Leaf False Leaf)
The shape of the tree is preserved; only the values change. GHC can even write this instance for you: add {-# LANGUAGE DeriveFunctor #-} (already on in GHC2021) and deriving (Show, Functor).
Kinds: why Functor Tree and not Functor (Tree Int)?
Tree on its own is not a type of values; it needs a parameter to become one (Tree Int). Haskell describes this with kinds: Int has kind Type (written * in older code), while Tree and Maybe have kind Type -> Type. Functor instances are for type constructors of kind Type -> Type, which is why we write instance Functor Tree and instance Functor Maybe. For Either e a, which has two parameters, the instance is for Either e, which is why fmap only touches the Right side.
The Functor laws
Every lawful Functor instance must satisfy two rules, which guarantee that fmap changes values and nothing else:
| Law | Meaning |
|---|---|
fmap id x == x |
mapping the identity function changes nothing |
fmap (f . g) x == fmap f (fmap g x) |
mapping twice is the same as mapping the composition |
main :: IO ()
main = do
let xs = Just 7
f = (* 2)
g = (+ 3)
print (fmap id xs == xs)
print (fmap (f . g) xs == (fmap f . fmap g) xs)
print (fmap (f . g) [1, 2, 3] == (fmap f . fmap g) [1, 2, 3])True
True
True
A "functor" that, for instance, reversed a list while mapping would break the first law. The laws are not checked by the compiler; they are a promise instance writers make. The Laws & Testing lesson shows how to check them with property tests.
Test yourself
What is fmap (* 2) (Just 5)?
10Just 10Just 5Nothing
What is fmap length (Left "oops" :: Either String String)?
Left 4Right 4Left "oops"4
Which law must every Functor satisfy?
fmap f x == xfmap id x == xfmap f (fmap f x) == fmap f xfmap f [] == [f]