Functors, Applicatives, And Monads In Pictures (In Elm)

This is a translation of Functors, Applicatives, And Monads In Pictures from Haskell into Elm. I left the Haskell examples as reference.

I don’t want to take any merit for writing this, I only went through the fun exercise of translating the code snippets in Elm.

If you enjoy this post be sure to say thanks to the author of the original version: Aditya Bhargava, @_egonschiele on Twitter.

This is the list of operators and function mentioned in the article:

(+) Addition
(*) Multiplication
(//) Integer division
(%) Modulo operation
(<|) Backward function application
(|>) Forward function application
(<<) Function composition
(>>) Function composition
Maybe.Maybe
Maybe.map
Maybe.map2
Maybe.andThen
List.map
List.concatMap

With parenthesis operator can be used without the infix notation like2 + 3 == (+) 2 3, so (+)3 return a function with type annotation number -> number.

All Elm code example can run inside elm-repl, if you don’t have Elm installed you can use the online version of elm-repl. To write multiline command be sure to add “/” at the end of the line, if not already present.

Here’s a simple value:

And we know how to apply a function to this value:

Simple enough. Lets extend this by saying that any value can be in a context. For now you can think of a context as a box that you can put a value in:

Now when you apply a function to this value, you’ll get different results depending on the context. This is the idea that Functors, Applicatives, Monads, Arrows etc are all based on. The Maybe data type defines two related contexts:

In a second we’ll see how function application is different when something is a Just a versus a Nothing. First let's talk about Functors!

Functors

When a value is wrapped in a context, you can’t apply a normal function to it:

This is where fmap comes in. fmap is from the street, fmap is hip to contexts. fmap knows how to apply functions to values that are wrapped in a context. For example, suppose you want to apply (+3) to Just 2. Use fmap:

Bam! fmap shows us how it's done! But how does fmap know how to apply the function?

Just what is a Functor, really?

Functor is a typeclass. Here's the definition:

A Functor is any data type that defines how fmap applies to it. Here's how fmap works:

So we can do this:

And fmap magically applies this function, because Maybe is a Functor. It specifies how fmapapplies to Justs and Nothings:

Here’s what is happening behind the scenes when we write fmap (+3) (Just 2):

So then you’re like, alright fmap, please apply (+3) to a Nothing?

Like Morpheus in the Matrix, fmap knows just what to do; you start with Nothing, and you end up with Nothing! fmap is zen. Now it makes sense why the Maybe data type exists. For example, here's how you work with a database record in a language without Maybe:

But in Haskell:

If findPost returns a post, we will get the title with getPostTitle. If it returns Nothing, we will return Nothing! Pretty neat, huh? <$> is the infix version of fmap, so you will often see this instead:

Here’s another example: what happens when you apply a function to a list?

Lists are functors too! Here’s the definition:

Okay, okay, one last example: what happens when you apply a function to another function?

Here’s a function:

Here’s a function applied to another function:

The result is just another function!

So functions are Functors too!

When you use fmap on a function, you’re just doing function composition!

Applicatives

Applicatives take it to the next level. With an applicative, our values are wrapped in a context, just like Functors:

But our functions are wrapped in a context too!

Yeah. Let that sink in. Applicatives don’t kid around. Control.Applicative defines <*>, which knows how to apply a function wrapped in a context to a value wrapped in a context:

i.e:

Using <*> can lead to some interesting situations. For example:

Here’s something you can do with Applicatives that you can’t do with Functors. How do you apply a function that takes two arguments to two wrapped values?

Applicatives:

Applicative pushes Functor aside. "Big boys can use functions with any number of arguments," it says. "Armed <$> and <*>, I can take any function that expects any number of unwrapped values. Then I pass it all wrapped values, and I get a wrapped value out! AHAHAHAHAH!"

And hey! There’s a function called liftA2 that does the same thing:

Monads

How to learn about Monads:

  1. Get a PhD in computer science.
  2. Throw it away because you don’t need it for this section!

Monads add a new twist.

Functors apply a function to a wrapped value:

Applicatives apply a wrapped function to a wrapped value:

Monads apply a function that returns a wrapped value to a wrapped value. Monads have a function >>= (pronounced "bind") to do this.

Let’s see an example. Good ol’ Maybe is a monad:

Suppose half is a function that only works on even numbers:

What if we feed it a wrapped value?

We need to use >>= to shove our wrapped value into the function. Here's a photo of >>=:

Here’s how it works:

What’s happening inside? Monad is another typeclass. Here's a partial definition:

Where >>= is:

So Maybe is a Monad:

Here it is in action with a Just 3!

And if you pass in a Nothing it's even simpler:

You can also chain these calls:

Cool stuff! So now we know that Maybe is a Functor, an Applicative, and a Monad.

Now let’s mosey on over to another example: the IO monad:

Specifically three functions. getLine takes no arguments and gets user input:

readFile takes a string (a filename) and returns that file's contents:

putStrLn takes a string and prints it:

All three functions take a regular value (or no value) and return a wrapped value. We can chain all of these using >>=!

Aw yeah! Front row seats to the monad show!

Haskell also provides us with some syntactical sugar for monads, called do notation:

Conclusion

  1. A functor is a data type that implements the Functor typeclass.
  2. An applicative is a data type that implements the Applicative typeclass.
  3. A monad is a data type that implements the Monad typeclass.
  4. A Maybe implements all three, so it is a functor, an applicative, and a monad.

What is the difference between the three?

  • functors: you apply a function to a wrapped value using fmap or <$> (for example: Maybe.map in Elm)
  • applicatives: you apply a wrapped function to a wrapped value using <*> or liftA (for example: Maybe.map2 (|>) or Maybe.map2 in Elm)
  • monads: you apply a function that returns a wrapped value, to a wrapped value using >>= or liftM (for example: Maybe.andThen in Elm)

So, dear friend (I think we are friends by this point), I think we both agree that monads are easy and a SMART IDEA(tm). Now that you’ve wet your whistle on this guide, why not pull a Mel Gibson and grab the whole bottle. Check out LYAH’s section on Monads. There’s a lot of things I’ve glossed over because Miran does a great job going in-depth with this stuff.

Examples in Ellie: https://ellie-app.com/NZqfGnCyBpa1

Gist: https://gist.github.com/lucamug/d24b18d99686d194373fec83e0b17cf7

This is a translation of Functors, Applicatives, And Monads In Pictures from Haskell into Elm. I left the Haskell examples as reference.

I don’t want to take any merit for writing this, I only went through the fun exercise of translating the code snippets in Elm.

If you enjoy this post be sure to say thanks to the author of the original version: Aditya Bhargava, @_egonschiele on Twitter.

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