Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

1 of 4
Aristotle Pagaltzis
  • 119.5k
  • 24
  • 102
  • 101

[Disclaimer: I am still trying to fully grok monads. The following is just what I have understood so far. If it’s wrong, hopefully someone knowledgeable will call me on the carpet.]

Arnar wrote:

Monads are simply a way to wrapping things and provide methods to do operations on the wrapped stuff without unwrapping it.

That’s precisely it. The idea goes like this:

  1. You take some kind of value and wrap it with some additional information. Just like the value is of a certain kind (eg. an integer or a string), so the additional information is of a certain kind.

    F.ex. that extra information might be a Maybe or an IO.

  2. Then you have some operators that allow you to operate on the wrapped data while carrying along that additional information. These operators use the additional information to decide how to change the behaviour of the operation on the wrapped value.

    F.ex., if you add a Maybe Int to a Maybe Int, then the operator will look at the Maybes wrapping the Ints to see if they both have a valid value – if so, it passes them to the addition operator, otherwise it returns an Maybe Int that says it’s empty.

But the example is what happens for a Maybe. If the extra information was an IO, then that special operator defined for IOs would be called instead, and it could do something totally different before performing the addition. (OK, adding two IO Ints together is probably nonsensical – I’m not sure yet.)

Basically, "monad" roughly means "pattern". But instead of a book full of informally explained and specifically named Patterns, you now have a language construct – syntax and all – that allows you to declare a pattern as a thing in your program. (The imprecision here is all the patterns have to follow a particular form, so it’s not quite patterns. But I think that’s the closest term that most people know.)

And that is why people find them so confusing: because they are such a generic concept.

But imagine what this means: instead of having to read the Gang of Four book and memorise the construction of all the patterns, you just write code that implements these patterns in an agnostic, generic way once and then you are done! You can then reuse this pattern, like Visitor or Strategy or Façade or whatever, by decorating the operations in your code with it without having to implement it over and over!

So that is why people who understand monads find them so useful: it’s not some ivory tower concept that intellectual snobs pride themselves on understanding (OK, that too, of course, teehee), but actually makes code simpler.

Aristotle Pagaltzis
  • 119.5k
  • 24
  • 102
  • 101

AltStyle によって変換されたページ (->オリジナル) /