Cases
Usage
• Cases[ , , ... , pattern] 给出了匹配模式 pattern 的  的列表。
• Cases[expr, pattern, levspec] 在由匹配模式的levspec指定的级别上给出了expr所有部分的列表。
• Cases[expr, pattern -> rhs, levspec] 给出了匹配模式的 rhs 的值。
Notes
• Cases 的第一个参数并不需要有头 List. • Cases[expr, pattern, levspec, n] 给出了expr中匹配模式的前 n 个部分. • 参见 Mathematica 全书: 节 2.3.2.
Further Examples
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]:=
|

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]:=
|
(同时参见 the Further Examples for the Heads option.)
|