ScalaFP: Let’s Begin With Semigroups.

While we start looking into functional programming, the first thing we find out is “Category Theory” and if you are not a mathematician, then, it is really a huge pain to find out the answers to questions like “what, how and when“. We are facing the same issue but after digging into it, we conclude that first step is to clear the concepts of “semigroups“, “monoids“, “monads” and more. Most of the FP programmers call them as functional design patterns.

In this post, we are trying to figure out, what are semigroups in the terms of a layman and for that, you just require simple mathematics knowledge.


According to mathematicians, semigroups are called algebraic structure. Algebraic structure means a set and operation (S, +). Let’s suppose we have a set of real numbers or integers or natural numbers {1, 2, 3, 4 ..n}. If that set has properties like closure and associativity, then those are called semigroups. Now let’s try to figure out what properties are these.


If we pick two elements from the set and perform some operation like (+) addition, (*) multiplication and the results belong to the same set, then those are called closure.  Example:

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

Select elements: { 2 , 3}

Operation: ( + ) Addition

Result: 5

5 belongs to set of integer means, this set and operation have property closure.



If we pick three elements from the set and perform operations twice, but during operations, we need to change the order as below.

export (1)If both results are same, that means set and operation follow associativity property. For example:

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

Select Elements: { 2, 3, 4}

Operation: ( + ) Addition

Associative Law:

( 2 + 3) + 4 = 2 + (3 + 4)

5 + 4 = 2 + 7

9 = 9

According to the result L.H.S(Left Hand Side) and R.H.S(Right Hand Side) both are equal, that means set and operation follow associative law, but if you trying to perform (-) subtraction with three elements you will not get equal result, that means, (-) subtraction is not following associative law.

The combination of above two properties is called Semigroups. Semigroup follows closure and associativity property.

Note:  Don’t confuse Associative with the Commutative property. In the Associative property position of the elements in the operation matters, i.e 1 + 2 does not equal to 2 + 1. 

Now the questions are:

  1. How can we use semigroups by using Scala?
  2. Where do we require to use semigroups?

In our next blog, we will try to answer the questions and create examples of semigroups using Scala as well as try to figure out its real-life usage.






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

7 thoughts on “ScalaFP: Let’s Begin With Semigroups.

Leave a Reply

%d bloggers like this: