此为 Mathematica 4 文档,内容基于更早版本的 Wolfram 语言
查看最新文档(版本11.2)

Cases

Usage

Cases[  ,  , ...  , pattern] 给出了匹配模式 pattern  的列表。
Cases[  , ...  , pattern -> rhs]给出了相对于匹配这个模式的  rhs的值列表。
Cases[expr, pattern, levspec] 在由匹配模式的levspec指定的级别上给出了expr所有部分的列表。
Cases[expr, pattern -> rhs, levspec] 给出了匹配模式的 rhs 的值。


Notes

• 例: Cases[ 2, x, 4 , _Integer]LongRightArrow .
Cases 的第一个参数并不需要有头 List.
Cases[expr, pattern, levspec, n] 给出了expr中匹配模式的前 n 个部分.
• 级别规格在A.3.6中描述.
• 参见 Mathematica 全书: 2.3.2.
• 同时参见: Select, Position, ReplaceList, Collect.
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.)