Home / Learn / 8 Choosing

Release v0.4.0Edition 0.2

8.2 when in full

Page 3 of 10

8.2.1 What when adds: arms by value

Section 4.3 taught when over a sum kind: the subject after when, one arm per variant, the fields an arm binds, the else arm, arms of several lines, and the rule that every variant needs an arm. That is the core of when, and most whens in a program are of that kind.

A when can also choose by a plain value: an Int, a Text or a Bool. Think of the aisle signs in a store. Aisle 1 is lighting, aisle 2 is rugs, and every other aisle is shown by its number. Or of the shelf a delivery goes to: one to four units on the low shelf, five to ten on the middle one, more on the floor. Each sign matches either one exact value or a range of values. This section teaches those arms, then every rule the checker and the verifier hold a when to.

8.2.2 Why when chooses by value

An else if chain can choose by a number, as zone_name of section 3.4 does: if zone == 1 then "home" else if zone == 2 then "neighbors" else "world". Each condition repeats zone ==, and nothing stops a later condition from testing another value, or a value an earlier one already took. With ten values, the chain is hard to read and easy to get wrong.

A when names the subject once, and each arm says only the value it matches. The checker then sees the whole choice at once. It reports an arm that repeats a value. And when there is no else, the verifier proves that the arms cover every value the subject can have, or shows you one they miss.

8.2.3 How to write literal and range arms

The step of this section has one function for each form, and its main prints one line for each:

src/aisles.unauna
--- Literal arms: whole numbers, then `else` for every other value.
aisle_name(aisle: Int) -> Text
=
  when aisle
    is 1 -> "lighting"
    is 2 -> "rugs"
    else -> "aisle {aisle}"

8.2.3.1 Literal arms

A literal is a value written out in the code, such as 2 or "RUG-07". An arm is 2 matches the value 2, and nothing else:

Output
rugs; aisle 7

A text works the same way:

src/aisles.unauna
--- Literal arms over a text.
family(sku: Text) -> Text
=
  when sku
    is "LAMP-01" -> "lamps"
    is "RUG-07" -> "rugs"
    else -> "other"
Output
rugs; other

The literal of an arm is a plain value: a text with interpolation braces, such as "{sku}", cannot be a pattern.

8.2.3.2 Literal arms over a Bool

A Bool has exactly two values, so arms for true and false cover it, with no else:

src/aisles.unauna
--- Literal arms over a `Bool`: `true` and `false` are all its values, so no `else` is needed.
gift_note(gift: Bool) -> Text
=
  when gift
    is true -> "wrap it"
    is false -> "no wrapping"
Output
wrap it; no wrapping

For a single condition, if gift then "wrap it" else "no wrapping" says the same in one line, and is the usual choice. The when form fits when each arm needs a block of its own.

8.2.3.3 Range arms

in 1..<10 matches a whole number from 1 up to 10, with 10 left out, and in 10..49 one from 10 to 49, with both ends included. A range has two forms: a..b includes its end b, and a..<b leaves it out.

src/aisles.unauna
--- Range arms: `..` includes its end, `..<` leaves it out.
box_size(units: Int) -> Text
=
  when units
    in 1..<10 -> "small box"
    in 10..49 -> "large box"
    else -> "pallet"
Output
small box; large box; pallet

9 units fit a small box, 10 need a large one, and 50 go on a pallet.

8.2.3.4 Arms that cover a refined range

When the subject's type is a range, such as Int in 0..999 of section 5.3, the arms can cover every value of it, and then the when needs no else. Literal and range arms may mix:

src/aisles.unauna
--- How full a shelf of up to 999 units is. A literal arm and two range arms cover every value
--- of the parameter's range, with no `else`.
fill(units: Int in 0..999) -> Text
=
  when units
    is 0 -> "empty"
    in 1..9 -> "almost empty"
    in 10..999 -> "stocked"
Output
empty; almost empty; stocked

is 0, in 1..9 and in 10..999 together match every whole number from 0 to 999, all the values units can have. How when behaves shows how una knows.

8.2.3.5 A choice inside an arm

An arm's value may itself be an if, or, in an arm of several lines, another when:

src/aisles.unauna
--- A `when` inside an arm, and an `if` inside another.
postage(zone: Zone, grams: Int) -> Int
=
  when zone
    is Local -> if grams > 1_000 then 400 else 300
    is National ->
      when grams
        in 0..500 -> 450
        else -> 600
    is Abroad -> 1200
