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:


knoldus-advt-sticker


 

This entry was posted in Functional Programming, Scala and tagged , , , , , , , , . Bookmark the permalink.

5 Responses to ScalaFP: Let’s Begin With Monoids

  1. Anurag Srivastava says:

    Reblogged this on Anurag Srivastava.

  2. Pingback: ScalaFP: Let’s Start with Implicit and Scala Cats | Knoldus

  3. Pingback: ScalaFP: Understanding Monoids In Scala Pragmatically | Knoldus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s