Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell No instance arising from a use of 'print'

Tags:

haskell

I want to write a function toTree that converts a list of values to a binary tree:

data Tree a = Leaf | Branch a (Tree a) (Tree a)
tree = Branch 6 (Branch 3 Leaf Leaf) (Branch 9 Leaf Leaf)

split :: [a] -> ([a], [a])
split lst = splitAt (((length lst) + 1) `div` 2) lst
toTree :: [a] -> Tree a
toTree (x: xs) = Branch x (toTree xm) (toTree xl) where (xm, xl) = split xs
toTree [] = Leaf

I cannot figure why I get this error on toTree [1,2,3]

 No instance for (Show (Tree a0)) arising from a use of `print'
 In the first argument of `print', namely `it'
 In a stmt of an interactive GHCi command: print it

I know this is a simple error to fix but I cannot seem to find what is causing it. How can I resolve this issue?

like image 738
donth77 Avatar asked Dec 02 '15 09:12

donth77


1 Answers

just add

data Tree a = Leaf | Branch a (Tree a) (Tree a)
            deriving Show

the error just says that Haskell does not know how to show a value of type Tree a0 (print is using show from the Show type-class)

And the easiest way is to auto-derive it

Or you have to implement it yourself using something like this:

instance (Show a) => Show (Tree a) where
  show Leaf = "leaf"
  show (Branch v l r) = "(left: " ++ show l ++ ") " ++ show v ++ " (right: " ++ show r ++ ")"

where I just made something up to give you something like this:

λ> toTree [1,2,3]
(left: (left: leaf) 2 (right: leaf)) 1 (right: (left: leaf) 3 (right: leaf))
like image 172
Random Dev Avatar answered Nov 15 '22 07:11

Random Dev