有人可以向我解释一下类型类的目的是什么吗Traversable
?
类型类定义是:
class (Functor t, Foldable t) => Traversable (t :: * -> *) where
So Traversable
is a Functor t
and Foldable t
.
The 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
必须是一个应用程序,为什么?函子还不够吗?