# Pattern matching

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Pattern_matching
> Markdown URL: https://mediated.wiki/source/Pattern_matching.md
> Source: https://en.wikipedia.org/wiki/Pattern_matching
> Source revision: 1355403941
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

Functional programming construct

This article is about pattern matching in [functional programming](/source/Functional_programming). For other uses, see [String matching](/source/String_matching) and [Pattern recognition](/source/Pattern_recognition).

For the use of variable matching criteria in defining abstract patterns to match, see [Regular expression](/source/Regular_expression).

This article needs more citations. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed. Find sources: "Pattern matching" – news · newspapers · books · scholar · JSTOR (February 2011) (Learn how and when to remove this message)

In [computer science](/source/Computer_science), **pattern matching** is the act of checking a given sequence of [tokens](/source/Lexical_analysis#Token) for the presence of the constituents of some [pattern](/source/Pattern). In contrast to [pattern recognition](/source/Pattern_recognition), the match usually must be exact: "either it will or will not be a match." The patterns generally have the form of either [sequences](/source/String_(computer_science)) or [tree structures](/source/Tree_structure). Uses of pattern matching include outputting the locations (if any) of a pattern within a token sequence, to output some component of the matched pattern, and to substitute the matching pattern with some other token sequence (i.e., [search and replace](/source/Regular_expression)).

Sequence patterns (e.g., a text string) are often described using [regular expressions](/source/Regular_expression) and matched using techniques such as [backtracking](/source/Backtracking).

Tree patterns are used in some [programming languages](/source/Programming_language) as a general tool to process data based on its structure, e.g. [C#](/source/C_Sharp_(programming_language)),[1] [F#](/source/F_Sharp_(programming_language)),[2] [Haskell](/source/Haskell),[3] [Java](/source/Java_(programming_language)),[4] [ML](/source/ML_(programming_language)), [Python](/source/Python_(programming_language)),[5] [Racket](/source/Racket_(programming_language)),[6] [Ruby](/source/Ruby_(programming_language)),[7] [Rust](/source/Rust_(programming_language)),[8] [Scala](/source/Scala_(programming_language)),[9] [Swift](/source/Swift_(programming_language))[10] and the symbolic mathematics language [Mathematica](/source/Wolfram_Mathematica) have special [syntax](/source/Syntax_(programming_languages)) for expressing tree patterns and a [language construct](/source/Language_construct) for [conditional execution](/source/Conditional_(computer_programming)) and value retrieval based on it.

Often it is possible to give alternative patterns that are tried one by one, which yields a powerful conditional programming construct. Pattern matching sometimes includes support for [guards](/source/Guard_(computer_science)).[11]

## History

See also: [Regular expression § History](/source/Regular_expression#History)

Early programming languages with pattern matching constructs include [COMIT](/source/COMIT) (1957), [SNOBOL](/source/SNOBOL) (1962), which introduced pattern matching as a core, first-class language capability for string and text manipulation. This [paradigm](/source/Paradigm) evolved into structured, tree-based data evaluation with [Refal](/source/Refal) (1968), which used pattern matching to manipulate symbolic expressions. The concept was soon adapted into [logic programming](/source/Logic_programming) with [Prolog](/source/Prolog) (1972), where pattern matching took the form of structural unification to resolve logical queries. [Functional programming languages](/source/Functional_programming) rapidly adopted and formalized the feature across the late 1970s and early 1980s, beginning with the [St Andrews Static Language (SASL)](/source/SASL_(programming_language)) (1976), [NPL](/source/NPL_(programming_language)) (1977), and the [Kent Recursive Calculator](/source/Kent_Recursive_Calculator) (KRC) (1981). [12]

The pattern matching feature of function arguments in the language [ML](/source/ML_(programming_language)) (1973) and its dialect [Standard ML](/source/Standard_ML) (1983) heavily formalized compile-time exhaustiveness checking. This approach has been carried over to some other functional programming languages that were influenced by them, such as [Haskell](/source/Haskell) (1990), [Scala](/source/Scala_(programming_language)) (2004), and [F#](/source/F_Sharp_(programming_language)) (2005). The pattern matching construct with the match keyword that was introduced in the [ML](/source/ML_(programming_language)) dialect [Caml](/source/Caml) (1985) was followed by languages such as [OCaml](/source/OCaml) (1996), [F#](/source/F_Sharp_(programming_language)) (2005), [F*](/source/F*_(programming_language)) (2011), and [Rust](/source/Rust_(programming_language)) (2015). Over time, multi-paradigm languages begin implementing [algebraic data types](/source/Algebraic_data_type) and pattern matching natively, culminating in modern implementations like [Python's](/source/Python_(programming_language)) match-case syntax (2021) and [Java's](/source/Java_(programming_language)) pattern matching enhancements (2023). [13]

Many [text editors](/source/Text_editor) support pattern matching of various kinds to facilitate advanced search-and-replace capabilities. The [QED editor](/source/QED_(text_editor)), designed by [Ken Thompson](/source/Ken_Thompson), was a pioneer in supporting regular expression searching. Thompson's implementation of regular expression parsing in [QED](/source/QED_(text_editor)) laid the groundwork for the text search utilities in [ed](/source/Ed_(text_editor)), [sed](/source/Sed), and [grep](/source/Grep). Furthermore, some versions of the [TECO](/source/TECO_(text_editor)) editor supported advanced matching features, including the logical OR operator in searches. [14]

[Computer algebra systems](/source/Computer_algebra_system) (CAS) generally support pattern matching on algebraic expressions to achieve symbolic simplification and integration. Early systems like [Macsyma](/source/Macsyma) (1968) used semantic pattern matching to recognize [algebraic equivalence](/source/Algebraic_equivalence); for example, its internal engine could successfully match both 3x2 + 4 and (x + 1)(x + 6) as occurrences of a "quadratic in x" pattern template. Modern computer algebra systems, including [Mathematica](/source/Wolfram_Mathematica) and [Maple](/source/Maple_(software)), rely heavily on pattern-matching rules to transform user expressions, find analytical solutions to [differential equations](/source/Differential_equation), and build user-defined simplification frameworks.[15]

## Terminology

Pattern matching involves specialized terminology.

**Matching**
- The act of comparing a *scrutinee* to a *pattern* (or collection of patterns), possibly selecting a *continuation*, extracting *bindings*, performing a *substitution*, or any combination of these. Also known as **destructuring**.

**Pattern**
- Syntax describing expected structure in the *scrutinee*, plus specification of portions of the scrutinee to extract (*bindings*) or ignore (*wildcards*). Pattern languages can be rich; see below for terminology denoting specific kinds of pattern.

**Scrutinee**
- The value to be examined and matched against a pattern. In most cases, this will be a data structure of some kind, with type [dual to](/source/Duality_(mathematics)) the pattern being applied. Also known as the **subject value** or **discriminant**.

**Continuation**
- In some languages, when multiple alternative patterns are applied to a scrutinee, when one alternative matches, an associated code fragment is executed in an environment extended with the matching pattern's *bindings*. This code fragment is the *continuation* associated with the pattern.

**Substitution**
- Replacement of a portion of a scrutinee data structure with some computed value. The computation may depend on the replaced portion of the scrutinee as well as on other bindings extracted from the scrutinee.

### Terminology of patterns

While some concepts are relatively common to many pattern languages, other pattern languages include unique or unusual extensions.

**[Binding](/source/Name_binding)**
- A way of associating a *name* with a portion of the scrutinee, so that the name is [bound to](/source/Name_binding) that portion when the continuation executes. For example, in Rust, match v { (a, b) => ... } expects v to be a pair, and a and b are bindings bringing variables of the same name into scope in the continuation ("...").

**Wildcard**
- Often written as a single underscore, _, the wildcard pattern accepts all values without examining them further, ignoring their structure. Also known as **discard**, the **wild pattern**, the **catch-all pattern**, or as a **hole**.

**[Guard](/source/Guard_(computer_science))**
- A *guard* is an expression that must succeed (or yield Boolean true) as a final step before considering a pattern to have successfully matched. In some languages (e.g. [Erlang](/source/Erlang_(programming_language))), guards are written using a restricted subset of the full language; in others (e.g. [Haskell](/source/Haskell)), guards may use the full language.

**Predicate**
- Some pattern languages allow user-defined *predicate* functions to be embedded in a pattern. The predicate is applied to the portion of the scrutinee corresponding to the position of the predicate in the pattern; if the predicate responds with Boolean false, the pattern is considered to have failed. For example, in Racket, the pattern (list (? even?) ...) first expects a list, and then applies the predicate even? to each element; the overall pattern thus succeeds only when the scrutinee is a list of even numbers.

**View pattern**
- Languages like Haskell[16] and Racket[17] include *view patterns*, where a user-defined function transforms the portion of the scrutinee corresponding to the position of the view pattern before continuing the match. View patterns generalize predicate patterns, allowing further matching on the result of the function rather than simply expecting a Boolean value.

**Constraint**
- Some pattern languages allow direct comparison of portions of the scrutinee with previously-computed (or constant) data structures. For example, the pattern (== expr) in Racket compares the value against the result of evaluating expr. In Erlang, mention of any variable already in scope in a pattern causes it to act as a constraint in this way (instead of as a binding).

**Literal pattern; atomic pattern**
- Patterns that match simple atomic data such as 123 or "hello" are called *literal patterns*.

**Compound pattern**
- Patterns that destructure compound values such as lists, hash tables, tuples, structures or records, with sub-patterns for each of the values making up the compound data structure, are called *compound patterns*.

**Alternative (or-pattern)**
- Many languages allow multiple alternatives at the top-level of a pattern matching construct, each associated with a *continuation*; some languages allow alternatives *within* a pattern. In most cases, such alternatives have additional constraints placed on them: for example, every alternative may be required to produce the same set of *bindings* (at the same types).

**Macros**
- Some languages allow macros in pattern context to allow abstraction over patterns. For example, in Racket, *match expanders* perform this role.[18]

## Types

### Primitive patterns

The simplest pattern in pattern matching is an explicit value or a variable. For an example, consider a simple function definition in Haskell syntax (function parameters are not in parentheses but are separated by spaces, = is not assignment but definition):

f 0 = 1

Here, 0 is a single value pattern. Now, whenever f is given 0 as argument the pattern matches and the function returns 1. With any other argument, the matching and thus the function fail. As the syntax supports alternative patterns in function definitions, we can continue the definition extending it to take more generic arguments:

f n = n * f (n-1)

Here, the first n is a single variable pattern, which will match absolutely any argument and bind it to name n to be used in the rest of the definition. In Haskell (unlike at least [Hope](/source/Hope_(programming_language))), patterns are tried in order so the first definition still applies in the very specific case of the input being 0, while for any other argument the function returns n * f (n-1) with n being the argument.

The wildcard pattern (often written as _) is also simple: like a variable name, it matches any value, but does not bind the value to any name. Algorithms for [matching wildcards](/source/Matching_wildcards) in simple string-matching situations have been developed in a number of [recursive](/source/Recursion) and non-recursive varieties.[19]

### Tree patterns

More complex patterns can be built from the primitive ones of the previous section, usually in the same way as values are built by combining other values. The difference then is that with variable and wildcard parts, a pattern does not build into a single value, but matches a group of values that are the combination of the concrete elements and the elements that are allowed to vary within the structure of the pattern.

A tree pattern describes a part of a tree by starting with a node and specifying some branches and nodes and leaving some unspecified with a variable or wildcard pattern. It may help to think of the [abstract syntax tree](/source/Abstract_syntax_tree) of a programming language and [algebraic data types](/source/Algebraic_data_type).

#### Haskell

In Haskell, the following line defines an algebraic data type Color that has a single data constructor ColorConstructor that wraps an integer and a string.

data Color = ColorConstructor Integer String

The constructor is a node in a tree and the integer and string are leaves in branches.

When we want to write [functions](/source/Function_(programming)) to make Color an [abstract data type](/source/Abstract_data_type), we wish to write functions to [interface](/source/Interface_(computer_science)) with the data type, and thus we want to extract some data from the data type, for example, just the string or just the integer part of Color.

If we pass a variable that is of type Color, how can we get the data out of this variable? For example, for a function to get the integer part of Color, we can use a simple tree pattern and write:

integerPart (ColorConstructor theInteger _) = theInteger

As well:

stringPart (ColorConstructor _ theString) = theString

The creations of these functions can be automated by Haskell's data [record](/source/Record_(computer_science)) syntax.

#### OCaml

This [OCaml](/source/OCaml) example which defines a [red–black tree](/source/Red%E2%80%93black_tree) and a function to re-balance it after element insertion shows how to match on a more complex structure generated by a recursive data type. The compiler verifies at compile-time that the list of cases is exhaustive and none are redundant.

type color = Red | Black
type 'a tree = Empty | Tree of color * 'a tree * 'a * 'a tree

let rebalance t = match t with
    | Tree (Black, Tree (Red, Tree (Red, a, x, b), y, c), z, d)
    | Tree (Black, Tree (Red, a, x, Tree (Red, b, y, c)), z, d)
    | Tree (Black, a, x, Tree (Red, Tree (Red, b, y, c), z, d))
    | Tree (Black, a, x, Tree (Red, b, y, Tree (Red, c, z, d)))
        ->  Tree (Red, Tree (Black, a, x, b), y, Tree (Black, c, z, d))
    | _ -> t (* the 'catch-all' case if no previous pattern matches *)

## Usage

### Filtering data with patterns

Pattern matching can be used to filter data of a certain structure. For instance, in Haskell a [list comprehension](/source/List_comprehension) could be used for this kind of filtering:

[A x|A x <- [A 1, B 1, A 2, B 2]]

evaluates to

[A 1, A 2]

### Pattern matching in Mathematica

In [Mathematica](/source/Mathematica), the only structure that exists is the [tree](/source/Tree_(data_structure)), which is populated by symbols. In the [Haskell](/source/Haskell) syntax used thus far, this could be defined as

data SymbolTree = Symbol String [SymbolTree]

An example tree could then look like

Symbol "a" [Symbol "b" [], Symbol "c" []]

In the traditional, more suitable syntax, the symbols are written as they are and the levels of the tree are represented using [], so that for instance a[b,c] is a tree with a as the parent, and b and c as the children.

A pattern in Mathematica involves putting "_" at positions in that tree. For instance, the pattern

A[_]

will match elements such as A[1], A[2], or more generally A[*x*] where *x* is any entity. In this case, A is the concrete element, while _ denotes the piece of tree that can be varied. A symbol prepended to _ binds the match to that variable name while a symbol appended to _ restricts the matches to nodes of that symbol. Note that even blanks themselves are internally represented as Blank[] for _ and Blank[x] for _x.

The Mathematica function Cases filters elements of the first argument that match the pattern in the second argument:[20]

Cases[{a[1], b[1], a[2], b[2]}, a[_] ]

evaluates to

{a[1], a[2]}

Pattern matching applies to the *structure* of expressions. In the example below,

Cases[ {a[b], a[b, c], a[b[c], d], a[b[c], d[e]], a[b[c], d, e]}, a[b[_], _] ]

returns

{a[b[c],d], a[b[c],d[e]]}

because only these elements will match the pattern a[b[_],_] above.

In Mathematica, it is also possible to extract structures as they are created in the course of computation, regardless of how or where they appear. The function Trace can be used to monitor a computation, and return the elements that arise which match a pattern. For example, we can define the [Fibonacci sequence](/source/Fibonacci_number) as

fib[0|1]:=1
fib[n_]:= fib[n-1] + fib[n-2]

Then, we can ask the question: Given fib[3], what is the sequence of recursive Fibonacci calls?

Trace[fib[3], fib[_]]

returns a structure that represents the occurrences of the pattern fib[_] in the computational structure:

{fib[3],{fib[2],{fib[1]},{fib[0]}},{fib[1]}}

#### Declarative programming

In symbolic programming languages, it is easy to have patterns as arguments to functions or as elements of data structures. A consequence of this is the ability to use patterns to declaratively make statements about pieces of data and to flexibly instruct functions how to operate.

For instance, the [Mathematica](/source/Mathematica) function Compile can be used to make more efficient versions of the code. In the following example the details do not particularly matter; what matters is that the subexpression {{com[_], Integer}} instructs Compile that expressions of the form com[_] can be assumed to be [integers](/source/Integer) for the purposes of compilation:

com[i_] := Binomial[2i, i]
Compile[{x, {i, _Integer}}, x^com[i], {{com[_],  Integer}}]

Mailboxes in [Erlang](/source/Erlang_(programming_language)) also work this way.

The [Curry–Howard correspondence](/source/Curry%E2%80%93Howard_correspondence) between proofs and programs relates [ML](/source/ML_(programming_language))-style pattern matching to [case analysis](/source/Proof_by_cases) and [proof by exhaustion](/source/Proof_by_exhaustion).

### Pattern matching and strings

By far the most common form of pattern matching involves strings of characters. In many programming languages, a particular syntax of strings is used to represent regular expressions, which are patterns describing string characters.

However, it is possible to perform some string pattern matching within the same framework that has been discussed throughout this article.

#### Tree patterns for strings

In Mathematica, strings are represented as trees of root StringExpression and all the characters in order as children of the root. Thus, to match "any amount of trailing characters", a new wildcard ___ is needed in contrast to _ that would match only a single character.

In Haskell and [functional programming](/source/Functional_programming) languages in general, strings are represented as functional [lists](/source/List_(computing)) of characters. A functional list is defined as an empty list, or an element constructed on an existing list. In Haskell syntax:

[] -- an empty list
x:xs -- an element x constructed on a list xs

The structure for a list with some elements is thus element:list. When pattern matching, we assert that a certain piece of data is equal to a certain pattern. For example, in the function:

head (element:list) = element

We assert that the first element of head's argument is called element, and the function returns this. We know that this is the first element because of the way lists are defined, a single element constructed onto a list. This single element must be the first. The empty list would not match the pattern at all, as an empty list does not have a head (the first element that is constructed).

In the example, we have no use for list, so we can disregard it, and thus write the function:

head (element:_) = element

The equivalent Mathematica transformation is expressed as

head[element, ]:=element

#### Example string patterns

In Mathematica, for instance,

StringExpression["a",_]

will match a string that has two characters and begins with "a".

The same pattern in Haskell:

['a', _]

Symbolic entities can be introduced to represent many different classes of relevant features of a string. For instance,

StringExpression[LetterCharacter, DigitCharacter]

will match a string that consists of a letter first, and then a number.

In Haskell, [guards](/source/Guard_(computer_science)) could be used to achieve the same matches:

[letter, digit] | isAlpha letter && isDigit digit

The main advantage of symbolic string manipulation is that it can be completely integrated with the rest of the programming language, rather than being a separate, special purpose subunit. The entire power of the language can be leveraged to build up the patterns themselves or analyze and transform the programs that contain them.

#### SNOBOL

Main article: [SNOBOL](/source/SNOBOL)

SNOBOL (*StriNg Oriented and symBOlic Language*) is a computer programming language developed between 1962 and 1967 at [AT&T](/source/AT%26T_Corporation) [Bell Laboratories](/source/Bell_Laboratories) by [David J. Farber](/source/David_J._Farber), [Ralph E. Griswold](/source/Ralph_E._Griswold) and Ivan P. Polonsky.

SNOBOL4 stands apart from most programming languages by having patterns as a [first-class data type](/source/First-class_object) (*i.e.* a data type whose values can be manipulated in all ways permitted to any other data type in the programming language) and by providing operators for pattern [concatenation](/source/Concatenation) and [alternation](/source/Alternation_(formal_language_theory)). Strings generated during execution can be treated as programs and executed.

SNOBOL was quite widely taught in larger US universities in the late 1960s and early 1970s and was widely used in the 1970s and 1980s as a text manipulation language in the [humanities](/source/Humanities).

Since SNOBOL's creation, newer languages such as [AWK](/source/AWK) and [Perl](/source/Perl) have made string manipulation by means of [regular expressions](/source/Regular_expression) fashionable. SNOBOL4 patterns, however, subsume [Backus–Naur form](/source/Backus%E2%80%93Naur_form) (BNF) grammars, which are equivalent to [context-free grammars](/source/Context-free_grammar) and more powerful than [regular expressions](/source/Regular_expression).[21]

## See also

- [Computer programming portal](https://en.wikipedia.org/wiki/Portal:Computer_programming)

- [Artificial Intelligence Markup Language](/source/Artificial_Intelligence_Markup_Language) (AIML) for an AI language based on matching patterns in speech

- [AWK](/source/AWK) language

- [Coccinelle](/source/Coccinelle_(software)) pattern matches C source code

- [Matching wildcards](/source/Matching_wildcards)

- [glob (programming)](/source/Glob_(programming))

- [Pattern calculus](/source/Pattern_calculus)

- [Pattern recognition](/source/Pattern_recognition) for fuzzy patterns

- [PCRE](/source/PCRE) Perl Compatible Regular Expressions, a common modern implementation of string pattern matching ported to many languages

- [REBOL parse dialect](/source/REBOL#parse) for pattern matching used to implement language dialects

- [Symbolic integration](/source/Symbolic_integration)

- [Tagged union](/source/Tagged_union)

- [Tom (pattern matching language)](/source/Tom_(pattern_matching_language))

- [SNOBOL](/source/SNOBOL) for a programming language based on one kind of pattern matching

- [Pattern language](/source/Pattern_language) — metaphoric, drawn from architecture

- [Graph matching](/source/Graph_matching)

- [Two-dimensional pattern matching](/source/Two-dimensional_pattern_matching)

## References

- The Mathematica Book, chapter [Section 2.3: Patterns](https://web.archive.org/web/20050408135452/http://documents.wolfram.com/mathematica/book/section-2.3)

- The Haskell 98 Report, chapter [3.17 Pattern Matching](http://haskell.org/onlinereport/exps.html#pattern-matching).

- Python Reference Manual, chapter [6.3 Assignment statements](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements).

- The [Pure](/source/Pure_(programming_language)) Programming Language, chapter [4.3: Patterns](https://web.archive.org/web/20110711112227/http://pure-lang.googlecode.com/svn/docs/pure-intro/pure-intro.pdf)

1. **[^](#cite_ref-1)** ["Pattern Matching - C# Guide"](https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching). 13 March 2024.

1. **[^](#cite_ref-2)** ["Pattern Matching - F# Guide"](https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching). 5 November 2021.

1. **[^](#cite_ref-3)** ["A Gentle Introduction to Haskell: Patterns"](https://www.haskell.org/tutorial/patterns.html). *www.haskell.org*.

1. **[^](#cite_ref-4)** ["Pattern Matching"](https://docs.oracle.com/en/java/javase/21/language/pattern-matching.html). *Oracle Help Center*.

1. **[^](#cite_ref-5)** ["What's New In Python 3.10 — Python 3.10.0b3 documentation"](https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching). *docs.python.org*. Retrieved 2021-07-06.

1. **[^](#cite_ref-6)** ["Pattern Matching"](https://docs.racket-lang.org/reference/match.html). *docs.racket-lang.org*. Retrieved 2025-06-25.

1. **[^](#cite_ref-7)** ["pattern_matching - Documentation for Ruby 3.0.0"](https://docs.ruby-lang.org/en/3.0.0/doc/syntax/pattern_matching_rdoc.html). *docs.ruby-lang.org*. Retrieved 2021-07-06.

1. **[^](#cite_ref-8)** ["Redirecting..."](https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html) *doc.rust-lang.org*. {{[cite web](https://en.wikipedia.org/wiki/Template:Cite_web)}}: Cite uses generic title ([help](https://en.wikipedia.org/wiki/Help:CS1_errors#generic_title))

1. **[^](#cite_ref-9)** ["Pattern Matching"](https://docs.scala-lang.org/tour/pattern-matching.html). *Scala Documentation*. Retrieved 2021-01-17.

1. **[^](#cite_ref-10)** ["Documentation"](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/patterns/). *docs.swift.org*.

1. **[^](#cite_ref-11)** Augustsson, Lennart (1985), Jouannaud, Jean-Pierre (ed.), ["Compiling pattern matching"](http://link.springer.com/10.1007/3-540-15975-4_48), *Functional Programming Languages and Computer Architecture*, vol. 201, Berlin, Heidelberg: Springer Berlin Heidelberg, pp. 368–381, [doi](/source/Doi_(identifier)):[10.1007/3-540-15975-4_48](https://doi.org/10.1007%2F3-540-15975-4_48), [ISBN](/source/ISBN_(identifier)) [978-3-540-15975-9](https://en.wikipedia.org/wiki/Special:BookSources/978-3-540-15975-9), retrieved 2026-05-21{{[citation](https://en.wikipedia.org/wiki/Template:Citation)}}: CS1 maint: work parameter with ISBN ([link](https://en.wikipedia.org/wiki/Category:CS1_maint:_work_parameter_with_ISBN))

1. **[^](#cite_ref-12)** Henderson, Peter (1980). *Functional programming: application and implementation*. Prentice-Hall international series in computer science. Englewood Cliffs, NJ: Prentice-Hall International. [ISBN](/source/ISBN_(identifier)) [978-0-13-331579-0](https://en.wikipedia.org/wiki/Special:BookSources/978-0-13-331579-0).

1. **[^](#cite_ref-13)** Pierce, Benjamin C. (2002). *Types and programming languages*. Cambridge, Massachusetts: MIT Press. [ISBN](/source/ISBN_(identifier)) [978-0-262-16209-8](https://en.wikipedia.org/wiki/Special:BookSources/978-0-262-16209-8).

1. **[^](#cite_ref-14)** ["https://dl.acm.org/action/cookieAbsent"](https://dl.acm.org/action/cookieAbsent). *ACM Digital Library*. [doi](/source/Doi_(identifier)):[10.1145/363347.363387](https://doi.org/10.1145%2F363347.363387). Retrieved 2026-05-21. {{[cite web](https://en.wikipedia.org/wiki/Template:Cite_web)}}: External link in |title= ([help](https://en.wikipedia.org/wiki/Help:CS1_errors#param_has_ext_link))

1. **[^](#cite_ref-15)** Apostolico, Alberto; Galil, Zvi, eds. (2020). *Pattern matching algorithms*. Oxford scholarship online. New York: Oxford University Press. [ISBN](/source/ISBN_(identifier)) [978-0-19-511367-9](https://en.wikipedia.org/wiki/Special:BookSources/978-0-19-511367-9).

1. **[^](#cite_ref-16)** ["6.7.2. View patterns — Glasgow Haskell Compiler 9.15.20250917 User's Guide"](https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/view_patterns.html). *ghc.gitlab.haskell.org*.

1. **[^](#cite_ref-17)** ["9 Pattern Matching"](https://docs.racket-lang.org/reference/match.html#(idx._(gentag._255._(lib._scribblings/reference/reference..scrbl)))). *docs.racket-lang.org*.

1. **[^](#cite_ref-18)** ["9 Pattern Matching"](https://docs.racket-lang.org/reference/match.html#(form._((lib._racket/match..rkt)._define-match-expander))). *docs.racket-lang.org*.

1. **[^](#cite_ref-19)** Cantatore, Alessandro (2003). ["Wildcard matching algorithms"](http://xoomer.virgilio.it/acantato/dev/wildcard/wildmatch.html).

1. **[^](#cite_ref-20)** ["Cases—Wolfram Language Documentation"](https://reference.wolfram.com/language/ref/Cases.html.en). *reference.wolfram.com*. Retrieved 2020-11-17.

1. **[^](#cite_ref-21)** Gimpel, J. F. 1973. A theory of discrete patterns and their implementation in SNOBOL4. Commun. ACM 16, 2 (Feb. 1973), 91–100. DOI=[http://doi.acm.org/10.1145/361952.361960](http://doi.acm.org/10.1145/361952.361960).

## External links

The Wikibook *[Haskell](https://en.wikibooks.org/wiki/Haskell)* has a page on the topic of: ***[Pattern matching](https://en.wikibooks.org/wiki/Haskell/Pattern_matching)***

Wikimedia Commons has media related to [Pattern matching](https://commons.wikimedia.org/wiki/Category:Pattern_matching).

- [Views: An Extension to Haskell Pattern Matching](https://archive.today/19990225161739/http://www.haskell.org/development/views.html)

- Nikolaas N. Oosterhof, Philip K. F. Hölzenspies, and Jan Kuper. [Application patterns](https://web.archive.org/web/20060304053330/http://wwwhome.cs.utwente.nl/~tina/apm/applPatts.pdf). A presentation at Trends in Functional Programming, 2005

- [JMatch](https://www.cs.cornell.edu/Projects/jmatch): the [Java](/source/Java_(programming_language)) language extended with pattern matching

- [ShowTrend](https://archive.today/20130630081135/http://www.showtrend.com/): Online pattern matching for stock prices

- [An incomplete history of the QED Text Editor](https://web.archive.org/web/20060211020429/http://cm.bell-labs.com/cm/cs/who/dmr/qed.html) by [Dennis Ritchie](/source/Dennis_Ritchie) - provides the history of regular expressions in computer programs

- [The Implementation of Functional Programming Languages, pages 53–103](http://research.microsoft.com/~simonpj/papers/slpj-book-1987/index.htm) Simon Peyton Jones, published by Prentice Hall, 1987.

- [Nemerle, pattern matching](https://github.com/rsdn/nemerle/wiki/Grok-Variants-and-matching#matching).

- [Erlang, pattern matching](http://erlang.org/doc/reference_manual/expressions.html#pattern).

- [Prop: a C++ based pattern matching language, 1999](https://web.archive.org/web/20090822225301/http://www.cs.nyu.edu/leunga/prop.html)

- [PatMat: a C++ pattern matching library based on](https://github.com/Henry/PatMat) [SNOBOL](/source/SNOBOL)/[SPITBOL](/source/SPITBOL)

- Temur Kutsia. [Flat Matching](https://dx.doi.org/10.1016/j.jsc.2008.05.001). Journal of Symbolic Computation 43(12): 858–873. Describes in details flat matching in Mathematica.

- [EasyPattern language](http://www.datamystic.com/easypatterns_reference.html) pattern matching language for non-programmers

v t e Programming paradigms Imperative Structured Jackson structures Block-structured Modular Non-structured Procedural Programming in the large and in the small Design by contract Invariant-based Nested function Object-oriented Class-based, Prototype-based, Object-based Agent Immutable object Persistent Uniform function call syntax Declarative Functional Recursive Anonymous function (Partial application) Higher-order Purely functional Total Strict GADTs Dependent types Functional logic Point-free style Expression-oriented Applicative, Concatenative Function-level, Value-level Monad Dataflow Flow-based Reactive (Functional reactive) Signals Streams Synchronous Logic Abductive logic Answer set Constraint (Constraint logic) Inductive logic Nondeterministic Ontology Probabilistic logic Query Domain- specific language (DSL) Algebraic modeling Array Automata-based (Action) Command (Spacecraft) Differentiable End-user Grammar-oriented Interface description Language-oriented List comprehension Low-code Modeling Natural language Non-English-based Page description Pipes and filters Probabilistic Quantum Scientific Scripting Set-theoretic Simulation Stack-based System Tactile Templating Transformation (Graph rewriting, Production, Pattern) Visual Concurrent, parallel Actor-based Automatic mutual exclusion Choreographic programming Concurrent logic (Concurrent constraint logic) Concurrent OO Macroprogramming Multitier programming Organic computing Parallel programming models Partitioned global address space Process-oriented Relativistic programming Service-oriented Structured concurrency Metaprogramming Attribute-oriented Automatic (Inductive) Dynamic Extensible Generic Homoiconicity Interactive Macro (Hygienic) Metalinguistic abstraction Multi-stage Program synthesis (Bayesian, by demonstration, by example, vibe coding) Reflective Self-modifying code Symbolic Template Separation of concerns Aspects Components Data-driven Data-oriented Event-driven Features Literate Roles Subjects Comparisons/Lists Comparison (multi-paradigm, object-oriented, functional), List (OO, by type)

v t e Strings String metric Approximate string matching Bitap algorithm Damerau–Levenshtein distance Edit distance Gestalt pattern matching Hamming distance Jaro–Winkler distance Lee distance Levenshtein automaton Levenshtein distance Wagner–Fischer algorithm String-searching algorithm Apostolico–Giancarlo algorithm Boyer–Moore string-search algorithm Boyer–Moore–Horspool algorithm Knuth–Morris–Pratt algorithm Rabin–Karp algorithm Raita algorithm Trigram search Two-way string-matching algorithm Zhu–Takaoka string matching algorithm Multiple string searching Aho–Corasick Commentz-Walter algorithm Regular expression Comparison of regular-expression engines Regular grammar Thompson's construction Nondeterministic finite automaton Sequence alignment BLAST Hirschberg's algorithm Needleman–Wunsch algorithm Smith–Waterman algorithm Data structure DAFSA Substring index Suffix array Suffix automaton Suffix tree Compressed suffix array LCP array FM-index Generalized suffix tree Rope Ternary search tree Trie Other Parsing Pattern matching Compressed pattern matching Longest common subsequence Longest common substring Sequential pattern mining Sorting String rewriting systems String operations

Authority control databases GND

---
Adapted from the Wikipedia article [Pattern matching](https://en.wikipedia.org/wiki/Pattern_matching) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Pattern_matching?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
