🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Records

A record is a custom type whose fields have names. The field names make values clear to build and to read.

A record value prints with its field names

The value is built by naming each field. print shows the record in its Show form.

data Person = Person { personName :: String, personAge :: Int } deriving (Show, Eq)

ana :: Person
ana = Person { personName = "Ana", personAge = 31 }

main :: IO ()
main = print ana

Field names are accessor functions

This value is built by position, with no field names. personName and personAge then read the fields back out.

data Person = Person { personName :: String, personAge :: Int } deriving (Show, Eq)

ana :: Person
ana = Person "Ana" 31

main :: IO ()
main = print (personName ana, personAge ana)

An update builds a new value

The update changes only the age field. The pair shows the original value first and the updated value second.

data Person = Person { personName :: String, personAge :: Int } deriving (Show, Eq)

ana :: Person
ana = Person { personName = "Ana", personAge = 31 }

older :: Person
older = ana { personAge = 32 }

main :: IO ()
main = print (ana, older)

Example

data Person = Person { personName :: String, personAge :: Int } deriving (Show, Eq)

ana :: Person
ana = Person { personName = "Ana", personAge = 31 }

bob :: Person
bob = Person "Bob" 31

celebrate :: Person -> Person
celebrate p = p { personAge = personAge p + 1 }

main :: IO ()
main = print (personName (celebrate ana), personAge (celebrate ana), ana == bob)

Key points

  • Record form: data Person = Person { personName :: String, personAge :: Int } deriving (Show, Eq) defines a record type.
  • Field names: personName and personAge name the two fields and state their types.
  • Building by name: Person { personName = "Ana", personAge = 31 } sets each field by its name.
  • Building by position: Person "Ana" 31 builds the same value with the fields in declaration order.
  • Accessors: each field name is also a function, so personAge p gives the age stored in p.
  • Update: p { personAge = 32 } builds a new value with that field changed and leaves p unchanged.

In this example, ana is built by field names and bob is built by position. celebrate reads the age with personAge and builds a new value with the age raised by one. The main line prints the name and new age of the updated value. ana == bob is False because the Eq support compares all fields and the names differ.

Note

the deriving (Show, Eq) part of this lesson makes Person values printable and comparable.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

If ana is a Person value, what does ana { personAge = 32 } do?