Records
Chapter 6 of 9Grouping named values.
Named values, grouped together
A record groups named values. Where a variant is one of several things, a record has all of several things:
Records never change. To "change" one, make a copy with a new value:
The ..ada means "everything from ada", and age: 37 replaces one field. The original ada is untouched. Bert always shows fields in alphabetical order, so age comes before name.
The .. form can only replace fields that already exist. Adding a new one fails:
To have a record with an email, write all its fields out: { name: ada.name, age: ada.age, email: "ada@example.com" }.
A record in a signature
A record's type is written like the record, with a type in place of each value:
Read the signature as: a record with a name and an age goes in, text comes out.
Functions that take any record with the right field
A function that reads .name works on any record that has a name, whatever else is in it:
Without a signature, getName accepts any record that has a name. The signature on describe above asks for exactly a name and an age.
Taking a record apart with match
A pattern like { x, y } fits a record and gives each field a name you can use in the arm:
You only list the fields you need. A record always fits, so one arm is enough. Record patterns also sit inside other patterns, such as an Ok holding a record: