Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Polymorphic Tree Sum

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

like image 410
saimn Avatar asked Jul 31 '12 14:07

saimn


1 Answers

The compiler can't verify that the outcome will be an Int. As it stands, you could call treeSum with an ITree Integer argument (and the operations wouldn't produce an Int).

Try changing the signature to treeSum :: Integral t => ITree t -> t.

like image 86
jtobin Avatar answered Sep 22 '22 21:09

jtobin