ZetCode

F# option type

last modified December 2, 2026

In this article we work with the option type, which represents a value that may be missing.

Many operations do not always have a result: a search may find nothing, a string may not contain a number, a division may have a zero divisor. In many languages such a function returns null or a special value like -1, and the caller has to remember to check it. In F# the function returns an option. A value of type int option is either Some n, which holds an integer, or None, which holds nothing. The type tells the caller that the value may be missing, and the compiler does not let the caller use the option as if it were a plain integer.

Some and None

An option is created with Some, which wraps a value, or with None.

some_none.fsx
let age = Some 34
let name = Some "Lucia"
let nickname: string option = None

printfn "%A" age
printfn "%A" name
printfn "%A" nickname
printfn "%b" (age = Some 34)

We create three options and print them.

let age = Some 34
let name = Some "Lucia"

The types are inferred from the wrapped values: age is an int option and name a string option.

let nickname: string option = None

None holds no value, so the compiler cannot tell which option it is. The annotation gives it the type string option. Options are compared by their contents, so age = Some 34 is true.

λ dotnet fsi some_none.fsx
Some 34
Some "Lucia"
None
true

Matching on an option

To use the value inside an option we match on it. The match must handle both cases, so the missing value cannot be forgotten.

match_option.fsx
let describe (count: int option) =
    match count with
    | Some 0 -> "no items"
    | Some 1 -> "one item"
    | Some n -> $"{n} items"
    | None -> "count unknown"

printfn "%s" (describe (Some 0))
printfn "%s" (describe (Some 1))
printfn "%s" (describe (Some 12))
printfn "%s" (describe None)

The describe function turns an optional count into text.

| Some 0 -> "no items"
| Some 1 -> "one item"
| Some n -> $"{n} items"

A Some pattern can contain a constant or a name. The first two rules match specific counts, the third binds any other count to n.

| None -> "count unknown"

If we left out the None rule, the compiler would warn that the match is incomplete.

λ dotnet fsi match_option.fsx
no items
one item
12 items
count unknown

Functions that return options

A function that cannot always produce a result returns an option. The caller then decides what to do when there is none.

returning.fsx
open System

let tryDivide (a: int) (b: int) =
    if b = 0 then None else Some (a / b)

let parseNumber (text: string) =
    if text <> "" && String.forall Char.IsDigit text then Some (int text)
    else None

printfn "%A" (tryDivide 20 4)
printfn "%A" (tryDivide 20 0)

printfn "%A" (parseNumber "128")
printfn "%A" (parseNumber "12a")
printfn "%A" (parseNumber "")

match parseNumber "45" with
| Some n -> printfn "twice %d is %d" n (n * 2)
| None -> printfn "not a number"

We write two functions whose results may be missing.

let tryDivide (a: int) (b: int) =
    if b = 0 then None else Some (a / b)

Both branches of the if have type int option. The function has type int -> int -> int option; a name starting with try is the usual hint that it returns an option.

let parseNumber (text: string) =
    if text <> "" && String.forall Char.IsDigit text then Some (int text)
    else None

String.forall checks that every character of the string is a digit. Only then is the text converted with int, which would fail on any other input.

λ dotnet fsi returning.fsx
Some 5
None
Some 128
None
None
twice 45 is 90

Options from the library

The F# collection functions whose names start with try return options instead of failing when there is no result.

library.fsx
let temperatures = [12; 17; 21; 25; 19; 14]

let firstWarm = temperatures |> List.tryFind (fun t -> t > 20)
let firstHot = temperatures |> List.tryFind (fun t -> t > 30)
let warmIndex = temperatures |> List.tryFindIndex (fun t -> t > 20)

printfn "%A %A %A" firstWarm firstHot warmIndex

let empty: int list = []

printfn "%A" (List.tryHead temperatures)
printfn "%A" (List.tryHead empty)
printfn "%A" (List.tryLast temperatures)
printfn "%A" (List.tryItem 2 temperatures)
printfn "%A" (List.tryItem 10 temperatures)

