我正在查看 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
该文件指出 -
This function may be used as a value for fmap in a Functor instance, provided that traverse is defined.
所以推测它可以用来推导出
fmap
对于 Traversable
实例。但是,Traversable
有 Functor
作为父类(super class)。class (Functor t, Foldable t) => Traversable t where
...
所以你不能定义
Traversable
未定义 Functor
的实例先例!无论您在哪里拥有 Traversable
,您可以访问 fmap
,这相当于(并且可能比)fmapDefault
.那么在哪里使用
fmapDefault
,而不是更熟悉的 fmap
?
最佳答案
它允许你写
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)
关于haskell - 'fmapDefault' 中的 'Data.Traversable' 有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31229674/