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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With