Type Class – Foldable

The next type class to look at is foldable, which is based on the Foldable type class in Haskell. In addition to being quite useful, this type class is a good demonstration of the interactions between type classes.

Where mappable is about transformation, foldable is about aggregation. For example, mapping a vector will return a new vector with its values transformed, while folding a vector will return some combination of those values.

It might appear as though every foldable is also mappable and vice versa, but there are some exceptions. For example, you can’t aggregate every result of a function. Likewise, mapping a binary search tree might require changing the tree structure going beyond plain mapping.

To demonstrate folding, the following code would output the sum of numbers from 1 to 10:

The lfold function is a left fold where objects are aggregated from the left or the “beginning”. In foldables like std::unordered_map, the actual order of aggregation is not consistent.

Notice that fold actually has a requirement that A is a monoid, alluding to the syntax of the future concepts lite. The idea is that if the value type is a monoid, a seed value and aggregation function can actually be obtained from the monoid type class.