[英]Using show with a list of lists in Haskell
我在使用show
打印列表列表给出的矩阵行时遇到了一些麻烦。
我有这个:
data Matrix = Mat Int [[Bit]]
deriving Eq
其中,参数Int
是平方矩阵的阶数,而Bit
是Int(0或1)。 我需要我的代码能够执行以下操作,并将Matrix
作为Show
的实例:
Main> Mat 3 [[0,0,1],[1,0,1],[1,1,1]
[0,0,1]
[1,0,1]
[0,0,1]
到目前为止,我只有:
instance Show Matrix where
show (Mat i (x:xs)) = (show x) ++ "\n"
但这显然只返回第一个列表。 您能帮我解决这个问题吗? 提前致谢。
最简单的方法是show
所有行,并将每个行放在各自的行中:
instance Show Matrix where
show (Mat _ rows) = unlines $ map show rows
这样做的轻微缺点是,它还在最后一行之后添加了换行符,为避免这种情况,您可以使用
instance Show Matrix where
show (Mat _ rows) = intercalate "\n" $ map show rows
(需要导入Data.List
来intercalate
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.