[英]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.