Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell, finding element in bst

Tags:

haskell

data Bst a = Empty | Node (Bst a) a (Bst a)

lElems :: Ord a => a -> Bst a -> Int
lElems _ Empty = -1
lElems n (Node l m r)
                | n == m = n
                | n > m = lElems n r
                | n < m = lElems n l

Here you see definition of type and program. I want to return element if it's in the tree and -1 if not.

However, I had this problem 
 Couldn't match expected type `Int' with actual type `a'
      `a' is a rigid type variable bound by
          the type signature for lElems :: Ord a => a -> Bst a -> Int
          at C:\Users\User\workspace\s\src\Main.hs:3:11

Can someone explain me what is wrong here?

like image 620
Aleksander Monk Avatar asked Nov 17 '25 05:11

Aleksander Monk


1 Answers

In the n == m case, lElems returns n. From the type signature, the function is declared as always returning Int. This means that n must be an Int, and thus, can't be any Ord a.

Try converting n into Int before returning it; that will probably require you to further constrain a, though.

Instead of returning -1 in the case where you don't find what you're looking for, consider changing the return type to Maybe a, or perhaps an Either value.

like image 107
Mark Seemann Avatar answered Nov 18 '25 19:11

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!