The Maybe and Either Monads
Learn about different types of monads in functional programming.
We'll cover the following
Sum types are especially useful for adding flow control to error handling. In Maybe and Either sum types, we have two monads that are presentable as type-classes in PHP. They’re versatile functors that can carry values in their objects to which computations/functions can be bound through functor methods. Their suitability for cleaner error handling is such that they encapsulate two subtypes for success and error values that are transformable using the bind
and map
method operations.
The Maybe monad
The Maybe monad is a sum type that stands out because a value defined or used within its context is either Just
or Nothing
(Some
or Nothing
in other domains). This duality means that, depending on the situation, a Maybe can only be Just
or Nothing
, much like a boolean.
-
The value subsumed in a
Just
context (Just
object), aJust
value, is associable with success. It’s valid and directly chainable. -
The
Nothing
context (Nothing
object) evaluates to a unit type (null
), but stands in for the output of a computation that might go wrong. It doesn’t change no matter which of the Maybe sum type’s methods is applied to it.
Imagine a function that, for some reason, only adds 10
to a value larger than 20
. This function has a glaring constraint and can enter anomalous territory upon violation of the condition. Implementing this logic with a simple if
statement results in a null
value when this function is invoked with a value less than or equal to 20
.
Get hands-on with 1200+ tech skills courses.