Reputation: 11
-- Binary Search tree
data Tree a = Empty
| Node a (Tree a) (Tree a)
deriving (Eq, Ord, Show)
leaf :: a -> Tree a
leaf x = Node x Empty Empty
insert :: (Ord a) => Tree a -> a -> Tree a
insert Empty x = leaf x
insert (Node x l r) y = case compare y x of
GT -> Node x l (insert r y)
_ -> Node x (insert l y) r
t1 :: Tree Int
t1 = Node 4 (leaf 3) (Node 7 (leaf 5) (leaf 10))
main = do
insert t1 8
Error message:
{-
Couldn't match expected type `IO b0' with actual type `Tree a0'
In the return type of a call of `insert'
In a stmt of a 'do' block: insert t1 8
-}
Upvotes: 1
Views: 2446
Reputation: 472
Your main
function is of type Tree Int
whereas compiled Haskell programs must have Type IO a
.
You can convert your Tree Int
value to IO (Tree Int)
with return :: a -> IO a
(signature simplified for your case):
main :: IO (Tree Int)
main = do
return (insert t1 8)
However, this won't print anything to the console because it simply returns your tree as a value. To print the result you can use print :: Show a => a -> IO ()
main :: IO ()
main = do
print (insert t1 8)
Upvotes: 5
Reputation: 64750
Your insert function results in a type Tree a
while main is typically a sequence of IO actions, type IO a
. Since Tree /= IO
you have a slight problem. Perhaps you would like to print the tree, main = print (insert t1 8)
.
Upvotes: 1