Monads And Their Applications in C#

If you have ever written code in most modern programming languages and even languages that are not functional in nature there is a very high probability that you have used some form of monadic structure. A monad is a structure that represents computations defined as sequences of steps: a type with a monad structure defines what it means to chain operations, or nest functions of that type together. This allows the programmer to build pipelines that process data in steps, in which each action is decorated with additional processing rules provided by the monad. As such, monads have been described as “programmable semicolons”.

Monads allow you to do things like method chaining, and flattening null and exception checks in highly nested code blocks.

Monadic Rules:

1.  Left identity
Identity.Compose(f) = f

2.  Right identity
f.Compose(Identity) = f

3.  Associative
f.Compose(g.Compose(h)) = (f.Compose(g)).Compose(h)

Example: Very basic Monad to factor out division by zero check in BMI calculation.

Monads are awesome, and I still have a lot to learn about them, however I can already see them everywhere in C#: IEnumerable, JQuery: Ajax Requests and lots more.

Until next time keep learning 🙂