I'm reading the typeclassopedia on Haskell wiki. When I came across the typeclass ((,) e)
which is an instance of functor, I was quite confused. According to the author
((,) e)
represents a container which holds an “annotation” of type e along with the actual value it holds.
However, I can't quite understand the meaning of this sentence since I can only see a sectioned tuple here. I also searched this typeclass on Hoogle but found nothing.
((,) e)
is not a typeclass; it's just a type. And indeed, it is a sectioned tuple. The idea here is that you can think of (e, a)
as a "container" holding a value of type a
and an "annotation" of type e
. The fmap
for ((,) e)
modifies the values, but not the annotations. In the "functor as container" analogy, the annotation is part of the container, rather than part of its contents.
Let's consider a sort of tree:
data Tree f a
= Leaf
| Node (Tree f a) (f a) (Tree f a)
instance Functor f => Functor (Tree f) where
fmap _ Leaf = Leaf
fmap f (Node l fa r) = Node (fmap f l) (fmap f fa) (fmap f r)
What do these look like? Tree Identity a
is a plain binary tree of elements of type a
. It could represent, e.g., a set of values. Tree ((,) k) a
, on the other hand, is a binary tree of pairs. It could represent a map from keys of type k
to values of type a
. Mapping over the tree with fmap
will modify the values, but leave the keys alone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With