[英]Using show with a list of lists in Haskell
I'm having some trouble using show
to print the rows of a matrix given by a list of lists. 我在使用show
打印列表列表给出的矩阵行时遇到了一些麻烦。
I have this: 我有这个:
data Matrix = Mat Int [[Bit]]
deriving Eq
Where the argument Int
is the order of the squared matrix and Bit
is an Int (0 or 1). 其中,参数Int
是平方矩阵的阶数,而Bit
是Int(0或1)。 I need that my code to be able to do the following, with Matrix
as an instance of Show
: 我需要我的代码能够执行以下操作,并将Matrix
作为Show
的实例:
Main> Mat 3 [[0,0,1],[1,0,1],[1,1,1]
[0,0,1]
[1,0,1]
[0,0,1]
So far I only have: 到目前为止,我只有:
instance Show Matrix where
show (Mat i (x:xs)) = (show x) ++ "\n"
But this obviously only returns the first list. 但这显然只返回第一个列表。 Could you help me with this problem? 您能帮我解决这个问题吗? Thanks in advance. 提前致谢。
The simple way is to show
all rows, and put them on their own line each: 最简单的方法是show
所有行,并将每个行放在各自的行中:
instance Show Matrix where
show (Mat _ rows) = unlines $ map show rows
The slight drawback of that is that it also adds a newline after the last row, to avoid that, you can use 这样做的轻微缺点是,它还在最后一行之后添加了换行符,为避免这种情况,您可以使用
instance Show Matrix where
show (Mat _ rows) = intercalate "\n" $ map show rows
(needs an import of Data.List
for intercalate
) (需要导入Data.List
来intercalate
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.