Monoid

A monoid can be thought of a class, like Op in the previous section, that has an associative binary operation. + (or plus or addition) is an associative binary addition. A monoid also has an identity operation, that is, you can +0 and get back the original value. If you think of times (*) instead of +, then the identify element is 1 because * 1 returns the original value.

When you look at scalaz and see Monoid, just think of a class whose instances have a function in it, like + and an identity element, like 0. That's it. For programmers, an instance of that class could then be passed around to different functions. Your function might take some arguments along with a monoid class instance. Then your function could perform an operation on the arguments not caring about the specific operation is being applied as long as it is expressed in your monoid instance. This sound pretty abstract but is very common. You may have written classes that have methods that have a name such as addItemToList or equivalent. You could have written performOpWithMonoid and passed in the monoid that holds the "add" logic.

Think of an instance of a monoid as a Strategy design pattern that defers logic to an object instance instead of hard coding it in your function.

In scalaz, a Monoid has the identity element zero and the binary association operation of append. In the example below, we create a Monoid for the Int type. Then we use it to print its zero and run the append method. You can see that in scalaz its just an object that has these two functions. You could pass an instance into your function and then use it.

scala> val m = Monoid[Int]
val m = Monoid[Int]
m: scalaz.Monoid[Int] = scalaz.std.AnyValInstances$$anon$5@52e4f6fc

scala> m.append(1,2)
m.append(1,2)
res13: Int = 3

scala> m.zero
m.zero
res15: Int = 0

A Semigroup is a Monoid but lacks the identity element. You could also say that a Monoid is an Applicative with an identity element.

Last updated