MatchQ, RepeatedNull
- To: mathgroup at yoda.physics.unc.edu
- Subject: MatchQ, RepeatedNull
- From: wsgbfs at win.tue.nl (Fred Simons)
- Date: Tue, 14 Sep 93 15:01:00 +0200
One of the things we like very much in Mma are patterns. Easy to work
with but in a sense difficult to understand.
In Mma we can construct patterns using blanks, names, defaults etc. and then
test if some Mma-tree satifies the pattern using MatchQ.
Here are some examples:
In[1]:= MatchQ[ a + b, Plus[ _.. ] ]
Out[1]= True
In[2]:= MatchQ[ x^3, x^_ ]
Out[2]= True
In[3]:= MatchQ[ x^2 + x^3, Plus[ (x^_).. ] ]
Out[3]= False
This result is unexpected. We ask wether x^2+x^3 satisfies the pattern
of a sum of any powers of x and Mma produces False.
After some puzzling we found that this is due to the evaluation of the
right-hand side, resulting in Repeated[Power[x, Blank[]]], while it should be
Plus[ ... ] or Repeated[Plus[ ... ]] to return True.
We can have Mma doing what we want by changing the attributes of MatchQ:
In[4]:= Unprotect[ MatchQ]
Out[4]= {MatchQ}
In[5]:= SetAttributes[ MatchQ, HoldRest ]
In[6]:= MatchQ[ x^2 + x^3, Plus[ (x^_).. ] ]
Out[6]= True
Is there a specific reason why MatchQ does NOT have attribute HoldRest?
When playing around with MatchQ we also found curious behaviour of
RepeatedNull, as shown in the following output.
In[7]:= MatchQ[ a, (_).. ]
Out[7]= True
In[8]:= MatchQ[ a, (_)... ]
Out[8]= False
Why does RepeatedNull not produce True if Repeated produces True?
Also when defining functions strange things may happen:
In[9]:= h[_...] := True
In[10]:= {h[a], h[a,a], h[a,b], h[]}
Out[10]= {True, True, True, True}
In[11]:= Clear[h]; h[a...] := True
In[12]:= {h[a], h[a,a], h[a,b], h[]}
Out[12]= {True, True, h[a, b], h[]}
The fourth item should have been True, we think.
Is this a bug in Mma 2.0 on a NeXT or is there something we do not
understand?
Frans Martens, Fred Simons
Eindhoven University of Technology