我想用帶元組(k,v)的鍵值葉子構建二叉樹。Haskell帶鍵值的二叉樹
我的代碼:
data Tree k v = EmptyTree
| Node (k, v) (Tree k v) (Tree k v)
deriving (Show, Eq, Ord, Read)
emptyTree :: (k,v) -> Tree k v
emptyTree (k,v) = Node (k, v) EmptyTree EmptyTree
treeInsert :: (Ord k) => (k,v) -> Tree k v -> Tree k v
treeInsert (k,v) EmptyTree = emptyTree (k, v)
treeInsert (a, b) (Node (k,v) left right)
| a == k = (Node (a,b) left right)
| a < k = (Node (a, b) (treeInsert (a, b) left) right)
| a > k = (Node (a, b) left (treeInsert (a, b) right))
現在我試圖填補這棵樹:
fillTree :: Int -> Tree k v -> Tree k v
fillTree x tree = treeInsert (x, x) tree
但我得到這個錯誤:
Couldn't match type `v' with `Int'
`v' is a rigid type variable bound by
the type signature for fillTree :: Int -> Tree k v -> Tree k v
有什麼原因和如何我修復它?
在這種情況下,刪除類型簽名,在GHCi中加載文件以及查看編譯器*認爲的類型應該是什麼會有幫助。 –
'emptyTree'是該函數的一個非常糟糕的名稱,因爲每個人都希望它返回一個'EmptyTree'。一個更好的名字就像'singleton'或'singleNode'。 – Landei