Skip to content
Variants — Custom Types
step 1/5

Reading — step 1 of 5

Learn

~1 min readPattern Matching

Variants define a type that's one of several variants — OCaml's killer type-modeling feature.

type shape =
  | Circle of float
  | Square of float
  | Rectangle of float * float

let area s =
  match s with
  | Circle r -> 3.14159 *. r *. r
  | Square s -> s *. s
  | Rectangle (w, h) -> w *. h

Note *., +., -., /. for floats — OCaml has separate operators for int and float (no implicit coercion).

Variants are how you eliminate null. The built-in option type is just:

type 'a option = None | Some of 'a

Use it for things that might be missing:

let safe_div a b =
  if b = 0 then None
  else Some (a / b)

The caller must pattern-match on Some x / None to use the result — no NullPointerException possible.

Records are like structs:

type point = { x : int; y : int }
let origin = { x = 0; y = 0 }
let () = print_int origin.x

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…