我怎么能告诉haskell,当show
在代数类型的变量列表上调用,每行后应该插入一个“\n”?
type Customer = (Int, Int, [Int])
我试图这样做:
instance of Show Customer where
show x = x ++ "\n"
但显然我只能为“数据......”之类的东西创建这样的实例。我该如何解决这个问题?
我需要导出
Show
只是为了一个客户列表,所以当我显示它时,输出很容易阅读,每行一个客户。
最佳答案
要仅显示在不同的行上,请不要更改 show
,就做unlines (map show customerList)
.这将显示它们中的每一个,然后将它们与中间的换行符重新组合在一起。
但是,您询问是否为 type
更改节目同义词,所以这里有你的选择:show
用于数据的基本序列化。如果你想做一些不同的事情,你有几个选择:
display
中定义你喜欢的布局方式。功能。 newtype
包装数据。 客户类型 = (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)]
关于Haskell 为自定义类型导出 Show,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13463678/