Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Data.Foldable

Generic operations over any Foldable container.

Each function is a constrained free function, not a class default method: it is written once against the Foldable(f) class methods and works for every instance (List, Option, and any future container) without a per-type copy. The prelude opens this module, so these names are in scope unqualified everywhere and subsume the old List-only sum/length/etc.

The folds are strict, so the short-circuiting versions (all, any, find, elem) still visit every element; for a pure predicate the result is identical to a left-to-right search. Every aggregation rides fold_l, which instances implement tail recursively, so a large container folds in constant stack on the native backend; only to_list uses fold_r, to build in order. Arithmetic has no Num class, so sum and product are fixed to Int, matching the operators + and *.

Functions and Values

sum

sum : forall a. (a(Int)) -> Int

The sum of a container of ints (0 when empty).

product

product : forall a. (a(Int)) -> Int

The product of a container of ints (1 when empty).

length

length : forall a b. (a(b)) -> Int

The number of elements.

is_empty

is_empty : forall a b. (a(b)) -> Bool

True when the container has no elements.

all

all : forall a b. ((a) -> Bool, b(a)) -> Bool

True when every element satisfies p (vacuously true when empty).

any

any : forall a b. ((a) -> Bool, b(a)) -> Bool

True when some element satisfies p.

find

find : forall a b. ((a) -> Bool, b(a)) -> Option(a)

The first element satisfying p as Some (leftmost match), or None.

elem

elem : forall a b. (a, b(a)) -> Bool

True when x is an element (Eq).

to_list

to_list : forall a b. (a(b)) -> List(b)

The elements as a List, in fold order.