Output
400; 600

A local parcel of 1200 grams takes the first arm, whose if gives 400. A national one of 700 grams takes the second arm, whose inner when has no range for 700 and gives its else, 600. An inner when starts on its own line, under the ->, as any arm of several lines does.

8.2.4 Shelves, boxes and rates

Here is the whole step, with each form in a function, and a main that prints one line for each:

src/aisles.unacheckrununa
module aisles

--- How far a parcel travels.
kind Zone = Local | National | Abroad

--- Where a customer collects a parcel.
kind Delivery = AtDoor | AtStore(store: Text)

--- Literal arms: whole numbers, then `else` for every other value.
aisle_name(aisle: Int) -> Text
=
  when aisle
    is 1 -> "lighting"
    is 2 -> "rugs"
    else -> "aisle {aisle}"

--- Literal arms over a text.
family(sku: Text) -> Text
=
  when sku
    is "LAMP-01" -> "lamps"
    is "RUG-07" -> "rugs"
    else -> "other"

--- Literal arms over a `Bool`: `true` and `false` are all its values, so no `else` is needed.
gift_note(gift: Bool) -> Text
=
  when gift
    is true -> "wrap it"
    is false -> "no wrapping"

--- Range arms: `..` includes its end, `..<` leaves it out.
box_size(units: Int) -> Text
=
  when units
    in 1..<10 -> "small box"
    in 10..49 -> "large box"
    else -> "pallet"

--- How full a shelf of up to 999 units is. A literal arm and two range arms cover every value
--- of the parameter's range, with no `else`.
fill(units: Int in 0..999) -> Text
=
  when units
    is 0 -> "empty"
    in 1..9 -> "almost empty"
    in 10..999 -> "stocked"

--- The arms are tried in order: 150 units are in both ranges, and the first arm wins.
rate(units: Int) -> Text
=
  when units
    in 100..999 -> "pallet rate"
    in 10..999 -> "case rate"
    else -> "unit rate"

--- A `when` inside an arm, and an `if` inside another.
postage(zone: Zone, grams: Int) -> Int
=
  when zone
    is Local -> if grams > 1_000 then 400 else 300
    is National ->
      when grams
        in 0..500 -> 450
        else -> 600
    is Abroad -> 1200

--- Where to collect a parcel, seen from the store `store`. The arm binds the field `store`
--- under another name, `other`, since `store` is already the parameter's name.
pickup(delivery: Delivery, store: Text) -> Text
=
  when delivery
    is AtDoor -> "at the door"
    is AtStore(store: other) -> if other == store then "here" else "at {other}"

--- The shelf for a number of units. Check yourself: what does `main` print for 0, 5 and 12?
shelf(units: Int) -> Text
=
  when units
    in 1..4 -> "low shelf"
    in 5..10 -> "middle shelf"
    else -> "floor"

--- Prints one line for each function.
pub main() -> Unit
  uses @console: Console[print]
=
  @console.print("{aisle_name(2)}; {aisle_name(7)}")
  let rug = family("RUG-07")
  let mug = family("MUG-03")
  @console.print("{rug}; {mug}")
  @console.print("{gift_note(true)}; {gift_note(false)}")
  @console.print("{box_size(9)}; {box_size(10)}; {box_size(50)}")
  @console.print("{fill(0)}; {fill(7)}; {fill(450)}")
  @console.print("{rate(150)}; {rate(50)}; {rate(5)}")
  @console.print("{postage(Local, grams: 1_200)}; {postage(National, grams: 700)}")
  let home = "Harbour Road"
  let here = pickup(AtStore(store: home), store: home)
  let there = pickup(AtStore(store: "Mill Lane"), store: home)
  @console.print("{here}; {there}")
  @console.print("{shelf(0)}; {shelf(5)}; {shelf(12)}")
  1. aisle_name and family. Literal arms over an Int and a Text, each ending with else.
  2. gift_note. Literal arms over a Bool, with no else.
  3. box_size. Range arms, then else for the values they leave out.
  4. fill. A literal arm and two range arms that cover the parameter's whole range.
  5. rate. Two ranges that overlap. How when behaves explains which one wins.
  6. postage. An if in one arm, and a when in another.
  7. pickup. A field bound under another name, store: other, as in section 4.3, since the parameter is already called store.
  8. let rug = family("RUG-07"). A text literal cannot stand inside the braces of an interpolation, so main names each result first, as A text inside an interpolation showed.

una run . prints:

Output
rugs; aisle 7
rugs; other
wrap it; no wrapping
small box; large box; pallet
empty; almost empty; stocked
pallet rate; case rate; unit rate
400; 600
here; at Mill Lane

8.2.5 How when behaves

8.2.5.1 The arms are tried in order

When the program runs, the arms are tried from the first to the last, and the first that matches gives the value. Over variants and literals, a value can match only one arm, since a repeated one is an error. Ranges may overlap, and then the order decides:

src/aisles.unauna
--- The arms are tried in order: 150 units are in both ranges, and the first arm wins.
rate(units: Int) -> Text
=
  when units
    in 100..999 -> "pallet rate"
    in 10..999 -> "case rate"
    else -> "unit rate"
Output
pallet rate; case rate; unit rate

150 is in both 100..999 and 10..999, and the first arm wins. Overlapping ranges are legal, but a reader must read them in order to know the answer. Prefer ranges that do not overlap, such as in 10..99 for the second arm, so that each arm can be read alone.

8.2.5.2 Literals and ranges must cover every value

Over variants, the checker counts the arms, as section 4.3 showed. Over literals and ranges with no else, counting is not enough: an Int has no end. So whether the arms cover every value is a proof obligation, of a kind that section 5.4 left for this section: exhaustive. Its goal is that the subject matches one of the arms, and the verifier proves it with the facts it has, among them the subject's type. una obligations . lists one for each when of the step that has literal or range arms and no else:

Terminal
$ una obligations .
proven   ob-31a6bafaaaa6 exhaustive    src/aisles.una:28:3 gift == true or gift == false
proven   ob-79340fc876dd exhaustive    src/aisles.una:44:3 units == 0 or units in 1..9 or units in 10..999

The goal of each is the arms joined by or. For gift_note, gift == true or gift == false holds for every Bool. For fill, units == 0 or units in 1..9 or units in 10..999 holds because the type of units says that it is between 0 and 999. Both are proven, so they cost nothing at run time. The other lines of the listing are the refinements of the three calls of fill in main, one per argument.

When the arms leave a gap, the obligation is refuted. Replace the else of box_size with a last range:

src/aisles.unadiff
--- a/src/aisles.una
+++ b/src/aisles.una
@@ -37,3 +37,3 @@
     in 10..49 -> "large box"
-    else -> "pallet"
+    in 50..1000 -> "pallet"
 
Diagnostic
[U5001] Error: exhaustiveness of this `when`, `units in 1..<10 or units in 10..49 or units in 50..1000`, is refuted
    ╭─[ src/aisles.una:35:3 ]
    │
 35 │   when units
    │   ──┬─
    │     ╰─── exhaustiveness of this `when`, `units in 1..<10 or units in 10..49 or units in 50..1000`, is refuted
    │ Help: repair 1: add an `else` arm, or arms for the values the others miss
    │ Note 2: counterexample: units = 1001

The first line quotes what the verifier tried to prove: that units is in one of the three ranges. The marks point at the when. Note 2 is the counterexample, a value that no arm matches: 1001, just past the last range. 0 and every negative number fall through too. The Help gives the two repairs: an else, or arms for the missing values. An else ends the question: a when with else has no exhaustive obligation at all.

8.2.5.3 else comes last

An else matches every value, so an arm after it can never run. Move the else of aisle_name to the top:

src/aisles.unadiff
--- a/src/aisles.una
+++ b/src/aisles.una
@@ -12,5 +12,5 @@
   when aisle
+    else -> "aisle {aisle}"
     is 1 -> "lighting"
     is 2 -> "rugs"
-    else -> "aisle {aisle}"
 
Diagnostic
[U2008] Error: this arm follows the `else` arm, so no value reaches it; `else` must be the last arm
    ╭─[ src/aisles.una:14:5 ]
    │
 13 │     else -> "aisle {aisle}"
    │     ──┬─
    │       ╰─── the `else` arm
 14 │     is 1 -> "lighting"
    │     ──┬─
    │       ╰─── this arm follows the `else` arm, so no value reaches it; `else` must be the last arm
    │
    │ Note: run `una explain U2008` for an explanation
────╯

The first mark shows the else, and the second an arm after it. The checker reports each arm that follows the else, here two, each as U2008.

8.2.5.4 Every arm can be reached

The same code, U2008, reports every other arm that no value can reach. This version of the step repeats a literal in family, repeats a variant in postage, and ends postage with an else after arms for every zone:

