没有因使用“显示”而引起的(显示a)实例

时间:2019-04-30 10:03:38

标签: haskell show

(显示a)的任何实例均不因使用“显示”而产生 在“(++)”的第一个参数中,即“显示一个”

data LTree a = Leaf a | Node (LTree a) (LTree a)
instance Show (LTree a) where
    show (Leaf a) = "{" ++ show a ++ "}"
    show (Node fe fd) = "<" ++ (show fe)++ "," ++(show fd)++ ">"
Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))

我应该得到:

<{1},<<{3},{4}>,<{8},{7}>>>

1 个答案:

答案 0 :(得分:11)

在您的行中:

    show (Leaf a) = "{" ++ show a ++ "}"

您调用show a,其中a是类型a的元素,但不是表示该类型a是一个实例Show的值,因此您需要在instance声明中添加约束:

instance Show a => Show (LTree a) where
    show (Leaf a) = "{" ++ show a ++ "}"
    show (Node fe fd) = "<" ++ (show fe)++ "," ++(show fd)++ ">"

因此,我们在这里说LTree a是show give 的实例。aShow的实例。对于您给定的样本数据,我们将获得:

Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
<{1},<<{3},{4}>,<{8},{7}>>>