TExcelTAD
Home › OCaml › OCaml Variants

OCaml Variants

A variant type (also called a sum type or algebraic data type) describes a value that is one of several alternatives. Each alternative is a constructor, which starts with a capital letter.

ocaml · try it yourself
type suit = Hearts | Diamonds | Clubs | Spades

let colour s =
  match s with
  | Hearts | Diamonds -> "red"
  | Clubs | Spades -> "black"

let symbol = function
  | Hearts -> "♥" | Diamonds -> "♦" | Clubs -> "♣" | Spades -> "♠"

let () =
  List.iter
    (fun s -> Printf.printf "%s is %s\n" (symbol s) (colour s))
    [ Hearts; Clubs; Spades ]
♥ is red
♣ is black
♠ is black

A variant with only plain constructors works like an enum in other languages, but the compiler knows the full list of cases: if you forget Spades in a match, you get a warning.

Constructors with data

Constructors can carry data, written with of. Different constructors can carry different types:

ocaml · try it yourself
type payment =
  | Cash
  | Card of string * int          (* card brand, last 4 digits *)
  | Voucher of { code : string; value : float }

let describe = function
  | Cash -> "paid in cash"
  | Card (brand, last4) -> Printf.sprintf "paid by %s card ending %04d" brand last4
  | Voucher { code; value } -> Printf.sprintf "voucher %s worth %.2f" code value

let () =
  [ Cash; Card ("Visa", 42); Voucher { code = "SPRING"; value = 10.0 } ]
  |> List.iter (fun p -> print_endline (describe p))
paid in cash
paid by Visa card ending 0042
voucher SPRING worth 10.00

Voucher uses an inline record: named fields that exist only inside that constructor. This is clearer than a long tuple.

Why variants are powerful

Variants let you make invalid states unrepresentable. Compare two ways to model a network connection:

ocaml
(* a record with optional fields: what does "connected = false but session_id = Some 7" mean? *)
type conn_bad = { connected : bool; session_id : int option; error : string option }

(* a variant: each state carries exactly the data that makes sense for it *)
type conn =
  | Disconnected
  | Connecting of int          (* attempt number *)
  | Connected of int           (* session id *)
  | Failed of string           (* error message *)

With the variant, a value cannot be both connected and failed, and every match must handle all four states.

ocaml · try it yourself
type conn = Disconnected | Connecting of int | Connected of int | Failed of string

let step = function
  | Disconnected -> Connecting 1
  | Connecting n when n >= 3 -> Failed "too many attempts"
  | Connecting n -> if n = 2 then Connected 9001 else Connecting (n + 1)
  | (Connected _ | Failed _) as final -> final

let show = function
  | Disconnected -> "disconnected"
  | Connecting n -> "connecting (attempt " ^ string_of_int n ^ ")"
  | Connected id -> "connected, session " ^ string_of_int id
  | Failed msg -> "failed: " ^ msg

let () =
  let rec run state n =
    print_endline (show state);
    if n > 0 then run (step state) (n - 1)
  in
  run Disconnected 4
disconnected
connecting (attempt 1)
connecting (attempt 2)
connected, session 9001
connected, session 9001

Recursive variants

A variant can refer to itself. This is how you define lists, trees and expression languages:

ocaml · try it yourself
type expr =
  | Num of int
  | Add of expr * expr
  | Mul of expr * expr

let rec eval = function
  | Num n -> n
  | Add (a, b) -> eval a + eval b
  | Mul (a, b) -> eval a * eval b

let rec show = function
  | Num n -> string_of_int n
  | Add (a, b) -> "(" ^ show a ^ " + " ^ show b ^ ")"
  | Mul (a, b) -> show a ^ " * " ^ show b

let () =
  let e = Mul (Add (Num 2, Num 3), Num 4) in
  Printf.printf "%s = %d\n" (show e) (eval e)
(2 + 3) * 4 = 20

The built-in list type is itself a variant, roughly type 'a list = [] | (::) of 'a * 'a list.

Polymorphic variants (a glimpse)

OCaml also has polymorphic variants, written with a backtick (`Red). They need no type declaration and can be shared between types. They are handy for small sets of tags, but ordinary variants give clearer error messages, so start with those.

ocaml · try it yourself
let to_hex = function `Red -> "#f00" | `Green -> "#0f0" | `Blue -> "#00f"

let () = print_endline (String.concat " " (List.map to_hex [ `Red; `Blue ]))
#f00 #00f

Test yourself

How do you declare a constructor Square that carries a float?

  1. Square : float
  2. Square of float
  3. Square(float)
  4. square of float

What is a key advantage of variants over a record with many optional fields?

  1. They are faster to print
  2. They make invalid combinations of data impossible to represent
  3. They can be mutated
  4. They need no pattern matching

Which type definition is recursive?

  1. type t = A | B
  2. type t = Leaf | Node of t * int * t
  3. type t = { x : int }
  4. type t = int * int