Hacker News new | ask | show | jobs
by tomsmeding 1061 days ago
Instead of rising to the bait and trying to explain monads, let's talk about why it seems to be hard to explain monads.

They're very general. Classes in OOP are general too — surely you can model lots of things with them — but a class always models a category of things with similar functionality, and an instance of that class is one of those things.

Monads are much more flexible than that. You can model nondeterminism with monads, as well as side-effects, exception-based error handling, state, (backtracking) search algorithms, and more. Could all of those things be an instance of the same OOP class? Surely not. Yet in Haskell, 'Monad' is just a "type class" (not dissimilar to an interface / abstract class in the OOP world).

Monad tutorials typically try to do one of the following things:

1. Try to explain the entirety of monads by giving a metaphor (burritos, anyone?) that only works for some of the instantiations of the pattern. It turns out to be hard to find a metaphor that covers all ground that Monad does, unsurprisingly. Personally I think this method is good, as long as you're honest about what it does not give you: an intuition for all Monad instances. It just gives you an intuition about some of them, but that could already be plenty to work with them usefully (and see 3. below).

2. Try to let the reader invent Monad by showing various instantiations and asking the reader to find the pattern. Personally I think this misses the point somewhat; yes, you can see the pattern, but that doesn't give any understanding per se. Why are those things similar, and why does it make sense to abstract over the idea?

3. Not actually explain, but instead say "work with them a bit and you'll understand soon enough". This is the one I'm most in favour of — after giving a special-purpose intuition for the monads you'll be working with as a beginner (IO, perhaps parser combinators, and not much else; perhaps lists (nondeterminism) to jump-start exploration into non-imperative monads).

Note that none of these give a nice and polished answer to what a monad is.

As alluded to above, the closest OOP equivalent to the kind of thing that Monad is, is a design pattern. It's a design pattern that can be encoded into a three-line definition in the language itself, and is super general.