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
答案 0 :(得分:4)
如果您创建类似Person
的记录类型,则会获得以下字段选择器:
firstName :: Person -> String
lastName :: Person -> String
age :: Person -> Int
因此,您可以map firstName
覆盖列表,将[Person]
变为[String]
。
然后,打印firstName
只是mapM_ (putStrLn . firstName) people
。