Scala Monad

We have done a lot in those last months !

Today is the dayMonadstops being scary.

We already learned aboutFunctor,Foldable,Applicative, andTraversable.

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

As you can see, it is simply aFunctorandApplicative, with one extra feature:flatten. Which allows us to define the world famousflatMap. As you can see in the definition,flatMapis simplymapfollowed byflatten.

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

  • map: which describe how to apply a transformation to the inner typeAof the wrapperF.
  • pure: which describe how to wrap aAinto aF[A]
  • flatten: which describe how to compactF[F[A]]in toF[A]

Those concepts are all that needed to enable complex behavior likefilterorflatMap.

I also wanted to show off what we learned in the last episode aboutTypeClasseswith theimplicit objectand theimplicit classwhich 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