3 ms·
I think that "Overridable semicolon" captures most of what a monad is and why you'd want to use it. Imagine that the compiler provided a hook into the language
by nostrademons 17y ago
I think that "Overridable semicolon" captures most of what a monad is and why you'd want to use it. Imagine that the compiler provided a hook into the language so that you could pass around statements (the monad type), a means to convert an expression to a statement (return), and the semicolon operator that combines two statements (>>=). And then instead of implicitly letting you do anything in a statement, it required that you explicitly program the effects of that statement into the semicolon operator.
The simplest possible semicolon is one that lets you do anything, including interact with the outside environment. That's the IO monad. But you could also have a semicolon that limits your side-effects to one particular area of memory - that's the State monad. Or you could have one that doesn't execute any of the following statements if an error occurs - that's an exception monad. Or you could have one that attempts to atomically execute a bunch of statements that may read & write from a block of memory, but if that memory is changed by another thread, the effects are all rolled back and tried again. That's the STM (software transactional memory) approach to concurrency. Or you could have one that sends a webpage to the user's browser with an HTML representation of the state, waits for a response, and then executes the rest of the statements. That's the approach taken by WASH, one of the Haskell web frameworks.
It's a powerful tool, because it's basically rewriting the fundamentals of how the language works. And because of that, very few people ever have a reason to create a new monad type, which is why examples tend to fall flat. It also interacts heavily with other Haskell features, eg. you don't get this correspondence between monads and statements without Haskell's do-notation, and you can't use them to affect control flow without lazy evaluation, and they become very difficult to reason about without a static type system.