在((++))的第一个参数中,“ 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)++ ">"
Run Code Online (Sandbox Code Playgroud)
Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
Run Code Online (Sandbox Code Playgroud)
我应该得到:
<{1},<<{3},{4}>,<{8},{7}>>>
Run Code Online (Sandbox Code Playgroud)
Wil*_*sem 11
在您的行中:
Run Code Online (Sandbox Code Playgroud)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)++ ">"Run Code Online (Sandbox Code Playgroud)
因此,这里我们说的LTree a是show的一个实例,而给定的 a是的一个实例Show。对于您给定的样本数据,我们将获得:
Prelude> Node (Leaf 1) (Node (Node (Leaf 3) (Leaf 4)) (Node (Leaf 8) (Leaf 7)))
<{1},<<{3},{4}>,<{8},{7}>>>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90 次 |
| 最近记录: |