Learn the formal definition of monads with the corresponding PHP code.

We'll cover the following

Monads are versatile functors built on top of polymorphic concepts, and complete a genealogy of type-classes. The versatility of monads is such that they allow programmers to write context-rich maps. With a monad, it is possible to compose branching logic (like that seen in the Maybe and Either sum types), computations (I/O-bound and CPU-bound 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, left-identity, and right-identity. 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 left-identity 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 monad-bound function with said value. We can conclude that the function, $f$, evaluates to a type-class instance.

• The right-identity 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 floating-point value encapsulated in it.

Get hands-on with 1200+ tech skills courses.