Functional Programming in Scala with the Monoid

This blog will look at the Monoid and is the 3rd in a sequence of 5, as a result of our Coding Guild session on August 1st about functional programming concepts. In the session, TypeClasses, Semigroups, Monoids, Functors and Applicatives were covered. The Cats library has been used, but not extensively introduced.

This time it is about Monoids. It builds upon the concepts that were covered in the previous blog posts (about Typeclasses and Semigroups). So if you didn’t read them yet …

In the previous post about Semigroups we already saw how the |+| operator works. Please revisit if it is not immediately clear how it works.

And when we run the code, in console it shows:

---- SummingExample ----
balance: Money(24,34)
my marbles: 19

But ouch, replication again. If we look closely at the code we see that the only difference between the two functions is the initial empty value for the foldLeft. Let’s refactor. Let’s define a fold with the empty value as a parameter:

The new code means that for every call we need to have an implicit Semigroup available, plus we need to pass an empty value on every call. But it can even simpler, with a Monoid. A Monoid is a Semigroup with an empty definition. Or, more formally: A Semigroup is a typeclass that defines an associative binary operation, called combine and an identity element:

Delen:

Gerelateerd

My goal is to build systems that last! A system that will put a smile on the face of people using it and the people paying for it. In my mind the Typesafe Reactive Platform (Scala, Akka, Play, etc.) will be a big game changer in the coming years. It is giving a boost to Reactive programming. Together with DDD (Domain Driven Design) and CQRS (Command Query Responsibility Segregation) we will be able to implement all business requirements in a way that fits the rapid changing world. Helping the business to realize their needs is what it is all about. I have great interest in software languages and technologies and how to use them to help the business in new and better ways.