【问题标题】:Class Instances and ambiguous occurence in HaskellHaskell 中的类实例和模棱两可的出现
【发布时间】:2011-09-20 23:47:32
【问题描述】:

代码如下:

data Tree t = NilT
            | Node t (Tree t) (Tree t)

instance Show (Tree t) where
  show NilT = ""
  show Node t l r = (show t) ++ ", " ++ (show l) ++ ", " ++ (show r)

如何在默认设置的“t show”中使用“show”,在自己定义的树形数据中使用“show”?

【问题讨论】:

标签: haskell instance ambiguous


【解决方案1】:

要使用show t,您必须将约束Show t 添加到您的实例定义中。

instance Show t => Show (Tree t) where
    show NilT = ""
    show (Node t l r) = show t ++ ", " ++ show l ++ ", " ++ show r

您的模式 Node t l r 周围也缺少括号,我删除了对 show 的调用周围的括号,因为它们是多余的,因为函数应用程序已经具有最高优先级。

【讨论】:

  • 您可能还想查看hlint,它为您做了一些括号修复工作(除其他外)。
【解决方案2】:

附注:有一个函数Data.List.intersperse 用于在列表元素之间放置一个值。

show (Node t l r) = concat $ intersperse ", " [show t, show l, show r]

或者更短,正如哈马尔指出的那样:

show (Node t l r) = intercalate ", " [show t, show l, show r]

很遗憾你不能写map show [t, l, r],因为列表元素需要有一个唯一的类型。

【讨论】:

  • 还有Data.List.intercalate,也是拼接结果的。
  • 哦,谢谢,我已经在想了,因为我在 TextByteString 看到过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
  • 2012-12-18
  • 2014-08-12
  • 2018-05-10
  • 2012-10-18
相关资源
最近更新 更多