And Monads for All: The State Monad
I think this article makes a simple concept seem unnecessarily convoluted. The first paragraph says:<p>&gt; This very complex object coming from the Category Theory is so important in functional programming that is very hard to program without it in this kind of paradigm.<p>May I try to dispel this myth that monads (and functional programming ideas in general) are complex?<p>New functional programmer are often faced with a dilemma: how do I do side effects (e.g., mutable state) in a purely functional way? Isn&#x27;t that a contradiction? In 1989, Eugenio Moggi gave us a compelling answer to these questions: monads. The idea of monads originally comes from category theory, but category theory is not at all necessary to understand them as they apply to programming.<p>We start with this: since a pure functional programming language doesn&#x27;t have step-by-step <i>procedures</i> built into the language, we instead have to choose our own suitable representation for impure programs and define a notion for composing them together. For example, a <i>stateful program</i> (a program that has read&#x2F;write access to some piece of mutable state) can be represented by a function which takes the initial state and returns a value and the new state (as a pair).<p>So, for example, if the mutable state is some integer value, then stateful programs that return a value of type `a` will have this type:<p><pre><code>  Int -&gt; (a, Int)
</code></pre>
Let&#x27;s give that type constructor a convenient name:<p><pre><code>  StatefulProgram(a) = Int -&gt; (a, Int)
</code></pre>
One key piece of the story is that this type constructor is a <i>functor</i>, which is just a fancy way to say that we can `map` over it (like we can for lists):<p><pre><code>  map(f, program) = function(initialState) {
    (result, newState) = program(initialState)
    return (f(result), newState)
  }
</code></pre>
Then, if we have a stateful program which produces a string (i.e., its type is `StatefulProgram(String)`) and a function `stringLength` which takes a string and returns its length, we could easily convert the program into a new program that returns the length of the string instead of the string itself:<p><pre><code>  newProgram = map(program, stringLength)
</code></pre>
Another way to phrase this is: we can compose a stateful program with a pure function to get a new stateful program. But that&#x27;s not quite enough to write useful programs. We need to be able to compose two stateful programs together. There are a few equivalent ways to define this. In Haskell, we would have a function pronounced <i>bind</i> that takes a stateful program and a callback. The callback gets the result of the stateful program and returns a new stateful program to run next.<p><pre><code>  bind(program, callback) = function(initialState) {
    (result, newState) = program(initialState)
    newProgram = callback(result)
    return newProgram(newState)
  }
</code></pre>
Some languages call this function `flatMap` instead of `bind`. In JavaScript, this is like the `then` function for promises. Whatever we call it, we can easily use it to write a helper function which sequences two stateful programs:<p><pre><code>  sequence(program1, program2) = bind(program1, function(result) {
    return program2
  })
</code></pre>
This amounts to running the first program, throwing away its result (see that the `result` variable is never used), and then running the second program.<p>One more ingredient is needed to make this `StatefulProgram` idea really useful. We need a way to construct a stateful program that just produces a value without touching the state. We&#x27;ll call this function `pure`:<p><pre><code>  pure(x) = function(initialState) {
    return (x, initialState)
  }
</code></pre>
Here&#x27;s what makes `StatefulProgram` a monad:<p>a) First of all, it needs to be a functor. That amounts to having a `map` function like we defined above.<p>b) We need a way to construct a `StatefulProgram(a)` given an `a`. That&#x27;s our `pure` function.<p>c) We need some notion of composition. That&#x27;s given by our `bind` function. (And note that `sequence` is just a special case of `bind` where the callback doesn&#x27;t use its argument.)<p>Category theory also gives us some common sense laws that monads must satisfy. For example, `bind(pure(x), callback) = callback(x)`.<p>The brilliant insight of Eugenio Moggi is that these three functions are essentially an interface for any kind of side effect. Mutable state is just one example. We could represent other kinds of side-effectful programs in the same way. For example, a program which returns <i>multiple times</i> could be represented as a list. Then the `map` and `flatMap`&#x2F;`bind` functions are exactly what you expect, and the `pure` function just constructs a list with a single element. Other examples of monads are IO (for interacting with the operating system), continuations (for doing fancy control flow), maybe&#x2F;optional (for programs that may return a `null` value), exceptions, logging, reading from an environment (e.g., for threading environment variables through your program), etc. They all have the same interface, which is represented in Haskell as the `Monad` type class (type classes are Haskell&#x27;s notion of interfaces).<p>Haskell also provides a convenient syntax called `do notation` for working with monads (this is a vast generalization of the async&#x2F;await syntax that is creeping into some popular languages). For example, a stateful program that reads the state and mutates it could be written like this:<p><pre><code>  program = do
    x &lt;- get     -- Read the state
    put 3        -- Update the state
    pure (x + 3) -- Return what the state used to be plus 3
</code></pre>
In our syntax, that would be equivalent to writing:<p><pre><code>  program = bind(get, function(x) {
    return bind(put(3), function(result) {
      return pure(x + 3)
    })
  })
</code></pre>
That callback hell is quite an eyesore, and I think that&#x27;s one of several reasons why monads are not very popular outside of the Haskell community.