Haskell No example related to the use of "print",

I want to write a toTree function 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 can’t understand 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 bug to fix, but I cannot find what causes it. How can I solve this problem?

+4
source share
1 answer

just add

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

the error just says that Haskell doesn't know how to show the type value Tree a0( printuses showfrom the class show)

And the easiest way is to automatically output it

Or you should 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 did something to give you something like this:

λ> toTree [1,2,3]
(left: (left: leaf) 2 (right: leaf)) 1 (right: (left: leaf) 3 (right: leaf))
+6
source

Source: https://habr.com/ru/post/1618254/


All Articles