【发布时间】:2017-03-15 02:09:49
【问题描述】:
我正在尝试构造一个函数来打印二叉树,所以我这样做了:
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.
【问题讨论】:
-
提示:
left函数的结果应该是什么类型,你写的类型签名说明了什么? -
我正在尝试获取树的左侧,所以我收到一棵树并返回另一棵树的左孩子
-
如果你只是想让
left返回左子树,你不需要在里面使用show——show产生一个String。 -
我不明白...为什么不呢?如果我想打印树?
-
返回树与打印它不是一回事。如果你想打印树,你只需要
show;在这种情况下,left的返回类型应该是String,而不是Tree a(而且给你的函数起一个更具体的名称也可能是个好主意,例如printLeft)。