Re: Why does this pattern fail to match?
- To: mathgroup at smc.vnet.net
- Subject: [mg114171] Re: Why does this pattern fail to match?
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Fri, 26 Nov 2010 05:27:09 -0500 (EST)
Hi kj, Patterns are Mathematica expressions, and as such, can evaluate. If they do, this happens one step before MatchQ evaluates (in your examples). FullForm will tell you what are the expressions MatchQ really sees: In[3]:= FullForm[Times[___,Power[___],___]] Out[3]//FullForm= Power[BlankNullSequence[],3] This is because In[4]:= Times[x,Power[x],x] Out[4]= x^3 whatever is x (happens to be ___ here). Use HoldPattern to prevent the pattern from evaluation: In[5]:= MatchQ[Times[-1,Power[s,-1]],HoldPattern[Times[___,Power[___],___]]] Out[5]= True HoldPattern is like Hold, but invisible to a pattern-matcher for pattern-matching purposes. It was designed to be used exactly to prevent patterns from evaluation. I discussed similar issues also here: http://www.mathprogramming-intro.org/book/node349.html Another possible solution in this particular case: In[6]:= MatchQ[Times[-1,Power[s,-1]],Unevaluated[Times[___,Power[___],___]]] Out[6]= True I'd still prefer the one with HoldPattern though. Hope this helps. Regards, Leonid On Thu, Nov 25, 2010 at 1:57 PM, kj <no.email at please.post> wrote: > > > > > I'm tearing my hair out over this one. Could someone please explain > to me why all the following MatchQ expressions > > MatchQ[Times[ -1, Power[s, -1] ], > Times[___, Power[___], ___]] > > MatchQ[Times[ -1, Power[s, -1]], > Times[___, Power[___] ]] > > MatchQ[Times[ -1, Power[s, -1] ], > Times[___, _Power , ___]] > > return False? (In all cases, s is undefined). And yet, this succeeds: > > MatchQ[Times[ -1, Power[s, -1]], > Times[___, _Power ]] > > > Is there a systematic way to debug/troubleshoot such pattern matching > problems? Trace is useless here. > > Also, whatever the reason is for the failure of this pattern to > match, where is this reason documented? I've gone blind poring > over the documentation trying to find an answer, without success. > > TIA! > > ~kj > >