Scala Monad

We have done a lot in those last months !

Today is the day Monad stops being scary.

We already learned about Functor, Foldable, Applicative, and Traversable.

We have almost encountered all the beast of Category Theory at this point. Today we are going to tackle Monad.

As you can see, it is simply a Functor and Applicative, with one extra feature: flatten. Which allows us to define the world famous flatMap. As you can see in the definition, flatMap is simply map followed by flatten.

When you look at the implementation, we only need a few concept defined:

  • map: which describe how to apply a transformation to the inner type A of the wrapper F.
  • pure: which describe how to wrap a A into a F[A]
  • flatten: which describe how to compact F[F[A]] in to F[A]

Those concepts are all that needed to enable complex behavior like filter or flatMap.

I also wanted to show off what we learned in the last episode about TypeClasses with the implicit object and the implicit class which allow us to give a shortcut for the function we want to use often.

As always, if you have any questions, reach out on Discord !

Reveal more information and clues
Load Exercise