Diagnostic
error U2008 at src/aisles.una:23:5: this literal is already matched by an earlier arm
error U2008 at src/aisles.una:68:5: variant `Local` is already matched by an earlier arm
error U2008 at src/aisles.una:69:5: no value reaches this `else`: the arms above match every variant of `Zone`

Each message names the problem: "this literal is already matched by an earlier arm", "variant Local is already matched by an earlier arm", and "no value reaches this else: the arms above match every variant of Zone". Each one is a sign of a mistake in the choice, such as a copied arm whose value was never changed, so una refuses it instead of ignoring it.

8.2.5.5 Every arm gives the same type

All the arms of one when give values of one type, as both branches of an if do. An arm that gives a number where the others give a text is reported at that arm, U2001, as section 4.3 showed.

8.2.5.6 A pattern holds no condition

A pattern says which variant or which value an arm matches, and nothing more: an arm cannot add a condition of its own. Try to price heavy local parcels in an arm of their own:

src/aisles.unadiff
--- a/src/aisles.una
+++ b/src/aisles.una
@@ -60,3 +60,4 @@
   when zone
-    is Local -> if grams > 1_000 then 400 else 300
+    is Local if grams > 1_000 -> 400
+    is Local -> 300
     is National ->
Diagnostic
[U0101] Error: unexpected keyword `if`, expected `->`
    ╭─[ src/aisles.una:61:14 ]
    │
 61 │     is Local if grams > 1_000 -> 400
    │              ─┬
    │               ╰── unexpected keyword `if`, expected `->`

After the pattern is Local, the parser expected ->. Put the condition inside the arm, as postage does: is Local -> if grams > 1_000 then 400 else 300. A pattern also matches one level only: is AtStore(store: other) binds a field, and cannot say what the field must hold. Test the field in the arm's value instead.

8.2.5.7 A bound name is new

The names an arm binds exist only in that arm, and they are new names: an arm cannot bind a name that is already bound around the when, such as a parameter. Bind the field of pickup under its own name, store, which the parameter already has:

src/aisles.unadiff
--- a/src/aisles.una
+++ b/src/aisles.una
@@ -74 +74 @@
-    is AtStore(store: other) -> if other == store then "here" else "at {other}"
+    is AtStore(store) -> if store == store then "here" else "at {store}"
Diagnostic
[U1002] Error: `store` is already bound in this scope; a local cannot rebind another
    ╭─[ src/aisles.una:74:16 ]
    │
 70 │ pickup(delivery: Delivery, store: Text) -> Text
    │                            ──┬──
    │                              ╰──── first defined here
    │
 74 │     is AtStore(store) -> if store == store then "here" else "at {store}"
    │                ──┬──

The first mark shows the parameter, "first defined here", and the second the field bound again. Una refuses it, since store == store would no longer say which store is which. Bind the field under another name, is AtStore(store: other).

8.2.6 when, if or is

Section 4.3 compared the three for sums. With values in the picture, the choice is:

Which to use:

You want to… Use
A different value for each variant of a sum when, one arm per variant, no else
One question about the variant, as a Bool is: delivery is AtStore
A value for some exact numbers or texts when with literal arms, and else
A value for bands of numbers when with range arms that do not overlap, and else unless they cover the type
A choice by a condition that compares two values, such as other == store if
A condition on top of a variant when, with an if inside the arm

A when over a sum without else is the strongest of these: add a variant, and the checker points at every when that must say what it means. A when over numbers with ranges is the clearest way to write bands, since the verifier proves they leave no gap.

8.2.7 Check yourself: when by value

The step ends with a function that chooses a shelf by how many units arrive:

src/aisles.unauna
--- The shelf for a number of units. Check yourself: what does `main` print for 0, 5 and 12?
shelf(units: Int) -> Text
=
  when units
    in 1..4 -> "low shelf"
    in 5..10 -> "middle shelf"
    else -> "floor"

main prints shelf(0), shelf(5) and shelf(12) on one line. What does it print? And what would una check . report without the else?

Show the answer
Output
floor; middle shelf; floor

5 is not in 1..4, since 4 is that range's end. It is in 5..10, so it goes on the middle shelf. 12 is above 10, so it falls to else. 0 is in neither range either, so it falls to else too: an else catches the values below the ranges as well as above them. Without the else, the verifier would report U5001, since some values, such as 0 and 11, match no arm.

Next:8.3 What a branch proves: guards