ScalaFP: Let’s Begin With Monoids

As we discussed in our semigroups post, monoids are also kind of functional design patterns. Most of the FP beginners are always confused between Monads and Monoids. According to them both are the same, Is It? In this post, we will be trying to learn “what monoids are according to mathematical terms?” For this, we just require the basic mathematical knowledge.

Monoids

The one line definition of Monoid is “Monoid must be a semigroup with identity element but not vice versa“. I am sure, this online definition gives you some picture of monoids. As we know, monoids must be a semigroup which means, “monoids have closure and associative property” as well as an identity element.

We are pretty much familiar with closure and associative property in our last post, but today let’s figure out, what is identity element.

Identity Element:

Let’s suppose we have a set of integers.If we perform an operation on a single element of the set with an identity element, then the result must be equal to the single element as below:

export (2)

In the above diagram (e) is an identity element, which depends on the operation you perform and after the operation, the result must be equal to (x). Take another mathematical example:

Set of Integer: {1, 2, 3, 4, …. n}

Element: 2

Operation: (+) Addition

Identity Element: 0

Result: 2 + 0 = 2

According to the above example, we are performing (+)Addition operation, that’s why our identity element is 0, But if we need to perform multiplication our identity element will become 1. The identity element depends on the type and operation we perform.

Now, we have an idea about monoids, which contains all three properties. But the questions which still remain are :

  1. What are the benefits of identity elements within monoids?

  2. How can we use monoids with Scala?

  3. Where we require Monoids?

We will be trying to resolve all of these questions in our next post. I hope you enjoyed it.

References:

  • https://www.youtube.com/watch?v=OWm6Nw7mltA&index=1&list=PLnzDeyLkEDqhFtlhKQ2c2wYCcIU2Lusy-&t=0s

knoldus-advt-sticker


 

Written by 

Harmeet Singh is a lead consultant, with experience of more than 5 years. He is #programmer #geek #scala #java #jvm #functional #back2basics #foodlover #family http://www.harmeetsingh.in/

6 thoughts on “ScalaFP: Let’s Begin With Monoids

Leave a Reply

%d bloggers like this: