Description

The Foldable concept represents data structures that can be reduced to a single value.

Generally speaking, folding refers to the concept of summarizing a complex structure as a single value, by successively applying a binary operation which reduces two elements of the structure to a single value. Folds come in many flavors; left folds, right folds, folds with and without an initial reduction state, and their monadic variants. This concept is able to express all of these fold variants.

Another way of seeing Foldable is as data structures supporting internal iteration with the ability to accumulate a result. By internal iteration, we mean that the loop control is in the hand of the structure, not the caller. Hence, it is the structure who decides when the iteration stops, which is normally when the whole structure has been consumed. Since C++ is an eager language, this requires Foldable structures to be finite, or otherwise one would need to loop indefinitely to consume the whole structure.

Note

While the fact that Foldable only works for finite structures may seem overly restrictive in comparison to the Haskell definition of Foldable, a finer grained separation of the concepts should mitigate the issue. For iterating over possibly infinite data structures, see the Iterable concept. For searching a possibly infinite data structure, see the Searchable concept.

Minimal complete definition

fold_left or unpack

However, please note that a minimal complete definition provided through unpack will be much more compile-time efficient than one provided through fold_left.

for an appropriate definition of [] and prepend. The notion of linearization is useful for expressing various properties of Foldable structures, and is used across the documentation. Also note that Iterables define an extended version of this allowing for infinite structures.

Compile-time Foldables

A compile-time Foldable is a Foldable whose total length is known at compile-time. In other words, it is a Foldable whose length method returns a Constant of an unsigned integral type. When folding a compile-time Foldable, the folding can be unrolled, because the final number of steps of the algorithm is known at compile-time.

Additionally, the unpack method is only available to compile-time Foldables. This is because the return type of unpack depends on the number of objects in the structure. Being able to resolve unpack's return type at compile-time hence requires the length of the structure to be known at compile-time too.

In the current version of the library, only compile-time Foldables are supported. While it would be possible in theory to support runtime Foldables too, doing so efficiently requires more research.

Provided conversion to Sequences

Given a tag S which is a Sequence, an object whose tag is a model of the Foldable concept can be converted to an object of tag S. In other words, a Foldable can be converted to a SequenceS, by simply taking the linearization of the Foldable and creating the sequence with that. More specifically, given a Foldablexs with a linearization of [x1, ..., xn] and a Sequence tag S, to<S>(xs) is equivalent to make<S>(x1, ..., xn).

Free model for builtin arrays

Builtin arrays whose size is known can be folded as-if they were homogeneous tuples. However, note that builtin arrays can't be made more than Foldable (e.g. Iterable) because they can't be empty and they also can't be returned from functions.

Primer on monadic folds

A monadic fold is a fold in which subsequent calls to the binary function are chained with the monadic chain operator of the corresponding Monad. This allows a structure to be folded in a custom monadic context. For example, performing a monadic fold with the hana::optional monad would require the binary function to return the result as a hana::optional, and the fold would abort and return nothing whenever one of the accumulation step would fail (i.e. return nothing). If, however, all the reduction steps succeed, then just the result would be returned. Different monads will of course result in different effects.

Variables

Return the number of elements in the structure that compare equal to a given value.Given a Foldable structure xs and a value value, count returns an unsigned integral, or a Constant thereof, representing the number of elements of xs that compare equal to value. For this method to be well-defined, all the elements of the structure must be Comparable with the given value. More...

Return the number of elements in the structure for which the predicate is satisfied.Specifically, returns an object of an unsigned integral type, or a Constant holding such an object, which represents the number of elements in the structure satisfying the given predicate. More...

Equivalent to fold_left; provided for convenience.fold is equivalent to fold_left. However, it is not tag-dispatched on its own because it is just an alias to fold_left. Also note that fold can be called with or without an initial state, just like fold_left: More...

