GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||
GeezerVison is showing en.wikipedia.org — Pattern matching - Wikipedia (Redirected from Structural pattern matching) This article is about pattern matching in functional programming. For other uses, see String matching and Pattern recognition.
For the use of variable matching criteria in defining abstract patterns to match, see Regular expression.
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 have 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] Java,[4] ML, Python,[5] Racket,[6] Ruby,[7] Rust,[8] Scala,[9] Swift[10] and the symbolic mathematics language Mathematica have 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.[11] HistorySee also: Regular expression § History
Early programming languages with pattern matching constructs include COMIT (1957), SNOBOL (1962), which introduced pattern matching as a core, first-class language capability for string and text manipulation. This paradigm evolved into structured, tree-based data evaluation with Refal (1968), which used pattern matching to manipulate symbolic expressions. The concept was soon adapted into logic programming with Prolog (1972), where pattern matching took the form of structural unification to resolve logical queries. Functional programming languages rapidly adopted and formalized the feature across the late 1970s and early 1980s, beginning with the St Andrews Static Language (SASL) (1976), NPL (1977), and the Kent Recursive Calculator (KRC) (1981).[12] The pattern matching feature of function arguments in the language ML (1973) and its dialect 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 (1990), Scala (2004), and F# (2005). The pattern matching construct with the Many text editors support pattern matching of various kinds to facilitate advanced search-and-replace capabilities. The QED editor, designed by Ken Thompson, was a pioneer in supporting regular expression searching. Thompson's implementation of regular expression parsing in QED laid the groundwork for the text search utilities in ed, sed, and grep. Furthermore, some versions of the TECO editor supported advanced matching features, including the logical OR operator in searches.[14] Computer algebra systems (CAS) generally support pattern matching on algebraic expressions to achieve symbolic simplification and integration. Early systems like Macsyma (1968) used semantic pattern matching to recognize algebraic equivalence; for example, its internal engine could successfully match both TerminologyPattern matching involves specialized terminology.
Terminology of patternsWhile some concepts are relatively common to many pattern languages, other pattern languages include unique or unusual extensions.
TypesPrimitive patternsThe 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 The wildcard pattern (often written as Tree patternsMore 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 types. HaskellIn Haskell, the following line defines an algebraic data type 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 to make 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 integerPart (ColorConstructor theInteger _) = theInteger As well: stringPart (ColorConstructor _ theString) = theString The creations of these functions can be automated by Haskell's data record syntax. OCamlThis 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 *) UsageFiltering data with patternsPattern 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 <- [A 1, B 1, A 2, B 2]] evaluates to [A 1, A 2] Pattern matching in MathematicaIn Mathematica, the only structure that exists is the tree, which is populated by symbols. In the 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 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, The Mathematica function 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 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 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[3],{fib[2],{fib[1]},{fib[0]}},{fib[1]}} Declarative programmingIn 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 com[i_] := Binomial[2i, i] Compile[{x, {i, _Integer}}, x^com[i], {{com[_], Integer}}] Mailboxes in Erlang also work this way. The Curry–Howard correspondence between proofs and programs relates ML-style pattern matching to case analysis and proof by exhaustion. Pattern matching and stringsBy 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 stringsIn 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 lists 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 head (element:list) = element We assert that the first element of In the example, we have no use for head (element:_) = element The equivalent Mathematica transformation is expressed as head[element, ]:=element Example string patternsIn 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 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. SNOBOLMain article: SNOBOL
SNOBOL (StriNg Oriented and symBOlic Language) is a computer programming language developed between 1962 and 1967 at 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 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. 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 expressions fashionable. SNOBOL4 patterns, however, subsume Backus–Naur form (BNF) grammars, which are equivalent to context-free grammars and more powerful than regular expressions.[21] See also
References
External linksThe Wikibook Haskell has a page on the topic of: Pattern matching Wikimedia Commons has media related to Pattern matching.
Hidden categories:
| ||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |