All Articles

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 nil, null, or 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.

Unsafe Example

Consider the 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 is head :: [a] -> a. The function expects [a] which has concrete values, meaning [] is not allowed.

Safe Example

To make 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 Maybe a.

> headSafe [] 
Nothing

With this new implementation, programs that use headSafe must check for Nothing, and handle the flow of the program accordingly.

Summary

Optional types enhances the way in which programs check for errors. The result is an alternative way of error handling.

Published 11 Dec 2015