我如何理解列表的 Traversable 实现
How can i understand this Traversable implementation for lists
我无法理解以下内容 example from the NICTA course:
instance Traversable List where
traverse ::
Applicative f =>
(a -> f b)
-> List a
-> f (List b)
traverse f =
foldRight (\a b -> (:.) <$> f a <*> b) (pure Nil)
接下来,我将List
替换为[]
,所以我们有:
instance Traversable [] where
traverse ::
Applicative f =>
(a -> f b)
-> [a]
-> f ([b])
traverse f =
foldRight (\a b -> (:) <$> f a <*> b) []
特别是下面对(<*>)
类型的推导有什么问题?
(:) :: a -> [a] -> [a]
(<$>) :: a -> b -> F a -> F b, F for Functor
(因此...)
(:) <$> :: F a -> F ([a] -> [a])
f :: a -> A b :: ((->) a) (A b), A for Applicative
(因此...)
(:) <$> f :: ((->) a) ([a] -> [a])
(:) <$> f a :: [a] -> [a]
(<*>) :: A (a -> b) -> A a -> A b
what's wrong with the following derivation?
这段话有问题:
(:) <$> f :: ((->) a) ([a] -> [a])
函数应用程序始终优先于任何运算符,因此 (:) <$> f a
不是您推导中的 ((:) <$> f) a
,而是 (:) <$> (f a)
。剩下的就很顺利了(你可能想在阅读下面的解决方案之前尝试自己完成它):
(:) <$> :: F a -> F ([a] -> [a]) -- The third line of your derivation.
f :: a -> A b
f a :: A b
(:) <$> f a :: A ([b] -> [b])
(<*>) :: A (a -> b) -> A a -> A b
(:) <$> f a :: A ([b] -> [b])
(:) <$> f a <*> :: A [b] -> A [b]
b :: A [b]
(:) <$> f a <*> b :: A [b]
我无法理解以下内容 example from the NICTA course:
instance Traversable List where
traverse ::
Applicative f =>
(a -> f b)
-> List a
-> f (List b)
traverse f =
foldRight (\a b -> (:.) <$> f a <*> b) (pure Nil)
接下来,我将List
替换为[]
,所以我们有:
instance Traversable [] where
traverse ::
Applicative f =>
(a -> f b)
-> [a]
-> f ([b])
traverse f =
foldRight (\a b -> (:) <$> f a <*> b) []
特别是下面对(<*>)
类型的推导有什么问题?
(:) :: a -> [a] -> [a]
(<$>) :: a -> b -> F a -> F b, F for Functor
(因此...)
(:) <$> :: F a -> F ([a] -> [a])
f :: a -> A b :: ((->) a) (A b), A for Applicative
(因此...)
(:) <$> f :: ((->) a) ([a] -> [a])
(:) <$> f a :: [a] -> [a]
(<*>) :: A (a -> b) -> A a -> A b
what's wrong with the following derivation?
这段话有问题:
(:) <$> f :: ((->) a) ([a] -> [a])
函数应用程序始终优先于任何运算符,因此 (:) <$> f a
不是您推导中的 ((:) <$> f) a
,而是 (:) <$> (f a)
。剩下的就很顺利了(你可能想在阅读下面的解决方案之前尝试自己完成它):
(:) <$> :: F a -> F ([a] -> [a]) -- The third line of your derivation.
f :: a -> A b
f a :: A b
(:) <$> f a :: A ([b] -> [b])
(<*>) :: A (a -> b) -> A a -> A b
(:) <$> f a :: A ([b] -> [b])
(:) <$> f a <*> :: A [b] -> A [b]
b :: A [b]
(:) <$> f a <*> b :: A [b]