# manual-try-fold

Prefer Iterator.tryFold over reducing a propagated Result accumulator

Reducing a Result accumulator continues calling the reducer after failure only to propagate the same error again.
Instead, you SHOULD call `tryFold` so iteration stops at the first failed Result.

The rule requires propagation to be the reducer's first operation, preserving every observable effect.

- Category: performance
- Level: warning
- Fix: suggestion
- Scope: module

## Reported

```ds title="main.ds"
import { Iterator } from "destack:iter";

function sum(values: Iterator<int32>): Result<int32, string> {
    return values.reduce((result, value) => {
        const total = result?;

        Result.ok(total + value)
    }, Result.ok(0));
}
```

## Accepted

```ds title="main.ds"
import { Iterator } from "destack:iter";

function sum(values: Iterator<int32>): Result<int32, string> {
    return values.tryFold(0, (total, value) => Result.ok(total + value));
}
```

## Prior art

- [Clippy · manual_try_fold](https://rust-lang.github.io/rust-clippy/master/index.html#manual_try_fold)

[language/linter/src/rules/performance/manual_try_fold.rs:8](https://github.com/destack-sh/destack/blob/main/language/linter/src/rules/performance/manual_try_fold.rs#L8)
