Hacker News new | ask | show | jobs
by chombier 2390 days ago
A monad is for composing computations with effects: let's say you have some function f:: a -> b returning some b, but now you need the computation to happen with some extra effect (throwing exception, changing state, futures, etc).

A way to model effects is to have f :: a -> Tb, where T is a type constructor encapsulating a value of type b produced with some effect. Let's call this new f a T-program, then a monad is exactly what you need to compose T-programs nicely.

The monad "return" is the simplest T-program, and the monad "bind" helps you compose T-programs: given another T-program g :: b -> Tc, you cannot simply compose g with f since the types don't match. However, the bind operator >>= :: (b -> Tc) -> Tb -> Tc gives you a function (>>= g) :: Tb -> Tc which does compose with f, producing a new T-program: a -> Tc. So now you can compose T-programs, yay! The monad laws ensure that T-programs form a category, which is to say that composition works the right way.

So a monad is just the plumbing you need to compose computations with effects in a nice way.

1 comments

> A monad is for composing computations with effects

To nitpick: that's only one particular use of some monads.

It's pretty close to how both Moggi and Wadler formulated it in their respective seminal papers which introduced monads for representing different notions of computations in functional languages.
Well of course, but arguably there's not much space between "monads-as-containers/burritos" and "monoids-in-the-category-of-endofunctors" presentations...

If you know a better one in between I'm all ears :)