After learning about Functor, the next piece with no dependency is Foldable.
Similarly to Functor, this concept is taken from Category Theory and used in Functional Programing.
The operation fold allows is an aggregation. It takes a starting element and combine it with the Foldable type following the recipe provided by the method f
.
Fold can the used to implement reduce
. You should try it ! The difference with reduce
is that the start element is either the identity of the operation provided in f
, meaning an element that does not change the value, for instance empty string ""
for the string concatenation operation or the 0
for the +
operation in Int
type. It is possible to implement a version of reduce
where the start element is simply the first element to be combined in the fold
if you have access to a function head
for instance. You will have to handle cases when the Foldable
provided is empty too.
As you can see fold implementation is relying on recursion. We talked about recursion in a previous episode.
Now you have seen Functor
and Foldable
!