[英]Checking if two n-ary trees are equal in Haskell
I am trying to implement a simple boolean function in Haskell to check if two n-ary trees are equal. 我试图在Haskell中实现一个简单的布尔函数,以检查两个n元树是否相等。
My code is: 我的代码是:
-- This is the n-ary tree definition.
-- (I know "Leaf a" is not necessary but I prefer to write it for clarity)
data Tree a = Leaf a | Node a [Tree a]
deriving (Show)
-- This is a simple tree used for test purposes
t :: Tree Int
t = Node 3 [Node 5 [Leaf 11, Leaf 13, Leaf 15], Leaf 7, Leaf 9]
treeEquals :: Eq a => Tree a -> Tree a -> Bool
treeEquals (Leaf n1) (Leaf n2) = n1 == n2
treeEquals (Node n1 xs1) (Node n2 xs2) = n1 == n2 && and(zipWith (treeEquals) xs1 xs2)
treeEquals _ _ = False
My problem is that if I do tests such as: 我的问题是,如果我进行以下测试:
treeEquals t t
treeEquals t (Leaf 3)
treeEquals t (Node 3 [Leaf 7])
it returns correctly false because the trees are not equal, but if I try a test such as: 它正确返回false,因为树不相等,但是如果我尝试测试,例如:
treeEquals t (Node 3 [])
It doesn't work because it returns true as the trees were equals. 它不起作用,因为当树相等时返回true。
Do you know what I am doing wrong? 你知道我在做什么错吗?
Why don't you just derive Eq
and use ==
? 为什么不只导出
Eq
并使用==
呢?
The problem with your current code is the zipWith
. 您当前代码的问题是
zipWith
。 It stops as soon as it reaches the end of the shorter list, so zipWith treeEquals foo []
always returns []
(regardless of what foo
is). 一旦到达较短列表的末尾,它就会停止,因此
zipWith treeEquals foo []
始终返回[]
(无论foo
是什么)。
Here's an (untested) alternative solution: 这是(未试用的)替代解决方案:
treeEquals :: Eq a => Tree a -> Tree a -> Bool
treeEquals (Leaf n1) (Leaf n2) = n1 == n2
treeEquals (Node n1 xs1) (Node n2 xs2) = n1 == n2 && listTreeEquals xs1 xs2
where
listTreeEquals [] [] = True
listTreeEquals (x1 : xs1) (x2 : xs2) = treeEquals x1 x2 && listTreeEquals xs1 xs2
listTreeEquals _ _ = False
treeEquals _ _ = False
在zipWith之前添加另一个&&,并检查列表的长度是否相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.