我正在查看Data.Traversable的文档,并偶然发现了fmapDefault - https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base/Data-Traversable.html#g:3
fmapDefault :: Traversable t => (a -> b) -> t a -> t b文件中说-
该函数可用作函子实例中fmap的值,条件是定义遍历。
因此,可以推测它可以用于派生Traversable实例的一个Traversable。然而,Traversable将Functor作为超类。
class (Functor t, Foldable t) => Traversable t where
...因此,如果不首先定义Traversable实例,就不能定义Functor实例!而且,无论哪里有Traversable,都可以访问fmap,这相当于(可能比fmapDefault更高效)。
那么,人们会在哪里使用fmapDefault,而不是更熟悉的fmap呢?
发布于 2015-07-05 11:11:33
它允许你写
data Foo a = ...
instance Functor Foo where -- we do define the functor instance, but we “cheat”
fmap = fmapDefault -- by using `Traversable` in its implementation!
instance Traversable Foo where
traverse = ... -- only do this manually.尽管如此,我不认为这真的是明智的。函子实例通常是徒手完成的,而且显而易见的实现可能比Traversable派生的实现更有效。通常,实例实际上可以自动创建:
{-# LANGUAGE DeriveFunctor #-}
data Foo a = ...
deriving (Functor)https://stackoverflow.com/questions/31229674
复制相似问题