Genesis
Genesis

Reputation: 159

Printing data types - 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]

I'm looking for multiple ways of printing the firstNames of each element within the people list.

Printing these elements can be printed in forms such as:

Upvotes: 1

Views: 775

Answers (1)

Cactus
Cactus

Reputation: 27626

If you create a record type like Person, you get the following field selectors:

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

So you can map firstName over your list to turn your [Person] into a [String].

Printing the firstNames, then, is a mere mapM_ (putStrLn . firstName) people.

Upvotes: 4

Related Questions