Getting values from Data in Haskell

Viewed 223
type Name = String
type Age = age
data Person = P Name Age derieving (eq)
type People = [Person]

smiths = [P "John" 21, P "Willy" 26]

How to get Johns age? Is there any function like (smiths!!0).age? Or is it only possible with pattern matching?

1 Answers

You can perform pattern matching:

(\(P _ a) -> a) (smiths !! 0)

But it might be better to define Person with record syntax:

data Person = P {
    name :: Name
  , age :: Age
  } deriving Eq

Then Haskell will automatically construct a "getter" age :: Person -> Age, and then you can access this with:

age (smiths !! 0)
Related