三天后我有一个 Haskell 考试,所以我想我应该练习一下,然后回顾过去的考试,其中一个具有以下 Tree 数据类型:
data Tree a = Leaf1 a | Leaf2 a a | Node (Tree a) (Maybe (Tree a)) deriving (Eq, Ord, Show)
一开始似乎没有什么挑战性,但后来我意识到我必须为这棵树编写一个 Traversable 实例。处理叶子很容易:
instance Traversable Tree where
traverse f (Leaf1 a) = Leaf1 <$> f a
traverse f (Leaf2 a b) = Leaf2 <$> f a <*> f b
但是,我开始遇到 Node.js 的问题。
traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
traverse f (Node l (Just r)) = Node <$> traverse f l <*> Just (traverse f r)
自然,这些不起作用,我无法理解第二个 <*> 之后应该发生的事情。我尝试使用漏洞,但 ghci 给我的消息并没有太大帮助(我知道问题出在类型上,但我不知道应该如何解决它)。
这是我尝试编译它时收到的错误消息:
* Couldn't match type `f' with `Maybe'
`f' is a rigid type variable bound by
the type signature for:
traverse :: forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> Tree a -> f (Tree b)
at exam.hs:92:3-10
Expected type: f (Maybe (Tree b))
Actual type: Maybe (Maybe (Tree b))
* In the second argument of `(<*>)', namely `Nothing'
In the expression: Node <$> traverse f t <*> Nothing
In an equation for `traverse':
traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
* Relevant bindings include
f :: a -> f b (bound at exam.hs:94:12)
traverse :: (a -> f b) -> Tree a -> f (Tree b)
(bound at exam.hs:92:3)
|
94 | traverse f (Node t Nothing) = Node <$> traverse f t <*> Nothing
| ^^^^^^^
有人可以给我一些指示或解决此问题的可能吗?