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 / Built-in Functions / Programming / Pattern Matching  /
Cases

  • Cases[ , , ... , pattern ] gives a list of the that match the pattern.
  • Cases[ , ... , pattern -> rhs ] gives a list of the values of rhs corresponding to the that match the pattern.
  • Cases[ expr , pattern , levspec ] gives a list of all parts of expr on levels specified by levspec which match the pattern.
  • Cases[ expr , pattern -> rhs , levspec ] gives the values of rhs which match the pattern.
  • Example: Cases[ 2, x, 4 , _Integer].
  • The first argument to Cases need not have head List.
  • Cases[ expr , pattern , levspec , n ] gives the first n parts in expr which match the pattern.
  • Level specifications are described in Section A.3.6.
  • See the Mathematica book: Section 2.3.2.
  • See also: Select, Position, ReplaceList, Collect.
  • Related package: Statistics`DataManipulation`.

    Further Examples

    (See also the Further Examples for the Heads option.)
    This command returns the summands that are powers.

    In[1]:=

    Out[1]=

    This returns the expressions that occur in the sum at any level and are powers. Note how matches x_^y_ in one occurrence and y_ in another.

    In[2]:=

    Out[2]=

    Cases can also perform an arbitrary replacement in the terms that match the given pattern. Here we pick all multiples of three, replacing them by their squares.

    In[3]:=

    {4, 5, 9, 6, 8, 5, 4, 0, 9, 4, 5, 2, 10, 6, 3, 7, 4, 2, 2, 8}

    Out[3]=

    This substitution can be useful, for example, in controlling recursion. Here is a set of rules that define a finite-state automaton with six states and a four-input alphabet. (The first argument of fsa is the state, and the second is the input; the return value is the state to which the automaton moves. The 0 state indicates failure, and 1 is the initial state.)

    In[4]:=

    Suppose we want to list all strings of length at most maxlen that are accepted by the automaton, that is, that do not take the automaton to the failure state. The function Recurse does the job using Cases (one might instead use Do or Table).

    In[5]:=

    The function Useful tests whether or not a transition should be taken.

    In[6]:=

    Here is the result with maxlen=4. The strings are grouped hierarchically.

    In[7]:=

    Out[7]=

    In[8]:=