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. Base includes 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. sum and product aggregate through the Num class, so they work at any numeric carrier (Int, I64, U64, Float); the literal seeds 0 and 1 adapt to the carrier the way any numeric literal does.
Functions and Values
sum
sum : forall a b. (a(b)) -> b given Foldable(a), Num(b)
The sum of a container of numbers (0 when empty).
(sum([1, 2, 3, 4]), sum([1.5, 2.75]))
(10, 4.25)
product
product : forall a b. (a(b)) -> b given Foldable(a), Num(b)
The product of a container of numbers (1 when empty).
product([1, 2, 3, 4])
24
length
length : forall a b. (a(b)) -> Int given Foldable(a)
The number of elements.
length([1, 2, 3])
3
is_empty
is_empty : forall a b. (a(b)) -> Bool given Foldable(a)
True when the container has no elements.
is_empty([1, 2, 3])
false
all
all : forall a b. ((a) -> Bool, b(a)) -> Bool given Foldable(b)
True when every element satisfies p (vacuously true when empty).
all(\(x) -> x > 0, [1, 2, 3])
true
any
any : forall a b. ((a) -> Bool, b(a)) -> Bool given Foldable(b)
True when some element satisfies p.
any(\(x) -> x > 2, [1, 2, 3])
true
find
find : forall a b. ((a) -> Bool, b(a)) -> Option(a) given Foldable(b)
The first element satisfying p as Some (leftmost match), or None.
find(\(x) -> x > 1, [1, 2, 3])
Some(2)
elem
elem : forall a b. (a, b(a)) -> Bool given Eq(a), Foldable(b)
True when x is an element (Eq).
elem(2, [1, 2, 3])
true
to_list
to_list : forall a b. (a(b)) -> List(b) given Foldable(a)
The elements as a List, in fold order (Option yields zero or one).
to_list(Some(5))
[5]