Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Monads are a very effective technique for expressing custom requirements in your type system, e.g. "this function must be called only in a database transaction", "this function writes an audit log entry", "this function requires this level of authorization". The kind of thing you might think you would have to do via AOP/decorators/monkeypatching, you can usually do in plain old code (with all the attendant advantages) via a monad.

If your type system can't express them then you lose most of the advantages and they're pretty pointless.



I find this perspective intriguing, can you elaborate on that? For example why `m a -> (a -> m b) -> m b` but not something else?


> why `m a -> (a -> m b) -> m b` but not something else?

it's basically continuation-passing-style (`a -> m b` is the "continuation"), you might as well ask "why can you represent so many control-flow things using CPS?". idk why, but you can!

from another angle, you could compare Monad with the less powerful Applicative. a formulation[0] that's easier to parse than the usual one[1] is:

  class Functor f => Applicative f where
    unit :: f ()
    pair :: f a -> f b -> f (a, b)
if you're familiar with JS Promises, a rough analogy would be

  >>=  (Monad)        Promise.then
  pair (Applicative) ≈ Promise.all
  unit   (Applicative) =
  return (Monad)       = Promise.resolve
ignoring parallelism, you can implement Promise.all using Promise.then, but not the other way around.

---

[0] Called "Monoidal" here: https://stackoverflow.com/q/45267953 [1] https://en.m.wikibooks.org/wiki/Haskell/Applicative_functors...


Some people describe monads as "programmable semicolons" - they're pretty much the general concept of sequencing, "do this then do that", or indeed of imperative code. I don't think they're necessarily the ideal abstraction - something like ArrowChoice is "better" in a lot of cases - but in practice they seem to come up a hell of a lot, you can represent almost anything as a monad.


Why monads and not something else? Because monads appear to be a/the mathematical structure underlying the denotation of programs with effects.

Why that type signature? You only have two options: that, or m (m a) -> m a. The former is more popular for ergonomic reasons mostly. It doesn’t really matter.


Because so many types above are m of something. You as a programmer get to decide how that m type works, so you have a lot of control there.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: