簡體   English   中英

在Haskell中將show與列表列表一起使用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM