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. 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).
sum([1, 2, 3, 4])
10
product
product : forall a. (a(Int)) -> Int
The product of a container of ints (1 when empty).
product([1, 2, 3, 4])
24
length
length : forall a b. (a(b)) -> Int
The number of elements.
length([1, 2, 3])
3
is_empty
is_empty : forall a b. (a(b)) -> Bool
True when the container has no elements.
is_empty([1, 2, 3])
false
all
all : forall a b. ((a) -> Bool, b(a)) -> Bool
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
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)
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
True when x is an element (Eq).
elem(2, [1, 2, 3])
true
to_list
to_list : forall a b. (a(b)) -> List(b)
The elements as a List, in fold order (Option yields zero or one).
to_list(Some(5))
[5]