Insert value into ordered tree in Haskell

Basically, I defined the data type of the tree, which is defined as follows:

data Tree a = Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving (Eq, Ord, Show)

Now I need to create a function to insert the value into an ordered tree (it does not need to sort the tree, just add the value). This is what I came up with:

insert :: a -> Tree a -> Tree a
insert x Empty      = Leaf x
insert x (Leaf m)   | m < x     = Node (Leaf x) m Empty
                    | otherwise = Node Empty m (Leaf x)
insert x (Node l m r)   | x > m     = Node (Leaf l) m (insert x r)
                        | otherwise = Node (insert x l) m (Leaf r)

However, when I run this, I get the following error message:

Cannot match the expected type 'a' (hard variable) against the expected type 'Tree a' 'a' is associated with the type signature for 'insert' in Main.hs: 11:10 In the first argument is "Leaf", namely "l", In the first argument is 'Node', namely '(Leaf l)' In the expression: Node (Leaf l) m (insert xr)

, - , , , .

+5
3

-checker-ese :

'a' (a )

, a, (, "" ), - .

'Tree a'

, Tree, . , .

'a' 'insert' Main.hs: 11:10

, , .

"", "l" 'Node', '(Leaf l)' : Node (Leaf l) m (insert x r)

, , .

, : l Tree a, , a. l, , , , . a? Tree. , l Tree a! et voila, , .

..., , , .

+9

,

insert x (Node l m r)   | x > m     = Node (Leaf l) m (insert x r)
                        | otherwise = Node (insert x l) m (Leaf r)

insert x (Node l m r)   | x > m     = Node l m (insert x r)
                        | otherwise = Node (insert x l) m r

l r .

+9

lis the first parameter Nodeand therefore has a type Tree a(all left subtree). Leafon the other hand, it simply takes one value as a parameter, not a whole tree. Therefore, Leaf lit gives a type error, since it is trying to make a sheet from a whole tree. You probably just wanted linstead Leaf lin this place.

Also, what is the difference between Leaf xand Node Empty x Empty? Are you sure you need both constructors?

+2
source

All Articles