1
我已經定義了一個(矩陣)數據類型,作爲2D列表中的自定義數據類型:實例顯示列表爲
newtype Matrix a = M [[a]]
和Show
一個實例,如下所示:
instance Show a => Show (Matrix a) where
show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
其行爲像這樣:
> mat = M [[3,1,8],[6,3,0],[6,8,8]]
> mat
3 1 8
6 3 0
6 8 8
但是,我想處理它如何打印列表,因爲默認行爲看有點奇怪。我該如何指定?我試過這樣的東西:
instance Show a => Show ([Matrix a]) where
show mat = case mat of
[M a] -> intercalate "\n" (map (unwords . map show) a) ++ "\n"
(m:ms) -> show m ++ "\n" ++ show ms
instance Show a => Show (Matrix a) where
show (M a) = intercalate "\n" (map (unwords . map show) a) ++ "\n"
show (m:ms) = show m ++ "\n" ++ show ms
但我只是語法錯誤。我嘗試使用Google搜索這個問題,但我找不到任何東西(也許我使用了錯誤的關鍵字?)
在此先感謝。
編輯:
期望中的輸入和輸出:
mat1 = M [[1,2],[3,4]]
mat2 = M [[1,2],[3,4]]
> [mat1, mat2]
1 2
3 4,
1 2
3 4
你顯示了你已經有工作的輸入和輸出。你可以添加一個示例輸入和你遇到麻煩的所需輸出嗎? – Libby
這可能會有幫助!編輯。 – user3668541
我不確定這是否是一個好主意。 'Show'通常意味着產生單行數據表示,通常爲此使用Haskell語法。使用像這樣的多行文本將與所有標準容器(如數組,地圖,集合等)發生奇怪的結合(列表'[]'是例外的,並且可以自定義)。我會考慮使用自定義漂亮打印常規'代表性',它位於'Show'類之外。 – chi