Monoids and foldable collections

To show how useful monoids are with collections that support the foldLeft and foldRight functions, let's take a look at the standard Scala list and the declarations of these two functions:

def foldLeft[B](z: B)(f: (B, A) => B): Bdef foldRight[B](z: B)(f: (A, B) => B): B

Usually, the z parameter in these two functions is called the zero value, so if A and B are of the same type, we will end up with the following:

def foldLeft[A](z: A)(f: (A, A) => A): Adef foldRight[A](z: A)(f: (A, A) => A): A

Looking at the functions now, we can see that these are exactly monoid rules. This means that we can write an example as shown in the following code, which uses the monoids we created previously:

object MonoidFolding ...

Get Scala Design Patterns - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.