What are monoids in functional programming? Explain with examples in javascript

What is a Monoid?

A monoid consists of three components:

  1. A set of values.

  2. An associative binary operation that combines two values of the set, producing another value of the same set.

  3. An identity element within the set, which when combined with any other element using the binary operation yields the other element unchanged.

Examples of Monoids

1. Addition Monoid

Consider the set of integers along with the addition operation. The identity element is 0, and addition is associative. For example:

// Set of integers with addition
const integers = [1, 2, 3, 4, 5];

// Associative operation: Addition
const addition = (a, b) => a + b;

// Identity element: 0
const identity = 0;

// Result of combining all elements using addition
const result = integers.reduce(addition, identity);
console.log(result); // Output: 15

2. String Concatenation Monoid

Another example is the set of strings with concatenation as the operation and an empty string as the identity element:

// Set of strings with concatenation
const strings = ["Hello", " ", "World"];

// Associative operation: String concatenation
const concatenation = (a, b) => a + b;

// Identity element: Empty string
const identity = "";

// Result of combining all strings using concatenation
const result = strings.reduce(concatenation, identity);
console.log(result); // Output: "Hello World"

Using Monoids for Function Composition

Monoids are incredibly useful for composing functions. We can define a function that combines two functions and an identity function that leaves a value unchanged. Here's how it works:

// Function composition using monoids
const compose = (f, g) => x => f(g(x));

// Identity function
const identity = x => x;

// Example functions
const addOne = x => x + 1;
const double = x => x * 2;

// Composing addOne and double functions
const composedFunction = compose(addOne, double);

console.log(composedFunction(3)); // Output: 7 (3 * 2 + 1)

Conclusion

Monoids provide a powerful abstraction for composing values and functions in functional programming. By understanding the properties of monoids and how they operate, you can write more concise, modular, and reusable code in JavaScript. Whether you're dealing with mathematical operations, string manipulation, or function composition, leveraging monoids can greatly enhance your programming experience.

Did you find this article valuable?

Support Coolhead by becoming a sponsor. Any amount is appreciated!