|
Further Examples: Cases
Here is an expression.
In[1]:= 
This command returns the powers in expr at level .
In[2]:= 
Out[2]= 
This returns the subexpressions that occur at any level and are powers. Note how , and match in one occurrence and b_ in another.
In[3]:= 
Out[3]= 
This returns the subexpressions at levels and that are powers.
In[4]:= 
Out[4]= 
This returns the first subexpressions at levels and that are powers.
In[5]:= 
Out[5]= 
Here is another expression.
In[6]:= 
Each expression at level that matches a[_] is returned as _.
In[7]:= 
Out[7]= 
In[8]:= 
Out[8]= 
This returns those expressions at level that match the pattern a[_] _.
In[9]:= 
Out[9]= 
Here part of each expression at level that matches a[_] is returned.
In[10]:= 
Out[10]= 
Here part of each expression at levels or that matches a[_] is returned.
In[11]:= 
Out[11]= 
Cases can also perform an arbitrary replacement in the terms that match the given pattern. Here we pick out all multiples of three from a random list, replacing them by their squares.
In[12]:= 
Out[12]= 
In[13]:= 
Out[13]= 
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[14]:= 
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[15]:= 
The function Useful tests whether or not a transition should be taken.
In[16]:= 
Here is the result with maxlen=4. The strings are grouped hierarchically.
In[17]:= 
Out[17]= 
This gives all elements of the list that trivially reduce to match an integer.
In[18]:= 
Out[18]= 
The first element of the list does not match an integer, but Simplify reduces it to an integer.
In[19]:= 
Out[19]= 
The function unevaluatedCases gives all elements (in unevaluated form) that simplify to match a given pattern.
In[20]:= 
In[21]:= 
Here are all elements from the original list that Simplify reduces to an integer.
In[22]:= 
Out[22]= 
The function unevaluatedCases2 gives all parts of an expression (in unevaluated form) that match a given pattern.
In[23]:= 
In[24]:= 
In[25]:= 
Out[25]= 
In[26]:= 
Out[26]= 
In[27]:= 
(See also the Further Examples for the Heads option.)
|