F# · Lesson 6

Option and Result

Model "might be missing" with Option and "might fail" with Result, then chain steps into railway-style pipelines instead of null checks and exceptions.

8 min read

In short

  • option: Some or None, never null
  • Option.map, Option.bind, Option.defaultValue chain with |>
  • Result: Ok or Error with a reason
  • bind for steps that can fail, map for steps that cannot
  • Exceptions for outages, Error for expected failures

Why F# code has (almost) no null

In TypeScript you write string | undefined and, with strictNullChecks, the compiler nags you to check it. F# goes one step further: values of F# types (records, unions, lists, tuples) are never supposed to be null. When a value might be missing you say so in the type with Option.

▶ Try
function findUser(id: number): User | undefined {
  return users.find(u => u.id === id);
}
▶ Try
let findUser (id: int) : User option =
    users |> List.tryFind (fun u -> u.Id = id)
  • User option (also written Option<User>) has exactly two shapes: Some user or None.
  • List.tryFind is the safe twin of List.find. In F#, functions starting with try return an option instead of throwing.

Option is just a discriminated union from the standard library:

▶ Try
type Option<'T> =
    | None
    | Some of 'T

So you consume it with match, exactly like your own unions:

▶ Try
const user = findUser(42);
const name = user !== undefined ? user.name : "guest";
▶ Try
let name =
    match findUser 42 with
    | Some user -> user.Name   // `user` is the unwrapped User
    | None -> "guest"

.NET libraries written in C# can still hand you null (for example a missing environment variable). Convert at the boundary: Option.ofObj (System.Environment.GetEnvironmentVariable "PORT") gives None for null. After that, the rest of your code never has to think about null again.

The Option module: stop matching everything by hand

Writing match for every option gets noisy. The Option module has small helpers. Each takes the option as the last argument so they chain with |>.

F#MeaningRough TS equivalent
Option.map f opttransform the value if there is onex === undefined ? undefined : f(x)
Option.bind f optf itself returns an option; don't nestx === undefined ? undefined : f(x) where f may return undefined
Option.defaultValue d optunwrap, with a fallbackx ?? d
Option.orElse other optif None, try another optionx ?? other (where other may be undefined too)
Option.filter pred optkeep the value only if pred holdsx !== undefined && pred(x) ? x : undefined

A realistic example: read a port from config, fall back to 8080.

▶ Try
function getPort(settings: [string, string][]): number {
  const entry = settings.find(([key]) => key === "PORT");
  const n = entry ? Number.parseInt(entry[1], 10) : NaN;
  return Number.isNaN(n) ? 8080 : n;
}
▶ Try
let tryParseInt (s: string) : int option =
    match System.Int32.TryParse s with
    | true, n -> Some n
    | false, _ -> None

let getPort (settings: (string * string) list) : int =
    settings
    |> List.tryFind (fun (key, _) -> key = "PORT")
    |> Option.map snd
    |> Option.bind tryParseInt
    |> Option.defaultValue 8080

Line by line:

  • System.Int32.TryParse s is a .NET method with an out parameter. F# turns it into a tuple (succeeded, value), and | true, n -> picks the number out.
  • List.tryFind ... gives (string * string) option: the whole pair, if found.
  • Option.map snd keeps only the value part (snd returns the second item of a pair), giving string option.
  • Option.bind tryParseInt: tryParseInt already returns an option. Option.map would give int option option; bind flattens it to int option.
  • Option.defaultValue 8080 leaves the option world with a plain int.

Result: failure with a reason

None says "nothing here" but not why. For validation and business rules you want the reason, so F# has Result:

▶ Try
type Result<'T, 'TError> =
    | Ok of 'T
    | Error of 'TError

In TypeScript you would hand-roll the same discriminated union:

▶ Try
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

function parseAge(input: string): Result<number, string> {
  const n = Number.parseInt(input, 10);
  if (Number.isNaN(n)) return { ok: false, error: `not a number: ${input}` };
  if (n < 0) return { ok: false, error: "age cannot be negative" };
  return { ok: true, value: n };
}
▶ Try
let parseAge (input: string) : Result<int, string> =
    match System.Int32.TryParse input with
    | false, _ -> Error $"not a number: {input}"
    | true, n when n < 0 -> Error "age cannot be negative"
    | true, n -> Ok n
  • Ok n and Error "..." are the two cases; both sides of the match must produce the same Result<int, string>.
  • when n < 0 is a guard: the case only matches if the condition holds.

Exceptions vs Result. In F# codebases, exceptions are for things that really are exceptional (a bug, the database is down). Expected failures (bad input, a business rule saying no) are returned as Error values, so the type forces the caller to deal with them.

Errors as a discriminated union

Strings are fine for a quick script. At work, model errors as a union so callers can match on them:

▶ Try
type SignupError =
  | { kind: "nameRequired" }
  | { kind: "invalidEmail"; email: string }
  | { kind: "tooYoung"; age: number };
