A Primer on Optionals
Optionals allow programs to have values which can be nothing or something. These are known as Optional Types in Functional Programming (FP), otherwise known as Nullable Types outside of FP.
By having optionals, a program can safely handle errors along the way. Optionals in Haskell are defined as:
data Maybe a = Just a | Nothing
Nothing is the equivalent of
None in other programming languages.
Just a on the other hand, means that the value of
a is “something”; in other programming languages this is represented with
Some T where
T is a generic value.
head function in Haskell, it returns the value of the first element of a list. However, if the list is empty an error occurs.
> head  *** Exception: Prelude.head: empty list
This happens because the signature of
head :: [a] -> a. The function expects
[a] which has concrete values, meaning
 is not allowed.
head safe, the return value must become an optional.
headSafe :: [a] -> Maybe a headSafe  = Nothing headSafe (x:xs) = (Just x)
In this example,
headSafe is safe since it returns a
> headSafe  Nothing
With this new implementation, programs that use
headSafe must check for
Nothing, and handle the flow of the program accordingly.
Optional types enhances the way in which programs check for errors. The result is an alternative way of error handling.