[英]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.