使用'show'时没有(Show a)的实例

问题描述 投票:3回答:1

使用'show'时没有(Show a)的实例在'(++)'的第一个参数中,即'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}>>>
haskell show
1个回答
11
投票

在你的行:

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

你调用show aaa类型的元素,但是并不是说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是一个节目的实例给定aShow的一个实例。对于您给定的样本数据,我们获得:

Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
<{1},<<{3},{4}>,<{8},{7}>>>
© www.soinside.com 2019 - 2024. All rights reserved.