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 foldLeft
in it, as shown in the following code:
scala> class MyMonoid { | def iden = "" | def f(x: String, y: String) = x.concat(y) | } defined class MyMonoid scala> val p = new MyMonoid p: MyMonoid = MyMonoid@4e9658b5 scala...