Message Boards Message Boards

4 Replies
1 Total Likes
View groups...
Share this post:

Contradictory behaviour in pattern matching

Posted 11 years ago
MatchQ do not seem to treat the inbuilt functions Power and Times in the same way:
In[1]:= MatchQ[Power[a, b], Power[_, _]]

Out[1]= True
In[2]:= MatchQ[Times[a, b], Times[_, _]]

Out[2]= False
An explanation, or what am I doing wrong?
POSTED BY: Hans Milton
4 Replies
You need HoldPattern to prevent that patter from evaluating to Power[_,2].

MatchQ[Times[a, b], HoldPattern[Times[_, _]]]

Out[19]= True
POSTED BY: Daniel Lichtblau
Posted 11 years ago
But could you please elaborate on why HoldPattern is needed in case of Times, but not Power?
POSTED BY: Hans Milton
As I stated, Times[_,_] evaluates to Power[_,2]. This happens before MatchQ ever sees its arguments. Power[_,_] on the other hand evalautes to itself. The different matching outcomes are explained by these facts.
POSTED BY: Daniel Lichtblau
Posted 11 years ago
Yes, as can be seen:
In[4]:= Times[_, _]

Out[4]= _^2
Thanks for very fast response!
POSTED BY: Hans Milton
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract