F Sharp Programming/Option Types

An option type can hold two possible values:  or. Option types are frequently used to represent optional values in calculations, or to indicate whether a particular computation has succeeded or failed.

Using Option Types
Let's say we have a function that divides two integers. Normally, we'd write the function as follows: This function works just fine, but it's not safe: it's possible to pass an invalid value into this function which results in a runtime error. Here is a demonstration in fsi:

executes just fine, but  throws a division by zero exception.

Using option types, we can return  on a successful calculation, or   if the calculation fails:

Notice an important difference between our  and   functions:

returns an, while   returns an. Since our  function returns a different data type, it informs clients of our function that the application has entered an invalid state.

Option types are conceptually similar to nullable types in languages like C#, however F# option types do not use the CLR  representation in IL due to differences in semantics.

Pattern Matching Option Types
Pattern matching option types is as easy as creating them: the same syntax used to declare an option type is used to match option types:

Other Functions in the Module
 
 * Returns the value of a  option.

 
 * Returns  for a   option,   otherwise.

 
 * Returns  for a   option,   otherwise.

 
 * Given, returns  . Given  , returns  , where   is the given mapping function.

 
 * Applies the given function to the value of a  option, does nothing otherwise.