具有键值的Haskell二叉树

时间:2011-07-20 17:38:38

标签: algorithm haskell binary-search-tree

我想用带有元组(k,v)的键值叶子构建二叉树。

我的代码:

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

原因是什么以及如何解决?

1 个答案:

答案 0 :(得分:6)

您的类型过于笼统或过于具体。它应该是

fillTree :: Int -> Tree Int Int -> Tree Int Int

fillTree :: (Ord a) => a -> Tree a a -> Tree a a

您的原始声明是尝试将(Int, Int)插入Tree k v 中的任何kv 。它说无论你有什么样的树,我们都可以插入一对Int。这显然是无稽之谈,正如您treeInsert的签名所示,只有(k, v)类型的对可以插入Tree k v

treeInsert :: (Ord k) => (k, v) -> Tree k v -> Tree k v