Monads

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

Definition of monads

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 x>>=f=fxreturn \space x >>= f = f \circ x
Right identity m>>=return=mm >>= return = m
Associativity (m>>=f)>>=g=m>>=(xfx>>=g)(m >>= f) >>= g = m >>= (x \longrightarrow f x >>= g)

Note: mm is a monad, ff and gg are functions, xx is a value encapsulated in a monadic context, >>=>>= is the bind operation, returnreturn is a monad constructor.

  • The left-identity property validates whether a function, ff, bound to a monadic construct, mm, whose context contains a specified value, xx, is the same as a direct call of the monad-bound function with said value. We can conclude that the function, ff, 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 1300+ tech skills courses.