我是Haskell的新手并且一直在尝试构建一个压缩函数,该函数适用于具有以下数据结构的树:
data Tree a = Leaf | Node a (Tree a) (Tree a) deriving Show
到目前为止,我有这个:
treezip :: (Tree a) -> (Tree b) -> (Tree(a,b))
treezip (Node a leftSubtreea rightSubtreea) (Node b leftSubtreeb rightSubtreeb) =
let l = treezip leftSubtreea leftSubtreeb
r = treezip rightSubtreea rightSubtreeb
in Node a l r
然而,每当我尝试将模块加载到GHCi中时,我都会收到错误,指向最后一行代码并特别关注变量a
。
我一直绞尽脑汁想弄清楚为什么这不起作用。任何帮助将不胜感激
答案 0 :(得分:4)
不要对编译器起作用,让它帮助你!
为了使这样的函数正确,最好只从“外壳定义”开始:
treeZip (Node a lSa rSa) (Node b lSb rSb) = Node _ _ _
编译器会回来:
• Found hole: _ :: (a, b)
Where: ‘a’ is a rigid type variable ...(_bla, bla_)
‘b’ is a rigid type variable ....
• In the first argument of ‘Node’, namely ‘_’
In the expression: Node _ _ _
In an equation for ‘treeZip’:
treeZip (Node a lSa rSa) (Node b lSb rSb) = Node _ _ _
• Relevant bindings include
rSb :: Tree b (bound at /tmp/wtmpf-file20584.hs:4:38)
lSb :: Tree b (bound at /tmp/wtmpf-file20584.hs:4:34)
b :: b (bound at /tmp/wtmpf-file20584.hs:4:32)
rSa :: Tree a (bound at /tmp/wtmpf-file20584.hs:4:21)
lSa :: Tree a (bound at /tmp/wtmpf-file20584.hs:4:17)
a :: a (bound at /tmp/wtmpf-file20584.hs:4:15)
因此,它会告诉您第一个_
类型的孔应填充(a,b)
类型的内容。我们有这种类型的东西吗?好吧,我们可以轻松地构建它,即通过a
和b
并将它们放在一个元组中!
treezip (Node a lSa rSa) (Node b lSb rSb) = Node (a,b) _ _
...给
• Found hole: _ :: Tree (a, b)
Where: ‘a’ is a rigid type variable bound by...
是的,你已经解决了那个 - 它应该是子树的拉链。
treeZip (Node a lSa rSa) (Node b lSb rSb)
= Node (a,b) (treeZip lSa lSb) (treeZip rSa rSb)