We look for values in a list of temperatures.

let firstWarm = temperatures |> List.tryFind (fun t -> t > 20)

List.tryFind returns the first element that satisfies the predicate, wrapped in Some, or None when no element does. List.tryFindIndex returns the position instead.

printfn "%A" (List.tryHead empty)

List.tryHead, List.tryLast, and List.tryItem return None for an empty list or an index out of range. Their counterparts without try raise an error in these cases. Lists are covered in F# list.

λ dotnet fsi library.fsx
Some 21 None Some 2
Some 12
None
Some 14
Some 21
None

Default values

Often a missing value can be replaced with a default. The Option module has functions for that, so we do not have to write a match every time.

defaults.fsx
let configured: int option = None
let given = Some 8080

let port = configured |> Option.defaultValue 80
printfn "port: %d" port
printfn "port: %d" (given |> Option.defaultValue 80)

let computeDefault () =
    printfn "computing the default"
    443

printfn "port: %d" (given |> Option.defaultWith computeDefault)
printfn "port: %d" (configured |> Option.defaultWith computeDefault)

printfn "%b %b" (Option.isSome given) (Option.isNone given)
printfn "%b %b" (Option.isSome configured) (Option.isNone configured)

We read a port number that may not be configured.

let port = configured |> Option.defaultValue 80

Option.defaultValue returns the wrapped value, or the default when the option is None. The option comes last, so the function works well in a pipeline.

printfn "port: %d" (given |> Option.defaultWith computeDefault)

Option.defaultWith takes a function of type unit -> int and calls it only when the value is missing. This is useful when computing the default is expensive. The output shows that computeDefault runs only once.

printfn "%b %b" (Option.isSome given) (Option.isNone given)

Option.isSome and Option.isNone test which case an option is.

λ dotnet fsi defaults.fsx
port: 80
port: 8080
port: 8080
computing the default
port: 443
true false
false true

Transforming options

Option.map applies a function to the value inside an option and wraps the result again. A None passes through unchanged.

transform.fsx
let price = Some 120.0
let missing: float option = None

let withTax p = p * 1.2

printfn "%A" (price |> Option.map withTax)
printfn "%A" (missing |> Option.map withTax)

let label = price |> Option.map (fun p -> $"{p:F2} EUR")
printfn "%A" label

let cheap = price |> Option.filter (fun p -> p < 100.0)
let affordable = price |> Option.filter (fun p -> p < 200.0)
printfn "%A %A" cheap affordable

price
|> Option.map withTax
|> Option.map (fun p -> $"{p:F2} EUR")
|> Option.defaultValue "no price"
|> printfn "%s"

We work with a price that may be missing.

printfn "%A" (price |> Option.map withTax)
printfn "%A" (missing |> Option.map withTax)

The withTax function takes a plain float. Option.map lets us apply it to a float option without unwrapping it ourselves. The mapped function can change the type: the label is a string option.

let cheap = price |> Option.filter (fun p -> p < 100.0)

Option.filter keeps the value only when it satisfies the predicate; otherwise the result is None.

price
|> Option.map withTax
|> Option.map (fun p -> $"{p:F2} EUR")
|> Option.defaultValue "no price"
|> printfn "%s"

The functions combine into a pipeline. The value stays inside the option until Option.defaultValue takes it out at the end.

λ dotnet fsi transform.fsx
Some 144.0
None
Some "120.00 EUR"
None Some 120.0
144.00 EUR

Chaining with Option.bind

When the function we apply returns an option itself, Option.map would produce a nested option such as Some (Some 5). Option.bind applies such a function and keeps a single level, so steps that may fail can be chained.

bind.fsx
open System

let parseNumber (text: string) =
    if text <> "" && String.forall Char.IsDigit text then Some (int text)
    else None

let validMonth (n: int) =
    if n >= 1 && n <= 12 then Some n else None

let monthName (n: int) =
    let names = ["Jan"; "Feb"; "Mar"; "Apr"; "May"; "Jun"
                 "Jul"; "Aug"; "Sep"; "Oct"; "Nov"; "Dec"]
    List.tryItem (n - 1) names

