Groovy Monads
In the last two posts, I have discussed how to implement functors and applicatives in Groovy. This post discusses the related topic of monads.
Before we start, let’s review the essence of the differences between these three concepts. The primary method for functors, applicatives and monads are map, apply and flatMap respectively.
Class  Primary Method  Argument  Argument  Result  

Monad<T<_>> 
flatMap 
T<A> 
F<A, T<B>> 
T<B> 

Functor<T<_>> 
map 
T<A> 
F<A, B> 
T<B> 

Applicative<T<_>> 
apply 
T<A> 
T<F<A, B>> 
T<B> 
In the table above, I have used invalid syntax to represent the class to indicate that Functor, Applicative and Monad all take a single generic type argument. The type argument itself takes a single type argument. In Groovy, we make do with a lack of higher order types and represent the class without the <_> component, e.g. Functor<T> [3].
We deduce that the differences between the classes in the table are:

Functor: apply a function (F<A, B>) to a contextual value using map.

Applicative: apply a contextual function (T<F<A, B>>) to a contextual value using apply.

Monad: apply a function that returns a contextual value (F<A, T<B>>) to a contextual value using flatMap.
We define a Monad class containing two abstract methods unit and flatMap. Monad inherits from the Applicative class, in practice, the two abstract methods unit and flatMap are sufficient to implement Functor’s map method and Applicative’s pure and apply methods.
@TypeChecked
abstract class Monad<M> extends Applicative<M> {
abstract <B> M<B> unit(B b)
abstract <A, B> M<B> flatMap(M<A> ma, F<A, M<B>> f)
// other concrete methods omitted for clarity
}
As we have done previously for functors and applicatives, let’s create concrete monads for java.util.List and fj.data.Option (we could have done similarly for java.util.Optional) to build intuition on how these work.
@TypeChecked
class ListMonad extends Monad<List> {
@Override
def <A> List<A> unit(A a) {
[a]
}
@Override
def <A, B> List<B> flatMap(List<A> list, F<A, List<B>> f) {
def result = new LinkedList<B>()
for (A a: list) {
result.addAll(f.f(a))
}
result
}
}
@TypeChecked
class OptionMonad extends Monad<Option> {
@Override
def <A> Option<A> unit(A a) {
Option.some(a)
}
@Override
def <A, B> Option<B> flatMap(Option<A> o, F<A, Option<B>> f) {
o.isSome() ? f.f(o.some()) : Option.<B>none()
}
}
My intent is to show some examples of using these simple monads and some concrete methods we can derive from the monad methods unit and flatMap in the next post[4].
Bibliography

[1] FunctionalGroovy, https://github.com/mperry/functionalgroovy

[2] Functors, Applicatives, And Monads In Pictures, http://adit.io/posts/20130417functors,_applicatives,_and_monads_in_pictures.html

[3] Groovy Functors, http://mperry.github.io/2014/07/01/groovyfunctors.html.