Pattern matching

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 has to 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] ML, Python,[4] Ruby,[5] Rust,[6] Scala,[7] Swift[8] 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.[citation needed]

  1. ^ "Pattern Matching - C# Guide". 13 March 2024.
  2. ^ "Pattern Matching - F# Guide". 5 November 2021.
  3. ^ A Gentle Introduction to Haskell: Patterns
  4. ^ "What's New In Python 3.10 — Python 3.10.0b3 documentation". docs.python.org. Retrieved 2021-07-06.
  5. ^ "pattern_matching - Documentation for Ruby 3.0.0". docs.ruby-lang.org. Retrieved 2021-07-06.
  6. ^ "Pattern Syntax - The Rust Programming Language".
  7. ^ "Pattern Matching". Scala Documentation. Retrieved 2021-01-17.
  8. ^ "Patterns — The Swift Programming Language (Swift 5.1)".