[英]implementing binary search tree insertion in Haskell
我正在實現BST的插入功能,下面是我的代碼:
data Tree a = Empty | Branch a (Tree a) (Tree a)
deriving (Show, Eq)
tinsert :: Tree a -> a -> Tree a
tinsert Empty a = Branch a Empty Empty
tinsert (Branch a left right) b
| b == a = Branch a left right
| b < a = Branch a (tinsert left b) right
| b > a = Branch a left (tinsert right b)
當我在ghci中加載這個函數時,它給了我很多錯誤,這些錯誤似乎與比較部分有關。 我沒有看到任何問題。 我是Haskell的新手,有人可以幫忙嗎? 非常感謝。
將tinsert
類型更改為
tinsert :: (Ord a) => Tree a -> a -> Tree a
解決它。
這是必要的,因為函數(<)
和(>)
來自Ord
類型類,並且您需要擁有類型簽名中的函數。
你也使用==
和(==) :: Eq a => a -> a -> Bool
,但是Eq
是Ord
的超類,所以編譯器知道如果你有(<)
可用,你已經有了==
,所以你也不需要說Eq a
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.