Home / Docs / Standard library / Prelude

fold

Release v0.4.0Edition 0.1 and later

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

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

See also

map

Example

src/shop.unauna
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:

Output
highest 2499

Specification

Generated from the standard modules of una v0.4.0 (docs/std/listing.json, which is not part of the specification). The specification governs: spec/14 §1.