7

I'm implementing the insert function of a BST, below is my code:

data Tree a = Empty | Branch a (Tree a) (Tree a) 
    deriving (Show, Eq)

tinsert             :: Tree a -> a -> Tree a 
tinsert Empty a         = Branch a Empty Empty
tinsert (Branch a left right) b
    | b == a = Branch a left right
    | b < a = Branch a (tinsert left b) right
    | b > a = Branch a left (tinsert right b)

When I was loading this function in ghci, it gave me many errors, which seem to be related to the comparison parts. I don't see any problem with it. I'm new to Haskell, could anybody help? Thanks a lot.

user2407038
  • 14,400
  • 3
  • 29
  • 42
J Freebird
  • 3,664
  • 7
  • 46
  • 81
  • 1
    Please add the details of the error messages you are getting and what you've tried to fix them. – Ganesh Sittampalam Jan 18 '14 at 08:52
  • 2
    Since you are comparing the objects inside the tree, they must be members of the `Ord` typeclass. The type of `<` is `Ord a => a -> a -> Bool`. The correct type for your function would be `Ord a => Tree a -> a -> Tree a`. – user2407038 Jan 18 '14 at 08:59

1 Answers1

11

Changing the type of tinsert to

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

fixes it.

This is necessary because the functions (<) and (>) are from the Ord typeclass, and you need to own up to that in the type signature.

You also use == and (==) :: Eq a => a -> a -> Bool, but Eq is a superclass of Ord, so the compiler knows that if you have (<) available you already have ==, so you don't need to say Eq a as well.

Pharap
  • 3,826
  • 5
  • 37
  • 51
Chris Taylor
  • 46,912
  • 15
  • 110
  • 154
  • 3
    Hi Chris, thanks a lot, but it's actually tinsert :: (Ord a) =》 Tree a -> a -> Tree a. I fixed it. Thanks for the info. – J Freebird Jan 18 '14 at 17:48