r/functionalprogramming • u/lastsurvivor969 • Dec 17 '25
Question Yet another attempt at monad explanation
Hey I've been thinking about how to understand and explain monads for a while, trying both from a formal and practical point of view. It's been nagging me for a while, so I figured I could share my thoughts so far based on different sources I've read.
I'm approaching this from the perspective of software development. I would like to hear if others agree/disagree with the intuition I have.
The formal prerequisites of monad:
Semigroup (associativity): A formal property where; any
ordergrouping of operations will yield the same result.- Example: Multiplication a *(b*c) = (a*b)*c
- Example: Addition a+(b+c) = (a+b)+c
Monoid (Semigroup & Identity): A formal property where; The semigroup property is present and an "identity" operation that makes it possible to return the result of previous operations.
- Example: Multiplication a * b * c * 1 = a * b * c
- Example Addition a + b + c + 0 = a + b + c
- skip formality of endofunctors because this might lead to a rabbit hole in category theory...
Combine this with features of functional programming:
Model types with uncertainty: A type that encapsulates maybe a value OR an error
- Example notation: Normal type a , Uncertain type m a
Functions as values: Generally speaking, higher order functions that take arbitrary functions (expressions) as input.
- Example notation: A function that takes input function and returns a result type (a -> b) -> b
The above properties/features compliment each other so that we arrive at the monad type signature (takes two input arguments): m a -> (a -> m b) -> m b
How is a monad useful:
- Multiple monad executions can be chained together in arbitrary order (see semigroup)
- A specific monad execution might be unnecessary/optional so it can return result of previous monad executions instead (see monoid)
- Errors due to uncertainty are already modelled as types, so if a monad execution returns Error, it can be moved to the appropriate part of the program that handles errors (see types with uncertainty)
What business implications are there to using monad:
- Given a dependency to an external component that might fail, an error can be modelled pre-emptively (as opposed to reacting with try-catch in imperative style).
- An optional business procedure, can be modelled pre-emptively (see monoid)
- Changes in business procedure, can require changes in the sequence order of monad executions (which kinda goes against the benefits of semigroup property and potentially be a headache to get the types refactored so they match with subsequent chain monads again)
24
u/ScientificBeastMode Dec 17 '25
Man, I just call it “sequential operations that carry contextual info.” That’s really what it comes down to in practice.
Yes there are more abstract kinds of monads and other interesting aspects to focus on, but for a typical programmer, a monad is just a data structure with an operation that can chain onto itself while implicitly passing along a context to each new operation in the sequence. And they all basically have the same type-level structure.
This explains promises/futures, state, IO, nested list processing, nested tree processing, etc.
I don’t even bother with the category theory when explaining it to juniors. I don’t even mention functors unless it seems pertinent in the moment or they seem to care about the higher level theory.
7
u/Risc12 Dec 18 '25
Monads don’t get explained to you, they come to you. You uncover them, the universe present them to you.
One could learn monads in a day by programming, or one can read blogposts for a lifetime without gaining any understanding.
/uj
6
u/EluciusReddit Dec 17 '25
Why dodge category theory? Every other explanation is just long-winded, full of metaphors and lacking definitions, hand waving, etc.
Take the categorical definition, explain it clearly, then apply it to the category of types.
5
u/phlummox Dec 18 '25
The best way to explain monads probably depends a lot on your audience. But for most people, it's easier to see concrete examples and abstract from them, rather than by starting with definitions and working towards examples.
I think the wording could also do with tightening up in a few places. For a semigroup, "any order of operations" seems a bit vague, and might suggest that the operands can be re-ordered. Better to hew more closely to traditional definitions - here's Wikipedia's: "the order in which the operations are performed does not matter as long as the sequence of the operands is not changed" (my emphasis).
And similar for the definition of monad - it needs to be clear that although we can choose to evaluate particular operations in any order we like, the sequence of operands needs to remain the same.
Kudos to you though for sharing your ideas - feedback is always helpful for sharpening one's understanding.
3
u/jeenajeena Dec 17 '25
You should make this a blob post, enriching it with code examples
3
u/peterb12 Dec 17 '25
I'm fond of thinking of it this way, even though it blurs a lot of detail:
Just like we can think of a functor as a "mappable", we can think of a monad as a "sequenceable".
3
u/catbrane Dec 18 '25
People (in my experience!) seem to fall into programmer camps and mathematician camps.
I'd have two parallel paths of explanation, one starting from the least abstract and working up (you can write complete monadic IO system in less than 50 lines of pure Haskell), and one starting from the most abstract and mathematical top and working down. Hopefully the two meet in the middle somewhere.
From a programming point of view, monads are a wrapper around continuations, so you can link it to things like the denotational semantics of imperative languages (usually implemented with continuations), which in turn shows that monads are tiny imperative languages embedded in a pure functional language.
3
u/vu47 Dec 18 '25
I'm a mathematician and computer scientist who prefers FP, and I just thought I'd clarify some points from an algebraic structures point of view.
Your definition of semigroup has redundancy in it. You say:
You say associativity, which means precisely a(bc) = (ab)c for all a, b, c in the set of elements comprising the semigroup. Then you give the examples. I would make it clear that this is exactly what associativity is: if you have multiple computations, you can bracket them any way. This is called associativity. You cannot, however, change their order.
(Note that there are lots of forms of "weakened associativity" which don't hold all the time. For example, the octonions are not associative. They have a weakened form of associativity called alternativity, where (xx)y = x(xy) and y(xx) = (yx)x. Higher complex algebras like the sedenions have even less associativity, i.e. they only have power associativity, which means that:
x^(m+n) = x^m x^n, i.e. if you have something like xxxxxxx you can bracket it any way you want, but if you introduce a second value y ≠ x into the computation, this all falls apart.
This seems intuitive, because every other structure you've probably ever seen in your life has this property, but there are absolutely structures that are not power associative, although they are usually esoteric and not of any practical value from a CS / FP point of view.
I wouldn't say that the monoid has "the semigroup property" because there is no "semigroup property." A semigroup has properties. It itself isn't a property. A monoid is just a semigroup with a designated identity element (usually called 0 in an additive monoid and 1 in a multiplicative monoid, but in monoids of m x m matrices, in the additive matrix monoid, the all 0 matrix is the identity and in the multiplicative matrix monoid, the identity matrix is - unsurprisingly - the identity). In monoids of functions from a set A to A, the identity function (i.e. f(a) = a) is the identity.
Groups are also really important and while they aren't needed so much in FP since you often just want to use a monoid to do something like a fold expression, they are indispensible. A group is just a monoid where every element has an inverse element where if you combine an element with its inverse, it equals the identity. (So, in an additive group like the integers, the inverse of a is -a, and a + (-a) = 0, the additive identity. The integers don't form a multiplicative group because the only elements with inverses are -1 and 1.)
Commutativity (i.e. ab = ba, which does not follow from associativity and is a separate property) should be mentioned somewhere, probably, even if just as a footnote. There are commutative monoids and groups (which are called Abelian groups, just to make things confusing, since almost everything else is called commutative, e.g. commutative semiring, commutative monoid).
If you find this stuff interesting, I'd check out rings and fields, too, which have two operators (you can think of them as addition and multiplication), and you can also think of them often as the interplay between, e.g., and abelian group over all the elements and a monoid over the non-zero elements. Fields are very special and widely used in combinatorial constructions, coding theory, and cryptography.
3
u/-asap-j- Dec 18 '25
I found this video to be very digestible: https://youtu.be/C2w45qRc3aU
Using Optional as an example of a monad seriously helped create that sense of intuition.
2
u/yojimbo_beta Dec 18 '25
I am not deep into FP, but I do like using monads and am a PL enthusiast (possibly why this post popped up on my feed)
I have a very different perspective - my orientation towards monads is what they let me do, rather than their formal rules
Trying to define monads in terms of laws or functors or semigroups feels to me like trying to define a sandwich in terms of sandwich laws. We don't really count the faces of a sandwich, we eat them for their useful properties
I use monads because they let me express a series of actions, with a common operation over those action (functor), AND I can compose those series which means the monad becomes "invisible". I can think at two layers, one being a cross cutting concern.
I don't think the type system is necessary to define a monad, because you can do monad like things in untyped languages. Maybe that is a semantic question.
2
u/gotnoboss Dec 18 '25
So many “mathy” explanations. For the masses, I generally explain it like so.
It’s a box that contains a value. There are different boxes that all contain values but provided different effects. These boxes may have varying APIs but they all share a fundamental set of APIs that all behave the same way and follow the same rules. Using these boxes allows you to chain operations together easily to operate safely on their contained value. Once you know how to use one of these boxes, the other boxes should be familiar.
That’s more or less it.
2
u/Greenscarf_005 Dec 20 '25
I think explaining javascript Promise chain (.then) and Array.flatMap could be more intuitive
7
u/Massive-Squirrel-255 Dec 17 '25
I would be careful with that terminology. The term "order" makes me think of something like "I can do f first, then g, or I can do g first, then f, and it doesn't matter." But this would be commutativity: g * f = f * g. And for many monads that property doesn't really make sense in general, because the types don't match up for that equation to type check.
Anecdotally, if you pick up a typical textbook on abstract algebra, the term "semigroup" is not mentioned anywhere. This is because examples of things that are just semigroups, but not monoids, are uncommon. On the other hand, monoids arise in many situations. For example, concatenation of strings is a monoid structure on strings.
Here is something to chew on. As you say, the bind function for a monad
mhas type:m a -> (a -> m b) -> m b.And the
return(orpure) function has typea -> m a. I think that it is useful to consider these as part of a larger sequence of functions:comp0 : a -> m acomp1 : (a -> m b) -> (a -> m b)comp2 : (a -> m b) -> (b -> m c) -> (a -> m c)comp3 : (a -> m b) -> (b -> m c) -> (c -> m d) -> (a -> m d)And we could keep doing this as long as we wanted, out to
compn. Do you see the pattern here?This is one thing monads are useful for, but it's not the only thing. It would not be very important to invent the monad abstraction if there was only one example of monads. Moggi, the first person to apply monads to computer science, suggested that a value of type
m ais "a computation of typea". If the computation may fail, then we could modelm aasMaybe a. If the computation is nondeterministic, then we could modelm aasList a, to account for the multiple values it might return in different execution paths. If the computation has a side effect, thenm awould be the type of computations which return a value of typeabased on the state of the world, and also perform some change in the state of the world.I'm not sure what you mean by preemptively, but it's true that Haskell's type system tracks whether a function can fail. On the other hand, there are also imperative programming languages like Java which support statically checked exceptions, so there's information available to the compiler and the programmer ahead of execution about whether an operation may fail.
Hm, again, I'm not really sure what you mean by this.
In ordinary programming, if I have a sequence of functions
f : a -> b, g : b -> c, h : c -> d, it is possible for me to define a function of typea -> dby composing them. This composition is evidently associative - so evident, that the notationf(g(h(x))does not even signal to us whetherfis composed withgfirst orhis composed withhfirst, they are implicitly treated the same. Moreover, for any type there is a special identity functiona -> awhich does nothing, and composing it with any other function gives the same result.The concept of "monad" comes from the observation that for certain generic type constructors
m, there is a way to compose functionsf : a -> m b, g : b -> m c, h : c -> m dand get a functionh . g . f : a -> m deven though the types don't line up property. Moreover, there is a special identity functiona -> m awhich does nothing, and can be "skew-composed" with any functionf : a -> m borg: b->m ato get the same function back. The concept of "monad" explains exactly what additional structure is needed in addition to the type constructormin order to define this "skew-composition", and the algebraic laws are imposed to make this composition satisfy the same properties that ordinary function composition does, so that we can just writeh(g(f(x)))without thinking of whetherhis composed withgfirst, orgis composed withffirst: in OCaml, this is denoted:and it's not really obvious from this notation whether
fis combined withgfirst, orgis combined withhfirst. It doesn't really matter. They just happen in sequence: firstf, theng, thenh.0
u/[deleted] Dec 17 '25
[deleted] — view deleted comment