Haskell派生Show为自定义类型

Sus*_*ded 7 haskell instance show

如何告诉haskell在show代数类型的变量列表上调用时,应在每行之后插入"\n"?

type Customer = (Int, Int, [Int])
Run Code Online (Sandbox Code Playgroud)

我试着这样做:

instance of Show Customer where
show x = x ++ "\n"
Run Code Online (Sandbox Code Playgroud)

但显然我只能为"数据......"创造这样的实例.我怎么解决这个问题?

我需要派生出Show一个客户列表,这样当我显示它时,输出很容易阅读,每行一个客户.

And*_*ewC 10

要只显示在不同的行上,请不要更改show,只需这样做unlines (map show customerList).这将显示它们中的每一个,然后将它们与中间的换行符重新组合在一起.


但是,您询问有关更改show的type同义词,因此以下是您的选项:

show用于数据的基本序列化.如果你想做一些不同的事情,你有几个选择:

  1. 编写一个在这个实例中执行此操作的函数.
  2. 制作您自己的Display类,并定义您希望如何在其display功能中进行布局.
  3. 使用a newtype来包装数据.
  4. 声明您自己的客户类型.
  5. 稍后添加换行符

    类型Customer =(Int,Int,[Int])

例1

displayC :: Customer -> String
displayC = (++"\n").show
Run Code Online (Sandbox Code Playgroud)

例2

{-# LANGUAGE TypeSynonymInstances,  FlexibleInstances #-}
class Display a where
  display :: a -> String

instance Display Customer where
   display x = show x ++ "\n"
Run Code Online (Sandbox Code Playgroud)

(注意你应该说instance Display Customer而不是instance of Display Customer.)

示例输出:

*Main> display ((3,4,[5,6])::Customer)
"(3,4,[5,6])\n"
Run Code Online (Sandbox Code Playgroud)

但是,应谨慎使用这些语言扩展.

例3

newtype Cust = Cust Customer
displayCust (Cust c) = show c ++ "\n"
Run Code Online (Sandbox Code Playgroud)

例4

data CustomerTup = CTup Int Int [Int]
displayCTup (CTup a b cs) = show (a,b,cs) ++ "\n"
Run Code Online (Sandbox Code Playgroud)

甚至更好,

data CustomerRec = CRec {custno::Int, custAge::Int, custMeasurements::[Int]}
  deriving Show
displayCRec r = show (custno r,custAge r,custMeasurements r) ++ "\n"
Run Code Online (Sandbox Code Playgroud)

你甚至可以坚持Show实例的做事方式.该data方法是好的,因为有更多的类型安全,并记录类型阻止你做琐碎的错误位置的错误.

例5

stuff = unlines $ map show  [(1,2,[3,4]),(5,6,[7,8,9])]
Run Code Online (Sandbox Code Playgroud)

甚至

morestuff = unlines [show (1,2,[3,4]), 
                     show (5,6,[7,8,9]),
                     "are all more numbery than",
                     show (True,4,False)]
Run Code Online (Sandbox Code Playgroud)