Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Pattern matching
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Act of checking a given sequence of tokens for the presence of the constituents of some pattern}} {{About|pattern matching in [[functional programming]]||string matching|and|pattern recognition}} {{For|the use of variable matching criteria in defining abstract patterns to match|regular expression}} {{More citations needed|date=February 2011}} In [[computer science]], '''pattern matching''' is the act of checking a given sequence of [[Lexical analysis#Token|tokens]] for the presence of the constituents of some [[pattern]]. In contrast to [[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 [[String (computer science)|sequences]] or [[tree structure]]s. 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., [[Regular expression|search and replace]]). Sequence patterns (e.g., a text string) are often described using [[regular expression]]s and matched using techniques such as [[backtracking]]. Tree patterns are used in some [[programming language]]s as a general tool to process data based on its structure, e.g. [[C Sharp (programming language)|C#]],<ref>{{cite web|url=https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching|title=Pattern Matching - C# Guide|date=13 March 2024}}</ref> [[F Sharp (programming language)|F#]],<ref>{{cite web|url=https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/pattern-matching|title=Pattern Matching - F# Guide|date=5 November 2021}}</ref> [[Haskell]],<ref>[http://www.haskell.org/tutorial/patterns.html A Gentle Introduction to Haskell: Patterns]</ref> [[Java (programming language)|Java]],<ref>https://docs.oracle.com/en/java/javase/21/language/pattern-matching.html</ref> [[ML (programming language)|ML]], [[Python (programming language)|Python]],<ref>{{Cite web|title=What's New In Python 3.10 — Python 3.10.0b3 documentation|url=https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching|access-date=2021-07-06|website=docs.python.org}}</ref> [[Ruby (programming language)|Ruby]],<ref>{{Cite web|title=pattern_matching - Documentation for Ruby 3.0.0|url=https://docs.ruby-lang.org/en/3.0.0/doc/syntax/pattern_matching_rdoc.html|access-date=2021-07-06|website=docs.ruby-lang.org}}</ref> [[Rust (programming language)|Rust]],<ref>{{cite web |url=https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html |title=Pattern Syntax - The Rust Programming Language}}</ref> [[Scala (programming language)|Scala]],<ref>{{Cite web|title=Pattern Matching|url=https://docs.scala-lang.org/tour/pattern-matching.html|access-date=2021-01-17|website=Scala Documentation}}</ref> [[Swift (programming language)|Swift]]<ref>{{cite web|url=https://docs.swift.org/swift-book/ReferenceManual/Patterns.html|title=Patterns — The Swift Programming Language (Swift 5.1)}}</ref> and the symbolic mathematics language [[Wolfram Mathematica|Mathematica]] have special [[Syntax (programming languages)|syntax]] for expressing tree patterns and a [[language construct]] for [[Conditional (computer programming)|conditional execution]] 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 [[Guard (computer science)|guards]].{{citation needed|date=January 2019}} ==History== {{See also|Regular expression#History}} {{Expand section|date=May 2008}} Early programming languages with pattern matching constructs include [[COMIT]] (1957), [[SNOBOL]] (1962), [[Refal]] (1968) with tree-based pattern matching, [[Prolog]] (1972), St Andrews Static Language ([[SASL (programming language)|SASL]]) (1976), [[NPL (programming language)|NPL]] (1977), and [[Kent Recursive Calculator]] (KRC) (1981). The pattern matching feature of function arguments in the language [[ML (programming language)|ML]] (1973) and its dialect [[Standard ML]] (1983) has been carried over to some other [[functional programming]] languages that were influenced by them, such as [[Haskell]] (1990), [[Scala (programming language)|Scala]] (2004), and [[F Sharp (programming language)|F#]] (2005). The pattern matching construct with the <code>match</code> keyword that was introduced in the [[ML (programming language)|ML]] dialect [[Caml]] (1985) was followed by languages such as [[OCaml]] (1996), [[F Sharp (programming language)|F#]] (2005), [[F* (programming language)|F*]] (2011), and [[Rust (programming language)|Rust]] (2015). Many [[text editor]]s support pattern matching of various kinds: the [[QED (text editor)|QED editor]] supports [[regular expression]] search, and some versions of [[TECO (text editor)|TECO]] support the OR operator in searches. [[Computer algebra system]]s generally support pattern matching on algebraic expressions.<ref>Joel Moses, "Symbolic Integration", MIT Project MAC MAC-TR-47, December 1967</ref> ==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): <syntaxhighlight lang="haskell"> f 0 = 1 </syntaxhighlight> 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: <syntaxhighlight lang="haskell"> f n = n * f (n-1) </syntaxhighlight> Here, the first <code>n</code> 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 (programming language)|Hope]]), 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 <code>n * f (n-1)</code> with n being the argument. The wildcard pattern (often written as <code>_</code>) is also simple: like a variable name, it matches any value, but does not bind the value to any name. Algorithms for [[matching wildcards]] in simple string-matching situations have been developed in a number of [[recursion|recursive]] and non-recursive varieties.<ref>{{cite web| last=Cantatore| first=Alessandro| title=Wildcard matching algorithms| year=2003| url=http://xoomer.virgilio.it/acantato/dev/wildcard/wildmatch.html}}</ref> ===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]] of a programming language and [[algebraic data type]]s. ====Haskell==== In Haskell, the following line defines an algebraic data type <code>Color</code> that has a single data constructor <code>ColorConstructor</code> that wraps an integer and a string. <syntaxhighlight lang="haskell"> data Color = ColorConstructor Integer String </syntaxhighlight> The constructor is a node in a tree and the integer and string are leaves in branches. When we want to write [[function (programming)|functions]] to make <code>Color</code> an [[abstract data type]], we wish to write functions to [[Interface (computer science)|interface]] 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 <code>Color</code>. 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 <code>Color</code>, we can use a simple tree pattern and write: <syntaxhighlight lang="haskell"> integerPart (ColorConstructor theInteger _) = theInteger </syntaxhighlight> As well: <syntaxhighlight lang="haskell"> stringPart (ColorConstructor _ theString) = theString </syntaxhighlight> The creations of these functions can be automated by Haskell's data [[Record (computer science)|record]] syntax. ====OCaml==== This [[OCaml]] example which defines a [[red–black 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. <syntaxhighlight lang="ocaml"> 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 *) </syntaxhighlight> ==Usage== ===Filtering data with patterns=== Pattern matching can be used to filter data of a certain structure. For instance, in Haskell a [[list comprehension]] could be used for this kind of filtering: <syntaxhighlight lang="haskell"> [A x|A x <- [A 1, B 1, A 2, B 2]] </syntaxhighlight> evaluates to [A 1, A 2] ===Pattern matching in Mathematica=== In [[Mathematica]], the only structure that exists is the [[Tree (data structure)|tree]], which is populated by symbols. In the [[Haskell]] syntax used thus far, this could be defined as <syntaxhighlight lang="haskell"> data SymbolTree = Symbol String [SymbolTree] </syntaxhighlight> An example tree could then look like <syntaxhighlight lang="mathematica"> Symbol "a" [Symbol "b" [], Symbol "c" []] </syntaxhighlight> In the traditional, more suitable syntax, the symbols are written as they are and the levels of the tree are represented using <code>[]</code>, so that for instance <code>a[b,c]</code> 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, <code>A</code> is the concrete element, while <code>_</code> denotes the piece of tree that can be varied. A symbol prepended to <code>_</code> binds the match to that variable name while a symbol appended to <code>_</code> restricts the matches to nodes of that symbol. Note that even blanks themselves are internally represented as <code>Blank[]</code> for <code>_</code> and <code>Blank[x]</code> for <code>_x</code>. The Mathematica function <code>Cases</code> filters elements of the first argument that match the pattern in the second argument:<ref>{{Cite web|title=Cases—Wolfram Language Documentation|url=https://reference.wolfram.com/language/ref/Cases.html.en|access-date=2020-11-17|website=reference.wolfram.com}}</ref> <syntaxhighlight lang="mathematica"> Cases[{a[1], b[1], a[2], b[2]}, a[_] ] </syntaxhighlight> evaluates to <syntaxhighlight lang="mathematica"> {a[1], a[2]} </syntaxhighlight> Pattern matching applies to the ''structure'' of expressions. In the example below, <syntaxhighlight lang="mathematica"> Cases[ {a[b], a[b, c], a[b[c], d], a[b[c], d[e]], a[b[c], d, e]}, a[b[_], _] ] </syntaxhighlight> returns <syntaxhighlight lang="mathematica"> {a[b[c],d], a[b[c],d[e]]} </syntaxhighlight> because only these elements will match the pattern <code>a[b[_],_]</code> 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 <code>Trace</code> can be used to monitor a computation, and return the elements that arise which match a pattern. For example, we can define the [[Fibonacci number|Fibonacci sequence]] as <syntaxhighlight lang="mathematica"> fib[0|1]:=1 fib[n_]:= fib[n-1] + fib[n-2] </syntaxhighlight> Then, we can ask the question: Given fib[3], what is the sequence of recursive Fibonacci calls? <syntaxhighlight lang="mathematica"> Trace[fib[3], fib[_]] </syntaxhighlight> returns a structure that represents the occurrences of the pattern <code>fib[_]</code> in the computational structure: <syntaxhighlight lang="mathematica"> {fib[3],{fib[2],{fib[1]},{fib[0]}},{fib[1]}} </syntaxhighlight> ====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]] function <code>Compile</code> 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 <code>{{com[_], Integer}}</code> instructs <code>Compile</code> that expressions of the form <code>com[_]</code> can be assumed to be [[integer]]s for the purposes of compilation: <syntaxhighlight lang="mathematica"> com[i_] := Binomial[2i, i] Compile[{x, {i, _Integer}}, x^com[i], {{com[_], Integer}}] </syntaxhighlight> Mailboxes in [[Erlang (programming language)|Erlang]] also work this way. The [[Curry–Howard correspondence]] between proofs and programs relates [[ML (programming language)|ML]]-style pattern matching to [[Proof by cases|case analysis]] and [[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]] languages in general, strings are represented as functional [[List (computing)|lists]] of characters. A functional list is defined as an empty list, or an element constructed on an existing list. In Haskell syntax: <syntaxhighlight lang="haskell"> [] -- an empty list x:xs -- an element x constructed on a list xs </syntaxhighlight> The structure for a list with some elements is thus <code>element:list</code>. When pattern matching, we assert that a certain piece of data is equal to a certain pattern. For example, in the function: <syntaxhighlight lang="haskell"> head (element:list) = element </syntaxhighlight> We assert that the first element of <code>head</code>'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 <code>list</code>, so we can disregard it, and thus write the function: <syntaxhighlight lang="haskell"> head (element:_) = element </syntaxhighlight> The equivalent Mathematica transformation is expressed as head[element, ]:=element ====Example string patterns==== In Mathematica, for instance, <syntaxhighlight lang="mathematica"> StringExpression["a",_] </syntaxhighlight> will match a string that has two characters and begins with "a". The same pattern in Haskell: <syntaxhighlight lang="haskell"> ['a', _] </syntaxhighlight> 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, [[Guard (computer science)|guards]] could be used to achieve the same matches: <syntaxhighlight lang="haskell"> [letter, digit] | isAlpha letter && isDigit digit </syntaxhighlight> 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|SNOBOL}} SNOBOL (''StriNg Oriented and symBOlic Language'') is a computer programming language developed between 1962 and 1967 at [[AT&T Corporation|AT&T]] [[Bell Laboratories]] by [[David J. Farber]], [[Ralph E. Griswold]] and Ivan P. Polonsky. SNOBOL4 stands apart from most programming languages by having patterns as a [[first-class object|first-class data type]] (''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]] and [[alternation (formal language theory)|alternation]]. 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]]. Since SNOBOL's creation, newer languages such as [[AWK]] and [[Perl]] have made string manipulation by means of [[regular expression]]s fashionable. SNOBOL4 patterns, however, subsume [[Backus–Naur form]] (BNF) grammars, which are equivalent to [[context-free grammar]]s and more powerful than [[regular expression]]s.<ref>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.</ref> ==See also== {{Portal|Computer programming}} * [[Artificial Intelligence Markup Language]] (AIML) for an AI language based on matching patterns in speech * [[AWK]] language * [[Coccinelle (software)|Coccinelle]] pattern matches C source code * [[Matching wildcards]] * [[glob (programming)]] * [[Pattern calculus]] * [[Pattern recognition]] for fuzzy patterns * [[PCRE]] Perl Compatible Regular Expressions, a common modern implementation of string pattern matching ported to many languages * [[REBOL#parse|REBOL parse dialect]] for pattern matching used to implement language dialects * [[Symbolic integration]] * [[Tagged union]] * [[Tom (pattern matching language)]] * [[SNOBOL]] for a programming language based on one kind of pattern matching * [[Pattern language]] — metaphoric, drawn from architecture * [[Graph matching]] ==References== {{Refbegin}} * The Mathematica Book, chapter [https://web.archive.org/web/20050408135452/http://documents.wolfram.com/mathematica/book/section-2.3 Section 2.3: Patterns] * The Haskell 98 Report, chapter [http://haskell.org/onlinereport/exps.html#pattern-matching 3.17 Pattern Matching]. * Python Reference Manual, chapter [https://docs.python.org/2/reference/simple_stmts.html#assignment-statements 6.3 Assignment statements]. * The [[Pure (programming language)|Pure]] Programming Language, chapter [https://web.archive.org/web/20110711112227/http://pure-lang.googlecode.com/svn/docs/pure-intro/pure-intro.pdf 4.3: Patterns] {{Refend}} {{Reflist}} ==External links== {{Wikibooks|Haskell|Pattern matching}} {{Commons category}} *[https://archive.today/19990225161739/http://www.haskell.org/development/views.html Views: An Extension to Haskell Pattern Matching] * Nikolaas N. Oosterhof, Philip K. F. Hölzenspies, and Jan Kuper. [https://web.archive.org/web/20060304053330/http://wwwhome.cs.utwente.nl/~tina/apm/applPatts.pdf Application patterns]. A presentation at Trends in Functional Programming, 2005 *[http://www.cs.cornell.edu/Projects/jmatch JMatch]: the [[Java (programming language)|Java]] language extended with pattern matching *[https://archive.today/20130630081135/http://www.showtrend.com/ ShowTrend]: Online pattern matching for stock prices *[https://web.archive.org/web/20060211020429/http://cm.bell-labs.com/cm/cs/who/dmr/qed.html An incomplete history of the QED Text Editor] by [[Dennis Ritchie]] - provides the history of regular expressions in computer programs *[http://research.microsoft.com/~simonpj/papers/slpj-book-1987/index.htm The Implementation of Functional Programming Languages, pages 53–103] Simon Peyton Jones, published by Prentice Hall, 1987. *[https://github.com/rsdn/nemerle/wiki/Grok-Variants-and-matching#matching Nemerle, pattern matching]. *[http://erlang.org/doc/reference_manual/expressions.html#pattern Erlang, pattern matching]. *[https://web.archive.org/web/20090822225301/http://www.cs.nyu.edu/leunga/prop.html Prop: a C++ based pattern matching language, 1999] *[https://github.com/Henry/PatMat PatMat: a C++ pattern matching library based on] [[SNOBOL]]/[[SPITBOL]] * Temur Kutsia. [https://dx.doi.org/10.1016/j.jsc.2008.05.001 Flat Matching]. Journal of Symbolic Computation 43(12): 858–873. Describes in details flat matching in Mathematica. *[http://www.datamystic.com/easypatterns_reference.html EasyPattern language] pattern matching language for non-programmers {{Strings|state=collapsed}} {{Authority control}} {{DEFAULTSORT:Pattern Matching}} [[Category:Pattern matching| ]] [[Category:Conditional constructs]] [[Category:Articles with example Haskell code]] [[Category:Functional programming]] [[Category:Programming language comparisons]] <!-- Hidden categories below --> [[Category:Articles with example code]] [[Category:Articles with example OCaml code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:About
(
edit
)
Template:Authority control
(
edit
)
Template:Citation needed
(
edit
)
Template:Cite web
(
edit
)
Template:Commons category
(
edit
)
Template:Expand section
(
edit
)
Template:For
(
edit
)
Template:Main
(
edit
)
Template:More citations needed
(
edit
)
Template:Portal
(
edit
)
Template:Refbegin
(
edit
)
Template:Refend
(
edit
)
Template:Reflist
(
edit
)
Template:See also
(
edit
)
Template:Short description
(
edit
)
Template:Strings
(
edit
)
Template:Wikibooks
(
edit
)