A monad is a thing you put things in so you can do things with them.
Nimmo
Posted on April 3, 2022
You can skip reading this post now, if you like - it's all there in the title. But if you want to hear a little more, okay, I won't deprive you.
Think of a time when you've needed to process some inconsistent data. You won't have to think very far before you realise that you've had to do this any time you've had an optional/nullable value somewhere - something in JS that may or may not be truthy
, something in Java that may or may not be null
, something in Haskell that is a Maybe something
.
Let's say in JavaScript, I have an array of values (things) which I know may include undefined
values.
const myJsArray =
[value1, value2, value3]
Now I want iterate over (do something with) this array.
const double = x => x * 2
const myNewArray = myJsArray.map(double)
You probably don't want to end up with an array that contains a series of NaN
values; you already know that that's the first step on many paths that can lead to confusion for your users.
You've got your things, and you want to do something with those things
So what do you need? A thing you put those things in, so you can do something with them. You need a monad!
Earlier I mentioned Haskell's Maybe type. This type can store one of two variants: Just something
, or Nothing
. This means that even if you can't be sure whether something contains a value or not, you can still perform consistent operations anyway - the operation that you're trying to perform is required to handle what to do in either scenario, and then you can't end up with unexpected junk data somewhere else in your application. Or to put it another way - you know you can do the thing you wanted to on your thing because it was in a thing!
Why did I write this?
I've heard lots of different explanations of monads over the years. People tend to like using fancy words in their explanations, and I've seen lots of people shy away from Functional Programming altogether as soon as someone has mentioned monads to them. In fact, the Elm community doesn't even like to say the word monad (opting for Custom Types
instead, which I agree is a simpler term), because it is so commonly linked with unnecessary confusion.
Google "What is a monad?" and you'll probably see the same thing explained in lots of ways, but I bet none are quite as simple as the explanation you read before even reading this post. Although if you happen to get this post in your results...you're now also one step away from understanding recursion.
Posted on April 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.