繁体   English   中英

检查Haskell中的两个n元树是否相等

[英]Checking if two n-ary trees are equal in Haskell

我试图在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。

你知道我在做什么错吗?

为什么不只导出Eq并使用==呢?

您当前代码的问题是zipWith 一旦到达较短列表的末尾,它就会停止,因此zipWith treeEquals foo []始终返回[] (无论foo是什么)。

这是(未试用的)替代解决方案:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM