I want to build binary tree with key – value leafs with tuple (k,v).
My code:
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))
Now i’m trying to fill this tree:
fillTree :: Int -> Tree k v -> Tree k v
fillTree x tree = treeInsert (x, x) tree
But I get this error:
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
What’s the cause and how can I fix it?
Your type is either too general or too specific. It should be
or
Your original declaration was trying to insert
(Int, Int)into aTree k vfor anyk,v. It was saying that no matter what kind of tree you have, we can insert a pair ofInts in it. This is clearly nonsense, and as your signature fortreeInsertindicates, only pairs of type(k, v)can be inserted into aTree k v.