The Maybe type encapsulates the concept of Some (contains a value) and None (no value present). With these two abstractions we are able to safety handle the event of no value being present, without NullPointerException’s being thrown and null checks.
The implementation above uses two small prototypical class definitions to define Some and None. We then return the ability to take a value of a plain type and put it into a Maybe container, along with the capability to lift a function into the Maybe space.
Division by Zero Example
The first example of using the Maybe type I will demonstrate is in the case of handling division by zero errors.
In the event that the denominator is zero instead of throwing an exception or returning null (as shown in the basic
div implementation) we will instead lift the function into the Maybe type and return a Some or None.
This may not seem like much of a win at this time but when we later look at examples of composing these expressions together you will be shown its full power.
Property Retrieval Example
Another case were
Again, we are able to highlight how the basic
get function returns the object property or undefined if not present, were as lifting it into the Maybe type provides us with the Some and None abstractions.
We are then able to compose multiple
mget functions together, handling application on the Maybe containers using
You will notice that
fmap double wraps the resulting value, this is due to as being a Functor definition its’ action is to wrap the resulting value (from our provided function) back into the given container.
However, in the case of the
bind Monad definition, it instead does not wrap the value back into the container upon completion, but instead relies on the function itself to return the correctly typed value.