Home / Learn / 7 Results and failures
7.4 Failures as values: attempt and Result
Page 5 of 12
7.4.1 What attempt and Result are
The handling clauses of section 7.3 decide on the spot, at the call. Sometimes you want to keep the outcome and decide later. Think of the card slips at a till at the end of the day: each slip says "approved", or "declined, and why". The clerk files every slip and counts them later; one declined card does not stop the pile.
attempt turns one call into such a slip. attempt raw.parse_int() runs the call and gives a value of the type Result[T, E], a generic sum kind of the prelude with two variants:
Ok(value)when the call returned, with the value, of the typeT;Err(failure)when the call failed, with the failure, of the error kindE.
attempt itself never fails: a failure becomes an Err, which a when takes apart like any sum kind.
7.4.2 Why a form needs failures as values
The examples of this section read quantities with the prelude's own failing function, parse_int, which turns a text into an Int and fails with ParseError, a sum kind of the prelude: Empty for an empty text, NoDigits for a sign alone, NotADigit(at) with the position of the first wrong character, counted from 0, and TooLong for more than 4300 digits. Unlike to_int, it says why a text is not a number. Both exist from edition 0.2 on.
An order form has three boxes for quantities. With if error pass, the first box that fails ends the whole function, and the boxes after it are never read:
module batch
--- The units of the three quantities typed into an order form, added up. One quantity that
--- is not a number fails the whole form.
total_units(first: Text, second: Text, third: Text) -> Int
fails ParseError
=
let first_units = first.parse_int()
if error pass
let second_units = second.parse_int()
if error pass
let third_units = third.parse_int()
if error pass
first_units + second_units + third_units
--- Adds up two order forms: one with three numbers, one with two that are not.
pub main() -> Unit
uses @console: Console[print]
=
let good = total_units("12", second: "3", third: "5")
if error use -1
let mixed = total_units("12", second: "", third: "3x")
if error use -1
@console.print("{good} and {mixed}")una run . prints:
20 and -1The first form adds up to 20. The second holds one good quantity and two bad ones, and the whole form comes out as -1: the function stopped at the empty text, the second box, and the caller cannot tell which box failed, or why, or how many were good. if error use 0 on each box would hide the failures instead. To report every box, the program must keep each outcome, good or bad, and carry on.
7.4.3 How to write attempt
7.4.3.1 attempt and a let
The usual form gives the outcome a name: let outcome = attempt raw.parse_int(). attempt is followed by exactly one call, and no clause goes under it: attempt is the handling.
7.4.3.2 attempt as the whole body
A function whose body is only attempt returns the outcome, and cannot fail itself:
--- A typed quantity as a number, or the reason it is not one. The whole body is `attempt`.
parse_typed(raw: Text) -> Result[Int, ParseError] = attempt raw.parse_int()Its result type is written out: Result[Int, ParseError], the type of parse_int's value and the kind it fails with.
7.4.3.3 Taking a Result apart: when
--- One line of the report for a typed quantity.
describe(raw: Text, outcome: Result[Int, ParseError]) -> Text
=
when outcome
is Ok(value) -> "'{raw}': {value} units"
is Err(failure) -> "'{raw}': {explain(failure)}"is Ok(value) binds the value, and is Err(failure) binds the failure. When the arm does not need the failure, write is Err alone, as show does in section 7.5.
7.4.3.4 A question about the outcome: is_ok
outcome.is_ok() is true for Ok and false for Err, without taking the outcome apart. It suits a count.
7.4.4 Reporting every typed quantity
This step reports each of four typed quantities with the reason ParseError gives, and counts the good ones:
module batch
--- A typed quantity as a number, or the reason it is not one. The whole body is `attempt`.
parse_typed(raw: Text) -> Result[Int, ParseError] = attempt raw.parse_int()
--- Why a typed quantity is not a whole number, for a person to read.
explain(failure: ParseError) -> Text
=
when failure
is Empty -> "nothing was typed"
is NoDigits -> "a sign with no digits"
is NotADigit(at) -> "not a digit at position {at}"
is TooLong -> "more than 4300 digits"
--- One line of the report for a typed quantity.
describe(raw: Text, outcome: Result[Int, ParseError]) -> Text
=
when outcome
is Ok(value) -> "'{raw}': {value} units"
is Err(failure) -> "'{raw}': {explain(failure)}"
--- The report line of a typed quantity: `attempt` keeps the outcome, and `describe` reads it.
report(raw: Text) -> Text
=
let outcome = attempt raw.parse_int()
describe(raw, outcome: outcome)
--- 1 for a typed quantity that is a number, 0 for one that is not: `is_ok` in a condition.
accepted(raw: Text) -> Int = if parse_typed(raw).is_ok() then 1 else 0
--- Reports four typed quantities, and counts the good ones.
pub main() -> Unit
uses @console: Console[print]
=
@console.print(report("12"))
@console.print(report(""))
@console.print(report("-"))
@console.print(report("3x"))
let count = accepted("12") + accepted("") + accepted("-") + accepted("3x")
let last = parse_typed("7")parse_typed(raw: Text) -> Result[Int, ParseError] = attempt raw.parse_int(). The whole body isattempt, so the function returns the outcome and cannot fail itself.explain. Awhenturns each variant ofParseErrorinto words.let outcome = attempt raw.parse_int(), inreport. The usual form. Nothing fails, even for a bad quantity: the failure is a value inoutcome, whichdescribereads.parse_typed(raw).is_ok(), inaccepted.is_oksays whether aResultisOk, and theifturns the answer into 1 or 0, somaincan add them up.
una run . prints:
'12': 12 units
'': nothing was typed
'-': a sign with no digits
'3x': not a digit at position 1
1 of 4 accepted, then Ok(7)Every quantity gets its line, with its own reason. The last value is printed as Ok(7): a Result is printed like any other value of a sum kind.
7.4.5 How attempt behaves
7.4.5.1 One call, the whole expression
attempt applies to the whole expression after it, and that expression must be one call. It is tempting to write attempt and a question about the outcome on one line:
--- a/src/batch.una
+++ b/src/batch.una
@@ -24,3 +24,3 @@
=
- let outcome = attempt raw.parse_int()
+ let outcome = attempt raw.parse_int().is_ok()
describe(raw, outcome: outcome)una check . reports three errors. The first is the one to read:
[U2001] Error: argument `r` of `is_ok` must be `Result[_, _]`, found `Int`
╭─[ src/batch.una:25:25 ]
│
25 │ let outcome = attempt raw.parse_int().is_ok()
│ ───────┬───────
│ ╰───────── argument `r` of `is_ok` must be `Result[_, _]`, found `Int`
│
│ Note: run `una explain U2001` for an explanationattempt took the whole of raw.parse_int().is_ok(), which is the call is_ok(raw.parse_int()). Its argument r is the Int that parse_int gives, not a Result, so the types do not match. The other two errors follow from the same line: parse_int is now nested inside another call (U3013), and outcome has become a Result of a Bool. The fix is two lines: let outcome = attempt raw.parse_int(), then outcome.is_ok() where the question is asked.
7.4.5.2 What an Ok value keeps
When the outcome is Ok, everything the called function promises about its result in its header holds for the value, as after a direct call: its ensures (section 5.2), and its result type, refined kinds included. Section 7.6 relies on this.
7.4.5.3 A stored failure is not raised again
An Err(failure) is a value. fail names a variant where a failure is decided, so fail failure with a stored failure does not check (re-raising a stored failure). To pass a failure on, handle the call with if error pass and do not attempt it.
7.4.5.4 attempt of a call that cannot fail
In editions 0.1 and 0.2, attempt of a call that cannot fail is accepted. In edition 0.3, it is U3026: remove the attempt and use the value directly.
7.4.6 Choosing how to handle a failure
The table compares the handling clauses, attempt, and checked, which section 7.5 introduces:
Which to use:
| You want to… | Use |
|---|---|
| Carry on with a default | if error use / if none use |
| Let the caller decide, same error kind | if error pass |
| Report the failure in your own terms | if error fail V(cause: error) |
| Keep the outcome, to report or count it | attempt, then when or is_ok |
| Accept outside input that no proof can establish | checked (section 7.5) |
7.4.7 Check yourself: attempt
parse_int does not trim spaces. Predict what this prints:
@console.print("{count} of 4 accepted, then {last}")
let padded = parse_typed(" 5")Show the answer
Err(NotADigit(0))The space at position 0 is not a digit, so parse_int fails with NotADigit(at: 0). parse_typed is an attempt, so the failure comes back as a value, Err(…), and nothing fails: the program prints it and goes on.
Next:7.5 When no proof can decide: checked and opaque predicates