打印数据类型 - Haskell

时间:2015-12-17 01:42:23

标签: list haskell

data Person = Person { firstName :: String
                     , lastName :: String
                     , age :: Int
                     } deriving (Show)


buffy = Person "Buffy" "Summers" 22
burt = Person "Burt" "Reynolds" 23
cloud = Person "Cloud" "Strife" 22
rick = Person "Rick" "Sanchez" 21

people = [buffy,burt,cloud,rick]

我正在寻找多种方法来打印firstName列表中每个元素的people个。

打印这些元素可以采用以下形式打印:

  • x1,x2,x3,...xn
  • [x1,x2,x3,...xn]

  • 多行:

    x1  
    x2   
    x3   
    ...  
    xn
    

1 个答案:

答案 0 :(得分:4)

如果您创建类似Person的记录类型,则会获得以下字段选择器:

firstName :: Person -> String
lastName :: Person -> String
age :: Person -> Int

因此,您可以map firstName覆盖列表,将[Person]变为[String]

然后,打印firstName只是mapM_ (putStrLn . firstName) people