F# Options

The purpose of this article is to provide a comprehensive overview of F# Option type. This article is going to cover the process of creating and working with Option values, including how you can safely deal with missing values, as well as the way in which you can extract values from Option types through pattern matching. The Option module allows you to manage Option values effectively and function as a user with option values.

F# uses the option type when there is no value to be assigned to a variable or function in calculations. Calculations can use option types to represent optional values in the calculations. The values can be Some(x) or None.

For example, if one performs a division function in a normal situation, then it might return a value, but if the denominator is zero, then it might throw an exception. When the options are used here, it will be easier to determine whether the function has succeeded or failed.

The underlying type of an option determines whether it holds a value of the type, or it holds no value at all.

F# Options Uses

As an example, let us look at a division function. This is explained in the following program.

We will write a function called division, and tell it there are two parameters: 40 and 2.


let division a b = a / b let result = division 40 2 printfn "Result of division is: %d" result

After executing the example, the output will be as follows:

Result of division is: 20

If we place 0 in the second argument, we will get an exception:


let division a b = a / b let result = division 40 0 printfn "Result of division is: %d" result

Program will thrown the following example:

Unhandled Exception:
System.DivideByZeroException: Division by zero

We can use option types in such cases to infer whether the operation was successful or not by returning Some (value) when it was successful or it was unsuccessful.

As an example, let us take a look at what options can be used for:


let division a b = match b with | 0 -> None | _ -> Some(a/b)let result : int option = division 40 2 printfn "Result of division is: %A " result

It will output as:

Result of division is: Some 20

Option Properties and Methods

There are a number of properties and methods available in the option type, including:

Property or methodTypeOverview
NoneT optionAn option value which is defined as the None value can be created in a static property.
IsNoneboolA true value is returned if the option has a value of None.
IsSomeboolWhen the value of the option is not None, the value returned by this function is true.
SomeT optionStatic members create options that are not None, as opposed to static members that create options that are None.
ValueTA NullReferenceException is thrown if the value underlying this is None, otherwise the underlying value is returned.

Finding Elements Through Option

This method allows you to find elements from a list based on the type of option available:


let findingElements index li = if index >= 0 & index < List.length li then Some (List.item index li) else Nonelet list = [1; 2; 3; 4; 5] let elem = findingElements 3 listmatch elem with | Some x -> printfn "Found element: %d" x | None -> printfn "Element not found"

The output of the above example is as follows:

Found element: 4

Positive Number Check

Below is an example of checking whether the number is positive or not:


let isPositive (x : int) = if x > 0 then Some(x) else Nonelet result : int option = isPositive(-11) printfn "The value is: %A " result //this will print null if value is negative

The output of the above program is:

The value is: null

Sum of Elements

This example sums all the option elements in the list:


let num = [Some 10; Some 5; None; Some 7; None]let sum = num |> List.choose (fun x -> x) |> List.sumprintfn "Sum of numbers are: %d" sum

This will print sum of all the element:

Sum of numbers are: 22

Example Explanation

This F# code defines a list called num that contains a mix of Some values and None values. Then, the code calculates the sum of the non-null values in the list and prints the result to the console.

A list called num contains five elements. The first, second, and fourth elements are Some values containing the numbers 10, 5, and 7, respectively.

The third and fifth elements are None values, representing missing or null data.

The List.choose and List.sum functions calculate the sum of the non-null values in the num list.

The List.choose function is a higher-order function that takes a list and a function as input. The function is applied to each element of the list, and the resulting list contains only the values returned by the function as some values. In this case, the function passed to List.choose is the identity function, which simply returns the input value. Since None values are excluded by the List.choose function, the resulting list only contains Some values from the original list.

The resulting list of Some values is then passed to the List.sum function, which calculates the sum of the elements in the list.

Finally, it prints the sum of all the numbers.

Correct Number Check

This program checks if the number is 44 or not using different option properties, if it is then it will print true, else it prints false and if there is no value then it will return null.


let numberCheck = function | Some(44) -> true | Some(_) | None -> falseprintfn "%A" (numberCheck (Some(44))) printfn "%A" (numberCheck (Some(48))) printfn "%A" (numberCheck None)

Output will be as:


Please subscribe to our newsletter below in order to stay up to date with all the latest developments in F# functional programming language and to learn more about the language.

We value your feedback.

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!

Leave a Reply

Your email address will not be published. Required fields are marked *