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 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 | |
Right identity | |
Associativity |
Note: is a monad, and are functions, is a value encapsulated in a monadic context, is the bind operation, is a monad constructor.
-
The left-identity property validates whether a function, , bound to a monadic construct, , whose context contains a specified value, , is the same as a direct call of the monad-bound function with said value. We can conclude that the function, , 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 1400+ tech skills courses.