在Haskell中,当您进行模式匹配时,您将被迫解压缩,如此示例代码
data Mlist a = Mlist [a]
instance Show a => Show (Mlist a) where
show (Mlist xs) = show xs
m = Mlist [1, 2, 3]
然后当我在解释器中输入m
时,我期待“{1,2,3}”,但我得到[1,2,3]。
这有什么不对?我认为这会有效,因为我在xs上使用show函数。
答案 0 :(得分:3)
show
始终会为您提供以String
开头并以'['
结尾的']'
。如果您需要'{'
和'}'
,只需替换它们。
instance Show a => Show (Mlist a) where
show (Mlist xs) = concat ["{", init . tail $ show xs, "}"]