Embedding a binary search tree in Haskell

I am implementing the BST insert function, 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 loaded this function into ghci, it gave me a lot of errors that seem to be related to the comparative parts. I do not see any problems with this. I'm new to Haskell, can anyone help? Many thanks.

+4
source share
1 answer

Type change tinsertto

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

corrects him.

This is necessary because the functions (<)and (>)belong to the class Ord, and you need to have a type signature before that.

== (==) :: Eq a => a -> a -> Bool, Eq Ord, , (<) ==, , Eq a.

+8

All Articles