Maybe (aka Optional or Option)
The Maybe
type can be thought of being like a list that can only hold exactly zero or one element. I prefer the naming Maybe
as it alludes to a missing value from some process rather than Optional
or Option
which seem like inputs and if I weren't going to provide an input, why go through the trouble of packaging it.
If we use the notation []
for an empty Maybe
and the notation [5]
for a Maybe
containing a value, we can immediately tell that flatMap
would work on them as it does on a list of zero or one element. One condition for this extended flatMap
which works on things other than lists is that the output shape of the function parameter should be the same as the input shape of the data. So if we flatMap
a Maybe
the function should return a Maybe
. The type of content in the input and output Maybe
do not need to be the same. So for instance we can flatMap
a Maybe<Integer>
input with the functionsquare_root
that returns a Maybe<Integer>
if the input integer was a square number (e.g. 1, 4, 9, 16, etc) and an empty Maybe
otherwise.
...
Last updated
Was this helpful?