let readMonth (text: string) =
    parseNumber text
    |> Option.bind validMonth
    |> Option.bind monthName

printfn "%A" (Some "4" |> Option.map parseNumber)

for input in ["4"; "11"; "13"; "x"] do
    match readMonth input with
    | Some name -> printfn "%-3s -> %s" input name
    | None -> printfn "%-3s -> invalid month" input

The text of a month number is parsed, checked, and turned into a name.

let readMonth (text: string) =
    parseNumber text
    |> Option.bind validMonth
    |> Option.bind monthName

Each step takes a plain value and returns an option. When a step returns None, the following steps are skipped and the whole chain returns None.

printfn "%A" (Some "4" |> Option.map parseNumber)

This line shows why map is not enough here: mapping a function that returns an option gives an option inside an option.

λ dotnet fsi bind.fsx
Some (Some 4)
4   -> Apr
11  -> Nov
13  -> invalid month
x   -> invalid month

Options and null

.NET methods signal a missing value with null. Option.ofObj turns a possibly null reference into an option at the boundary, so the rest of the F# code works with options only.

nulls.fsx
open System

let readSetting (name: string) =
    Environment.GetEnvironmentVariable name |> Option.ofObj

let editor = readSetting "ZC_EDITOR" |> Option.defaultValue "nano"
printfn "editor: %s" editor

let text: string = null
printfn "%A" (Option.ofObj text)
printfn "%A" (Option.ofObj "falcon")

let middleName: string option = None
let forDotNet = Option.toObj middleName
printfn "%b" (isNull forDotNet)

We read an environment variable that is not set.

let readSetting (name: string) =
    Environment.GetEnvironmentVariable name |> Option.ofObj

GetEnvironmentVariable returns null when the variable does not exist. Option.ofObj converts null to None and any other value to Some.

let forDotNet = Option.toObj middleName

Option.toObj goes the other way, for .NET code that expects null instead of an option.

λ dotnet fsi nulls.fsx
editor: nano
None
Some "falcon"
true

Collecting readings

In the last example a list of sensor readings contains some entries that are not numbers. We skip the invalid ones and compute statistics from the rest.

readings.fsx
open System

let parseReading (text: string) =
    let t = text.Trim()
    if t <> "" && String.forall Char.IsDigit t then Some (int t)
    else None

let raw = ["21"; " 23"; "err"; "19"; ""; "25 "; "n/a"; "22"]

let readings = raw |> List.choose parseReading
let failed = raw.Length - readings.Length

printfn "valid: %A" readings
printfn "failed: %d" failed

let average =
    if readings.IsEmpty then None
    else Some (readings |> List.averageBy float)

match average with
| Some avg -> printfn "average: %.2f" avg
| None -> printfn "no valid readings"

readings
|> List.tryFind (fun r -> r > 24)
|> Option.map (fun r -> $"first reading above 24: {r}")
|> Option.defaultValue "no reading above 24"
|> printfn "%s"

The readings come in as strings, some with spaces around them.

let readings = raw |> List.choose parseReading

List.choose applies a function that returns an option to every element. It keeps the values inside Some and drops the None results, so readings is a plain int list.

let average =
    if readings.IsEmpty then None
    else Some (readings |> List.averageBy float)

An average of an empty list does not exist, so we return an option. List.averageBy float converts the integers before averaging.

λ dotnet fsi readings.fsx
valid: [21; 23; 19; 25; 22]
failed: 3
average: 22.00
first reading above 24: 25

Source

F# language reference: Options

FSharp.Core: Option module

In this article we have worked with the option type: we have created Some and None values, matched on them, written functions that return options, used try functions of the list module, supplied defaults, transformed and chained options with Option.map, Option.filter and Option.bind, and converted null. When we need to know why a value is missing, we use the F# Result type. Options are a predefined discriminated union; unions of our own are covered in F# discriminated unions, and the struct variant voption in F# struct types.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.