当前位置:  开发笔记 > 编程语言 > 正文

Haskell没有使用'print'产生的实例

如何解决《Haskell没有使用'print'产生的实例》经验,为你挑选了1个好方法。

我想编写一个函数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> Carsten..:

加上

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

错误只是说,哈斯克尔不知道如何来显示类型的值Tree a0(print使用showShow类型级)

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

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

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

推荐阅读
周扒pi
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有