如何调用show instace来打印二叉树?

时间:2017-03-15 02:09:50

标签: haskell tree

我正在尝试构建一个函数来打印二叉树,所以我这样做了:

instance Show a => Show (Tree a) where
  show Null = "_"
  show (Nod x e d) = "(" ++ show x ++ " " ++ show e ++ " " ++ show d ++ ")"


left :: Tree a -> Tree a
left (Nod x e d) = show e

但是我收到了这条消息:

Couldn't match type `[Char]' with `Tree a'
Expected type: Tree a
  Actual type: String
In the return type of a call of `show'
In the expression: show e
In an equation for `left': left (Nod x e d) = show e Failed, modules loaded: none.

1 个答案:

答案 0 :(得分:0)

您的类型和值不匹配。您的函数left :: Tree a -> Tree a表示它返回Tree a,但函数正文show e会返回String(因为show :: Show a => Tree a -> String)。

如果你想要一个将树打印到stdout的函数,你需要有一个执行IO的函数和一个Show约束,以便知道树的元素是{{1}的实例},所以它的类型必须是:Show,正文将是:left :: Show a => Tree a -> IO ()left (Nod x e d) = print e

如果你想要一个带树的函数并将其左侧作为print :: Show a => a -> IO ()返回,你需要将函数的结果类型更改为String,并添加前面提到的{{约束:String,身体就像你拥有它一样。

如果你想要一个带树的函数并将它的左侧返回作为树,你应该保留你拥有的类型签名,但是要从身体中删除Show (因为您没有转换为left :: Show a => Tree a -> String):show