Summary
The idea of representing an idealized version of an object with something called a pattern is central to mathematics and computer science. For the purposes of search, patterns provide a template with which to compare expressions. They can be used to filter data by selecting only those parts that match the pattern. Because of the wide applicability of patterns, many modern programming languages have extensive pattern-matching capabilities that enable them to identify objects that meet some criteria in order to classify, select, or transform those objects through the use of rules.
Pattern matching in Mathematica is done through a powerful yet flexible pattern language. Used in rules to transform expressions from one form to another, they can be applied to broad classes of expressions or they can be limited to very narrowly-defined objects through the use of conditional and structured pattern matching. Pattern matching is the key to identifying which rules should be applied to expressions that you wish to transform.
If you have used regular expressions in languages such as Perl or Ruby, or via libraries in Java, Python, or C++, then you are already familiar with pattern matching on strings (discussed further in Chapter 7). Mathematica's pattern language generalizes this to arbitrary objects and expressions. Although the syntax may be new to you, with practice it becomes natural, providing a direct connection between the statement of a problem and its expression in a program. This chapter starts with an introduction to patterns and pattern matching and then proceeds to a discussion of transformation rules in which patterns are used to identify the parts of an expression that are to be transformed. The chapter concludes with several concrete examples that make use of pattern matching and transformation rules to show their application to some common programming tasks.
- Type
- Chapter
- Information
- Essentials of Programming in Mathematica® , pp. 95 - 132Publisher: Cambridge University PressPrint publication year: 2015