Monads Aren't That Hard
You should know what sets and types are, what a function is, and the consequences of composing functions.
In a programming language, you have types that are given to you and types that you can construct with your own definitions. Some examples of these are Int
, Bool
, and function types Int -> Int -> Int
. You may also may have types that generalize over types, an example is the type Optional<T>
where T
refers to any type. Notice that there is a difference between the types Optional<Int>
, Optional<Bool>
, and Optional<T>
.
We can construct the set
to be the set of all optional types. It is again worth noting that
Optional<T>
must have T
refer to a specific type. Now we can define a function
which maps each type Optional
, and
that corresponds to a generic type, in the same way Optional
. We can now impose additional structure on
that assigns every value
which is sort of odd to think about, but basically it maps values that are of a generic type Optional
would be
which has the obvious implementation. Lastly, there needs to be the map
which is a function that takes some function Optional
, this would be
which also has the obvious implementation. These functions give us enough to define the convenient binary operation
where the function
Finally, the algebraic rules for these functions are the following equalities, for all
where the left equalities is use the more concise M<T>
that coresponds to M
behaves like a monad. That’s all it is really, a generic type, with certain functions, satisfying some weird laws.
Above is insufficient to understand the benefits and patterns that monads provide. Usually the laws are disregarded as the type structure is usually enough to constrain the possible implementations. It isn’t obvious, but monadic behavior captures a very important sense in computing: composition of computational effects, which when understood and used correctly, makes you feel like a poet.
Additional Notes
Most of the time, it makes the most sense to define just the two functions
as the existence of the other