Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 40 ยท Variants and Pattern Matching

Option and Result: Handling Absence and Errors as Values

Replace null and error codes with OCaml's option and result types. Learn Option and Result modules, map, bind, let-operators and when to choose each over exceptions.

OCaml has no null. A value of type int is always an integer. When a result might be missing, the type says so: int option. When an operation can fail with a reason, the type says that too: (int, string) result. These are ordinary variants from the standard library, so the compiler forces you to deal with the missing or failing case before you can touch the value.

This removes a whole class of bugs, the null pointer error, from the language.

OCaml is not available in the site's code runners, so ocaml blocks are read-only. The Python stand-ins model the same shapes.

The two types

OCAML
type 'a option = None | Some of 'a
type ('a, 'e) result = Ok of 'a | Error of 'e

You get them without importing anything. Functions that might not have an answer return an option:

OCAML
let first_even xs = List.find_opt (fun x -> x mod 2 = 0) xs

let show = function
  | Some n -> "found " ^ string_of_int n
  | None -> "none"

let () = print_endline (show (first_even [ 1; 3; 8; 5 ]))
(* prints: found 8 *)

The standard library uses the _opt suffix for the non-raising version of a function: List.find_opt, Hashtbl.find_opt, int_of_string_opt, List.assoc_opt. The versions without the suffix raise exceptions (Not_found, Failure).

Working with options

The Option module has the helpers you need:

OCAML
Option.map (fun x -> x * 2) (Some 4)      (* Some 8 *)
Option.map (fun x -> x * 2) None          (* None *)
Option.value (Some 3) ~default:0          (* 3 *)
Option.value None ~default:0              (* 0 *)
Option.bind (Some 4) (fun x -> if x > 0 then Some (x - 1) else None)  (* Some 3 *)
Option.is_some (Some 1)                   (* true *)
Option.get (Some 5)                       (* 5, raises Invalid_argument on None *)
  • map transforms the value if there is one.
  • bind chains a step that itself might return None.
  • value supplies a default.
  • get is a shortcut that gives up safety. Use it only where None is truly impossible.

Chaining with let operators

Nested match on options gets deep. OCaml 4.08 added binding operators that flatten the chain:

OCAML
let ( let* ) = Option.bind

let parse_pair a b =
  let* x = int_of_string_opt a in
  let* y = int_of_string_opt b in
  Some (x + y)

(* parse_pair "3" "4" = Some 7
   parse_pair "3" "x" = None *)

Each let* unwraps a Some and continues, or stops the whole chain at the first None. The same pattern works for result using Result.bind.

The result type

An option says that something failed. A result says why:

OCAML
let parse_age s =
  match int_of_string_opt s with
  | None -> Error ("not a number: " ^ s)
  | Some n when n < 0 -> Error "age cannot be negative"
  | Some n -> Ok n

let () =
  match parse_age "-4" with
  | Ok n -> Printf.printf "age %d\n" n
  | Error msg -> Printf.printf "error: %s\n" msg
(* prints: error: age cannot be negative *)

The Result module mirrors Option: Result.map, Result.bind, Result.map_error, Result.value, Result.to_option, Result.is_ok.

OCAML
let ( let* ) = Result.bind

let validate name age =
  let* name = if name = "" then Error "empty name" else Ok name in
  let* age = parse_age age in
  Ok (name, age)

The error type is yours to choose. A string is quick; a variant is better for code that must react to each failure kind:

OCAML
type error = Empty_name | Bad_age of string | Negative_age
flowchart LR
    A["parse name"] -->|"Ok"| B["parse age"]
    B -->|"Ok"| C["Ok (name, age)"]
    A -->|"Error e"| X["Error e"]
    B -->|"Error e"| X

Figure: a result chain stops at the first Error and carries it to the end.

Option or result or exception?

Situation Use
Lookup that may find nothing option
Failure the caller should handle, with a reason result
Programmer error or truly exceptional event exception
Early exit from deep recursion or loops local exception

Exceptions are cheap in OCaml and perfectly acceptable. Many standard-library functions use them. The guideline is that values appear in types and are checked by the compiler, while exceptions are invisible in the type, so prefer option and result for failures that callers are expected to handle. See exceptions for the details.

Stand-in: a result chain in Python

Python Stand-in: Ok/Error values and bind

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 input()), it gets the next line from this box.

Python Stand-in: option helpers

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 input()), it gets the next line from this box.

Python uses None for the absent case, and nothing in the language reminds you to check it. In OCaml the type int option cannot be added to an int until you unwrap it.

Common mistakes

  • Calling Option.get or List.hd and trusting that the value is there. Match instead.
  • Using string errors everywhere and then comparing messages. Use a variant for errors the program reacts to.
  • Mixing styles: a function that sometimes returns None and sometimes raises is hard to use. Pick one per function and document it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the suffix convention for non-raising standard-library functions?

    List.find_opt, Hashtbl.find_opt and int_of_string_opt return an option instead of raising.
  2. 2. What does Option.value None ~default:7 return?

    value unwraps the option and returns the default when it is None.
  3. 3. When should you prefer result over option?

    Error e carries information about the failure; None only says that something is missing.
  4. 4. What does let* x = e1 in e2 do when e1 is None (with let* = Option.bind)?

    bind short-circuits on None, so the rest of the chain is skipped.

Summary

  • option models a value that may be absent, result a computation that may fail with a reason.
  • Both are plain variants. The compiler forces you to handle every case.
  • The Option and Result modules provide map, bind, value and friends, and let* flattens chains.
  • Use values for expected failures and exceptions for the truly exceptional.

Next: Polymorphic Variants and GADTs