Monads
Learn the formal definition of monads with the corresponding PHP code.
We'll cover the following
Definition of monads
Monads are versatile functors built on top of polymorphic concepts, and complete a genealogy of typeclasses. The versatility of monads is such that they allow programmers to write contextrich maps. With a monad, it is possible to compose branching logic (like that seen in the Maybe and Either sum types), computations (I/Obound and CPUbound code), and effects (the integer residue of a print call for instance). Like functors, monads follow the laws of the calculus from which they originate. The cornerstone monad principles are the mathematical forms of associativity, leftidentity, and rightidentity. They are as follows:
Law  Mathematical Representation 

Left identity  $return \space x >>= f = f \circ x$ 
Right identity  $m >>= return = m$ 
Associativity  $(m >>= f) >>= g = m >>= (x \longrightarrow f x >>= g)$ 
Note: $m$ is a monad, $f$ and $g$ are functions, $x$ is a value encapsulated in a monadic context, $>>=$ is the bind operation, $return$ is a monad constructor.

The leftidentity property validates whether a function, $f$, bound to a monadic construct, $m$, whose context contains a specified value, $x$, is the same as a direct call of the monadbound function with said value. We can conclude that the function, $f$, evaluates to a typeclass instance.

The rightidentity principle is based on establishing that the return method evaluates to a type class, and by extension, to a monad instance. This proves that it behaves similarly to a monad constructor.

Associativity, the third and final monad property, proves whether successive function bindings to a monad mirror the result obtained from chaining the same functions within a function.
As is the case with the functor proofs in the previous lesson, additions to the Calculator
type class are imperative. The main addition, bind
, serves the purpose of the $>>=$ operator in the discussion above. The other function, exec
, unwraps the object and reveals the floatingpoint value encapsulated in it.
Get handson with 1200+ tech skills courses.