11

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?

4

1 回答 1

9

正如 dfeuer 所说,Set是 aFoldable不是 a的一个很好的例子Functor

考虑以下类型Set.map

map :: Ord b => (a -> b) -> Set a -> Set b

请注意,这几乎 fmap是,但它需要一个额外的Ord b约束。由于您有此约束,因此不能将其作为Functor.

请注意Set,即使有这个限制,它也不是 Haskell 上的函子。给定巧妙设置的Eq实例,我们可以打破fmap f . fmap g === fmap (f . g). 请参阅此Stack Overflow 问题以进行进一步讨论。

如那里所述,Set “子类别”上的(endo)函子,其Hask具有作为集合的有序类型,并且具有作为态射的保序映射

因此,即使不明显,我们无法制作Set仿函数这一事实实际上暗示了一个真正的数学问题,而不仅仅是我们类型类机制的限制。

于 2016-03-08T02:27:20.513 回答