我试图在 Haskell 中实现一个简单的布尔函数来检查两个 n 元树是否相等。
我的代码是:
-- 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
我的问题是,如果我进行以下测试:
treeEquals t t
treeEquals t (Leaf 3)
treeEquals t (Node 3 [Leaf 7])
它正确返回false,因为树不相等,但是如果我尝试进行以下测试:
treeEquals t (Node 3 [])
它不起作用,因为它在树相等时返回 true。
你知道我做错了什么吗?