---
title: "fold"
url: https://una-lang.org/en/docs/std/prelude/fold/
release: v0.4.0
edition: "0.1 and later"
source: https://github.com/una-lang/una/blob/v0.4.0/docs/std/listing.json
---

# fold

A function of the prelude, in scope in every module. Edition 0.1 and later.

## Edition 0.1

```una
pub fold[T, U](xs: List[T], initial: U, step: fn(U, T) -> U) -> U
```

Starts from `initial` and, for each element `x` of `xs` from the first to the last, replaces the accumulator `acc` by `step(acc, x)`, calling `step` at most once per element; the result is the last accumulator, `initial` when `xs` is empty. In edition 0.2 and later it takes an effectful and failing `step`, and stops at the first failure (`spec/14 §1`).

## Edition 0.2 and later

```una
pub fold[T, U](xs: List[T], initial: U, step: fn(U, T) -> U) -> U
  uses of step
  fails of step
```

Starts from `initial` and, for each element `x` of `xs` from the first to the last, replaces the accumulator `acc` by `step(acc, x)`, calling `step` at most once per element; the result is the last accumulator, `initial` when `xs` is empty. In edition 0.2 and later it takes an effectful and failing `step`, and stops at the first failure (`spec/14 §1`).

In editions 0.2, 0.3, 0.4, 0.5. In edition 0.1: `step` has no effects and cannot fail\: the declaration has no `uses of step` or `fails of step`.

## Parameters

- `xs`: the list
- `initial`: the accumulator before the first element
- `step`: the next accumulator\, from the last one and an element

## Returns

`U`: the last accumulator\: `initial` when `xs` is empty\, otherwise `step` applied from the first element to the last.

## Effects

Those of `step`: it calls `step` from the first element on\, at most once per element\, has the effects of `step`\, and stops at the first failure of `step`\, which becomes its own.

## Use instead

- [`sum`](https://una-lang.org/en/docs/std/prelude/sum/) to add integers

## See also

[`map`](https://una-lang.org/en/docs/std/prelude/map/)

## Example

`src/shop.una`

```una
module shop

--- The most expensive price of a cart, starting from zero.
pub main() -> Unit
  uses @console: Console[print]
=
  let prices = [1999, 499, 2499]
  let highest = prices.fold(initial: 0, step: fn(best, p) -> max(best, b: p))
  @console.print("highest {highest}")
```

`una run .` prints:

```text
highest 2499
```

## Specification

- [`spec/14 §1`](https://una-lang.org/en/docs/spec/14-standard-library/#s1)

Generated from the standard modules of una v0.4.0 ([`docs/std/listing.json`](https://github.com/una-lang/una/blob/5fec93d88932b333feec25e589355a2cb34c37b5/docs/std/listing.json), which is not part of the specification). The specification governs: [`spec/14 §1`](https://una-lang.org/en/docs/spec/14-standard-library/#s1).
