Hacker News new | ask | show | jobs
by i2talics 44 days ago
I've long suspected that one of the things that makes monads notoriously difficult to explain to people outside of the Haskell ecosystem is that very few other languages even have a kind system that you are allowed to manipulate in code (and in some, like C++, it's so esoteric that you basically never see it). First explaining that you can even abstract over "type->type" kinded things gets you a lot of the way towards monads without actually describing monads.
8 comments

> things that makes monads notoriously difficult to explain to people outside of the Haskell ecosystem

Huh, I thought a monad is just a monoid in the category of endofunctors, what's the problem?

It's about as difficult as describing vectors in math. Vectors aren't really "little arrows" or "things with magnitude and direction" (because then functions wouldn't count), I think there's a similarly cryptic saying that "a vector is just an element of a vector space" or "a tensor is anything that transforms like a tensor".

In both cases what they really are is an abstract concept defined by things that satisfy some definitions, but in practice it's easier to just look at a few concrete examples like Maybe.

And here I was convinced that they’re burritos!

I will say that explaining functors to my coworkers was always much simpler, and then naturally led to monads

I suspect all branches of tech have their rite of passage.

For haskellers, it is writing a monad tutorial

For javascripters, it is writing a framework

For make-stuff-with-LLM people, it is producing a diagram explaining your code generation factory

... and so on

The problem is not monads. Any programmer understands the need to represent "the world". It is the need to keep that representation modular that leads to monad transformers, which makes regular people (like me) simply check out and go back to C++

https://en.wikipedia.org/wiki/Monad_transformer

Monads have no inherent connection to any notion of "the world"; that's just a thing for Haskell's IO monad specifically (and perhaps derivatives thereof) because what that abstracts over is effects that are external to the program.

A monad is any construct of abstraction that obeys the Monad Laws. This may seem a useless definition, but my point is that deriving a useful intuition for the concept of the monad is necessarily challenging because they cannot readily be boiled down any further than that without loss of information.

The best intuitive explanation I've developed so far is that a monad is an abstraction over structures of ordered computations. The most ready examples for non-functional programmers are probably exceptions (and their handlers) and nullable types (typically called "optional types" in languages with first-class handling of such things, unlike Java).

Interesting. I come from a math background and for me, monads capture a notion of "things that depend on a type". So for every type X you can think about Lists/Records/Trees/... of X. And if you're lucky this gadget let's you do two things: 1. You can turn every instance x of X into a primitive List/Record/Tree/... of Xs. 2. You can flatten Lists of Lists of Xs into plain Lists of Xs, etc.

This is something you see a lot once you know what you're looking for.

And if you're really lucky, these two are nicely compatible:

For example there are two ways to get from L(L(L(X))) to L(X): By either flattening first in the inside or first on the outside.

And for a monad, you get the same result either way.

And the computational part is then really more of a consequence: If you've got some function of type X->L(Y) and another one of type Y->L(Z) then you can compose them to a function of type X->L(Z).

What also makes the monad more interesting than just composition or flattening is that when executing the ordered computation, you can decide next computations based on previous results. This was what really made it click for me.
I find it easier to think of them as transforms which turn "a function which accepts/returns plain values" into a "function which accepts and returns a type which embeds plain values".

    map     :: (a -> b)     -> (t a -> t b) -- Functor
    bind    :: (a -> t b)   -> (t a -> t b) -- Monad
    cobind  :: (t a -> b)   -> (t a -> t b) -- Comonad
    ap      :: t (a -> b)   -> (t a -> t b) -- Applicative
The resulting function type is the same in all these cases - the difference is the type of the input function. There are other similar functions which return a `(t a -> t b)` too.

The "ordered computation" isn't unique to monads, it applies to all of these when you chain them. For monads particularly though, you can't begin the continuation until the previous result has been generated - whereas with a comonad, you can begin the continuation right away and extract the value afterwards (inside the continuation).

Can also think of it like a producer/consumer or push/pull thing. Monads push values into some type `t`, and comonads pull values out of `t`.

The naming of `return` is perhaps unfortunate as it gives the impression you're returning a value (done to make do-notation look like imperative code) - but monads don't return values. `return` produces a computation.

`coreturn` is usually called `extract`, which is better naming - it extracts a value from a computation.

The order of arguments is also unfortunate because it makes the above pattern less obvious - they're usually written as:

    fmap :: f a -> (a -> b) -> f b
    bind :: m a -> (a -> m b) -> m b
So it's not obvious that `fmap` is transforming a function `(a -> b)` into one `(f a -> f b)`, etc.
yes ~ one perspective is "a monad is an monoid in the (...) category of endofunctors"; the other perspective is "a monad is a kleisli category"
Not sure if going back to C++ is the answer, given how much Haskell like code one can write since C++20, and it has gotten even better with newer standards.
That may be true for functions which operate on a generic Monad typeclass, but typeclasses (Higher kinded types) aren't required to implement concrete Functor / Applicative / Monad instances for a particular type, e.g. Maybe:

    fmap f Nothing = Nothing
    fmap f (Just x) = Just (f x)

    pure x = Just x

    Nothing >>= f = Nothing
    Just x >>= f = f x
"Generic" and "for a particular type" cancel out.

You don't need List<A> to write an IntList, nor do you need + to work on different integers in order to have a particular integer.

Agreed. But there's a big difference between parametric polymorphism (List<A>) and ad-hoc polymorphism like typeclasses. It would be very painful to have to write a new list type for any kind of value type it might hold, but with monads you have many fewer distinct implementations (mainly just Maybe / Either / List / State / IO) and their actions are so different that you almost have to know exactly which monad you are using in the code, so "generic" code that can operate with any monad is less useful.
When people say they don’t understand Monad, my first assumption is that they are wearing their ignorance as a badge of honor.

Otherwise memorize a little bit and dispose of the mystery. It’s not that far out.

Some OO languages have a parallel concept in "Metaclass" (https://en.wikipedia.org/wiki/Metaclass) i.e. the class of a class which is structurally similar to "Kind" though of course the mechanics are quite different.

I still have an old book Putting Metaclasses to Work - A New Dimension in Object-Oriented Programming by Forman et.al somewhere.

There is also the classic The Art of the Metaobject Protocol by Kiczales et.al which is quie relevant here - https://en.wikipedia.org/wiki/The_Art_of_the_Metaobject_Prot...

The key difference is that the Type guys do it at compile time (correctness) while the OO guys do it at runtime (flexibility).

I think most of the difficulty in explaining monads is the IO monad specifically. Leave that off and monads seem almost trivial. Add it back and whatever trivial mental model you just built stops working altogether.
It seems that in java you could write `ArrayList<A>`. I think this type is actually of kind "type -> type". But in java it seems that we cannot have the type `A<B>`, and functors and monads require that..
Just to polish that,

ArrayList's kind is type->type

ArrayList<A>'s kind is type.

The A is what plugs into type on the LHS of the arrow, leaving only the RHS remaining.

No, monads are largely a solution to problems introduced by pure functional programming, problems that impure languages don’t have in the first place.

I like monads as a concept, but in practice I find them frustrating and unnecessarily complicated. I worked on a large game written in Haskell and eventually gave up because dealing with monads made development so cumbersome.

I love the idea, but for real-world projects I’d rather avoid the complexity.

I don't even disagree with your distaste for monads but it has nothing to do with the actual comment I made.
The thing that makes monads difficult is laziness and the anti math circle jerk.

You start from a functor which is a data type that admits a map operation.

Then you add of, or pure, to make an applicative functor, and then you add flatmap to make a monad.

It's odd, the stereotype of software developers is a know-it-all attitude, but start talking about types and you get excuses that boil down to 'I'm incapable of learning to understand the thing you learned to understand'.
There is a video called A New Programming Fundamentals Course that contains some concepts that are very helpful to understand cases like these. I'd recommend you watch, it's free: https://www.youtube.com/watch?v=EV13CNrq4ZA

Namely, the section on "Mapping knowledge webs" (around 3:33). It explains people can struggle to adopt concepts that are too far outside their current knowledge, but that it can still be possible for them to pick it up if they can build a path to it from their current knowledge. (This often presents itself as the "depth-first" learning style)

A lot of commenters here, talking about how monads are so simple and how not being able to learn them is just lazy, are misunderstanding how learning fundamentally works. You have to expand the knowledge graph in the direction of monads before it will be easy to pick up monads. You have to build a path. You cannot simply teach monads right off the bat and expect someone to intuitively "get it". People who intuitively "get it" are people who already have a path.

I wasn't born on the path!
You are still totally capable of building knowledge without a path! It's just, you know, incredibly impaired the more existing knowledge you have. It is very difficult to stop the brain from forming connections and trying to understand things with existing concepts. So you will often find it snapping to incorrect ones or getting into confused panic or whatever when you truly don't know how to relate something. This can discourage people from pushing through and really memorizing a novel thing that they can't relate to yet. It's basically like rote learning where you have to just memorize the unfamiliar information even if you can't fully link it up yet. Not being able to link it up yet tends to really really bug people.
I used to be a big Haskell fan and had a lot of fun writing and using monads. And I agree that once you get them, the basic idea is quite simple. I’ve even used monads to prove a small compiler correct in Lean.

But in practice, I think monads are a poor tool for large-scale software development. I spent a long time trying to build a large game in Haskell and eventually gave up out of frustration with the complexity they introduced.

Monads make sense as a way to manage effects in pure languages like Haskell/Lean/Idris/Agda. But outside that context, I don’t think the additional abstraction is worth the cost.

Understanding how monads work is one thing. Understanding why they’re needed in the first place, and when they’re not, is another.

OCaml isn't pure and neither is F# iirc do you see a bit less monad heavy code in large codebases there?

What sort of situations would you want to give up a little purity or error handling at the type level? Maybe at a boundary where you can just write a very ugly imperative but quarantined section to give it a simpler type?

Exactly. Functor to Applicative to Monad is the order that I remember from Learn You a Haskell and it made sense back then.
> The thing that makes monads difficult is laziness and the anti math circle jerk.

That's quite a hateful way to describe lack of knowledge.

There are some prerequisites that make it easier to understand monads, and a lot of programmers don't even know those. That can make learning monads difficult right off the bat.

No there's no complexity behind monads except laziness and anti math circle jerk.

It's really basic concepts, much easier than the analysis you do in high school.

But people would rather sit through monad as boxes or burritos cringe tutorials.

Your math explanation starts with a math concept that the vast, vast, vast majority of people will have never even heard of, even in math-adjacent fields. It's not anti-math reasoning. It's a lack of self-awareness that your background is very math heavy, which makes that particular explanation make sense to you. I've gone my entire schooling, as a student who was always one of the few who were "good at math", all the the way through my CS education, without ever having heard of a functor until I came across the Haskell monad explanation meme.

Your next step could be to blame the school systems if you want, but that doesn't help the situation at hand.

>> You start from a functor which is a data type that admits a map operation. Then you add of, or pure, to make an applicative functor, and then you add flatmap to make a monad.

> Your math explanation starts with a math concept that the vast, vast, vast majority of people will have never even heard of, even in math-adjacent fields

Let me take this apart.

1. a data type that admits a map operation

Present in most languages including JavaScript. Not a mathematical issue.

2. add of, or pure, to make an applicative functor

I had to look this up. It was new content for me, maybe 5 or 10 minutes believing I would get it.

3. add flatmap

This didn’t scare me but maybe it scares others. Not a mathematical issue here, though. Being in C++ doesn’t make this concept mainstream, I guess?

https://en.cppreference.com/cpp/container/flat_map

I majored in mathematics and I learned category theory before touching any serious Haskell, and I still found most of the "monad tutorials" kind of opaque and handwavy, and I think there are inherently non-trivial details unrelated to the notion of functor etc.
No there are no trivial details, and you don't need a mathematics major or category theory to understand what a functor is.

It's a pair of a type constructor F(a) and a map operation a -> b to get an F(b).

The two "non-trivial" details are the fact that the map operation has to respect identity, map(id) = id, and function composition: map(g ∘ f) = map(g) ∘ map(f)

None of those concepts is any difficult, nor requires any "math major" or non-trivial details, because the are not there.

FWIW I dropped out of high school to pursue programming more directly. I regret it now because of the job market crash, but it's also too late for me to go back.
Lack of knowledge is not the problem at all. Anti-intellectualism is.
You can try to blame lack of knowledge on anything you want, but at the end of the day Hacker News is for intellectual curiosity and even HN readers don't all know what monads are.
I think you missed the “not”.
Nope.