7.6 Patterns

pattern::=value-name
constant
pattern as value-name
( pattern )
( pattern : typexpr )
pattern | pattern
constr pattern
`tag-name pattern
#typeconstr
pattern { , pattern }+
{ field [: typexpr] [= pattern] { ; field [: typexpr] [= pattern] } [; ] [ ; ] }
[ pattern { ; pattern } [ ; ] ]
pattern :: pattern
[| pattern { ; pattern } [ ; ] |]
char-literal .. char-literal
lazy pattern
exception pattern

See also the following language extensions:local opens,first-class modules,attributes andextension nodes.

The table below shows the relative precedences and associativity ofoperators and non-closed pattern constructions. The constructions withhigher precedences come first.

OperatorAssociativity
..
lazy (see section 7.6)
Constructor application, Tag applicationright
::right
,
|left
as

Patterns are templates that allow selecting data structures of agiven shape, and binding identifiers to components of the datastructure. This selection operation is called pattern matching; itsoutcome is either “this value does not match this pattern”, or“this value matches this pattern, resulting in the following bindingsof names to values”.

Variable patterns

A pattern that consists in a value name matches any value,binding the name to the value. The pattern _ also matchesany value, but does not bind any name.

Patterns are linear: a variable cannot be bound several times bya given pattern. In particular, there is no way to test for equalitybetween two parts of a data structure using only a pattern (butwhen guards can be used for this purpose).

Constant patterns

A pattern consisting in a constant matches the values thatare equal to this constant.

Alias patterns

The pattern pattern1as value-name matches the same values aspattern1. If the matching against pattern1 is successful,the name value-name is bound to the matched value, in addition to thebindings performed by the matching against pattern1.

Parenthesized patterns

The pattern (pattern1) matches the same values aspattern1. A type constraint can appear in aparenthesized pattern, as in (pattern1: typexpr). Thisconstraint forces the type of pattern1 to be compatible withtypexpr.

“Or” patterns

The pattern pattern1| pattern2 represents the logical “or” ofthe two patterns pattern1 and pattern2. A value matchespattern1| pattern2 if it matches pattern1 orpattern2. The two sub-patterns pattern1 and pattern2must bind exactly the same identifiers to values having the same types.Matching is performed from left to right.More precisely,in case some value v matches pattern1| pattern2, the bindingsperformed are those of pattern1 when v matches pattern1.Otherwise, value v matches pattern2 whose bindings are performed.

Variant patterns

The pattern constr( pattern1, … , patternn) matchesall variants whoseconstructor is equal to constr, and whose arguments matchpattern1patternn. It is a type error if n is not thenumber of arguments expected by the constructor.

The pattern constr_ matches all variants whose constructor isconstr.

The pattern pattern1:: pattern2 matches non-empty lists whoseheads match pattern1, and whose tails match pattern2.

The pattern [pattern1; … ; patternn] matches listsof length n whose elements match pattern1patternn,respectively. This pattern behaves likepattern1:: … :: patternn::[].

Polymorphic variant patterns

The pattern `tag-name pattern1 matches all polymorphic variantswhose tag is equal to tag-name, and whose argument matchespattern1.

Polymorphic variant abbreviation patterns

If the type [('a,'b,…)] typeconstr = [[tag-name]($49815e5ab82eadea.md#tag-name)<sub>1</sub> [typexpr]($2ecc3987e27872fa.md#typexpr)<sub>1</sub>|… | tag-namen typexprn] is defined, then the pattern #typeconstris a shorthand for the following or-pattern:([tag-name]($49815e5ab82eadea.md#tag-name)<sub>1</sub>(_: [typexpr]($2ecc3987e27872fa.md#typexpr)<sub>1</sub>)| … | tag-namen(_: typexprn)). It matches all values of type [<typeconstr].

Tuple patterns

The pattern pattern1, … , patternn matches n-tupleswhose components match the patterns pattern1 through patternn. Thatis, the pattern matches the tuple values (v1, …, vn) such thatpatterni matches vi for i = 1,… , n.

Record patterns

The pattern {field1 [=pattern1] ; … ; fieldn [=patternn] } matches records that define at least the fieldsfield1 through fieldn, and such that the value associated tofieldi matches the pattern patterni, for i = 1,… , n.A single identifier fieldk stands for fieldk= fieldk ,and a single qualified identifier module-path. fieldk standsfor module-path. fieldk= fieldk .The record value can define more fields than field1fieldn; the values associated to these extra fields are not takeninto account for matching. Optionally, a record pattern can be terminatedby ;_ to convey the fact that not all fields of the record type arelisted in the record pattern and that it is intentional.Optional type constraints can be added field by field with{field1: typexpr1= pattern1;… ; fieldn: typexprn= patternn} to force the typeof fieldk to be compatible with typexprk.

Array patterns

The pattern [|pattern1; … ; patternn|]matches arrays of length n such that the i-th array elementmatches the pattern patterni, for i = 1,… , n.

Range patterns

The pattern'c'..'d' is a shorthand for the pattern

'c'|'c1'|'c2'| …|'cn'|'d'

where c1, c2, …, cn are the charactersthat occur between c and d in the ASCII character set. Forinstance, the pattern '0'..'9' matches all characters that are digits.

Lazy patterns

(Introduced in Objective Caml 3.11)

pattern::=

The pattern lazypattern matches a value v of type Lazy.t,provided pattern matches the result of forcing v withLazy.force. A successful match of a pattern containing lazysub-patterns forces the corresponding parts of the value being matched, eventhose that imply no test such as lazyvalue-name or lazy_.Matching a value with a pattern-matching where some patternscontain lazy sub-patterns may imply forcing parts of the value,even when the pattern selected in the end has no lazy sub-pattern.

For more information, see the description of module Lazy in thestandard library (Module Lazy).

Exception patterns

(Introduced in OCaml 4.02)

A new form of exception pattern, exceptionpattern , is allowedonly as a toplevel pattern or inside a toplevel or-pattern undera match…with pattern-matching(other occurrences are rejected by the type-checker).

Cases with such a toplevel pattern are called “exception cases”,as opposed to regular “value cases”. Exception cases are appliedwhen the evaluation of the matched expression raises an exception.The exception value is then matched against all the exception casesand re-raised if none of them accept the exception (as with atry…with block). Since the bodies of all exception and valuecases are outside the scope of the exception handler, they are allconsidered to be in tail-position: if the match…with blockitself is in tail position in the current function, any function callin tail position in one of the case bodies results in an actual tailcall.

A pattern match must contain at least one value case. It is an error ifall cases are exceptions, because there would be no code to handlethe return of a value.