编写Show的实现

时间:2018-03-17 10:33:14

标签: haskell

我正在尝试为我的Tree类型编写自己的show实现。但是以下代码:

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

instance Show (Tree a) where
    show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
    show (Leaf a) = show a

屈服于:

main.hs:11:21: error:
    • No instance for (Show a) arising from a use of ‘show’
      Possible fix:
        add (Show a) to the context of the instance declaration
    • In the expression: show a
      In an equation for ‘show’: show (Leaf a) = show a
      In the instance declaration for ‘Show (Tree a)’
   |
11 |     show (Leaf a) = show a
   |                     ^^^^^^

我真的不明白编译器告诉我的是什么。

什么是正确的实施?为什么?

2 个答案:

答案 0 :(得分:3)

您需要明确声明类型变量Show存在a实例:

instance (Show a) => Show (Tree a) where
  show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
  show (Leaf a) = show a

答案 1 :(得分:1)

在您的实施中,您写道:

instance Show (Tree a) where
    show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
    show (Leaf a) = show a

这意味着您在show对象上调用a。但是Haskell无法保证它可以在show上调用a。因此,您需要添加类型约束Show a

instance Show a => Show (Tree a) where
    show (Branch a b) = show $ "<" ++ show a ++ "," ++ show b ++ ">"
    show (Leaf a) = show a