Hacker News new | ask | show | jobs
by chombier 1477 days ago
A monad is for composing effectful computations.

Effects are encoded using a polymorphic type with a `map` operation (called a functor), and effectful computations are functions `a -> E b` for some types `a, b` and effect `E`.

A monad is exactly the plumbing you need for composing effectful computations: it turns a computation `b -> E c` into a `E b -> E c` so that you can compose `a -> E b` with `E b -> E c` to get a composed computation `a -> E c`.

It does so in a way that makes effectful composition associative (i.e. the way you'd expect)

2 comments

Is Maybe/Option an effectful computation? Is List? I don't think it's really accurate to say this is what monads are "for". It's one use for monads but monads aren't "for" anything and there are monads that are not about effects.
"Effect" is perhaps a broader notion than one might think: it's an effect to write to a file or mutate some variable, sure, but it's also an effect to raise an exception, goto a label, raise an exception, execute asynchronously, be one of a set of possible outcomes, and plenty of other notions.

There's a name for the monad in which there is no effect: the identity monad.

The heart of a monad is the bind/flatMap/and_then interface, in which the value contained in the monad is computed on to produce a new monadic value. This is where the effect occurs: something other than just running the function happens.

If the bind implementation only runs the provided function then there's no effect, and it's the identity monad.

> Is Maybe/Option an effectful computation

Yes, Maybe/Options are a way of encoding partial functions/exceptions.

List is a way of encoding non-determinism.

Operations on a list (like map, filter) are not effectful computations.

The problem with many monad explanations is they explain only particular monads. IO and State can be thought of as effectful computations, but List operations cannot.

Monads are just a pattern for composing computations, it doesn't say anything about the semantics of those computations.

> but List operations cannot.

They can, the effect modeled by the list monad is non-determinism.