Published by @alf on 2016-08-22

One day, there was an interview and I’ve got a question, “What is a working Scala developer’s definition of a Monad?”

Now I want you to come up with your own definition before we proceed.

We can focus on different aspects of monads in order to come up with a good answer: the question mentions Scala, so there might be something Scala-specific about monads, it mentions “a working developer” — supposedly, as opposite to a mathematician — so we’ll need to see what *matters* for a developer, and why the mathematician’s definition might not suit us; in fact, Scala monads are not exactly monads in the mathematical sense, so we’ll need to look at that closer.

# Syntax Sugar PoV

Let’s start with Scala: the main reason we care about monads in Scala is that there’s a syntax sugar for them (as explained in Wadler:1992, any monad can be used in for-comprehensions).

syntax sugar example

Now, a syntax sugar means that compiler will convert (desugar) the for loop into something less fancy. How does it do that? Scala documentation (Scala-yield-FAQ) says, “Scala’s “for comprehensions” are syntactic sugar for composition of multiple operations with foreach, map, flatMap, filter or withFilter. Scala actually translates a for-expression into calls to those methods, so any class providing them, or a subset of them, can be used with for comprehensions.” The Scala Programming Language by Martin Odersky explains that in further details: http://www.artima.com/pins1ed/for-expressions-revisited.html#...

(Note the “Things become a bit more involved if the left hand side of the generator is an arbitrary pattern pat instead of a single variable or a tuple.” bit — but I digress)

We can play with the desugared view by using REPL and the following mode: http://www.scala-lang.org/old/node/10553 http://stackoverflow.com/questions/9891407/getting-the-desuga...

# Monad Laws PoV

# That Pesky Future

The associativity law falls apart in case of the Future monad. Is it really a problem? Can it bite?

## Links

Wadler:1992 http://dl.acm.org/citation.cfm?id=143169 Scala-yield-FAQ http://docs.scala-lang.org/tutorials/FAQ/yield.html

## Notes

Here’s a talk on monads in Scala and their role in for-comprehensions, by Dan Rosen. I found it to be a very good explanation of both monads for real-life, and the constructs behind for comprehensions :

http://www.youtube.com/watch?v=Mw_Jnn_Y5iA

There’s a “monads in Scala” talk, http://berniepope.id.au/docs/scala_monads.pdf, which is way too mathematical for our purposes.