Home / Docs / Standard library / Prelude
fold
A function of the prelude, in scope in every module. Edition 0.1 and later.
Edition 0.1
pub fold[T, U](xs: List[T], initial: U, step: fn(U, T) -> U) -> UStarts 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
pub fold[T, U](xs: List[T], initial: U, step: fn(U, T) -> U) -> U
uses of step
fails of stepStarts 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 listinitial: the accumulator before the first elementstep: 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
sumto add integers
See also
Example
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:
highest 2499Specification
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.