In computer science, pattern matching is the act of checking a given sequence of 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 he the form of either sequences or tree structures. 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).
Sequence patterns (e.g., a text string) are often described using regular expressions and matched using techniques such as backtracking.
Tree patterns are used in some programming languages as a general tool to process data based on its structure, e.g. C#,[1] F#,[2] Haskell,[3] Ja,[4] ML, Python,[5] Racket,[6] Ruby,[7] Rust,[8] Scala,[9] Swift[10] and the symbolic mathematics language Mathematica he special syntax for expressing tree patterns and a language construct for 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 guards.[citation needed]
History[edit] See also: Regular expression § History This section needs expansion. You can help by adding to it. (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) (1976), NPL (1977), and Kent Recursive Calculator (KRC) (1981).
The pattern matching feature of function arguments in the 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 (2004), and F# (2005). The pattern matching construct with the match keyword that was introduced in the ML dialect Caml (1985) was followed by languages such as OCaml (1996), F# (2005), F* (2011), and Rust (2015).
Many text editors support pattern matching of various kinds: the QED editor supports regular expression search, and some versions of TECO support the OR operator in searches.
Computer algebra systems generally support pattern matching on algebraic expressions.[11]
Terminology[edit]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 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[edit]While some concepts are relatively common to many pattern languages, other pattern languages include unique or unusual extensions.
Binding A way of associating a name with a portion of the scrutinee, so that the name is bound to 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 A guard is an expression that must succeed (or yield Boolean true) as a final step before considering a pattern to he successfully matched. In some languages (e.g. Erlang), guards are written using a restricted subset of the full language; in others (e.g. 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 he 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[12] and Racket[13] 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 he 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.[14] Types[edit] Primitive patterns[edit]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 = 1Here, 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), 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 in simple string-matching situations he been developed in a number of recursive and non-recursive varieties.[15]
Tree patterns[edit]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 leing 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 types.
Haskell[edit]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 StringThe constructor is a node in a tree and the integer and string are lees in branches.
When we want to write functions to make Color an abstract data type, we wish to write functions to 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 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 _) = theIntegerAs well:
stringPart (ColorConstructor _ theString) = theStringThe creations of these functions can be automated by Haskell's data record syntax.
OCaml[edit]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.
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[edit] Filtering data with patterns[edit]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:
[A x|A x