Reputation: 65
I'm having some trouble using show
to print the rows of a matrix given by a list of lists.
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). I need that my code to be able to do the following, with Matrix
as an instance of 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.
Upvotes: 1
Views: 571
Reputation: 183858
The simple way is to show
all rows, and put them on their own line each:
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
)
Upvotes: 8