今天下午我正在学习仿函数,并尝试为我刚刚编写的树数据类型编写一个仿函数。
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 有太多的争论,但我不知道如何写出来,以便它反射(reflect)我想要它做什么。
如果有人能帮助我解决这个问题,我将不胜感激。谢谢!
编辑: 这是我发现的一种可能的解决方案,但我不太明白。
instance Functor GTree where
fmap f (Node a ts) = Node (f a) (map (fmap f) ts)
最佳答案
fmap 的作用是接受一个类型为 a -> b
的函数加上一个 a
框,然后返回 b
框>。您应该使用 (Node a [])
和 (Node a xs)
而不是 n []
和 n a
,它将与没有任何子节点的 Node 和有子节点的 Node 进行匹配。
instance Functor GTree where
fmap f (Node a xs) = Node (f a) (fmap (fmap f) xs)
关于haskell - 我正在尝试在 Haskell 中为我的 Tree 数据类型定义 Functor 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073179/