【问题标题】:How can I call a show instace to print a binary tree?如何调用显示实例来打印二叉树?
【发布时间】: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)。

标签: haskell tree


【解决方案1】:

您的类型和值不匹配。你的函数left :: Tree a -> Tree a 说它返回一个Tree a,但函数体show e 返回一个String(因为show :: Show a => Tree a -> String)。

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

如果你想要一个函数,它接受一棵树并将它的左侧作为String返回,你需要将函数的结果类型更改为String,并添加前面提到的Show约束:@ 987654334@,身体会和你一样。

如果你想要一个函数,它接受一棵树并返回它的左侧作为一棵树,你应该保留你拥有的类型签名,但从主体中删除show(因为你没有转换成String):left (Nod x e d) = e

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    相关资源
    最近更新 更多