Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 37 ยท Pattern Matching and Options

Option and ValueOption

Learn how F# replaces null with Option: Some and None, the Option module (map, bind, defaultValue), pipelines, ValueOption for performance, and interop with nullable .NET values.

Tony Hoare called the null reference his billion-dollar mistake. A value that might be missing looks exactly like one that is present, and the first time you forget to check, the program fails far from the cause. F# avoids the problem by making absence visible in the type. A value that might not exist has type option, and the compiler makes you deal with both cases.

Some and None

Option<'T> is a plain discriminated union (see Discriminated Unions):

FSHARP
type Option<'T> =
    | None
    | Some of 'T
FSHARP
let tryFindUser id =
    if id = 1 then Some "Ada" else None

match tryFindUser 1 with
| Some name -> printfn "found %s" name
| None -> printfn "nobody there"

The type of tryFindUser is int -> string option. A caller cannot pretend the result is a string: to get at the name they must match. By convention, functions that can fail to produce a value are named tryXxx and return an option, for example List.tryFind, Map.tryFind and Seq.tryHead. Their non-try siblings (List.find) throw an exception instead.

C# C# stand-in: nullable reference types as a rough equivalent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C#'s nullable annotations give a warning when you forget the check; the F# option gives a hard error, and works for every type, including ones like int that cannot be null.

Working with options: the Option module

Matching every time is tedious. The Option module has small functions for the common shapes:

FSHARP
let name = Some "ada"

name |> Option.map (fun s -> s.ToUpper())           // Some "ADA"
name |> Option.defaultValue "unknown"               // "ada"
None |> Option.defaultValue "unknown"               // "unknown"
name |> Option.isSome                               // true
name |> Option.filter (fun s -> s.Length > 5)       // None
  • Option.map f applies f inside a Some and leaves None alone.
  • Option.bind f is for functions that themselves return an option, and avoids nested Some (Some x).
  • Option.defaultValue and Option.defaultWith unwrap with a fallback.
  • Option.iter runs a side effect only for Some.

bind: chaining steps that may fail

FSHARP
let parseInt (s: string) =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | _ -> None

let safeDivide a b = if b = 0 then None else Some (a / b)

let compute (a: string) (b: string) =
    parseInt a
    |> Option.bind (fun x ->
        parseInt b
        |> Option.bind (fun y -> safeDivide x y))

compute "10" "2"    // Some 5
compute "10" "0"    // None
compute "ten" "2"   // None

Each step runs only if the previous one produced a value; the first None short-circuits the rest. Nesting like this gets heavy, so F# offers the option computation expression:

FSHARP
let compute2 a b =
    option {
        let! x = parseInt a
        let! y = parseInt b
        return! safeDivide x y
    }

let! unwraps a Some or stops the whole block with None. It reads like straight-line code and behaves like the bind chain above. (option { } ships in FSharp.Core 9 and later; on older versions you can define a small builder or use Option.bind.)

C# C# stand-in: chaining with null-propagation and a helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Options in collections

Options and lists combine well. List.choose maps and keeps only the Some results in one step:

FSHARP
let inputs = [ "1"; "x"; "3"; "" ; "5" ]
let numbers = inputs |> List.choose parseInt     // [1; 3; 5]

List.tryHead, List.tryFind and Seq.tryPick return options, and Option.toList or Option.toArray turn one into a collection. See Collections and Sequences for the other list functions.

ValueOption

Option is a heap-allocated union, one small object per Some. In hot loops that adds up. ValueOption (ValueSome / ValueNone) is a struct version:

FSHARP
let tryPositive n = if n > 0 then ValueSome n else ValueNone

match tryPositive 5 with
| ValueSome v -> printfn "%d" v
| ValueNone -> printfn "none"

The ValueOption module mirrors Option (ValueOption.map, ValueOption.defaultValue). A function can also opt in per call site: the [<return: Struct>] attribute makes a partial active pattern return a ValueOption. Use ValueOption in performance-sensitive code that returns options frequently, and plain Option everywhere else; its better tooling and wider support usually win.

flowchart LR
    A["tryFindUser 1"] -->|Some| B["Option.map ToUpper"]
    A -->|None| D["None"]
    B --> C["Option.defaultValue unknown"]
    D --> C
    C --> E["string"]

An option flows through a pipeline: Some is transformed, None passes straight through, and defaultValue finally leaves option-land.

Options and .NET null

.NET APIs return null. Turn a nullable reference into an option at the boundary and keep the rest of your code null-free:

FSHARP
let ofNullString (s: string) = Option.ofObj s           // null -> None
let ofNullableInt (n: System.Nullable<int>) = Option.ofNullable n

Option.toObj and Option.toNullable convert the other way when you call a .NET method that expects null.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of a function that might not return a string?

    An option in the return type forces callers to handle absence.
  2. 2. What does Option.map do when given None?

    map transforms the value inside Some and leaves None untouched.
  3. 3. When do you use Option.bind instead of Option.map?

    bind flattens: with map you would get an option of an option.
  4. 4. What is the main reason to use ValueOption?

    ValueOption is a struct, so it avoids allocating an object for each Some.

Summary

  • Option (Some / None) makes absence part of the type; no null needed.
  • tryXxx functions return options; plain versions throw.
  • Use Option.map, bind, filter and defaultValue to avoid repeated matching, or the option { } workflow for longer chains.
  • List.choose collects the Some results of a mapping.
  • ValueOption is the struct form for performance-critical code; convert .NET nulls with Option.ofObj.

Next: Result and Error Handling