Monads: Are they really that complicated?

Reading Time: 5 minutes

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.

Screenshot from 2019-04-21 14-45-40

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.

 

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

 

 

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

 

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.

Screenshot from 2019-04-21 15-01-19.pngTo 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.

 

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

 

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.

Screenshot from 2019-04-21 14-50-49.pngIn 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.  🙂

 
knoldus-advt-sticker

Written by 

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

Comments are closed.