• Cases[, ,
... , pattern]
• Cases[expr, pattern, levspec] 在由匹配模式的levspec指定的级别上给出了expr所有部分的列表。
• Cases[expr, pattern -> rhs, levspec] 给出了匹配模式的 rhs 的值。
• Cases 的第一个参数并不需要有头 List.
• Cases[expr, pattern, levspec, n] 给出了expr中匹配模式的前 n 个部分.
• 参见 Mathematica 全书:
This command returns the summands that are powers.
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.
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.
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.)
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).
The function Useful tests whether or not a transition should be taken.
Here is the result with maxlen=4. The strings are grouped hierarchically.
(同时参见 the Further Examples for the Heads option.)