10 Options

There's another built in variant in the OCaml library called options

type 'a option = None | Some of 'a

This means that option can either hold nothing (None), or something of type 'a (Some).

We can also put some more complex data in there:

How do we get the data out of an option? Pattern matching!

options are useful for returning something from a function that might return something, or might not.

Let's say we want to get the maximum value in a list. We can define list_max to take the biggest item in a list, and return an int option, where the value would be None if there's nothing in the list:

What went wrong here? In our call max h (list_max t), we're comparing an 'a to an 'a option, which doesn't exactly work. We need to get the value out of the option first.

Here we see two words we've never seen before, begin and end. They just mean ( and ) respectively, and help OCaml determine scope.

Options let us avoid the Billion Dollar Mistake. He invented Quick Sort, and he calls null his "billion dollar mistake." He was designing type system for an OOL, and he included null, which he believes has caused over a billions dollars lost in the past 40 years.