π― Pattern Matching Playground
Explore OCaml's most powerful feature interactively. Write match expressions, see how values flow through patterns, and practice with challenges.
Sandbox
Challenges
Reference
π Match Expression
π€ Result
Press βΆ Evaluate or Ctrl+Enter to run
Quick Examples
Complete challenges to practice pattern matching. Click one to load it into the sandbox.
Pattern Types in OCaml
Constant | 42, "hello", true, 3.14
Variable | x, name, _ (binds any value)
Wildcard | _ (matches anything, no binding)
Tuple | (x, y), (1, _, z)
List | [], [x], [x; y], x :: rest
Constructor | Some x, None, Ok v, Error e
Or-pattern | p1 | p2 (match either)
As-pattern | pattern as name (bind whole match)
Guard | pattern when condition
Nested | Some (x, [a; b]) (compose freely)
Record | { field1; field2 }
Literal range | 'a'..'z' (char ranges)
Exhaustiveness
OCaml checks that your patterns cover all possible cases at compile time. This playground simulates that check.
(* Complete - all cases covered *)
match opt with
| Some x -> x
| None -> 0
(* Incomplete - compiler warns! *)
match opt with
| Some x -> x
(* Warning: this pattern-matching is not exhaustive.
Missing case: None *)
Common Patterns & Idioms
(* Recursive list processing *)
let rec sum = function
| [] -> 0
| x :: rest -> x + sum rest
(* Option handling *)
let get_or_default default = function
| Some v -> v
| None -> default
(* Nested destructuring *)
match config with
| { mode = Auto; retries = n } when n > 0 -> retry n
| { mode = Manual } -> prompt_user ()
| _ -> use_defaults ()
(* Result chaining *)
match parse input with
| Ok ast -> Ok (eval ast)
| Error msg -> Error ("Parse: " ^ msg)