Left-fold of a structure using a binary operation and an optional initial reduction state.fold_left is a left-associative fold using a binary operation. Given a structure containing x1, ..., xn, a function f and an optional initial state, fold_left applies f as follows. More...

Right-fold of a structure using a binary operation and an optional initial reduction state.fold_right is a right-associative fold using a binary operation. Given a structure containing x1, ..., xn, a function f and an optional initial state, fold_right applies f as follows. More...

Perform an action on each element of a foldable, discarding the result each time.Iteration is done from left to right, i.e. in the same order as when using fold_left. If the structure is not finite, this method will not terminate. More...

Return the number of elements in a foldable structure.Given a Foldablexs, length(xs) must return an object of an unsigned integral type, or an IntegralConstant holding such an object, which represents the number of elements in the structure. More...

Return the greatest element of a non-empty structure with respect to a predicate, by default less.Given a non-empty structure and an optional binary predicate (less by default), maximum returns the greatest element of the structure, i.e. an element which is greater than or equal to every other element in the structure, according to the predicate. More...

Return the least element of a non-empty structure with respect to a predicate, by default less.Given a non-empty structure and an optional binary predicate (less by default), minimum returns the least element of the structure, i.e. an element which is less than or equal to every other element in the structure, according to the predicate. More...

Compute the product of the numbers of a structure.More generally, product will take any foldable structure containing objects forming a Ring and reduce them using the Ring's binary operation. The initial state for folding is the identity of the Ring's operation. It is sometimes necessary to specify the Ring to use; this is possible by using product<R>. If no Ring is specified, the structure will use the Ring formed by the elements it contains (if it knows it), or integral_constant_tag<int> otherwise. Hence,. More...

Equivalent to reverse_fold in Boost.Fusion and Boost.MPL.This method has the same semantics as reverse_fold in Boost.Fusion and Boost.MPL, with the extension that an initial state is not required. This method is equivalent to fold_right, except that the accumulating function must take its arguments in reverse order, to match the order used in Fusion. In other words,. More...

Equivalent to length; provided for consistency with the standard library.This method is an alias to length provided for convenience and consistency with the standard library. As an alias, size is not tag-dispatched on its own and length should be customized instead. More...

Compute the sum of the numbers of a structure.More generally, sum will take any foldable structure containing objects forming a Monoid and reduce them using the Monoid's binary operation. The initial state for folding is the identity of the Monoid. It is sometimes necessary to specify the Monoid to use; this is possible by using sum<M>. If no Monoid is specified, the structure will use the Monoid formed by the elements it contains (if it knows it), or integral_constant_tag<int> otherwise. Hence,. More...

Invoke a function with the elements of a Foldable as arguments.Given a function and a foldable structure whose length can be known at compile-time, unpack invokes the function with the contents of that structure. In other words, unpack(xs, f) is equivalent to f(x...), where x... are the elements of the structure. The length of the structure must be known at compile-time, because the version of f's operator() that will be compiled depends on the number of arguments it is called with, which has to be known at compile-time. More...

Variable Documentation

Return the compile-time value associated to a constant.This function returns the value associated to ...

Definition: value.hpp:54

Return the number of elements in the structure that compare equal to a given value.Given a Foldable structure xs and a value value, count returns an unsigned integral, or a Constant thereof, representing the number of elements of xs that compare equal to value. For this method to be well-defined, all the elements of the structure must be Comparable with the given value.

Parameters

xs

The structure whose elements are counted.

value

A value compared with each element in the structure. Elements that compare equal to this value are counted, others are not.

Return the number of elements in the structure for which the predicate is satisfied.Specifically, returns an object of an unsigned integral type, or a Constant holding such an object, which represents the number of elements in the structure satisfying the given predicate.

Parameters

xs

The structure whose elements are counted.

predicate

A function called as predicate(x), where x is an element of the structure, and returning a Logical representing whether x should be counted.

