使用'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}>>>
在你的行:
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
是一个节目的实例给定a
是Show
的一个实例。对于您给定的样本数据,我们获得:
Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
<{1},<<{3},{4}>,<{8},{7}>>>