3 ms·
Some examples: * Lists - you don't need to manually for-each over the items, the monad will do the unwrapping for you, reducing boilerplate * Optional values
by louthy 5y ago
Some examples:
* Lists - you don't need to manually for-each over the items, the monad will do the unwrapping for you, reducing boilerplate
* Optional values - you don't need to check for null/no-value, the monad will do that for you and end the computation if an expected value is missing
* State passing - constantly passing a Context type as an argument through your pure functions? Look no further than the State monad, it will do it for you
* Environment/Configuration - don't want to deal with global variables for configuration? Look no further than the Reader monad, it will automagically carry your config to you. This can also be used as a pure dependency-injection system, with none of those hideous DI frameworks and tools.
* Asynchrony - fed up of callback functions, and the boilerplate of dealing with the continuations? Use a promise/task/async monad, it will deal with the sequencing of your operations properly. This is an interesting one because monadic-asynchrony has inspired the async/await systems in C#, JS, and beyond. So, if you've ever used async/await and thought "wow, that was convenient", it's because they're monads.
* Error handling - Exceptions are effectively gotos, why not have something a bit more powerful? The Either monad, Validation monad, etc will handle errors, groups of errors, etc.
* Output aggregation - Want to build some output over the duration of your operation (building a list of strings, generating a document, summing some values, etc.), use the Writer monad to collect output and aggregate it using any available monoid pattern.
* Parsers - Want to declaratively build a parser and not have to worry about error handling, position in the stream, etc? Get the Parsec parser-monad on the case.
* DSLs - making a DSL to capture subsystems in your code-base? Use the Free monad with a sum-type to create a ready-to-go domain-specific language. Simply provide the interpreter.
Want to combinations of all of the above? Many monads can be composed to create a super-monad with the behaviours of both; they're call monad-transformers, and everything "just works".
Ultimately, it's about capturing common patterns and using the same interface to work with the monadic types (in Haskell it's called `do` notation, in C# it's called LINQ). They significantly reduce boilerplate, and allow for very succinct and declarative code.