# Monad ![[Monads#^se5abr]] **==A monad is a way of composing (or chaining) certain kind of functions together.== The type of functions that are chained is determined by the monad type, for example the [[Result Monad]] is a way of chaining functions that return results.** The way of composing functions is represented by the `bind` operation. A monad also requires a `return` operation, which takes an element `a` and returns an `E<a>`. ``` bind, or >>= : (a -> E<b>) -> E<a> -> E<b> or similarly : E<a> -> (a -> E<b>) -> E<b> ``` **The function composition (a.k.a. [[Kleisli composition]], `>=>`), is the [[Monoid]] operation referred to in the popular definition that states that "a monad is a monoid in the [[category]] of endofunctors."** The monad's [[Identity|identity element]] is the `return` operator (see [[Monad Laws]] article for more). Another way of thinking of monads is as functors that can be flattened (Mark Seemann): ![[Monads#^2ilhw4]] ![[Monads#^dbujzg]] In fact, given a `bind`, one can easily construct a `join`, and vice-versa: ```fsharp let join ee = ee >>= id let bind e f = e |>> f |> join ``` ## Monads are Used to Hide Boilerplate Code You can think of monads as a way to hide boilerplate code for the sake of emphasizing important code, which follow's Robert C. Martin's famous adage: > Abstraction is the elimination of the irrelevant and the amplification of the essential In other words monads help us improve signal-to-noise ration. ![[This Is Not a Monad Tutorial#^fve4o6]] One way of achieving that abstraction is Continuation Passing Style (CPS). See [[This Is Not a Monad Tutorial]] for more. ## Monads are Applicative Functors Because a `map` can be created using the `bind` and `return` operators, every monad is also a [[Covariant Functor|Covariant Functor]]. ```fsharp let map e f = e >>= (f >> result) ``` Every monad is also an [[Applicative Functor]], because the `apply` operator can be constructed using `bind` and `return` as well. ```fsharp let apply ef ea = ef >>= (map ea) ``` ^d2re07 ## Common Monads A [[Free Monad]] can be used to construct a monad from any [[Covariant Functor|Functor]]. A [[Trampoline]] is a specialized version of the free monad. The [[Result Monad]] is the bedrock of [[Railway Oriented Programming]]. [[The Test Data Generator Functor]] can be thought of as a Reader monad. And arguably the most popular .NET monad is the [[Dotnet Task Monad|.NET Task Monad]].