[英]Haskell deriving Show for custom type
如何告訴haskell當在代數類型的變量列表上調用show
時,應該在每行之后插入“\\ n”?
type Customer = (Int, Int, [Int])
我試着這樣做:
instance of Show Customer where
show x = x ++ "\n"
但顯然我只能為“數據......”創造這樣的實例。 我怎么解決這個問題?
我需要派生Show
只是為了一個Customers列表,所以當我顯示它時,輸出很容易閱讀,每行一個客戶。
要僅顯示在不同的行上,請不要更改show
,只需執行unlines (map show customerList)
。 這將顯示它們中的每一個,然后將它們與中間的換行符重新組合在一起。
但是,您詢問是否要更改type
同義詞的show,因此以下是您的選項:
show
用於數據的基本序列化。 如果你想做一些不同的事情,你有幾個選擇:
display
功能中進行布局。 newtype
包裝數據。 稍后添加換行符
類型Customer =(Int,Int,[Int])
例1
displayC :: Customer -> String
displayC = (++"\n").show
例2
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
class Display a where
display :: a -> String
instance Display Customer where
display x = show x ++ "\n"
(請注意,您應該說instance Display Customer
而不是instance of Display Customer
。)
示例輸出:
*Main> display ((3,4,[5,6])::Customer)
"(3,4,[5,6])\n"
但是,應謹慎使用這些語言擴展。
例3
newtype Cust = Cust Customer
displayCust (Cust c) = show c ++ "\n"
例4
data CustomerTup = CTup Int Int [Int]
displayCTup (CTup a b cs) = show (a,b,cs) ++ "\n"
甚至更好,
data CustomerRec = CRec {custno::Int, custAge::Int, custMeasurements::[Int]}
deriving Show
displayCRec r = show (custno r,custAge r,custMeasurements r) ++ "\n"
你甚至可以堅持使用Show
實例的做事方式。 data
方式很好,因為有更多的類型安全性,記錄類型可以阻止你做出瑣碎的錯誤位置錯誤。
例5
stuff = unlines $ map show [(1,2,[3,4]),(5,6,[7,8,9])]
甚至
morestuff = unlines [show (1,2,[3,4]),
show (5,6,[7,8,9]),
"are all more numbery than",
show (True,4,False)]
AndrewC的一個很好的補充:
6.編寫一個函數,在類Show
的任何類型的文本表示中添加一個新行:
display :: Show a => a -> String
display = flip shows "\n"
例如:
> display (2, 3, [5, 7, 11])
"(2,3,[5,7,11])\n"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.