O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Monoids

It is again pretty simple. From school math, we know that number multiplication is associative. And there is something like an identity element, 1 in case of multiplication. For example, the following expressions are equivalent:

(9*7)*2 = 9*(7*2)  

Even if we do the multiplication in any order, we get back 126. The identity element now is 1. Concatenating strings is also associative. In the following code, the identity element is "". The "Singing" + "" string is the same as "" + "Singing", and the line contains multiple strings:

((("Singing" + " In") + " The") + " Rain") 

This is the same as the one shown here:

("Singing" + " In") + (" The" + " Rain").

A data structure that obeys these rules is Monoid, and we have a natural way to use

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required