RE: Question on pattern matching
- To: mathgroup at smc.vnet.net
- Subject: [mg47803] RE: [mg47765] Question on pattern matching
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Tue, 27 Apr 2004 04:47:42 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
- Thread-topic: [mg47765] Question on pattern matching
>-----Original Message----- >From: Roman Green [mailto:rgreen at mail.ru] To: mathgroup at smc.vnet.net >Sent: Monday, April 26, 2004 8:41 AM >To: mathgroup at smc.vnet.net >Subject: [mg47803] [mg47765] Question on pattern matching > > >Hi, > >I am a very newbie in Mathematica so sorry for possibly stupid >question. > >In the following Mathematica's output >In[1]:= SetAttributes[k, Orderless] >In[2]:= k[a, b, b] /. k[x_, x_, y_] -> 0 >Out[2]= 0 >In[3]:= k[a, b, b] /. k_[x_, x_, y_] -> 0 >Out[3]= k[a, b, b] > >I can't understand why Mathematica can find match when >applying pattern >k[x_, x_, y_], but is unable with more general pattern k_[x_, x_, y_]. > >Thanks in advance. > >--- > >R. Green > > If you understand Out[2], you recognize that the Attribute Orderless is essential for the pattern to match: (first) the lhs ist brought into normal order: k[a, b, b] ---> k[a, b, b] (no change in this case) (then) for the pattern k[x_, x_, y_] it does not suffice to bring it to normal order, as shound not depend on the naming of the patterns variables (k[y_,y_,x_] should give equal matches). Instead, now all orderings of the the pattern variables are tried, but this shall only be done if the Head k has Attribute Orderless. Now the pattern k_ or kk_ or whatever, doesn't have this Attribute, hence no match for In[11]:= k[a, b, b] /. k_[x_, x_, y_] -> -1 Out[11]= k[a, b, b] but (of course) a match for In[12]:= k[a, a, b] /. k_[x_, x_, y_] -> 1 Out[12]= 1 as this doesn't need reordering. If you want to achieve (what I think) you want to do: In[13]:= k[a, b, b] /. expr : kk_[___] :> (expr /. kk[x_, x_, y_] -> 2) Out[13]= 2 Then the Orderless Attribute of k is exploited (if it just happens to have it). In[16]:= ClearAttributes[k, Orderless] In[17]:= k[a, b, b] /. expr : kk_[___] :> (expr /. kk[x_, x_, y_] -> 2 ) Out[17]= k[a, b, b] -- Hartmut Wolf