Equivalent to fold_left; provided for convenience.fold is equivalent to fold_left. However, it is not tag-dispatched on its own because it is just an alias to fold_left. Also note that fold can be called with or without an initial state, just like fold_left:

Left-fold of a structure using a binary operation and an optional initial reduction state.fold_left is a left-associative fold using a binary operation. Given a structure containing x1, ..., xn, a function f and an optional initial state, fold_left applies f as follows.

f(... f(f(f(x1, x2), x3), x4) ..., xn) // without state

f(... f(f(f(f(state, x1), x2), x3), x4) ..., xn) // with state

When the structure is empty, two things may arise. If an initial state was provided, it is returned as-is. Otherwise, if the no-state version of the function was used, an error is triggered. When the stucture contains a single element and the no-state version of the function was used, that single element is returned as is.

Signature

Given a FoldableF and an optional initial state of tag S, the signatures for fold_left are

A binary function called as f(state, x), where state is the result accumulated so far and x is an element in the structure. For left folds without an initial state, the function is called as f(x1, x2), where x1 and x2 are elements of the structure.

Right-fold of a structure using a binary operation and an optional initial reduction state.fold_right is a right-associative fold using a binary operation. Given a structure containing x1, ..., xn, a function f and an optional initial state, fold_right applies f as follows.

f(x1, f(x2, f(x3, f(x4, ... f(xn-1, xn) ... )))) // without state

f(x1, f(x2, f(x3, f(x4, ... f(xn, state) ... )))) // with state

Note

It is worth noting that the order in which the binary function should expect its arguments is reversed from fold_left.

When the structure is empty, two things may arise. If an initial state was provided, it is returned as-is. Otherwise, if the no-state version of the function was used, an error is triggered. When the stucture contains a single element and the no-state version of the function was used, that single element is returned as is.

Signature

Given a FoldableF and an optional initial state of tag S, the signatures for fold_right are

A binary function called as f(x, state), where state is the result accumulated so far and x is an element in the structure. For right folds without an initial state, the function is called as f(x1, x2), where x1 and x2 are elements of the structure.

Perform an action on each element of a foldable, discarding the result each time.Iteration is done from left to right, i.e. in the same order as when using fold_left. If the structure is not finite, this method will not terminate.

Parameters

xs

The structure to iterate over.

f

A function called as f(x) for each element x of the structure. The result of f(x), whatever it is, is ignored.

Return the number of elements in a foldable structure.Given a Foldablexs, length(xs) must return an object of an unsigned integral type, or an IntegralConstant holding such an object, which represents the number of elements in the structure.

Note

Since only compile-time Foldables are supported in the library right now, length must always return an IntegralConstant.

Return the greatest element of a non-empty structure with respect to a predicate, by default less.Given a non-empty structure and an optional binary predicate (less by default), maximum returns the greatest element of the structure, i.e. an element which is greater than or equal to every other element in the structure, according to the predicate.

If the structure contains heterogeneous objects, then the predicate must return a compile-time Logical. If no predicate is provided, the elements in the structure must be Orderable, or compile-time Orderable if the structure is heterogeneous.

Signature

Given a Foldable F, a Logical Bool and a predicate \( \mathtt{pred} : T \times T \to Bool \), maximum has the following signatures. For the variant with a provided predicate,

\[ \mathtt{maximum} : F(T) \times (T \times T \to Bool) \to T \]

for the variant without a custom predicate, T is required to be Orderable. The signature is then

\[ \mathtt{maximum} : F(T) \to T \]

Parameters

xs

The structure to find the greatest element of.

predicate

A function called as predicate(x, y), where x and y are elements of the structure. predicate should be a strict weak ordering on the elements of the structure and its return value should be a Logical, or a compile-time Logical if the structure is heterogeneous.

Tag dispatching

Both the non-predicated version and the predicated versions of maximum are tag-dispatched methods, and hence they can be customized independently. One reason for this is that some structures are able to provide a much more efficient implementation of maximum when the less predicate is used. Here is how the different versions of maximum are dispatched:

Return the least element of a non-empty structure with respect to a predicate, by default less.Given a non-empty structure and an optional binary predicate (less by default), minimum returns the least element of the structure, i.e. an element which is less than or equal to every other element in the structure, according to the predicate.

If the structure contains heterogeneous objects, then the predicate must return a compile-time Logical. If no predicate is provided, the elements in the structure must be Orderable, or compile-time Orderable if the structure is heterogeneous.

Signature

Given a FoldableF, a Logical Bool and a predicate \( \mathtt{pred} : T \times T \to Bool \), minimum has the following signatures. For the variant with a provided predicate,

\[ \mathtt{minimum} : F(T) \times (T \times T \to Bool) \to T \]

for the variant without a custom predicate, T is required to be Orderable. The signature is then

\[ \mathtt{minimum} : F(T) \to T \]

Parameters

xs

The structure to find the least element of.

predicate

A function called as predicate(x, y), where x and y are elements of the structure. predicate should be a strict weak ordering on the elements of the structure and its return value should be a Logical, or a compile-time Logical if the structure is heterogeneous.

Tag dispatching

Both the non-predicated version and the predicated versions of minimum are tag-dispatched methods, and hence they can be customized independently. One reason for this is that some structures are able to provide a much more efficient implementation of minimum when the less predicate is used. Here is how the different versions of minimum are dispatched:

Monadic left-fold of a structure with a binary operation and an optional initial reduction state.

Note

This assumes the reader to be accustomed to non-monadic left-folds as explained by hana::fold_left, and to have read the primer on monadic folds.

monadic_fold_left<M> is a left-associative monadic fold. Given a Foldable with linearization [x1, ..., xn], a function f and an optional initial state, monadic_fold_left<M> applies f as follows:

// with state

((((f(state, x1) | f(-, x2)) | f(-, x3)) | ...) | f(-, xn))

// without state

((((f(x1, x2) | f(-, x3)) | f(-, x4)) | ...) | f(-, xn))

where f(-, xk) denotes the partial application of f to xk, and | is just the operator version of the monadic chain.

When the structure is empty, one of two things may happen. If an initial state was provided, it is lifted to the given Monad and returned as-is. Otherwise, if the no-state version of the function was used, an error is triggered. When the stucture contains a single element and the no-state version of the function was used, that single element is lifted into the given Monad and returned as is.

Signature

Given a MonadM, a FoldableF, an initial state of tag S, and a function \( f : S \times T \to M(S) \), the signatures of monadic_fold_left<M> are

Monadic right-fold of a structure with a binary operation and an optional initial reduction state.

Note

This assumes the reader to be accustomed to non-monadic right-folds as explained by hana::fold_right, and to have read the primer on monadic folds.

monadic_fold_right<M> is a right-associative monadic fold. Given a structure containing x1, ..., xn, a function f and an optional initial state, monadic_fold_right<M> applies f as follows

// with state

(f(x1, -) | (f(x2, -) | (f(x3, -) | (... | f(xn, state)))))

// without state

(f(x1, -) | (f(x2, -) | (f(x3, -) | (... | f(xn-1, xn)))))

where f(xk, -) denotes the partial application of f to xk, and | is just the operator version of the monadic chain. It is worth noting that the order in which the binary function should expect its arguments is reversed from monadic_fold_left<M>.

When the structure is empty, one of two things may happen. If an initial state was provided, it is lifted to the given Monad and returned as-is. Otherwise, if the no-state version of the function was used, an error is triggered. When the stucture contains a single element and the no-state version of the function was used, that single element is lifted into the given Monad and returned as is.

Signature

Given a MonadM, a FoldableF, an initial state of tag S, and a function \( f : T \times S \to M(S) \), the signatures of monadic_fold_right<M> are

Compute the product of the numbers of a structure.More generally, product will take any foldable structure containing objects forming a Ring and reduce them using the Ring's binary operation. The initial state for folding is the identity of the Ring's operation. It is sometimes necessary to specify the Ring to use; this is possible by using product<R>. If no Ring is specified, the structure will use the Ring formed by the elements it contains (if it knows it), or integral_constant_tag<int> otherwise. Hence,.

For numbers, this will just compute the product of the numbers in the xs structure.

Note

The elements of the structure are not actually required to be in the same Ring, but it must be possible to perform mult on any two adjacent elements of the structure, which requires each pair of adjacent element to at least have a common Ring embedding. The meaning of "adjacent" as used here is that two elements of the structure x and y are adjacent if and only if they are adjacent in the linearization of that structure, as documented by the Iterable concept.

See the documentation for sum to understand why the Ring must sometimes be specified explicitly.

Equivalent to reverse_fold in Boost.Fusion and Boost.MPL.This method has the same semantics as reverse_fold in Boost.Fusion and Boost.MPL, with the extension that an initial state is not required. This method is equivalent to fold_right, except that the accumulating function must take its arguments in reverse order, to match the order used in Fusion. In other words,.

A binary function called as f(state, x), where state is the result accumulated so far and x is an element in the structure. For reverse folds without an initial state, the function is called as f(x1, x2), where x1 and x2 are elements of the structure.

Equivalent to length; provided for consistency with the standard library.This method is an alias to length provided for convenience and consistency with the standard library. As an alias, size is not tag-dispatched on its own and length should be customized instead.

Compute the sum of the numbers of a structure.More generally, sum will take any foldable structure containing objects forming a Monoid and reduce them using the Monoid's binary operation. The initial state for folding is the identity of the Monoid. It is sometimes necessary to specify the Monoid to use; this is possible by using sum<M>. If no Monoid is specified, the structure will use the Monoid formed by the elements it contains (if it knows it), or integral_constant_tag<int> otherwise. Hence,.

For numbers, this will just compute the sum of the numbers in the xs structure.

Note

The elements of the structure are not actually required to be in the same Monoid, but it must be possible to perform plus on any two adjacent elements of the structure, which requires each pair of adjacent element to at least have a common Monoid embedding. The meaning of "adjacent" as used here is that two elements of the structure x and y are adjacent if and only if they are adjacent in the linearization of that structure, as documented by the Iterable concept.

Why must we sometimes specify the Monoid by using sum<M>?

This is because sequence tags like tuple_tag are not parameterized (by design). Hence, we do not know what kind of objects are in the sequence, so we can't know a 0 value of which type should be returned when the sequence is empty. Therefore, the type of the 0 to return in the empty case must be specified explicitly. Other foldable structures like hana::ranges will ignore the suggested Monoid because they know the tag of the objects they contain. This inconsistent behavior is a limitation of the current design with non-parameterized tags, but we have no good solution for now.

Invoke a function with the elements of a Foldable as arguments.Given a function and a foldable structure whose length can be known at compile-time, unpack invokes the function with the contents of that structure. In other words, unpack(xs, f) is equivalent to f(x...), where x... are the elements of the structure. The length of the structure must be known at compile-time, because the version of f's operator() that will be compiled depends on the number of arguments it is called with, which has to be known at compile-time.

To create a function that accepts a foldable instead of variadic arguments, see fuse instead.

Parameters

xs

The structure to expand into the function.

f

A function to be invoked as f(x...), where x... are the elements of the structure as-if they had been linearized with to<tuple_tag>.

Rationale: unpack's name and parameter order

It has been suggested a couple of times that unpack be called apply instead, and that the parameter order be reversed to match that of the proposed std::apply function. However, the name apply is already used to denote normal function application, an use which is consistent with the Boost MPL library and with the rest of the world, especially the functional programming community. Furthermore, the author of this library considers the proposed std::apply to have both an unfortunate name and an unfortunate parameter order. Indeed, taking the function as the first argument means that using std::apply with a lambda function looks like