Alternatives

Alternatives as in (p1 | p2 | p3) are used when you want to refer to one of multiple patterns.  So in the next cell ( _Sin | _Cos | _Tan ) represents an expression with the with the head Sin, Cos, or Tan.

{^2, 2, Sin[1] + x, Cos[1] - 1/2, 3.4, Tan[x + 1]}/.(_Sin | _Cos | _Tan) Trigonometric

{^2, 2, Trigonometric + x, -1/2 + Trigonometric, 3.4, Trigonometric}

in the next cell (f) is defined when given one argument with the head Real or Integer.

Clear[f, s] f[x_Real | x_Integer] := x + 1 {f[2], f[2.4], f[2, 4], f[s]}

{3, 3.4, f[2, 4], f[s]}

In the next cell (f) is defined when given one or more real arguments or one or more integer arguments.  However, this definition isn't used when (f) is given a sequence of arguments where some are real and others are integer.  Allowing a mix of different patterns requires is demonstrated in the section on Repeated, RepeatedNull.

Clear[f, s] f[x__Real | x__Integer] := x + 1 {f[2], f[2.4], f[2, 4], f[2.4, 2.1], f[2, 2.4], f[s]}

{3, 3.4, 7, 5.5, f[2, 2.4], f[s]}

Instead of using  (x_Real  x_Integer) we can use  x : (_Real | _Integer).  
And instead of using (x__Real | x_Integer) we can use  x(__Real | __Integer).  

In addition any other combination of pattern matching constructs can be used with Alternatives.  Nuances of pattern matching are discussed in another section.

A common place to use Alternatives is in the second argument of MakeBoxes when you want to use a MakeBoxes rule for StandardForm, and TraditionalForm, but not for  InputForm, TableForm, etc.  In that case use  form:(StandardForm|TraditionalForm)  as the second argument in the MakeBoxes definition as in the next cell.  You can see below that this MakeBoxes rule is used for StandardForm, TraditionalForm, but not InputForm.

MakeBoxes[foo[expr_], form : (StandardForm | TraditionalForm)] := RowBox[{"{", MakeBoxes[expr, form], "}"}]


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page