Haskell没有使用' print'

时间:2015-12-02 09:30:26

标签: haskell

我想编写一个将值列表转换为二叉树的函数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

我知道这是一个修复的简单错误,但我似乎找不到导致它的原因。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

只需添加

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

错误只是说Haskell不知道如何显示类型为Tree a0的值(print正在使用show Show } type-class)

最简单的方法是自动导出它

或者您必须使用以下内容自行实现:

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))