3 ms·
Most programmers would probably prefer an explanation which focus on how monads work and what they are useful for, rather than just an allegory illustrating the
by olavk 17y ago
Most programmers would probably prefer an explanation which focus on how monads work and what they are useful for, rather than just an allegory illustrating the type signature.
For a typical developer with some experience in OO programming, a more useful analogy is with the command pattern.
In the command pattern, a "command" is an object which wraps a method call or some other statement or operation. The "invoker" is a client which can execute the command object. Command objects can be composed, so a compound command may consist of a sequence (or tree) of other command objects.
Hence a compound command is basically a small program, just with a lot of overhead since each statement is wrapped in a separate object. The benefit of the pattern is that the invoker can add some additional logic to the execution. For example the invoker could log state between each command execution, it could allow a client to single step through the command-chain, backtrack, replay and so on.
The command pattern could be used to e.g. implement exceptions in a language which didn't support exceptions natively. You just wrap all statements in command objects, and then have the invoker check the return value after each command execution - if the return value indicates an error, the invoker does not continue with the next command, but backtracks to the last "try" command.
In the same way it would also be possible to simulate continuations, parallel executions or other advanced language features using the appropriate invoker-logic. The pattern could be used to create all kinds of sublanguages with different semantics than the host language.
Monads is the equivalent of this in a functional language. Rather than wrapping operations in objects they are wrapped in closures.
The talk about apples trapped in boxes, burritos and so on, is just an attempt to explain the rather obvious fact that command objects are not interchangeable with ordinary values and statements. For example a command might calculate and return a number. But you can't add that command object to a ordinary number. You have to execute the command first and get the resulting number before it can be added to an ordinary number. Conversely you cannot insert an ordinary number or expression onto a chain of command objects. You have to wrap it in a command object first, before it can be composed with other commands.