Advantages of Monads
Learn about some of the advantages offered by monads.
We'll cover the following
Combining effects and purity
Monads exist to handle effects. As discussed earlier, functional programming likes purity. However, effects such as writing to a database or calling some API ruin this purity. This is because the call might work one moment and fail the next, making our results unpredictable. This is where monads are helpful. Because they act as containers, they can store effective behavior. For example, we have monads just for storing effects, typically called IO monads.
Furthermore, with map
, we can create functions that further transform the value saved in our container. Here comes the important thing, at least from a functional programming perspective. That is, the IO monad doesn’t create an effect until it’s called. This means that everything is pure until we call the program containing the IO monad(s). With this, effects and purity are combined.
Making the type system more powerful
Although purity is good, it’s a less important aspect of monads for a pragmatic programmer. Making our programs pure is only one aspect of the advantages monads offer. For example, monads make our type system more powerful because they offer more information about what a function is doing. A method written in a language like Java or C# tells the compiler that it will return a string, even if there’s a path in which it throws an exception. This can be accomplished in TypeScript as well:
Get hands-on with 1200+ tech skills courses.