Scala Foldable

After learning aboutFunctor, the next piece with no dependency isFoldable.

Similarly toFunctor, this concept is taken from Category Theory and used in Functional Programing.

The operationfoldallows is an aggregation. It takes a starting element and combine it with theFoldabletype following the recipe provided by the methodf.

Foldcan the used to implementreduce. You should try it ! The difference withreduceis that the start element is either the identity of the operation provided inf, meaning an element that does not change the value, for instance empty string""for the string concatenation operation or the0for the+operation inInttype. It is possible to implement a version ofreducewhere the start element is simply the first element to be combined in thefoldif you have access to a functionheadfor instance. You will have to handle cases when theFoldableprovided is empty too.

As you can seefoldimplementation is relying on recursion. We talked about recursion in a previous episode.

Now you have seenFunctorandFoldable!

Reveal more information and clues
Load Exercise