Friday, September 27, 2013

Functors, Monads, Applicatives – can be so simple

When I started trying to get into these weird topics named “functors” and “monads” and so on, which came up in the Scala mailing list, I was more than slightly confused [1]. I read some articles (in the beginning not many existed), listened to mails, consulted book chapters, and even started learning Haskell to consult the very fine “Learning a Haskell for great good” chapters on that matters. Different authors use different ways to explain -and implement!- these concepts, what in the end is helpful. You can read an article, think, read some other perspective, come back to the first article again, a.s.o.
But it took some time to realise how darn simple it all can be in principle (and took more time to finally write about it). I worked with and restructured some examples until the simplicity of it all became obvious. So let me now present you my perspective on it, and perhaps it will help you to get into these seemingly strange things:
Given some type constructor C[_] and two types A and B, we want to apply functions of type C[A]=>C[B] .
a) ( A=>B )      => ( C[A]=>C[B] )   | Functor
b) ( A=>C[B] ) => ( C[A]=>C[B] )   | Monad
c) ( C[A=>B] ) => ( C[A]=>C[B] )   | Applicative