Message Boards Message Boards

0
|
5229 Views
|
5 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Pattern matching in Cases with Head Power

Posted 11 years ago
Hi, I am trying to uderstand the behavior of the Cases funciton as follows: If I execute the command "Cases[y^2,_Power] it returns {}. If I put the expression in brackers as "Cases[ {y^2},_Power] it works and returns '{Y^2}'.  If I execute 'Cases[a y^2, _Power] it works and returns {y^2}.  I don't understand the failure to match the expression 'y^2' in 'Cases[y^2,_Power]'; it fails to match even using the option 'Heads->True' or any level specification.   Any help understanding this behavior is appreciated.
POSTED BY: Phillip Burns
5 Replies
 
Without the curly brackets, level specification n means all levels from 1 to n. When n is zero, there are no such levels. 

On the other hand, {n1, n2} specifies all levels between n1 and n2, for example {0, Infinity} and {n} means only level n.
POSTED BY: Ilian Gachevski
Posted 11 years ago
Thanks for the help; my mistake was not putting the brackets around the level specification which still seems like it should have worked, that is specifying '0' instead of '{0}'.
POSTED BY: Phillip Burns
Cases takes a level specification as its 3rd argument, Cases[expr, patttern, levelspec]. The (documented) default for levelspec is {1}.

Therefore, the following returns {}

In[27]:= Cases[y^2, _Power]

Out[27]= {}  

Cases
looks at only level 1 for an expression with head Power. It does not find any because there are none at that level. 

In[29]:= FullForm[y^2]

Out[29]//FullForm= Power[y, 2]


Heads -> True will make cases try to match the head of the expression as well. However,

In[96]:= MatchQ[Power, _Power]

Out[96]= False


So you still get an empty list.

In[28]:= Cases[y^2, _Power, Heads -> True]

Out[28]= {}


As Ilian pointed out above you can get the result you want by using a level specification of {0}.


In[44]:= Cases[y^2, _Power, {0}]

Out[44]= {y^2}
Posted 11 years ago
Thanks Ilian, I has specified leve 0 as in "Cases[y^2, _Power,0]', without the braces around the '0' which didn't work.  With the brace around the '0' it does work.  Thanks very much for the help!
POSTED BY: Phillip Burns
Level 0 needs to be included, e.g.
Cases[y^2, _Power, {0}]
POSTED BY: Ilian Gachevski
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract