我想编写一个函数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
Run Code Online (Sandbox Code Playgroud)
我无法理解为什么我会收到此错误 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
Run Code Online (Sandbox Code Playgroud)
我知道这是一个简单的错误修复,但我似乎无法找到导致它的原因.我该如何解决这个问题?
加上
data Tree a = Leaf | Branch a (Tree a) (Tree a)
deriving Show
Run Code Online (Sandbox Code Playgroud)
错误只是说,哈斯克尔不知道如何来显示类型的值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 ++ ")"
Run Code Online (Sandbox Code Playgroud)
我刚刚做了些什么来给你这样的东西:
?> toTree [1,2,3]
(left: (left: leaf) 2 (right: leaf)) 1 (right: (left: leaf) 3 (right: leaf))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2502 次 |
| 最近记录: |