(显示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}>>>
答案 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 的实例。a
是Show
的实例。对于您给定的样本数据,我们将获得:
Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
<{1},<<{3},{4}>,<{8},{7}>>>