我必須在haskell中編寫一個函數來檢查兩個二叉樹是否是彼此的鏡像。這是我迄今爲止,但我不知道如果真正& & areMirrorImages l1 r2 & & areMirrorImages r1 l2是正確的方式來做到這一點。我試圖邏輯與真正的遞歸調用areMirrorImages函數的結果。haskell二叉樹函數
-- Tests whether two BinaryTrees are mirror images of one another
areMirrorImages :: (Eq (BinaryTree a), Eq a) => BinaryTree a -> BinaryTree a -> Bool
areMirrorImages Empty Empty = True
areMirrorImages _ Empty = False
areMirrorImages Empty _ = False
areMirrorImages (Node x1 left1 right1) (Node x2 left2 right2) =
if (x1 == x2 && left1 == right2 && right1 == left2)
then True && (areMirrorImages left1 right2) && (areMirrorImages right1 left2)
else False
這是錯誤我得到當我試圖編譯:
A2.hs:2:0:
Non-type variables, or repeated type variables,
in the constraint: Eq (BinaryTree a)
(Use -fglasgow-exts to permit this)
In the type signature:
areMirrorImages :: (Eq (BinaryTree a), Eq a) =>
BinaryTree a -> BinaryTree a -> Bool
我似乎無法找出什麼是錯的
我可以建議你寫一個vanilla(unmirrored)相等函數和第二個函數來鏡像樹,然後說'isMirrorOf x y = x == mirror y'?編寫這樣的代碼往往更清晰。 – barsoap
'True && expr'是不必要的;它總是會評估爲'expr',所以你可以放棄'True &&'。 –
另請參見http://stackoverflow.com/questions/5012205/haskell-possible-fix-add-eq-a-to-the-context-of – Landei