▶ Try
type SignupError =
    | NameRequired
    | InvalidEmail of email: string
    | TooYoung of age: int

let describe (error: SignupError) : string =
    match error with
    | NameRequired -> "Please enter your name"
    | InvalidEmail email -> $"'{email}' is not a valid email"
    | TooYoung age -> $"You must be 18 or older (you are {age})"

If you later add a case, the compiler warns about every match that forgot it. That is a huge win over string errors.

Railway-oriented programming

Picture two parallel tracks: the Ok track and the Error track. Each step either keeps you on the Ok track or switches you to the Error track. Once you are on the Error track, the remaining steps are skipped and the first error comes out at the end.

  • Result.map f: f is a normal function ('a -> 'b). It runs only on Ok.
  • Result.bind f: f is a step that can fail ('a -> Result<'b, 'e>). It runs only on Ok, and the result is not nested.
  • Result.mapError f: transforms the error. Use it to convert another module's error type into yours.
▶ Try
function register(form: Form): Result<User, SignupError> {
  const name = validateName(form.name);
  if (!name.ok) return name;
  const email = validateEmail(form.email);
  if (!email.ok) return email;
  return { ok: true, value: { name: name.value, email: email.value } };
}
▶ Try
let register (form: Form) : Result<User, SignupError> =
    validateName form.Name
    |> Result.bind (fun name ->
        validateEmail form.Email
        |> Result.map (fun email -> { Name = name; Email = email }))
  • If validateName returns Error, Result.bind skips the lambda and passes the error through.
  • The lambdas are nested so that name is still in scope when we build the user. (The Computation Expressions topic shows result { let! ... }, which flattens this.)

When each step takes the previous step's output, the pipeline reads top to bottom:

▶ Try
let processOrder (raw: string) : Result<Receipt, OrderError> =
    raw
    |> parseOrder                // string -> Result<Order, OrderError>
    |> Result.bind validateOrder // Order  -> Result<Order, OrderError>
    |> Result.map applyDiscount  // Order  -> Order (cannot fail)
    |> Result.bind saveOrder     // Order  -> Result<Receipt, OrderError>

Result.bind needs both sides to use the same error type. When a step speaks a different error language, translate it with mapError:

▶ Try
type PaymentError =
    | CardDeclined
    | InsufficientFunds

type OrderError =
    | InvalidOrder of string
    | PaymentFailed of PaymentError

let pay (order: Order) : Result<Receipt, OrderError> =
    chargeCard order.Total           // Result<Receipt, PaymentError>
    |> Result.mapError PaymentFailed // Result<Receipt, OrderError>

Union cases are functions, so PaymentFailed can be passed directly where a PaymentError -> OrderError is expected.

Validation: first error vs all errors

bind stops at the first error ("fail fast"). That is right for a pipeline where step 2 needs step 1's output. Forms usually want every problem at once. Then you run the checks independently and collect the errors:

▶ Try
let errorsOf (result: Result<'a, 'e>) : 'e list =
    match result with
    | Ok _ -> []
    | Error e -> [ e ]

let validateAll (form: Form) : Result<Form, SignupError list> =
    let errors = errorsOf (validateName form.Name) @ errorsOf (validateEmail form.Email)
    if List.isEmpty errors then Ok form else Error errors

Common beginner mistakes

  • map where you needed bind. If the function already returns an option or result, map gives you int option option. Use bind.
  • Calling .Value on an option. opt.Value throws on None, just like user!.name in TS. Match, or use Option.defaultValue.
  • Wrong argument order. It is Option.defaultValue 0 opt, not Option.defaultValue opt 0. The option always comes last.
  • Mixing the two types. Option.bind on a Result (or Ok where Some is expected) is a type error. Use the matching module.
  • Throwing for validation. failwith "bad email" hides the failure from the type. Return Error (InvalidEmail email).
  • Mismatched error types in bind. Align them with Result.mapError first.
  • Checking for null on F# values. if user = null doesn't compile for records. Convert .NET nulls once with Option.ofObj.

Cheat sheet

▶ Try
Some 3, None                             // Option<'T>
Ok 3, Error "bad"                        // Result<'T, 'E>
List.tryFind / List.tryHead / Map.tryFind // safe lookups return options
Option.map f / Option.bind f             // transform / chain a step that may be missing
Option.defaultValue d                    // x ?? d
Option.orElse (Some d)                   // try another option
Option.filter pred                       // Some -> None when pred is false
Option.ofObj value                       // .NET null -> None
Result.map f / Result.bind f             // transform / chain a step that may fail
Result.mapError f                        // convert the error type
Result.defaultValue d / Result.toOption  // leave the Result world
match r with
| Ok v -> ...
| Error e -> ...

Practise this lesson

In the app: a short video, 6 exercises checked by real tests and a 11-question concept check. Free with a GitHub account. Running the exercises against their tests needs Pro.

Open in the app