Monad Transformers in Scala — Unlocked

Effect from a different angle

From another angle, we say any computation that should potentially yield A would become more intuitive and useful if it is yielding A under an effect, instead of a raw A . A typical example is trying to get an account from an account repository by passing an Id. If the computation has a return type of Account, it means, it should always exist. We want the computation’s return type to expose the fact that, account may or may not exist. In other words, it should return an Account under an effect — Option. Hence you may find the second get function in the below example to be more sensible.

Was that effect enough?

Well, we said the repository may or may not provide an account, and hence we returned an Option of account. We know the computation is under the effect Option. But is that enough to depict the behaviour of a database operation? What if the operation resulted in a database failure and you want to tell that to the user of the functionget?.This simply means the result should beeither a database exception or Option[A] . In other words, we need to lift Option[A] to another effect that can handle a database exception. We can use scalaz’s either \/ to depict this behaviour. The get function hence returns a DatabaseException \/ Option[A]. At this point you have fairly a complex return type that is basically a stack of two effects — Option and on top of it, \/[DatabaseException, ?].

Multiple Effects and Monad Transformers.

You are almost convinced that any computation can yield effects that are stacked upon each other similar to DatabaseException \/ Option[Account] . However, stacking the effects leads to difficulty in extracting the actual value that we need to further execute the rest of the computation with Account. We wish the stacked effect was just acting as one single effect — one single Monad, so that we can flatMap over it or map over it and continue the operation; something like this:

Mechanism behind Monad Transformers (Skip it if you want to skip it)

Recently I have posted a better version of this explanation in my blog here: https://afsalthaj.github.io/myblog/posts/2018-04-16-monad-transformers.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Afsal Thaj

Afsal Thaj

A software engineer and a functional programming enthusiast at Simple-machines, Sydney, and a hardcore hiking fan. https://twitter.com/afsalt2