While studying Applicative
deeper, I came to Traversable
. Although I already knew Foldable
from LYHGG, I haven't seen the former yet, so I started reading the Haskell wiki about Traversable.
While reading it, I understood why Foldable.fold
is parallel to Traversable.sequenceA
and Foldable.foldMap
is parallel to Traversable.traverse
.
I've seen also that every Traversable
is also a Foldable
and a Functor
, and sequenceA
and traversal
have a default implementation in terms of each other:
traverse f = sequenceA . fmap f
sequenceA = traverse id
So, as I have seen in LYHGG that foldMap
is a minimal complete definition for Foldable
, I thought that, it is parallel to traverse
, so fold
(which is parallel to sequenceA
) would be a minimal complete definition too (which it isn't)... Foldable
is not a Functor
like Traversable
is, so we cannot apply this:
foldMap f = fold . fmap f
fold = foldMap id -- this is ok
Why isn't every Foldable
a Functor
, and what would be an instance of Foldable
that actually isn't a Functor
?
Set
is a classic example of aFoldable
that's not aFunctor
. So are unboxed vectors. – HobsonSet
to understand why it isn't aFunctor
, but, Sets can be thought as containers of things that don't repeat... That being said, I cannot figure out quickly why it is not aFunctor
instance... – ConfabulationFunctor
doesn't give implementations the opportunity to constrain their type arguments. Imagine if someone wrotefmap f s
wheref :: Int -> Integer -> Integer
. The typeInteger -> Integer
is not even an instance ofEq
, let aloneOrd
, so there's no way to check for duplicates when mapping. The function could map multiple elements to identical functions, and you'd have no way of collapsing the duplicates. – Hobsonxs :: U.Vector Int
,fmap Just xs
would have to produce something of typeU.Vector (Maybe Int)
, which isn't a real thing. – HobsonTraversable
class was conceived first (e.g., McBride and Patterson, "Applicative Programming with Effects"; Gibbons and Oliveira, "The Essence of the Iterator Pattern").Foldable
was added as a superclass because of the "containers that aren'tFunctor
s" problem. ButfoldMap
falls out oftraverse
-ing with theConst
applicative, as shown in Gibbons and Oliveira's paper. – Kheda