# Monads: Are they really that complicated?

I have been working on Scala for around 2.5 years now, but still, feel that I have yet to explore a lot in this language. There are still a lot of topics unexplored.
One such topic is Monads. I have heard and read about it a lot of times but never actually got a chance to explore it. Recently I came across the term and thought about investing some time in exploring the same.
So this blog today is dedicated to What Monads are and what part they play in Scala language.

Before coming to Monads, let’s just quickly go through what Monoids and Functors are. These will help us to understand the monads in a much better way.

### A quick look At Monoids and Functors

#### Monoids

A Monoid is any type A that carries the following properties:

• Has some append method that can take two instances of A and produce another, singular, instance of A. This method is associative; if you use it to append multiple values together, the grouping of values doesn’t matter.
• Has some identity element such that performing append with identity as one of the arguments returns the other argument.
```object Sum extends Monoid[Int] {

def append(num1: Int,  num2: Int): Int = num1 + num2
def identity: Int = 0

}```

#### Functors

In simple words, a functor is a mapping between categories.
It maps some source category C to destination category F by mapping objects in C to objects in F and morphisms in C to morphisms in F. We say that (quoting myself) “given some object a or some arrow f: a → b from the original category, corresponding object (the one functor maps into) is denoted as F(a) and the corresponding arrow is denoted as F(f): F(a) → F(b)”.

A Functor instance must obey two laws:

• Composition: Mapping with f and then again with g is the same as mapping once with the composition of f and g
`fa.map(f).map(g) = fa.map(f.andThen(g))`
• Identity: Mapping with the identity function is a no-op
`fa.map(x => x) = fa`

```trait Functor[F[_]] {
def map[A, B](fa: F[A])(f: A => B): F[B]
}```

Let’s try to understand it with the help of an Example (Implementation of Option) :

```implicit val optionFunctor: Functor[Option] = new Functor[Option] {
def map[A, B](fa: Option[A])(f: A => B): Option[B] = fa match {
case None    => None
case Some(a) => Some(f(a))
}
}```

Now that you guys have some idea about what monoids and functors are, let’s now focus on understanding what Monads are.

### Monads: A class, a trait or a concept?

General Definition :
In functional programming, a monad is a design pattern that allows structuring programs generically while automating away boilerplate code needed by the program logic.

To simplify the above definition a bit more, We can think of monads as wrappers. You just take an object and wrap it with a monad.

Let’s just be clear on one thing: A Monad is not a class or a trait; Neither is it only dedicated to the Scala language. It is a concept related to functional programming.

When we create a monad around a value, we say that we lift the value into the container.

Here, the Unit is defined as: `A => M[A]`(pure/apply method)

`Monad` is a type that has implemented the `pure` and `flatMap`  methods.

```trait Monad[F[_]] {
def flatMap[A, B](fa: F[A])(f: (A) => F[B]): F[B]
def pure[A](x: A): F[A]
}```

Pure is a method that takes any type and creates the “computation builder”, wrapping it in the container type or “context”.

Using these methods, we can define the following using `flatMap` and `pure`:

• the `map`
• the Monoid operations `append` and `identity`
```trait Monad[M[_]] { // extends Monoid[_ => M[_]]
def pure[A](a: A): M[A]
def flatMap[A, B](a: M[A])(fn: A => M[B]): M[B]

def map[A, B](a: M[A])(fn: A => B): M[B] = {
flatMap(a){ b: A => pure(fn(b)) }
}

def append[A, B, C](f1: A => M[B], f2: B => M[C]): A => M[C] = { a: A =>
val bs: M[B] = f1(a)
val cs: M[C] = flatMap(bs) { b: B => f2(b) }
cs
}

def identity[A]: A => M[A] = a => pure(a)

}```

Scala collections use monads internally for functional composition ability. Some of these collections include :

• List
• For-comprehensions
• Option
• Map
• Set
• Vector
• Stream
and more…..

We will try to cover these in detail in future blogs. For now, we only need to know that each of these collections implements its own version of `Unit` (i.e. `apply`) and `flatMap`, and we can, therefore, treat them as monads.

### This is Interesting. But why Use Monads?

Now that we know what Monads are, let’s try to take it a little forward and try to understand why do we need it.

In case of a complex problem, the best way is to break down our problem into a number of small functions, and then compose those functions together into one master function that represents the entire task.

Composing functions is the reason why we want to use monads and should care about monads. It is also true to say that when we have side effects in our program, then the monads come into the picture.

We can create a container that can perform actions on its contents, and then use that container as a way to manage those contents and perform the actions we need, in the order we need to, encapsulating the whole operation through function composition. Instead of handling the objects and outputs of functions, we put the objects into a container and then write up a manifest of all the functions.

I hope that now you guys have some idea about what monoids, functors and monads are. I admit that the monads seem to be a complicated and advanced Scala topic, but once you get to know about it in detail, we will also feel comfortable in using it.

Hope This Helps. Stay Tuned for more.  🙂

#### Written by Anmol Sarna

Anmol Sarna is a software consultant having more than 1.5 years of experience. He likes to explore new technologies and trends in the IT world. His hobbies include playing football, watching Hollywood movies and he also loves to travel and explore new places. Anmol is familiar with programming languages such as Java, Scala, C, C++, HTML and he is currently working on reactive technologies like Scala, Cassandra, Lagom, Akka, Spark and Kafka.

## 3 thoughts on “Monads: Are they really that complicated?5 min read”

1. girdharshubham says:

Just what I was looking for!

1. Anmol Sarna says:

Happy to help 🙂