4.1 Records
Page 2 of 10
4.1.1 What a type and a kind are
A type is a set of values, together with what you may do with them. You met the built-in ones in chapter 2 and chapter 3: Int is the set of whole numbers, which you may add; Text is the set of texts, which you may join; Bool is the set of the two values true and false. The checker uses the types to refuse a program that, say, adds a text to a number.
The built-in types describe single values. A store's data is made of several values that belong together: a parcel has an order number, a weight and an address, and an address has a name, a street and a city. A kind is a type that you declare yourself, with the keyword kind, to describe such data. Una has four forms of kind, and this chapter teaches three of them:
- A record groups several named values that are all there at once. This section.
- A sum is one of several cases. Section 4.2.
- An alias gives an existing type another name. Aliases, in this section.
The fourth form, a kind with a condition such as "never negative", is in chapter 5.
Think of a record as a printed form, such as a shipping label with its boxes: "order", "weight", "name", "street", "city". The kind is the blank form. Each value of the kind is one filled-in copy, with something written in every box.
4.1.2 Why group values into a record
Without a record, a function that writes a parcel's label must take each part of the parcel as a parameter of its own:
module slips
--- The line printed on a parcel's label, from five loose values.
label(order: Text, grams: Int, name: Text, street: Text, city: Text) -> Text = "{order}: {name}, {street}, {city}, {grams} g"
pub main() -> Unit
uses @console: Console[print]
=
@console.print(label("A-1001", grams: 1200, name: "Corner Bakery", street: "12 Elm Road", city: "Northfield"))
@console.print(label("A-1002", grams: 300, name: "12 Elm Road", street: "Northfield", city: "Corner Bakery"))Like every example of this chapter, this one is a package of its own, made as chapter 2 explains, and the chapter's download, 04-kinds.tar.gz, holds them all. una run . prints:
A-1001: Corner Bakery, 12 Elm Road, Northfield, 1200 g
A-1002: 12 Elm Road, Northfield, Corner Bakery, 300 gThe second line is wrong: the street is printed as the name, and the store's name as the city. Every argument after the first has its label, so the call checks, but the values went into the wrong boxes, and all three are Text, so the checker cannot tell. The loose form has other costs too:
- Every function repeats the list. Each function that works on a parcel takes the same five parameters, and each call passes the same five values. Add a sixth part, a zone, and every one of them changes.
- A function gives back one value. A function that sends a parcel to a new address must give back a parcel: its order, weight and address together. With loose values, there is nothing to give back.
- Nothing says what belongs together. A reader of
labelsees five values, not one parcel and its address.
A record answers all three. It gathers the values under one name, a function takes it as one parameter, and a result can be a whole parcel.
4.1.3 How to write a record kind
4.1.3.1 The declaration
--- Where a parcel goes.
kind Address
name: Text
street: Text
city: TextA record kind is written in four parts:
kind. The keyword that declares a kind.Address. The kind's name. A kind's name starts with a capital letter, and each word in it starts with one too, as inReturnReason.- The fields. One per line, indented two spaces under the name. A field is one named part of the record: here
name,streetandcity. : Textafter each field. The field's type. Every value of the kind holds a value of that type in that field.
A field's type can be any type: Int, Text, Bool, another kind, or a list of values (chapter 10).
4.1.3.2 Building a value
To make a value of a record kind, write the kind's name like a call, and give every field, each with its name as a label: Address(name: "Corner Bakery", street: "12 Elm Road", city: "Northfield"). Written this way, the kind's name is the constructor, the function that builds a value of the kind. The labels work as the labels of a call (section 1.4), with one difference: a record of two or more fields labels every field, the first one too.
A record of one field may leave out the label. Note("fragile") builds the record Note of How a record behaves, whose one field is text.
4.1.3.3 Reading a field with a dot
parcel.grams reads the field grams of the value parcel. When the field is itself a record, the dots go on: parcel.address.city is the city of the parcel's address. It is the dot of method syntax, and when a value has a field of the name after the dot, the dot reads the field.
4.1.3.4 A field whose kind is a record
A field can hold a whole record. Parcel has a field address of kind Address, so each parcel holds an address with its three fields. The checker knows the type of every field, so parcel.address.city is a Text, and parcel.address.grams does not check.
4.1.4 An address inside a parcel
The module labels declares two record kinds, builds a parcel, and sends it to a second address:
module labels
--- Where a parcel goes.
kind Address
name: Text
street: Text
city: Text
--- A parcel ready to ship.
kind Parcel
order: Text
grams: Int
address: Address
--- The line printed on a parcel's label.
label(parcel: Parcel) -> Text = "{parcel.address.name}, {parcel.address.city}, {parcel.grams} g"
--- The same parcel, sent to another address. A record never changes: this builds a new one.
redirect(parcel: Parcel, address: Address) -> Parcel = Parcel(order: parcel.order, grams: parcel.grams, address: address)
pub main() -> Unit
uses @console: Console[print]
=
let home = Address(name: "Corner Bakery", street: "12 Elm Road", city: "Northfield")
let office = Address(name: "Corner Bakery", street: "4 Quay Street", city: "Southport")
let parcel = Parcel(order: "A-1001", grams: 1200, address: home)
let moved = redirect(parcel, address: office)
@console.print(label(parcel))
@console.print(label(moved))
@console.print("{home}")kind Addressandkind Parcel. Two record kinds.Parcelhas a field of kindAddress, so a parcel holds its address whole.parcel.address.city. Reading a field, and a field of a field.redirect. A record never changes after it is built. To "change" a field, you build a new record from the old one, with the new value in that field.parcelitself still goes to the first address, as the first line of the output shows.Address(name: "Corner Bakery", street: …, city: …). Building a value. Every field is given, each with its label.unaaccepts them in any order, butuna check .reports an order other than the declared one as not in canonical form (U7001), anduna fmt .puts them back in that order. There are no default values: a field left out is an error."{home}". Interpolation writes a record in the form you would type it in Una: its kind's name and every field.
una run . prints:
Corner Bakery, Northfield, 1200 g
Corner Bakery, Southport, 1200 g
Address(name: "Corner Bakery", street: "12 Elm Road", city: "Northfield")4.1.5 How a record behaves
The next step shows the rules of this part in one module. It declares a record of one field, an alias, and a record that holds both:
module packing
--- A note printed on a parcel: a record of one field.
kind Note
text: Text
--- A SKU is a text, under a name that says what it holds: an alias.
kind Sku = Text
--- A box on the packing table.
kind Box
sku: Sku
grams: Int
note: Note
--- The same box with another note. The box passed in does not change: a new one is built.
relabel(box: Box, text: Text) -> Box = Box(sku: box.sku, grams: box.grams, note: Note(text))
pub main() -> Unit
uses @console: Console[print]
=
let fragile = Note("fragile")
let lamp: Sku = "LAMP-01"
let box = Box(sku: lamp, grams: 1200, note: fragile)
let heavier = Box(sku: box.sku, grams: 1500, note: box.note)
@console.print("{box}")
@console.print("{heavier}")
@console.print("same box: {box == heavier}")
@console.print("{lamp.len} characters in {lamp}")
let marked = relabel(box, text: "this side up")
@console.print("{box.note.text}, then {marked.note.text}")una run . prints, among other lines:
Box(sku: "LAMP-01", grams: 1200, note: Note("fragile"))
Box(sku: "LAMP-01", grams: 1500, note: Note("fragile"))
same box: false
7 characters in LAMP-014.1.5.1 Every field, every time
A value of a record has a value in every field. There are no default values and no empty fields. Build a Parcel without one of its fields, and the checker reports U2009, "Parcel is missing field speed", as Leaving out a field shows. A field the kind does not declare is U2009 too: Address(…, zip: "1234") gives "Address has no field zip". Reading a field the kind does not have, as home.zip, is U1001, "Address has no field zip, and no function zip in scope applies".
4.1.5.2 A value never changes
A record value, once built, never changes. heavier is a second box, built from the fields of box with another weight: box still weighs 1200 grams, as the first line of the output shows. relabel works the same way, as a function: it builds a new box with the new note, and the box passed in keeps its own. A name that can take a new value, let edit, comes in chapter 9.
4.1.5.3 Equality, and how a record prints
== compares two records field by field: two records are equal when every field is equal. box == heavier is false, since their weights differ. Interpolation writes a record as you would build it, with its kind's name and every field labeled, and a record of one field without its label, as Note("fragile") shows. Interpolating a record works from edition 0.2 on, the edition of every package in this book.
4.1.5.4 Records are nominal
Records are nominal: two kinds with the same fields are two different types, because a kind is known by its name. Declare a Warehouse with the same three fields as Address, and pass one where redirect needs an address:
--- a/src/labels.una
+++ b/src/labels.una
@@ -4,0 +5,6 @@
+ name: Text
+ street: Text
+ city: Text
+
+--- A warehouse of the store. Its fields are those of an `Address`, but it is another kind.
+kind Warehouse
@@ -25 +31 @@
- let office = Address(name: "Corner Bakery", street: "4 Quay Street", city: "Southport")
+ let office = Warehouse(name: "North Depot", street: "4 Quay Street", city: "Southport")una check . reports:
[U2001] Error: argument `address` of `redirect` must be `Address`, found `Warehouse`
╭─[ src/labels.una:33:41 ]
│
33 │ let moved = redirect(parcel, address: office)
│ ───┬──
│ ╰──── argument `address` of `redirect` must be `Address`, found `Warehouse`
│
│ Note: run `una explain U2001` for an explanation
────╯Read it from the top. The first line names the problem: the argument address of redirect must be an Address, and it is a Warehouse. The marks point at office, the value of the wrong kind. The fields are the same, but a warehouse is not a customer's address, and the checker keeps the two apart. To send a parcel to the warehouse, build an Address from the warehouse's fields.
4.1.6 Aliases: another name for a type
kind Sku = Text, in the step of How a record behaves, is an alias: another name for an existing type. A Sku is a Text wherever one is expected, and the other way round, so lamp.len works on it as on any text, and "LAMP-01" can be given where a Sku goes. An alias is written kind, its name, = and the type it names. It may name another alias.
An alias documents what a field holds: sku: Sku says more than sku: Text. It does not keep two kinds apart the way a record does: a Sku and a customer's name are both Text, and the checker lets one go where the other goes. Chapter 5 adds a condition to an alias, as in kind Cents = Int where it >= 0, and the checker then proves that every value keeps it.
4.1.7 A record, loose values or an alias
Which to use:
| Your data… | Use |
|---|---|
| Has several parts that belong together, all there at once | A record, such as kind Parcel with its fields |
| Is passed around and given back as a whole | A record: one parameter, one result |
| Is one or two values that a single function needs | Plain parameters |
| Is an existing type under a name that says what it holds | An alias, such as kind Sku = Text |
| Must not be mixed up with another kind of the same shape | A record: records are nominal, aliases are not |
4.1.8 Check yourself: records
main, in the step of How a record behaves, ends with these two lines:
let marked = relabel(box, text: "this side up")
@console.print("{box.note.text}, then {marked.note.text}")box holds the note "fragile". What does the last line print?
Show the answer
fragile, then this side uprelabel builds a new box with the new note, and gives it back as marked. The box passed in, box, never changes, so its note still says fragile. Only marked has the new note.