Foldable
and Functor
offer two separate abstractions for types with structures that can be folded (or reduced) and mapped over, respectively.
A Foldable holds values that can be enumerated and combined together1. One can think of a Foldable as something that can be turned into a list (toList :: Foldable f => f a -> [a]
). Alternatively, one can think of Foldables as structures whose values can be combined monoidally: (Foldable t, Monoid m) => (a -> m) -> t a -> m
(of course, this requires the ability to enumerate them).
Functors, on the other hand, are structures that allow one to "lift" a function (a -> b)
to apply to the a
s held by the structure (fmap :: (a -> b) -> (f a -> f b)
). fmap
must preserve the structure being mapped over: a tree must have the same shape before and after, a list must have the same number of elements in the same order, Nothing
can't be turned into something, and so on. On the other hand, Foldables do not need to preserve this structure; the whole point is to discard the structure and produce a new one.
The Wiki refers to the fact that there is no way to supply a typeclass constraint to fmap
. fmap :: (Ord a, Ord b) => (a -> b) -> Set a -> Set b
does not unify with the type defined by the class, fmap :: (a -> b) -> f a -> f b
, which has no constraints. This makes an instance for Set
impossible to write.
However, this is just a language implementation issue and not a deeper mathematic statement about sets. The real reason that Foldable does not have a Functor superclass is simply that there are Foldable instances which are not Functor instances.
- "Hold" is a bit loose and is intended to be interpreted in the "Functors are containers" sense where
Proxy s a
holds zero a's, Identity a
holds one a, Maybe a
holds zero or one a, b -> a
holds |b|
a's, and so on.