Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 40 ยท Variants and Pattern Matching

Variant Types: Modelling Choices with Constructors

Learn OCaml variant types. Define types with several constructors, attach data to them, build recursive and parameterized types, and model real problems precisely.

A variant type says "a value is one of these alternatives". Each alternative has a name, called a constructor, and may carry data. Variants are the single most important modelling tool in OCaml. Where other languages use enums, class hierarchies, tagged unions or null checks, OCaml uses one feature that is checked completely by the compiler.

Variants are also called algebraic data types (sum types). Combined with pattern matching, they let you write code that cannot forget a case.

OCaml is not available in the site's code runners. The ocaml blocks below are read-only: every example was written to be compiled with OCaml 5 and the printed results are shown only where they are certain. The runnable Python blocks are labelled stand-ins: they mimic the same data shapes so you can experiment with the idea.

Constant constructors

The simplest variant is a list of names, like an enum:

OCAML
type weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun

let is_weekend d =
  match d with
  | Sat | Sun -> true
  | _ -> false

let () = print_endline (string_of_bool (is_weekend Sat))
(* prints: true *)

Constructor names start with a capital letter. There are no integer codes behind them that you can mix up: a weekday is not an int, and the compiler will not let you pass one where the other is expected.

Constructors that carry data

A constructor can hold values. After the keyword of you list the types, separated by *:

OCAML
type shape =
  | Circle of float
  | Rectangle of float * float
  | Triangle of float * float * float

let area = function
  | Circle r -> Float.pi *. r *. r
  | Rectangle (w, h) -> w *. h
  | Triangle (a, b, c) ->
      let s = (a +. b +. c) /. 2.0 in
      sqrt (s *. (s -. a) *. (s -. b) *. (s -. c))

Circle 2.0 and Rectangle (3.0, 4.0) are values. Circle on its own is a function float -> shape. Each shape carries exactly the data it needs, with no unused fields and no way to read a radius from a rectangle.

Stand-in: tagged values

A variant value is, in spirit, a tag plus a payload. This Python program builds the same structure with tuples and dispatches on the tag:

Python Stand-in: shapes as tagged tuples

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.

In Python nothing stops you from writing ("Circel", 1.0) and finding out at run time. In OCaml a misspelled constructor is a compile error.

Inline records

When a constructor has many fields, positions become hard to read. Use an inline record:

OCAML
type event =
  | Click of { x : int; y : int }
  | Key of { code : int; shift : bool }
  | Quit

let describe = function
  | Click { x; y } -> Printf.sprintf "click at %d,%d" x y
  | Key { code; shift } -> Printf.sprintf "key %d%s" code (if shift then " +shift" else "")
  | Quit -> "quit"

Inline records are not first-class values: you cannot take the record out of the constructor and pass it around alone. For that, declare a separate record type and write Click of click_info.

Parameterized types

A variant can take type parameters. The standard library defines options this way:

OCAML
type 'a option = None | Some of 'a

'a is a type variable, read "alpha". int option is either None or Some 3. You can define your own:

OCAML
type ('a, 'b) either = Left of 'a | Right of 'b

let l : (int, string) either = Left 42
let r : (int, string) either = Right "oops"

The syntax puts parameters before the type name: 'a list, ('k, 'v) map. Read it from left to right, like English: "a list of ints".

Recursive types

A variant may mention itself, which gives you trees and linked structures for free:

OCAML
type 'a tree =
  | Leaf
  | Node of 'a tree * 'a * 'a tree

let rec insert x = function
  | Leaf -> Node (Leaf, x, Leaf)
  | Node (l, v, r) as t ->
      if x < v then Node (insert x l, v, r)
      else if x > v then Node (l, v, insert x r)
      else t

let rec size = function
  | Leaf -> 0
  | Node (l, _, r) -> size l + 1 + size r

insert 5 Leaf gives Node (Leaf, 5, Leaf). The function is generic: it works for any type with the polymorphic comparison operators. The data structure and the function mirror each other, which is why recursion over variants feels natural. You will use this tree again in the expression evaluator project.

flowchart TD
    N1["Node 5"] --> N2["Node 3"]
    N1 --> N3["Node 8"]
    N2 --> L1["Leaf"]
    N2 --> L2["Leaf"]
    N3 --> L3["Leaf"]
    N3 --> L4["Leaf"]

Figure: the tree after inserting 5, 3 and 8 into an empty tree.

Stand-in: the same tree in Python

Python Stand-in: binary search tree as nested tuples

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.

Mutually recursive types

Two types that refer to each other are joined with and:

OCAML
type expr =
  | Num of int
  | Block of stmt list
and stmt =
  | Print of expr
  | Seq of stmt * stmt

The same and works for functions that call each other (let rec ... and ...).

Why variants beat flags

Compare two designs for "a connection that is closed, connecting, or open with a socket":

OCAML
type state =
  | Closed
  | Connecting of { attempt : int }
  | Open of { socket : int; opened_at : float }

A record with is_open : bool and socket : int option allows nonsense such as "closed with a socket". The variant makes illegal states unrepresentable: only Open has a socket. This phrase is one of the most repeated pieces of OCaml advice, and you will apply it in the state machine project.

Common mistakes

  • Writing Circle 2.0, 3.0 when you mean Rectangle (2.0, 3.0): constructors with several arguments take a tuple in parentheses.
  • Forgetting that constructors are capitalized and variables are lowercase. Red is always a constructor.
  • Using the same constructor name in two types in one scope. The latest definition wins, which can produce confusing type errors. Add a type annotation or qualify the name.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Some 3 have as its type?

    Some 3 wraps an int, so its type is int option. Type parameters are written before the type name in OCaml.
  2. 2. Which declaration gives each shape only the data it needs?

    Variant constructors can each carry different data, so a circle holds a radius and a rectangle holds two sides.
  3. 3. What is Circle (without arguments) when Circle of float is declared?

    A constructor with arguments is used like a function that builds the variant value.
  4. 4. What does the keyword and do between two type declarations?

    With and, each type can refer to the other one in its own definition.

Summary

  • A variant type lists named alternatives (constructors), each optionally carrying data with of.
  • Constructors are capitalized and, when they take arguments, behave like functions.
  • Types can be parameterized ('a option) and recursive ('a tree), and and joins mutually recursive definitions.
  • Design variants so that illegal states cannot be represented.

Next: Pattern Matching in Depth