Home / Learn / 7 Results and failures
7.1 A value that may be missing: Option
Page 2 of 12
7.1.1 What an Option is
Some questions have no answer. Ask a store for the price of a product it does not sell, ask the text "seven" for the number it holds, or ask a SKU for the position of a / it does not have: there is nothing to give back. An Option is the type of an answer that may be missing. Think of a parcel locker at a pickup point: you open it, and either a parcel is inside or the locker is empty. Before you carry anything away, you look.
Option[T] is a generic sum kind of the prelude (section 4.4) with two variants:
Some(value)holds one value of the typeT. A price lookup that finds the price givesSome(1990), anOption[Int].Noneholds nothing. It means "there is no value here".
T is the type parameter: it stands for whatever type the option may hold. Option[Int] may hold an Int, and Option[Product] a Product. An Option[Int] is not an Int: you cannot add it to a number, compare it with <, or use it where an Int is expected, until you have said what happens when it is None.
7.1.2 Why absence needs its own type
In many languages a search that finds nothing returns a special value, often called null, of the same type as a real answer. The type then says that a product is always there, and the first line that uses a missing product fails while the program runs, often far from the search.
In Una the type says it. Each example of this chapter is a package, made as chapter 2 explains, and the chapter's download, 07-failure.tar.gz, holds them all. Here, find_product gives back an Option[Product], and price_of reads the price from it as if the product were always found:
--- a/src/lookup.una
+++ b/src/lookup.una
@@ -21,5 +21,3 @@
let found = find_product(sku)
- when found
- is Some(product) -> Some(product.cents)
- is None -> None
+ Some(found.cents)
una check . reports:
[U1001] Error: `Option[Product]` has no field `cents`, and no function `cents` in scope applies
╭─[ src/lookup.una:22:14 ]
│
22 │ Some(found.cents)
│ ──┬──
│ ╰──── `Option[Product]` has no field `cents`, and no function `cents` in scope applies
│
│ Note: run `una explain U1001` for an explanation
────╯Read it from the top. found is an Option[Product], and the message says that this type has no field cents: the field belongs to Product, which the option may or may not hold. The mark points at .cents. The checker does not guess what a missing product should mean. You decide, with one of the forms of the next part, and the decision is written where the value is used.
7.1.3 How to write and use an Option
The step of this part shows each form on a shelf count, which a clerk may not have taken yet:
--- What a shelf label shows for a count that may be missing: `when` with both arms.
shown(count: Option[Int]) -> Text
=
when count
is Some(units) -> "{units} on the shelf"
is None -> "not counted yet"
--- Whether a shelf holds more than 10 units: `when` with an `else` arm.
well_stocked(count: Option[Int]) -> Bool
=
when count
is Some(units) -> units > 10
else -> false
--- The units to order for a shelf: a missing count orders a full shelf of 12.
to_order(count: Option[Int]) -> Int = 12 - count.or_else(default: 0)
--- Whether a shelf still needs counting: a test of the variant, in a condition.
needs_count(count: Option[Int]) -> Bool = count is None
--- The units typed by a clerk, or 0 when the text is not a number: `if none use`.
typed_units(raw: Text) -> Int
=
let units = raw.trim.to_int()
if none use 0
units7.1.3.1 Making one: Some, None, and the functions that return one
let counted = Some(14)
let missing: Option[Int] = None
@console.print("{counted} {missing}")Some(14) NoneSome(14) wraps a value. None holds nothing, so it says nothing about the type: write the type on the name, let missing: Option[Int] = None, as section 2.1 shows for any let. More often an Option comes from a function. Two functions of the prelude on a text return one: to_int, which reads a whole number, and find, which gives the position of the first place a smaller text appears:
let sku = "LAMP-01"
let dash = sku.find(text: "-")
let number = sku.slice(start: 5, end: 7).to_int()
let slash = sku.find(text: "/")
@console.print("{dash} {number} {slash}")Some(4) Some(1) Nonefind gives the position of the first - in LAMP-01, counted from 0. to_int reads the digits 01 as 1. LAMP-01 has no /, so the last search gives None.
7.1.3.2 Both cases: when
A when (section 4.3) takes an Option apart, as it takes apart any sum kind. shown has one arm per variant: is Some(units) binds the value inside to the name units, and is None says what to do without one. Each arm gives a Text, so the when gives one too.
@console.print("{shown(counted)} / {shown(missing)}")14 on the shelf / not counted yet7.1.3.3 One case and the rest: else
When only the Some case needs work, an else arm covers the other. well_stocked answers false for a missing count:
@console.print("{well_stocked(counted)} {well_stocked(missing)}")true false7.1.3.4 A default: or_else
count.or_else(default: 0) is the value inside Some, or the default for None. It is the short form of a when whose None arm is a plain value. to_order orders a full shelf of 12 units when no count is known:
@console.print("{to_order(Some(5))} {to_order(missing)}")7 127.1.3.5 A question about the case: is None and is_some
count is None is a condition, true or false, that tests the variant with is (section 4.2) without taking the value out. is_some() asks the same question the other way round:
@console.print("{needs_count(missing)} {missing.is_some()}")true false7.1.3.6 A default under the line: if none use
typed_units writes the default on its own line under the call: if none use 0. After that line, units is a plain Int. This line is a handling clause. It and if none fail, which turns a missing value into a failure, are taught with the other clauses in section 7.3.
let typed = typed_units(" 7 ")
let spelled = typed_units("seven")
@console.print("{typed} {spelled}")7 07.1.4 Looking up a price
The forms together, in a price lookup. find_product makes the option, price_of passes the absence on to its caller, and label decides what it means:
module lookup
--- A product the store sells, with the price of one unit in cents.
kind Product
sku: Text
cents: Int
--- The product with the SKU `sku`, or `None` when the store does not sell it.
find_product(sku: Text) -> Option[Product]
=
if sku == "LAMP-01"
Some(Product(sku: "LAMP-01", cents: 1990))
else if sku == "DESK-02"
Some(Product(sku: "DESK-02", cents: 15900))
else
None
--- The price of `sku`, or `None` when the store does not sell it.
price_of(sku: Text) -> Option[Int]
=
let found = find_product(sku)
when found
is Some(product) -> Some(product.cents)
is None -> None
--- What a product page shows for `sku`.
label(sku: Text) -> Text
=
let price = price_of(sku)
when price
is Some(cents) -> "{sku}: {cents} cents"
is None -> "{sku}: not sold here"
--- Prints two product pages, and three values that may be missing.
pub main() -> Unit
uses @console: Console[print]
=
@console.print(label("DESK-02"))
@console.print(label("CHAIR-09"))
let missing = price_of("CHAIR-09")
@console.print("{missing} or {missing.or_else(default: 0)}")
let typed = "3".to_int()
let dash = "LAMP-01".find(text: "-")
@console.print("{typed} and {dash}")find_product(sku: Text) -> Option[Product]. A function of your own that returns anOption:Somewith the product for the two SKUs the store sells, andNonefor any other. Each branch of theif(section 3.4) gives anOption[Product].when found. One arm per case,is Some(product)andis None. The name inSome(product)binds the value inside.Some(product.cents).price_ofitself returns anOption, so its caller decides what a missing price means.labeldecides: it prints "not sold here".missing.or_else(default: 0). The short form when a default is right: the value insideSome, or the default forNone."3".to_int()and"LAMP-01".find(text: "-"). Two functions of the prelude that return anOption.
una run . prints:
DESK-02: 15900 cents
CHAIR-09: not sold here
None or 0
Some(3) and Some(4)An Option is printed as Some(3) or None, which helps while you look for a mistake, but a report should say what the absence means, as label does.
7.1.5 How an Option behaves
7.1.5.1 A when covers both cases
A when over an Option must have an arm for Some and one for None, or an else. Leave the None arm out of shown, and una check . reports:
[U2007] Error: `when` does not match variant `None` of `Option`
╭─[ src/counts.una:6:3 ]
│
6 │ when count
│ ──┬─
│ ╰─── `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
───╯The message names the variant that has no arm, None, and the mark points at the when. The Help line gives both repairs: an arm is None, or an else arm. So when the day comes that a value is missing, the program already says what to do.
7.1.5.2 Options compare by what they hold
@console.print("{counted == Some(14)} {missing == None}")true trueSome(14) == Some(14) holds, and None == None holds. Some(0) and None differ: a count of zero is a count, and a missing count is not.
7.1.5.3 The default of or_else is computed first
Note
The default of or_else is an argument like any other, so it is computed before the call, whether it is used or not. Keep it a plain value, such as 0 or "other". A call that prints or can fail cannot be the default: give its result a name with let first.
7.1.6 Choosing how to use an Option
Which to use:
| You want to… | Use |
|---|---|
| Do different things when the value is there and when it is not | when with is Some(v) and is None |
| Work only on the value, with one answer for the rest | when with is Some(v) and else |
| Carry on with a default | or_else(default: v), or if none use v on the line under the call (section 7.3) |
| Know only whether there is a value | is_some(), or o is None in a condition |
| Make a missing value a failure of your function | if none fail V (section 7.3) |
Prefer a when when the absence needs its own words, as on a product page. Prefer or_else when the default is the honest answer, as 0 units on a shelf nobody stocked.
7.1.7 Check yourself: Option
The three functions of How to write and use an Option get one more set of counts:
@console.print("{shown(Some(0))} / {to_order(Some(12))} / {well_stocked(Some(10))}")What does the line print?
Show the answer
0 on the shelf / 0 / falseSome(0) is a count of zero, not a missing count, so shown takes the Some arm. to_order(Some(12)) is 12 − 12 = 0. well_stocked(Some(10)) takes the Some arm, and 10 > 10 is false.