# Result\<T, E\>

`Result<T, E>` represents either `Ok(T)` or `Err(E)`. Use it when the caller
needs to distinguish a value from a failure. The prelude does not declare `unwrap` or `expect` methods.

<!-- Legacy section anchors retained for existing links. -->
<a id="variants"></a>
<a id="construction"></a>
<a id="core-query-methods"></a>
<a id="isok-and-iserr"></a>
<a id="or-extract-value-with-fallback"></a>
<a id="orelse-extract-with-computed-fallback"></a>
<a id="transformations"></a>
<a id="map-transform-success-value"></a>
<a id="maperr-transform-error-value"></a>
<a id="andthen-chain-fallible-operations"></a>
<a id="orelse-fallback-on-error"></a>
<a id="best-practices"></a>

## Methods and types

These signatures summarize `lib/runtime/VexArch/src/prelude/result.vx`.
By-value methods consume the result according to its concrete payload's
ownership rules. `Result<T, E>` is Copy only when both payloads support Copy.

| Method | Signature and result |
| --- | --- |
| `isOk`, `isErr` | `(Result<T, E>) -> bool` |
| `or` | `(Result<T, E>, T) -> T`: success value or fallback payload |
| `orElse`, `rescue` | `(Result<T, E>, fn(E): T) -> T`: success value or payload computed from the error |
| `map` | `(Result<T, E>, fn(T): U) -> Result<U, E>` |
| `mapErr` | `(Result<T, E>, fn(E): E2) -> Result<T, E2>` |
| `flatMap` | `(Result<T, E>, fn(T): Result<U, E>) -> Result<U, E>` |
| `clone` | `(&Result<T, E>) -> Result<T, E>` where both payloads implement `Clone` |

`orElse` and `rescue` return a **payload**, not a replacement `Result`. To
choose another fallible operation, use `match` and return the desired `Result`.
The prelude does not declare `andThen`, `filter`, `ok`, `err`, or
`swap` as Result methods; do not assume those names are aliases.

## A runnable example

```vex [result-example.vx]
fn checked_half(n: i32): Result<i32, i32> {
    if n % 2 == 0 { return Ok(n / 2); }
    return Err(9);
}
fn main(): i32 {
    let ok: Result<i32, i32> = Ok(10);
    let err: Result<i32, i32> = Err(5);
    $println(ok.isOk());
    $println(err.isErr());
    $println(ok.or(99));
    $println(err.orElse(|e: i32| e + 1));
    let doubled: Result<i32, i32> = ok.map(|n: i32| n * 2);
    $println(doubled.or(0));
    let changed: Result<i32, i32> = err.mapErr(|e: i32| e + 10);
    $println(changed.orElse(|e: i32| e));
    let half: Result<i32, i32> = ok.flatMap(checked_half);
    $println(half.or(0));
    return 0;
}
```

Run `vex run result-example.vx`. The expected stdout is:

```text
true
true
10
6
20
15
5
```

