4.3 Taking a sum apart: when
Page 4 of 10
4.3.1 What when is
when chooses what to do by the variant of a value. Think of a sorting table in a warehouse, with one bin for each kind of delivery. Each parcel goes into the bin that matches its label, and each bin has its own instructions. when is that table:
- The subject is the value after
when: the parcel on the table. - An arm is one line under it: one bin, with its instructions.
- The pattern is the start of an arm, such as
is AtLocker(locker): what the arm matches. - After
->comes the arm's value: what thewhengives when that arm matches.
when is an expression, as if is (section 3.4): it gives the value of the arm that matched, so it can be a function's body or the value of a let.
4.3.2 Why when exists
is says which variant a value is. It does not give you the variant's fields. Try to read the locker of a locker delivery after testing it with is:
module pickup
--- Where a customer collects a parcel.
kind Delivery = AtDoor | AtLocker(locker: Text) | AtStore(store: Text, opens: Int)
--- Where to collect the parcel, written with `if` and `is` alone.
pickup_note(delivery: Delivery) -> Text = if delivery is AtLocker then "collect at locker {delivery.locker}" else "delivered to the door"
pub main() -> Unit
uses @console: Console[print]
=
@console.print(pickup_note(AtLocker(locker: "Station 14")))una check . reports:
[U1001] Error: `Delivery` has no field `locker`, and no function `locker` in scope applies
╭─[ src/pickup.una:7:101 ]
│
7 │ pickup_note(delivery: Delivery) -> Text = if delivery is AtLocker then "collect at locker {delivery.locker}" else "delivered to the door"
│ ───┬──
│ ╰──── `Delivery` has no field `locker`, and no function `locker` in scope applies
│
│ Note: run `una explain U1001` for an explanation
───╯The marks point at locker in delivery.locker. A Delivery has no field locker: only its variant AtLocker has one, and the checker does not use the if to narrow the value to that variant. The function has a second problem that no message points at: a store delivery falls into the else, so it would say "delivered to the door". An if covers the cases you thought of, and the rest fall into its else.
when solves both. Each arm names a variant and can bind its fields, which means give each field's value a name that the arm can use. And the checker makes sure that every variant has an arm.
4.3.3 How to write when
--- Binding fields by name. An arm binds only the fields it uses.
pickup_note(delivery: Delivery) -> Text
=
when delivery
is AtDoor -> "delivered to the door"
is AtLocker(locker) -> "collect at locker {locker}"
is AtStore(store, opens) -> "collect at {store} from {opens}:00"A when is written in four parts:
when delivery. The keyword, then the subject, on a line of its own.- The arms. One per line, indented two spaces under
when. is AtLocker(locker). The pattern:is, a variant of the subject's kind, and in parentheses the fields the arm binds.-> "collect at locker {locker}". The arm's value, after->. Inside it,lockeris the field's value.
A function whose body is a when is written in the long form, with = alone on its line: a when cannot follow = on the header's line. The step of this part has one small function for each form an arm takes, and its main prints one line for each. A when can also choose by a number or a text, and by a range of numbers; section 8.2 shows those arms.
4.3.3.1 Binding fields by name
is AtStore(store, opens) binds the fields store and opens under their own names. An arm binds only the fields it uses: is AtDoor binds nothing, and an arm may name a variant with fields and bind none of them.
collect at Harbour Road from 9:004.3.3.2 Binding a field under another name
field: name binds a field under a name of your choice. is AtStore(store: place) gives the field store the name place, and leaves opens out:
--- A field bound under another name, `store: place`, and a field left out.
store_name(delivery: Delivery) -> Text
=
when delivery
is AtStore(store: place) -> place
else -> "no store"Harbour Road; no storeUse it when the field's name is already taken in the function, or when another name reads better.
4.3.3.3 A field of a one-field variant under any name
A variant with one field binds it under any name, without the field: part. AtLocker has one field, locker, so is AtLocker(spot) binds it as spot:
--- A variant of one field binds it under any name.
locker_code(delivery: Delivery) -> Text
=
when delivery
is AtLocker(spot) -> "code for {spot}"
else -> "no code"code for Station 14; no codeOn a variant of two or more fields, a name must be a field's name: is AtStore(place) is U2009, "variant AtStore has no field place".
4.3.3.4 The else arm
else -> value matches every value that no arm before it matched. It is always the last arm. store_name uses one for every delivery that is not a store, and locker_code for every delivery that is not a locker.
4.3.3.5 An arm of several lines
When an arm needs more than one line, write nothing after ->, and put the arm's lines under it, indented two more spaces. The lines are a block, as a branch of an if over several lines is (section 3.4): let lines first, and the block's value is its last line.
--- An arm of several lines: a block, whose value is its last line.
opening(delivery: Delivery) -> Text
=
when delivery
is AtStore(store, opens) ->
let closes = opens + 9
"{store}, {opens}:00 to {closes}:00"
else -> "any time"Harbour Road, 9:00 to 18:004.3.3.6 when as the value of a let
A when can stand after let, and the name takes the value of the arm that matched:
let urgent = when locker
is AtDoor -> "no"
else -> "yes"
@console.print("collect soon: {urgent}")collect soon: yes4.3.4 Postage by zone and delivery
The module postage puts the forms to work on a parcel: a when with one arm per variant, a when with an else, and a when whose arms bind fields:
module postage
--- How far a parcel travels, nearest first.
kind Zone = Local | National | Abroad
--- Where a customer collects a parcel.
kind Delivery = AtDoor | AtLocker(locker: Text) | AtStore(store: Text, opens: Int)
--- The price of a zone, in cents. One arm for each variant, and no `else`.
zone_cents(zone: Zone) -> Int
=
when zone
is Local -> 300
is National -> 450
is Abroad -> 1200
--- The fee for bringing the parcel to the door. Every other place is free: `else`.
delivery_cents(delivery: Delivery) -> Int
=
when delivery
is AtDoor -> 250
else -> 0
--- Where to collect the parcel. Each arm binds the fields it uses, by name.
pickup_note(delivery: Delivery) -> Text
=
when delivery
is AtDoor -> "delivered to the door"
is AtLocker(locker) -> "collect at locker {locker}"
is AtStore(store, opens) -> "collect at {store} from {opens}:00"
pub main() -> Unit
uses @console: Console[print]
=
let store = AtStore(store: "Harbour Road", opens: 9)
@console.print("{zone_cents(National) + delivery_cents(AtDoor)} cents")
@console.print("{zone_cents(Abroad) + delivery_cents(store)} cents")
@console.print(pickup_note(store))
@console.print(pickup_note(AtLocker(locker: "Station 14")))zone_cents. One arm per variant, and noelse. IfZonegains a variant, thiswhenstops checking until it has an arm for it, as Howwhenbehaves shows. That is why it has noelse: anelsewould give a new zone the price of some other zone, silently.delivery_cents. One arm for the door, andelsefor every other place. Here theelsesays what the store means: every place but the door is free.is AtLocker(locker) -> …. The arm binds the fieldlockerand uses it.is AtDoorbinds nothing.is AtStore(store, opens) -> …. The names bind the fields of the same names.
una run . prints:
700 cents
1200 cents
collect at Harbour Road from 9:00
collect at locker Station 144.3.5 How when behaves
4.3.5.1 Every variant has an arm
A when over a sum must match every variant: each has an arm, or an else takes the rest. Add an island zone to Zone, and change nothing else:
--- a/src/postage.una
+++ b/src/postage.una
@@ -4 +4 @@
-kind Zone = Local | National | Abroad
+kind Zone = Local | National | Abroad | Islanduna check . reports:
[U2007] Error: `when` does not match variant `Island` of `Zone`
╭─[ src/postage.una:12:3 ]
│
12 │ when zone
│ ──┬─
│ ╰─── `when` does not match variant `Island` of `Zone`
│
│ Help: repair 1: add an arm for each missing variant, such as `is Island`, or an `else` arm
│
│ Note: run `una explain U2007` for an explanation
────╯The marks point at the when of zone_cents, and the message names the variant it does not match, Island. The Help line gives both repairs: an arm is Island, or an else. delivery_cents and pickup_note are not reported, since they do not choose by the zone. This is how a new variant shows you every place it touches: the checker lists each when that needs an arm.
4.3.5.2 One arm runs
The arms are tried from the top, and the first that matches gives the value. Only that arm runs. handover, in Check yourself: when, lists the store first and the door second, and gives the same answers as with the two arms the other way round, since a value matches only one variant.
4.3.5.3 Every arm gives the same type
All the arms of one when give values of one type, as both branches of an if do. In a function that gives back a Text, an arm that gives the number 3 is U2001, "note returns Text, found Int".
4.3.5.4 else comes last, and only when it is needed
An else before another arm is U2008: no value reaches the arms after it. An else after arms that already match every variant is U2008 too, since no value reaches it. Section 8.2 gives every rule of when.
4.3.6 when, if or is
Which to use:
| You want… | Use |
|---|---|
A Bool: is this value a given variant? |
is, such as delivery is AtLocker |
| A value for each variant, using its fields | when, with an arm for each variant |
| A value for one variant, and the same value for all the others | when with one arm and else |
| A choice by a condition that is not a variant, such as a weight | if |
| A rule that must be revisited when a variant is added | when with no else, so the checker reports it |
4.3.7 Check yourself: when
The step of this part ends with a function that says how the customer gets the parcel:
--- What the customer does to get the parcel. Check yourself: what does `main` print?
handover(delivery: Delivery) -> Text
=
when delivery
is AtStore(store: place, opens) -> "ask at {place} after {opens}:00"
is AtDoor -> "sign at the door"
else -> "code sent by text"main prints handover(AtDoor), handover(locker) and handover(store) on one line, where locker is AtLocker(locker: "Station 14") and store is AtStore(store: "Harbour Road", opens: 9). What does it print?
Show the answer
sign at the door; code sent by text; ask at Harbour Road after 9:00AtDoor matches the second arm. The locker matches neither the first nor the second, so it falls to else. The store matches the first arm, which binds the field store under the name place, and opens under its own name.