【发布时间】:2018-01-29 14:17:22
【问题描述】:
有人可以向我解释一下,类型类Traversable 的目的是什么?
类型类定义为:
class (Functor t, Foldable t) => Traversable (t :: * -> *) where
所以Traversable 是Functor t 和Foldable t。
traverse 函数是Traversable 的成员,具有以下签名:
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
为什么必须将结果包装到应用程序中?它的意义是什么?
我有以下例子:
module ExercisesTraversable where
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Checkers (quickBatch, eq, (=-=), EqProp)
import Test.QuickCheck.Classes (traversable)
type TI = []
newtype IdentityT a = IdentityT a
deriving (Eq, Ord, Show)
instance Functor IdentityT where
fmap f (IdentityT a) = IdentityT (f a)
instance Foldable IdentityT where
foldMap f (IdentityT a) = f a
instance Traversable IdentityT where
traverse f (IdentityT a) = IdentityT <$> f a
instance Arbitrary a => Arbitrary (IdentityT a) where
arbitrary = do
a <- arbitrary
return (IdentityT a)
instance Eq a => EqProp (IdentityT a) where (=-=) = eq
main = do
let trigger = undefined :: TI (Int, Int, [Int])
quickBatch (traversable trigger)
让我们看一下traverse的实现:
traverse f (IdentityT a) = IdentityT <$> f a
应用程序f a的结果类型必须是应用程序,为什么?一个函子还不够吗?
【问题讨论】:
-
Functor 对于
Identity实例来说就足够了,但这是一个微不足道的实例。这对于几乎任何递归类型都是不够的 - 看看Traversable []实例。 -
非应用版调用
Functor
标签: haskell