Home / Learn

Release v0.4.0

8 Choosing

Page 1 of 10

Most of what a program decides is a choice: which price a parcel pays, what a status means, whether a refund is owed. You have already met the two tools Una has for it, if in chapter 3 and when in chapter 4. This chapter finishes them. You learn the forms of if that do something only when a condition holds, every kind of arm a when can have and the rules the checker holds it to, what the verifier knows inside each branch, and kinds whose values contain smaller values of the same kind. You end with a tracker that follows a parcel from packing to delivery or return.

What you'll build

A shipment tracker for a small store. It prices each parcel by zone and weight, keeps each shipment's history of events, ignores a scan that arrives twice, and works out the refund for a parcel that came back:

Output
A-1001: postage 600
A-1001: with the courier, tracking CX-4471
A-1001: no change, still with the courier, tracking CX-4471
A-1001: delivered on day 3
A-1002: postage 1200
A-1002: returned on day 12, refused at the door; refund 3900

You will learn to:

  • write an if without else, which runs its lines only when its condition holds, and choose the right form of if;
  • write when with literal and range arms, and read every rule the checker holds a when to;
  • use what the verifier knows inside a branch to prove a division, a refined result or a product;
  • declare a kind that contains itself, and write the recursive functions that walk it.

Download this chapter's packages: each step is a package under steps/, and the chapter's program is day-to-day/; run una check . and una run . in one.

Why it works this way

In many languages, a choice is easy to get almost right. A chain of conditions forgets a case, and that case quietly takes the last branch. A switch misses a value, and the program does nothing for it. A division sits a few lines after the test that made it safe, and an edit moves it out of the test's reach. Each of these runs without complaint until the day the forgotten case arrives.

Una checks choices before the program runs. A when must say what happens for every variant of a sum, and for every number or text its arms can receive: a variant without an arm is an error, a range that leaves a gap is a proof that fails, with the value that falls through it. An arm that no value can reach is an error too. Inside each branch, the verifier knows the condition that led there, so a division, a refined result or a product is proven where it is written, and moving it out of the branch makes the proof fail at once. And a kind may contain itself only when its values can end, so every value you build is finite.

Key idea

In Una, every choice covers every case, and each branch is proven with the facts of the path that leads to it.

View the Markdown

Next:8.1 Every form of if