【发布时间】:2011-02-22 01:35:42
【问题描述】:
我今天下午正在学习函子,并正在尝试为我刚刚编写的树数据类型编写一个。
data GTree a = Node a [GTree a] deriving (Show, Read, Eq)
instance Functor GTree where
fmap f n [] = f n
fmap f n a = f n fmap a
我正在尝试编写它,以便如果列表为空,则映射到单个节点。否则,递归地映射列表。这是我得到的错误。
The equation(s) for `fmap' have three arguments, but its type `(a -> b) -> GTree a -> GTree b' has only two In the instance declaration for `Functor GTree'
我知道我有太多关于 fmap 的参数,但我不知道如何写出来以反映我想要它做的事情。
如果有人可以帮助我解决这个问题,将不胜感激。谢谢!
编辑: 这是我找到的一种可能的解决方案,但我不太明白。
instance Functor GTree where
fmap f (Node a ts) = Node (f a) (map (fmap f) ts)
【问题讨论】:
-
你需要使用构造函数:
fmap f (Node n []) = ... -
@luqui 感谢您的评论。这就说得通了。我尝试将该行更改为 fmap f (Node n []) = Node (f n) 并暂时注释掉第二行,但我仍然遇到错误。
-
Node接受两个参数,你只给了它一个。需要是Node (f n) []。不要放弃,尤其是对于左关联应用程序 (f x y = (f x) y),这可能需要一些时间来适应。 -
酷,感谢您向我指出这些东西。我对haskell很陌生,所以它有点融化我的大脑。我一定会坚持下去。 :)
标签: haskell