Haskell Polymorphic Tree Sum

Viewed 2201

I wrote the following code for handling a polymorphic binary tree in Haskell as a preperation for the functional programming exam next week:

data ITree t = Leaf | Node t (ITree t) (ITree t) 
             deriving (Eq, Ord, Show)

treeSum :: ITree t -> Int
treeSum Leaf = 0
treeSum (Node n t1 t2) = n + (treeSum t1) + (treeSum t2)

Now I have the problem, that the code doesn't compile:

...\tree.hs:8:26:
Couldn't match type `t' with `Int'
  `t' is a rigid type variable bound by
      the type signature for treeSum :: ITree t -> Int
      at ...\tree.hs:7:1
In the first argument of `(+)', namely `n'
In the first argument of `(+)', namely `n + (treeSum t1)'
In the expression: n + (treeSum t1) + (treeSum t2)
Failed, modules loaded: none.
Prelude>

Do you know what's wrong with treeSum? I think it has something to do with the polymorphic type of ITree, but I don't know how to solve this. Do I have to specify that the type t must be a type which can be counted/enumerated? Probably with a class instance of such a type class?

Thanks in advance for your help!

Simon

1 Answers
Related