---
title: "7.4 Failures as values: attempt and Result"
url: https://una-lang.org/en/learn/failure/failures-as-values-attempt-and-result/
release: v0.4.0
edition: "0.2"
---

# 7.4 Failures as values: attempt and Result

## 7.4.1 What `attempt` and `Result` are

The handling clauses of [section 7.3](https://una-lang.org/en/learn/failure/handling-a-failure-the-clauses/#s7-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 type `T`;
- `Err(failure)` when the call failed, with the failure, of the error kind `E`.

`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:

```una include="steps/14-batch-stops/src/batch.una" title="steps/14-batch-stops/src/batch.una" verified="check, run"
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:

```text include="steps/14-batch-stops/expected/output.txt"
20 and -1
```

The 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:

```una include="steps/15-attempt/src/batch.una#parse_typed" title="steps/15-attempt/src/batch.una"
--- 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`

```una include="steps/15-attempt/src/batch.una#describe" title="steps/15-attempt/src/batch.una"
--- 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](https://una-lang.org/en/learn/failure/when-no-proof-can-decide-checked-and-opaque-predicates/#s7-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:

:::steps
```una include="steps/15-attempt/src/batch.una#L1-L40" title="steps/15-attempt/src/batch.una"
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")
```

1. **`parse_typed(raw: Text) -> Result[Int, ParseError] = attempt raw.parse_int()`.** The whole body is `attempt`, so the function returns the outcome and cannot fail itself.
2. **`explain`.** A `when` turns each variant of `ParseError` into words.
3. **`let outcome = attempt raw.parse_int()`, in `report`.** The usual form. Nothing fails, even for a bad quantity: the failure is a value in `outcome`, which `describe` reads.
4. **`parse_typed(raw).is_ok()`, in `accepted`.** `is_ok` says whether a `Result` is `Ok`, and the `if` turns the answer into 1 or 0, so `main` can add them up.
:::

`una run .` prints:

```text include="steps/15-attempt/expected/output.txt#L1-L5"
'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:

```diff include="steps/15-attempt..steps/16-attempt-expression:src/batch.una" context="1" title="src/batch.una"
--- 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:

```text include="steps/16-attempt-expression/expected/rendered.txt#L1-L8"
[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 explanation
```

`attempt` 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](https://una-lang.org/en/learn/contracts/postconditions-ensures-and-counterexamples/#s5-2)), and its result type, refined kinds included. [Section 7.6](https://una-lang.org/en/learn/failure/data-from-outside-checking-it-once/#s7-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](https://una-lang.org/en/learn/failure/common-mistakes/#re-raising-a-stored-failure-u0101)). 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](https://una-lang.org/en/learn/failure/when-no-proof-can-decide-checked-and-opaque-predicates/#s7-5) introduces:

:::decide
**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](https://una-lang.org/en/learn/failure/when-no-proof-can-decide-checked-and-opaque-predicates/#s7-5)) |
:::

## 7.4.7 Check yourself: `attempt`

`parse_int` does not trim spaces. Predict what this prints:

```una include="steps/15-attempt/src/batch.una#L41-L42" title="steps/15-attempt/src/batch.una"
  @console.print("{count} of 4 accepted, then {last}")
  let padded = parse_typed(" 5")
```

:::answer Show the answer
```text include="steps/15-attempt/expected/output.txt#L6"
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.
:::
