|
|
|
|
|
by amalcon
5586 days ago
|
|
Monads basically let you add an extra calculation to your functions. Why would you want to do that? Mainly so that you don't have to do it manually. Think of it as tacking an extra calculation onto the side of each function that operates in the monad. For a "state" monad, that calculation is maintaining/passing the state. For a "logging" monad, that calculation is maintaining the log. For an "error handling monad", that calculation is checking for and propagating errors. |
|
Take the OP's example for the Writer monad, in which several functions needed to return a debug string "<function name> was called" in addition to their main return value. If I had these two functions+:
I might write a macro like the following (rather than a monad) to abstract away their common pattern: And then each function's definition could be written more concisely: ---+ Forgive me for indulging in the syntactic sugar from my own lisp->javascript project in these examples, but since we're dealing in JavaScript I couldn't resist. https://github.com/evanrmurphy/lava-script