我想编写一个函数toTree,它将值列表转换为二叉树:
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
我无法理解为什么我会收到此错误 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
我知道这是一个简单的错误修复,但我似乎无法找到导致它的原因.我该如何解决这个问题?
加上
data Tree a = Leaf | Branch a (Tree a) (Tree a) deriving Show
错误只是说,哈斯克尔不知道如何来显示类型的值Tree a0
(print
使用show
从Show
类型级)
最简单的方法是自动导出它
或者您必须使用以下内容自行实现:
instance (Show a) => Show (Tree a) where show Leaf = "leaf" show (Branch v l r) = "(left: " ++ show l ++ ") " ++ show v ++ " (right: " ++ show r ++ ")"
我刚刚做了些什么来给你这样的东西:
?> toTree [1,2,3] (left: (left: leaf) 2 (right: leaf)) 1 (right: (left: leaf) 3 (right: leaf))