Beliebte Suchanfragen
//

Monads demystified

8.12.2015 | 3 minutes of reading time

In this short post I want to take a look at monads from a pragmatic perspective, i.e. why and how monads can be useful for developers. I won’t talk about any theory, but instead show code examples in Scala. I’ll even call things monad which don’t fully obey the monad laws as long as they are monadic enough to be useful (well known experts did that before, so I’m not afraid).

Here comes the use case for monads:

Monads are for sequencing dependent contextual computations.

Let’s dissect this statement step-by-step. A computation is a function which takes an argument of type A and returns a “contextual” value of type M[A]:

1def f[A](a: A): M[A]

So obviously we’re talking about parameterized types like Option[A] or Future[A]. These types provide some sort of context for the type they are parameterized with. An Option[A] expresses the fact that there might or might not be a value of type A. And the context a Future[A] defines is an asynchronous – i.e. delayed and potentially erroneous – computation of type A.

Here are two examples for a computation returning a future:

1def f(n: Int): Future[Int] = Future(n + 1) // Not really rocket science ...
2def g(n: Int): Future[Int] = Future(n - 1) // Can you guess what I have in mind?

Imagine we want to first call f with some value and then g with the value contained in f‘s result. Put another way: we want to sequence the dependent computations g and f by somehow pulling the value out of the context of the result of the first computation and passing it to the second.

Now we are facing the problem that a future might hold a value or not. This is, because its value is determined asynchronously and the future might not yet be completed. And if something goes wrong, a future will hold a failure instead of a value. Therefore simply grabbing into the future to pull out the value won’t work.

This is where monads shine, because when we say that some parameterized type M[A] is a monad that means that there is a function called flatMap which takes a value of M[A] and a function A => M[B] and returns a value of M[B]:

1def flatMap[A, B](ma: M[A])(f: A => M[B]): M[B]

Getting back to our example, as a Future is a monad (well, monadic enough), it has a flatMap method. Therefore we can sequence f and g the following way:

1val n = f(42).flatMap(g) // Same as f(42).flatMap(n => g(n))
2assert(Await.result(n, 1.second) == 42)

So the monad itself – via its flatMap method – knows how to provide the value to the function to be sequenced. Hence instead of us trying to pull out its value we let the monad do this for us.

We could easily sequence more functions of the proper shape using flatMap, but that starts looking confusing quickly. Luckily there’s some special syntax support called for comprehensions which gets translated to flatMap calls:

1def h(n: Int): Future[Int] = Future(n * 2)
2 
3val m = for {
4  m1 <- f(42)
5  m2 <- g(m1)
6  m3 <- h(m2)
7} yield m3
8assert(Await.result(m, 1.second) == 84)

As you can see clearly, monads are for sequencing computations where the next computation depends on the value wrapped in the context of the previous one. That’s all that needs to be said, at least from a pragmatic perspective. Simple, eh?

If you want to dive deeper, here’s a totally incomplete suggestion of links:

Here comes the full example code (for the REPL):

1import scala.concurrent.{ Await, Future }
2import scala.concurrent.ExecutionContext.Implicits.global
3import scala.concurrent.duration.DurationInt
4 
5def f(n: Int): Future[Int] = Future(n + 1)
6def g(n: Int): Future[Int] = Future(n - 1)
7def h(n: Int): Future[Int] = Future(n * 2)
8 
9val n = f(42).flatMap(g)
10assert(Await.result(n, 1.second) == 42)
11 
12val m = for {
13  m1 <- f(42)
14  m2 <- g(m1)
15  m3 <- h(m2)
16} yield m3
17assert(Await.result(m, 1.second) == 84)

share post

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.