3

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?

2
  • 3
    In situations like this, it can be helpful to remove the type signature, load the file in GHCi, and see what the compiler thinks the type should be. Commented Jul 20, 2011 at 17:52
  • 2
    emptyTree is a really bad name for that function, as everybody would expect that it returns an EmptyTree. A better name would something like singleton or singleNode. Commented Jul 22, 2011 at 14:14

1 Answer 1

6

Your type is either too general or too specific. It should be

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

or

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

Your original declaration was trying to insert (Int, Int) into a Tree k v for any k, v. It was saying that no matter what kind of tree you have, we can insert a pair of Ints in it. This is clearly nonsense, and as your signature for treeInsert indicates, only pairs of type (k, v) can be inserted into a Tree k v.

treeInsert :: (Ord k) => (k, v) -> Tree k v -> Tree k v
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively, something like (Ord a) => a -> Tree a a -> Tree a a.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.