Welcome to the series on Functional Programming. During this post, I am going to explain the concepts of FP in the easiest way I can.

I’m still studying Functional Programming. But as you know, understanding each concept of FP is very confusing.


Let’s Talk About Magma First Before Jumping Into the Main Topic

Why do I want to talk about Magma all of a sudden? Because almost every concept in FP doesn’t exist in isolation. They mostly come from their parent-like concepts. It is like that you should be aware of what sports are to understand what soccer is. Semigroup comes from Magma, and Magma is the root concept of many existing concepts in FP.

Let’s say we have an array consisting of numbers, [1, 2, 3], and I have some functions performing as follows.

const magmas = {
  add: (x: number, y: number): number => x + y,
  sub: (x: number, y: number): number => x - y,
  mul: (x: number, y: number): number => x * y,
  div: (x: number, y: number): number => x / y,
};

All functions in magmas are two arity functions that take two numbers and return a number. For example, magmas.sub(5, 3) is equal to 2, a number.

Let’s say there’s a set of some elements, S, that all are T type (number type, in this example). And you pick any two elements from Sa and _b. _If the result of a · b is also a T type element, which is a member of _S, _and if this works with every random two elements in SS is considered Magma. (The · symbol in this example means any operation that works property with two elements).

Magma: a ∈ S, b ∈ S --> a·b ∈ S

For example, if · only contains the four binary operations, +, -, * and /, then all functions in magmas always return a Number type element after operating their calculation.


What is Semigroup?

Image for post

The image is from wiki

Okay, I said earlier in this post that Semigroup comes from Magma. Magma is a set of elements that always assures every element from it is still the same type element after operating, such as adding or subtracting.

Basically, if a set, S, of elements to be Semigroup, every element of it must meet the condition of Magma. Plus, they also must comply with the following rule.

If ab, and c are a member of a set _S _and where · is a binary operation, (a·b)·c must be equal to a·(b·c). Both of their results must be a member of S.

#functional-programming #function

Functional Programming Series: What Is a Semigroup?
1.15 GEEK