如何在haskell中将数组显示为来自新数据类型的字符串?

时间:2013-03-15 15:20:12

标签: haskell

在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函数。

1 个答案:

答案 0 :(得分:3)

列表上的

show始终会为您提供以String开头并以'['结尾的']'。如果您需要'{''}',只需替换它们。

instance Show a => Show (Mlist a) where
    show (Mlist xs) = concat ["{", init . tail $ show xs, "}"]