Skip to content

Instantly share code, notes, and snippets.

@mrange
Last active October 3, 2016 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrange/73c46612bbe12c14f346453f6301b771 to your computer and use it in GitHub Desktop.
Save mrange/73c46612bbe12c14f346453f6301b771 to your computer and use it in GitHub Desktop.
Use Option<'T> over null values in F#

In functional programming languages like F# null values are considered potentially harmful and poor style (non-idiomatic).

Consider this C# code:

    string x = SomeFunction ();
    int    l = x.Length;

x.Length will throw if x is null let's add protection:

    string x = SomeFunction ();
    int    l = x != null ? x.Length : 0;

Or:

    string x = SomeFunction () ?? "";
    int    l = x.Length;

Or:

    string x = SomeFunction ();
    int    l = x?.Length;

In idiomatic F# null values aren't used so our code looks like this:

    let x = SomeFunction ()
    let l = x.Length

However, sometimes there's a need for representing empty or invalid values. Then we can use Option<'T>:

    let SomeFunction () : string option = ...

SomeFunction either returns Some string value or None. We extract the string value using pattern matching

    let v =
      match SomeFunction () with
      | Some x  -> x.Length
      | None    -> 0

The reason this code is less fragile than:

    string x = SomeFunction ();
    int    l = x.Length;

Is because we can't call Length on a string option. We need to extract the string value using pattern matching and by doing so we are guaranteed that the string value is safe to use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment