This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Patterns  /

2.3.13 Patterns for Some Common Types of Expression

Using the objects described above, you can set up patterns for many kinds of expressions. In all cases, you must remember that the patterns must represent the structure of the expressions in Mathematica internal form, as shown by FullForm.
Especially for some common kinds of expressions, the standard output format used by Mathematica is not particularly close to the full internal form. But it is the internal form that you must use in setting up patterns.


Some typical patterns for numbers.

  • Here are the full forms of some numbers.
  • In[1]:= {2, 2.5, 2.5 + I, 2/7} // FullForm

    Out[1]//FullForm=

  • The rule picks out each piece of the complex numbers.
  • In[2]:= {2.5 - I, 3 + I} /. Complex[x_, y_] -> p[x, y]

    Out[2]=

  • The fact that these expressions have different full forms means that you cannot use x_+Iy_ to match a complex number.
  • In[3]:= {2.5 - I, x + I y} // FullForm

    Out[3]//FullForm=

  • The pattern here matches both ordinary integers, and complex numbers where both the real and imaginary parts are integers.
  • In[4]:= Cases[ {2.5 - I, 2, 3 + I, 2 - 0.5 I, 2 + 2 I},
    _Integer | Complex[_Integer, _Integer] ]

    Out[4]=

    As discussed in Section 1.4.1, Mathematica puts all algebraic expressions into a standard form, in which they are written essentially as a sum of products of powers. In addition, ratios are converted into products of powers, with denominator terms having negative exponents, and differences are converted into sums with negated terms. To construct patterns for algebraic expressions, you must use this standard form. This form often differs from the way Mathematica prints out the algebraic expressions. But in all cases, you can find the full internal form using FullForm[expr].

  • Here is a typical algebraic expression.
  • In[5]:= -1/z^2 - z/y + 2 (x z)^2 y

    Out[5]=

  • This is the full internal form of the expression.
  • In[6]:= FullForm[%]

    Out[6]//FullForm=

  • This is what you get by applying a transformation rule to all powers in the expression.
  • In[7]:= % /. x_^n_ -> e[x, n]

    Out[7]=


    Some typical patterns for algebraic expressions.

  • This pattern picks out linear functions of x.
  • In[8]:= {1, a, x, 2 x, 1 + 2 x} /. a_. + b_. x -> p[a, b]

    Out[8]=


    Some typical patterns for lists.

  • This defines a function whose argument must be a list containing lists with either one or two elements.
  • In[9]:= h[x:{ ({_} | {_, _})... }] := q

  • The definition applies in the second and third cases.
  • In[10]:= {h[{a, b}], h[{{a}, {b}}], h[{{a}, {b, c}}]}

    Out[10]=