# 3.10 Optional and Result

> `Optional` represents a value that may be missing and `Result` an operation that may go well or badly; both force you to look at the bad case before using the value.

Web page: https://pseudolearn.app/en/spec/tipos/opcional-resultado

> **In one sentence**
>
> `Optional` represents a value that may be missing and `Result` an operation that may go well or badly; both force you to look at the bad case before using the value.

## 3.10.1 How to write it

```pseudolearn
Define «name» As Optional<«type»> <- Some(«value»);
Define «name» As Optional<«type»> <- None;
Define «name» As Result<«type», «error type»> <- Success(«value»);
Define «name» As Result<«type», «error type»> <- Failure(«error»);
```

## 3.10.2 How it works

They are two built-in variants:

- `Optional<T>` has two shapes: `Some(value)` when there is a value and `None` when it is missing.
- `Result<T, E>` has two shapes: `Success(value)` when the operation went well and `Failure(error)` when it did not.

Like any variant, they are queried with `Switch`. There is no way to "take the value out and hope it is there": the program has to decide what to do in both cases.

### Program: A division that may fail

```pseudolearn
Subroutine dividir(a As Integer, b As Integer) As Result<Integer, String>
  If b = 0 Then
    Return Failure("no se divide entre cero");
  EndIf
  Return Success(a Div b);
EndSubroutine
Algorithm Division
  Switch dividir(10, 2) Do
    Success(cociente): Write "Cociente: ", cociente;
    Failure(motivo): Write "Error: ", motivo;
  EndSwitch
  Switch dividir(1, 0) Do
    Success(cociente): Write "Cociente: ", cociente;
    Failure(motivo): Write "Error: ", motivo;
  EndSwitch
EndAlgorithm
```

**Output**

```text
Cociente: 5
Error: no se divide entre cero
```

*The program finishes normally.*

**Figure 3.10-1: Optional and Result**

Two columns. Optional can be Some with a value or None. Result can be Success with a value or Failure with a reason. Below, a note says both cases must be considered with Switch, and that Propagate passes the error upwards.

Two boxes that may or may not be full. To open them, both possibilities must be considered.

## 3.10.3 Propagate

Inside a subroutine that also returns `Result` (or `Optional`), `Propagate` avoids writing a `Switch` for every call: if the value is `Success`, it gives its content; if it is `Failure`, it ends the subroutine returning that same error.

### Program: Passing the error upwards

```pseudolearn
Subroutine dividir(a As Integer, b As Integer) As Result<Integer, String>
  If b = 0 Then
    Return Failure("no se divide entre cero");
  EndIf
  Return Success(a Div b);
EndSubroutine
Subroutine mitadDelCociente(a As Integer, b As Integer) As Result<Integer, String>
  Define c As Integer <- Propagate dividir(a, b);
  Return Success(c Div 2);
EndSubroutine
Algorithm Encadenar
  Switch mitadDelCociente(20, 0) Do
    Success(valor): Write valor;
    Failure(motivo): Write "Falló: ", motivo;
  EndSwitch
EndAlgorithm
```

**Output**

```text
Falló: no se divide entre cero
```

*The program finishes normally.*

`Discard` makes it clear that you ignore a `Result` on purpose: `Discard dividir(4, 2);`.

> **Limit**
>
> - `Optional<Optional<T>>` tells `None` apart from `Some(None)`.
> - `Propagate` only works inside a subroutine whose return type matches (`Optional`, or `Result` with the same error type).
> - A `Result` ignored without `Discard` is an error: `resultNotHandled`.
> - A `Result` is not written, compared or passed by reference.

