pantry
A kitchen pantry: items with amounts, a shopping list of what ran out, and totals per measure.
This example is about data and contracts, with no outside world beyond the console. It declares every form of kind, gives several functions a contract, and lets the solver prove that no amount goes below zero and that no division is by zero. Read it when you want to see how types and contracts replace the checks that other languages leave to tests.
What it demonstrates:
kinddeclarations of every form: a choice, an alias, a record and a generic record;- refinements with
where:Nat, and a list that is never empty; - contracts with
requiresandensures; Optionand an exhaustivewhen;- a generic function that takes a function value;
- seven
exampleblocks.
Run it
From this directory:
una check . # copy examples/pantry
una test .
una run .
una build .
./target/una/pantry-exampleuna run . and the native executable print:
to buy: rice, oil
grams in stock: 700The pantry holds no rice and no oil, so they are on the list. Rice (0 g) and flour (700 g) are the items measured in grams. una test . runs the seven examples of src/pantry/stock.una:
example pantry.stock "restocking adds to the amount" ... ok
example pantry.stock "using up takes from the amount" ... ok
example pantry.stock "the shopping list names what ran out" ... ok
example pantry.stock "totals count one measure only" ... ok
example pantry.stock "an item the pantry does not have amounts to zero" ... ok
example pantry.stock "a bin counts the entries that match" ... ok
example pantry.stock "the average of three counts is rounded down" ... ok
7 examples: 7 passed, 0 failedHow it works
The package has two modules. pantry.stock holds the types and the functions, with their examples. pantry.main builds this morning's stock and prints the report. It may only print.
The types
pub kind Measure = Grams | Pieces | Milliliters
...
pub kind Label = Text
pub kind Item
name: Text
amount: Nat
measure: Measure
...
pub kind Bin[T]
label: Label
entries: List[T]
...
pub kind NonEmpty[T] = List[T] where it.len > 0Measureis a choice: a value is exactly one of the three variants.Labelis an alias: another name forText, which documents what the text means.Itemis a record. Itsamountis aNat, anIntthat is never negative. The solver checks that fact at every place that builds anItem.Bin[T]is a generic record: a labeled group of anything.NonEmpty[T]is a refinement: aList[T]with a fact that the solver must prove wherever a value of that type is made.
Contracts that keep amounts honest
pub use_up(item: Item, used: Nat) -> Item
requires used <= item.amount
ensures result.amount == item.amount - used
=
Item(name: item.name, amount: item.amount - used, measure: item.measure)item.amount - used must be a Nat, since amount is one. The solver proves it from the requires: whoever calls use_up must show that there is enough. restock has the matching ensures for addition. missing and shopping_list promise a result no longer than their input (ensures result.len <= items.len), and count_where a count no larger than its bin (ensures result <= bin.entries.len). A caller can rely on these without reading the bodies.
A division that cannot be by zero
pub average(counts: NonEmpty[Int]) -> Int = counts.sum() / counts.lenEvery division carries an obligation: the divisor is not zero. The parameter type says the list has at least one entry, so the solver proves it here. The caller pays instead: the example average([2, 4, 10]) must show that its list is not empty, and the solver proves that too.
Absence and generics
find returns an Option[Item] from first_where, and amount_of matches on it:
pub amount_of(items: List[Item], name: Text) -> Nat
=
when find(items, name)
is Some(item) -> item.amount
is None -> 0count_where[T] works on a Bin of any type. It takes the test to apply as a function value, keep: fn(T) -> Bool, and passes it straight on to filter.
What una check proves
una obligations . lists 27 obligations, all proven. Among them:
- each
ensuresabove, for every input; - every
Natstays at or above zero, includingitem.amount - used, whichuse_up'srequiresmakes safe; averagenever divides by zero;- every call meets its callee's
requires, such as the call touse_upin its example,4 <= Item(name: "eggs", amount: 6, measure: Pieces).amount.
The type checker adds the rest without the solver: every when on a choice covers all its variants, and every value has the type its place requires.
Common mistakes
Taking more than there is
Delete the requires used <= item.amount line of use_up. una check . reports that the new amount may be negative (its location and repairs shown; the notes after them are left out):
[U5001] Error: refinement `(item.amount - used) >= 0` is refuted
╭─[ src/pantry/stock.una:32:33 ]
│
32 │ Item(name: item.name, amount: item.amount - used, measure: item.measure)
│ ─────────┬────────
│ ╰────────── refinement `(item.amount - used) >= 0` is refuted
│
│ Help 1: repair 1: add a guard (`if` or a `when` arm) that handles the values where `(item.amount - used) >= 0` does not hold
│
│ Help 2: repair 2 (escape: checked; a runtime test replaces the static proof: the program fails at run time where the proof would have rejected it; it counts against [escape_budget] and is listed in the build report): check the value with `checked(value, (item.amount - used) >= 0) else fail <Variant>`
...The diagnostic points at item.amount - used on line 32. Its repairs are a guard, or a checked that tests the value at run time. Here the right fix is the requires: running out is the caller's decision, not something use_up can repair.
Dividing by the length of any list
Change the parameter of average to counts: List[Int]. The solver finds the empty list:
[U5001] Error: division obligation `counts.len != 0` is refuted
╭─[ src/pantry/stock.una:67:41 ]
│
67 │ pub average(counts: List[Int]) -> Int = counts.sum() / counts.len
│ ────────────┬────────────
│ ╰────────────── division obligation `counts.len != 0` is refuted
│
│ Help: repair 1: guard the division with `if counts.len != 0`
│
│ Note 1: obligation ob-57d6a6e35832 (division) is refuted: counts.len != 0
│
│ Note 2: counterexample: counts = List#0, counts.len = 0
│
│ Note 3: run `una explain U5001` for an explanation
────╯The repair offers a guard. The example prefers a type, NonEmpty[Int], because it states the rule once, in the header, where every caller sees it.
Forgetting a case
Delete the is None -> 0 arm of amount_of:
[U2007] Error: `when` does not match variant `None` of `Option`
╭─[ src/pantry/stock.una:56:3 ]
│
56 │ when find(items, name)
│ ──┬─
│ ╰─── `when` does not match variant `None` of `Option`
│
│ Help: repair 1: add an arm for each missing variant, such as `is None`, or an `else` arm
│
│ Note: run `una explain U2007` for an explanation
────╯Extend it
- Name the units. Add
pub unit_name(measure: Measure) -> Text, awhenwith one arm per measure ("g","pcs","ml"). Then add a variant,Kilograms, toMeasure.una check .reports a U2007 at yourwhen: the checker finds every match that the new case affects. - Warn before it runs out. Add
pub running_low(items: List[Item], below: Nat) -> List[Item]withensures result.len <= items.len, and an example where eggs at 2 are below 3 and flour at 700 is not. Hint:missinghas the same shape. - Use edition
0.2. Setedition = "0.2"inuna.toml. The package still checks. Then replace thefoldinmainthat joins the names withjoin(needed, separator: ", "), a prelude function of edition0.2. The output does not change.
Learn more
- Construct pages:
kind,where,requires,ensures,when,example. - Learn, the tutorial on the Una website: "Kinds" (
/learn/kinds/); "Collections" (/learn/collections/); "Contracts and the verifier" (/learn/contracts/). - Specification: kinds (spec/03 §2), refinements (spec/03 §3), clauses (spec/04 §2), obligation generation (spec/12 §3), the prelude (spec/14 §1).
Edition
Edition 0.1 (edition). It also checks unchanged under edition 0.2, as the third exercise shows.
Files
[package]
name = "pantry-example"
version = "0.1.0"
edition = "0.1"
[run]
entry = "pantry.main"
grants = ["console"]module pantry.main
import pantry.stock (Grams, Item, Milliliters, Pieces, shopping_list, total)
--- What the pantry holds this morning.
stock() -> List[Item] = [Item(name: "rice", amount: 0, measure: Grams), Item(name: "flour", amount: 700, measure: Grams), Item(name: "eggs", amount: 6, measure: Pieces), Item(name: "oil", amount: 0, measure: Milliliters)]
pub main() -> Unit
uses @console: Console[print]
=
let items = stock()
let needed = shopping_list(items)
let line = needed.fold(initial: "", step: fn(line, name) -> if line == "" then name else "{line}, {name}")
@console.print("to buy: {line}")
let grams = total(items, measure: Grams)
@console.print("grams in stock: {grams}")module pantry.stock
--- How an item is measured.
pub kind Measure = Grams | Pieces | Milliliters
--- A shelf label, as printed on the shelf.
pub kind Label = Text
pub kind Item
name: Text
amount: Nat
measure: Measure
--- A labeled group of anything: a shelf of items, a box of jars.
pub kind Bin[T]
label: Label
entries: List[T]
--- A list with at least one entry.
pub kind NonEmpty[T] = List[T] where it.len > 0
--- Adds `added` to an item.
pub restock(item: Item, added: Nat) -> Item
ensures result.amount == item.amount + added
=
Item(name: item.name, amount: item.amount + added, measure: item.measure)
--- Takes `used` from an item that has enough of it.
pub use_up(item: Item, used: Nat) -> Item
requires used <= item.amount
ensures result.amount == item.amount - used
=
Item(name: item.name, amount: item.amount - used, measure: item.measure)
--- The items that have run out.
pub missing(items: List[Item]) -> List[Item]
ensures result.len <= items.len
=
items.filter(keep: fn(i) -> i.amount == 0)
--- The names of the items to buy, in pantry order.
pub shopping_list(items: List[Item]) -> List[Text]
ensures result.len <= items.len
=
missing(items).map(each: fn(i) -> i.name)
--- How much of one measure the pantry holds.
pub total(items: List[Item], measure: Measure) -> Int = items.fold(initial: 0, step: fn(sum, i) -> if i.measure == measure then sum + i.amount else sum)
--- The item called `name`, when the pantry has it.
pub find(items: List[Item], name: Text) -> Option[Item] = items.first_where(keep: fn(i) -> i.name == name)
--- The amount left of `name`, zero when the pantry has none.
pub amount_of(items: List[Item], name: Text) -> Nat
=
when find(items, name)
is Some(item) -> item.amount
is None -> 0
--- How many entries of a bin satisfy `keep`.
pub count_where[T](bin: Bin[T], keep: fn(T) -> Bool) -> Nat
ensures result <= bin.entries.len
=
bin.entries.filter(keep).len
--- The average of some counts, rounded down.
pub average(counts: NonEmpty[Int]) -> Int = counts.sum() / counts.len
example "restocking adds to the amount"
do restock(Item(name: "rice", amount: 200, measure: Grams), added: 300)
expect result.amount == 500
example "using up takes from the amount"
do use_up(Item(name: "eggs", amount: 6, measure: Pieces), used: 4)
expect result.amount == 2
example "the shopping list names what ran out"
do shopping_list([Item(name: "rice", amount: 0, measure: Grams), Item(name: "eggs", amount: 6, measure: Pieces), Item(name: "oil", amount: 0, measure: Milliliters)])
expect result == ["rice", "oil"]
example "totals count one measure only"
do total([Item(name: "rice", amount: 500, measure: Grams), Item(name: "flour", amount: 200, measure: Grams), Item(name: "eggs", amount: 6, measure: Pieces)], measure: Grams)
expect result == 700
example "an item the pantry does not have amounts to zero"
do amount_of([Item(name: "eggs", amount: 6, measure: Pieces)], name: "milk")
expect result == 0
example "a bin counts the entries that match"
do count_where(Bin(label: "jars", entries: [3, 0, 5]), keep: fn(n) -> n > 0)
expect result == 2
example "the average of three counts is rounded down"
do average([2, 4, 10])
expect result == 5