The closures annotate their parameters to make the success and error types
visible at the call site. A callback for `orElse` receives the error type and
returns a success value. See [Closures](closures.md#type-inference).

<a id="the-rescue-operator"></a>
<a id="vs-quick-comparison"></a>
<a id="three-forms"></a>
<a id="in-practice"></a>
<a id="the-operator"></a>
<a id="with-option"></a>
<a id="error-type-conversion"></a>
<a id="conversion-methods"></a>
<a id="pattern-matching"></a>
<a id="comparison-with-exceptions"></a>

## Fallback and propagation

`result.or(expensive())` evaluates the argument before `or` is called.
`result.orElse(|error: E| fallback(error))` calls its closure only for `Err`.
For the `??` operator, `result ?? expensive()` evaluates the right side
only for `Err`. The rescue form `result !> |error: E| fallback(error)` exposes
the error to the fallback. A `?` propagates an `Err` from a function returning
an appropriate `Result`; see [Operators](../advanced/operators-reference.md).
Do not assume automatic conversion between different error types without
checking the compiler and the relevant conversion implementation.

To return another `Result` on failure, use a match:

```vex
fn recover(primary: Result<i32, i32>): Result<i32, i32> {
    return match primary {
        Ok(value) => Ok(value),
        Err(_) => Ok(0),
    };
}
```

<a id="common-patterns"></a>
<a id="validate-and-transform"></a>
<a id="retry-with-backoff"></a>
<a id="collecting-results"></a>
<a id="transactional-pattern"></a>

## Multi-step operations

Distinguish a failed first step from failure after a previous step succeeded.
If a withdrawal fails, do not attempt to refund it. If a later deposit fails
after a successful withdrawal, compensation can also fail and must have its
own reported outcome.

The complete example below uses in-memory test outcomes to make the branches visible. It is a control-flow exercise, not a payment implementation:

```vex [compensation.vx]
struct Ledger {
    source: i32,
    destination: i32,
    refund_attempts: i32,
}
fn withdraw(ledger: &Ledger!, succeeds: bool): Result<i32, i32> {
    if !succeeds { return Err(1); }
    ledger.source = ledger.source - 10;
    return Ok(10);
}
fn deposit(ledger: &Ledger!, amount: i32, succeeds: bool): Result<i32, i32> {
    if !succeeds { return Err(2); }
    ledger.destination = ledger.destination + amount;
    return Ok(amount);
}
fn refund(ledger: &Ledger!, amount: i32, succeeds: bool): Result<i32, i32> {
    ledger.refund_attempts = ledger.refund_attempts + 1;
    if !succeeds { return Err(3); }
    ledger.source = ledger.source + amount;
    return Ok(amount);
}
// 0 = completed, 1 = withdrawal failed, 2 = refunded, 3 = refund failed.
fn transfer(ledger: &Ledger!, first_ok: bool, second_ok: bool, refund_ok: bool): i32 {
    let amount = match withdraw(ledger, first_ok) {
        Ok(value) => value,
        Err(_) => { return 1; },
    };
    match deposit(ledger, amount, second_ok) {
        Ok(_) => { return 0; },
        Err(_) => {
            return match refund(ledger, amount, refund_ok) {
                Ok(_) => 2,
                Err(_) => 3,
            };
        },
    };
}
fn check(first: bool, second: bool, refund_ok: bool, outcome: i32,
         source: i32, destination: i32, refunds: i32): bool {
    let! ledger = Ledger { source: 100, destination: 0, refund_attempts: 0 };
    let result = transfer(&ledger, first, second, refund_ok);
    return result == outcome && ledger.source == source &&
           ledger.destination == destination && ledger.refund_attempts == refunds;
}
fn main(): i32 {
    if !check(false, true, true, 1, 100, 0, 0) { return 1; }
    if !check(true, true, true, 0, 90, 10, 0) { return 2; }
    if !check(true, false, true, 2, 100, 0, 1) { return 3; }
    if !check(true, false, false, 3, 90, 0, 1) { return 4; }
    $println("four paths ok");
    return 0;
}
```

Starting from source `100` and destination `0`, the four checks cover:

| Withdrawal | Deposit | Refund | Outcome | Source / destination | Refund attempts |
| --- | --- | --- | --- | --- | --- |
| Fails | Not attempted | Not attempted | Withdrawal failed (`1`) | 100 / 0 | 0 |
| Succeeds | Succeeds | Not attempted | Completed (`0`) | 90 / 10 | 0 |
| Succeeds | Fails | Succeeds | Refunded (`2`) | 100 / 0 | 1 |
| Succeeds | Fails | Fails | Refund failed (`3`) | 90 / 0 | 1 |

The program prints `four paths ok` and exits 0 when all four checks pass; a failed check exits nonzero. The model assumes each failed operation makes no change and has no ambiguous result; real services may fail after committing.

Compensation is not an atomic transaction: interruptions, retries, and
concurrent operations require durable transaction support or an explicitly
designed recovery protocol. A `Result` chain alone does not provide it.

## Related pages

- [Option](option-api.md)
- [Pattern Matching](pattern-matching.md)
- [Error Handling](../error-handling.md)