> **Common mistakes**
>
> Calling a function that returns `Result` and doing nothing with it is detected before running:
>
> ### Program: A forgotten result
>
> ```pseudolearn
> Subroutine dividir(a As Integer, b As Integer) As Result<Integer, String>
>   If b = 0 Then
>     Return Failure("no se divide entre cero");
>   EndIf
>   Return Success(a Div b);
> EndSubroutine
> Algorithm Olvido
>   dividir(4, 2);
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `resultNotHandled` (error, 8:3): Unhandled result of type result<integer, string>: handle it with switch, propagate it, or discard it explicitly
>
> *The program finishes with an error.*

> **Under the hood**
>
> `Propagate` becomes a tag check followed by an early return. Before leaving, the engine runs any pending `defer` clean-ups, in reverse order.
>
> **Intermediate representation**
>
> ```text
> module Encadenar en
> func @dividir(%0: i64, %1: i64, %2: cell<i64>, %3: cell<i64>, %4: cell<str>) -> unit {
> b0() mass 1:
>   stmt.enter @2:3-4:8
>   %5 = const.i64 0 @2:10-2:11
>   %6 = int.cmp eq, %1, %5 @2:8-2:9
>   decide.bool %6 @2:3-4:8
>   branch %6, b1(), b2()
> b1() mass 1:
>   stmt.enter @3:5-3:46
>   %7 = const.str "no se divide entre cero" @3:20-3:45
>   %8 = const.i64 0
>   %9 = value.undefined str
>   %10 = const.i64 1
>   %11 = value.reinterpret str, %7
>   cell.store %2, %10
>   cell.store %3, %8
>   cell.store %4, %11
>   stmt.exit @3:5-3:46
>   return @3:5-3:46
> b2() mass 0:
>   jump b3()
> b3() mass 1:
>   stmt.exit @2:3-4:8
>   stmt.enter @5:3-5:26
>   %12 = int.div %0, %1 @5:20-5:23
>   %13 = const.i64 0
>   %14 = value.undefined str
>   %15 = const.i64 0
>   %16 = value.reinterpret i64, %12
>   cell.store %2, %15
>   cell.store %3, %16
>   cell.store %4, %14
>   stmt.exit @5:3-5:26
>   return @5:3-5:26
> }
> func @mitadDelCociente(%0: i64, %1: i64, %2: cell<i64>, %3: cell<i64>, %4: cell<str>) -> unit {
> b0() mass 1:
>   stmt.enter @8:3-8:49
>   %5 = cell.local i64 @8:36-8:49
>   %6 = cell.local i64 @8:36-8:49
>   %7 = cell.local str @8:36-8:49
>   %8 = call @dividir(%0, %1, %5, %6, %7) @8:36-8:49
>   %9 = cell.load_raw %5 @8:36-8:49
>   %10 = cell.load_raw %6 @8:36-8:49
>   %11 = cell.load_raw %7 @8:36-8:49
>   %12 = const.i64 0
>   %13 = int.cmp eq, %9, %12
>   branch %13, b1(), b2()
> b1() mass 1:
>   %14 = value.reinterpret i64, %10
>   stmt.exit @8:3-8:49
>   stmt.enter @9:3-9:26
>   %15 = const.i64 2 @9:24-9:25
>   %16 = int.div %14, %15 @9:20-9:23
>   %17 = const.i64 0
>   %18 = value.undefined str
>   %19 = const.i64 0
>   %20 = value.reinterpret i64, %16
>   cell.store %2, %19
>   cell.store %3, %20
>   cell.store %4, %18
>   stmt.exit @9:3-9:26
>   return @9:3-9:26
> b2() mass 0:
>   %21 = value.reinterpret str, %11
>   %22 = const.i64 0
>   %23 = value.undefined str
>   %24 = const.i64 1
>   %25 = value.reinterpret str, %21
>   cell.store %2, %24
>   cell.store %3, %22
>   cell.store %4, %25
>   stmt.exit @8:26-8:49
>   return @8:26-8:49
> }
> func suspendible @main() -> unit {
> b0() mass 1:
>   stmt.enter @12:3-15:12
>   %0 = const.i64 20 @12:27-12:29
>   %1 = const.i64 0 @12:31-12:32
>   %2 = cell.local i64 @12:10-12:33
>   %3 = cell.local i64 @12:10-12:33
>   %4 = cell.local str @12:10-12:33
>   %5 = call @mitadDelCociente(%0, %1, %2, %3, %4) @12:10-12:33
>   %6 = cell.load_raw %2 @12:10-12:33
>   %7 = cell.load_raw %3 @12:10-12:33
>   %8 = cell.load_raw %4 @12:10-12:33
>   %9 = const.i64 0 @13:5-13:19
>   %10 = int.cmp eq, %6, %9
>   branch %10, b3(), b5()
> b1() mass 0:
>   stmt.exit @12:3-15:12
>   return @16:1-16:13
> b2() mass 0:
>   decide.none @12:3-15:12
>   jump b1()
> b3() mass 2:
>   %11 = const.i64 0
>   decide.case %11 @12:3-15:12
>   stmt.enter @13:5-13:19
>   %12 = value.reinterpret i64, %7
>   stmt.exit @13:5-13:19
>   stmt.enter @13:21-13:32
>   out.write %12, newline @13:21-13:32
>   stmt.exit @13:21-13:32
>   jump b1()
> b4() mass 2:
>   %13 = const.i64 1
>   decide.case %13 @12:3-15:12
>   stmt.enter @14:5-14:20
>   %14 = value.reinterpret str, %8
>   stmt.exit @14:5-14:20
>   stmt.enter @14:22-14:45
>   %15 = const.str "Falló: " @14:28-14:37
>   out.write %15, %14, newline @14:22-14:45
>   stmt.exit @14:22-14:45
>   jump b1()
> b5() mass 0:
>   %16 = const.i64 1 @14:5-14:20
>   %17 = int.cmp eq, %6, %16
>   branch %17, b4(), b6()
> b6() mass 0:
>   jump b2()
> }
> ```

**In short**
- `Optional<T>`: `Some(value)` or `None`.
- `Result<T, E>`: `Success(value)` or `Failure(error)`.
- They are queried with `Switch`; there is no shortcut that ignores the bad case.
- `Propagate` returns the error upwards; `Discard` ignores it on purpose.

**See also**
- [3.9 Variants](https://pseudolearn.app/en/spec/tipos/variantes.md)
- [6.8 Cleanups with Defer](https://pseudolearn.app/en/spec/control/diferir.md)
- [13.4 Effect order and the tape](https://pseudolearn.app/en/spec/motor/efectos.md)
