Abstract alge… what? Monads

The day has finally come. Today we’ll take a look at the noteworthy monads.

A monad, just like a monoid, may seem to be a concept taken from the deepest hell. It seems almost impossible to understand. Nothing could be further from the truth. Let’s try to shed light on this concept.

There are many definitions of what a monad is. Some are complicated, others are easier.

44b0bd758f8ee5c81362923f0d5c8e017c9ddf623925e60c29a4c015b89fbb45

As we are really fond of simple definitions, in this first contact with monads we’ll say that they are algebraic structures that have a constructor and a flatMap method which, as we already saw in previous posts, is a concatenation of a map method and a flatten.

What do we need to create a monad?

As we have already said, we need basically two methods: a constructor (commonly called apply) and a flatMap method.

In addition, there are some monadic laws to comply with. Those laws require that certain relations exist between the abovementioned functions. However, for better or worse, we are not going to analyse them in this post in order not to complicate it unnecessarily.

Case: Option type

Option type, as already mentioned in some other posts, is a monad.

Bdu68sACYAAfkkr

Let’s get into the insides of Scala to see how it’s defined:

def apply[A](x: A): Option[A] =
  if (x == null) None else Some(x)

def flatMap[B](f: A => Option[B]): Option[B] =
  if (isEmpty) None else f(this.get)

As can be appreciated, Option type has a constructor (apply) and a flatMap method. Thanks to these two methods (and to the compliance with monadic laws), we can say that Option type is a monad.

However, in Scala’s basic library, the Monad type is not defined. This is where Scalaz comes in. Let’s see how Scalaz defines the Option type as a monad:

def point[A](a: => A) = Some(a)

def bind[A, B](fa: Option[A])(f: A => Option[B]) =
  fa flatMap f

As can be seen, in Scalaz, the flatMap method is called bind. In turn, the point method calls a constructor and therefore, the apply method is called. Henceforth, if we define these two methods for our own types (them complying with monadic laws too), we’ll be able to create our own monads.

And, as they’ll have a flatMap and an apply methods (or same thing, a bind and a point methods), we’ll be able to use the for comprehension structure to make our code more readable, as we learned two weeks ago:

for {
  x <- Some(1)
  y <- Some(2)
} yield x + y //Some(3)

Conclusion

Monads are much more than we have described in this post. It’s a whole new world to explore. Apart from the abovementioned monadic laws, there are some predefined monads, such as the Reader one. Furthermore, the use of monads is geared towards avoiding side effects, which is quite important in pure functional programming. But all in due time 🙂

2 comentarios en “Abstract alge… what? Monads

Deja un comentario