RE: Pattern Matching Problem
- To: mathgroup at smc.vnet.net
- Subject: [mg43396] RE: [mg43377] Pattern Matching Problem
- From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
- Date: Fri, 29 Aug 2003 07:15:56 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
>-----Original Message----- >From: Ersek, Ted R [mailto:ErsekTR at navair.navy.mil] To: mathgroup at smc.vnet.net >Sent: Wednesday, August 27, 2003 10:05 AM >To: mathgroup at smc.vnet.net >Subject: [mg43396] [mg43377] Pattern Matching Problem > > >Consider the following: > >In[1]:= > ClearAll[f,a,b,c,w,x,y,z]; > expr=a+b+c+f[w,2]+f[w,3]+x+f[x,2]+f[x,3]+y+f[y,2]+f[z,2]; > > >Can somebody suggest a general way to seperate the terms above >into like >groups. By "like" I mean having the same second argument for >(f). So for >this example I want to get > >{a+b+c+x+y, f[w,2]+f[x,2]+f[y,2]+f[z,2], f[w,3]+f[x,3]} > >The pattern matcher should be able to do this because Plus has >attributes >Flat and Orderless. However I can't find a way to make it happen. > >------------------- >Thanks, > Ted Ersek > Using some sort of Delete (with complementary criterion) appears to work, e.g. In[17]:= seca = Union[Cases[expr, f[_, a_] :> a]] Out[17]= {2, 3} In[18]:= patts = Prepend[e_ /; ! MatchQ[e, f[_, #]] & /@ seca, f[_, _]] Out[18]= {f[_, _], e_ /; ! MatchQ[e, f[_, 2]], e_ /; ! MatchQ[e, f[_, 3]]} In[19]:= DeleteCases[expr, #] & /@ patts Out[19]= {a + b + c + x + y, f[w, 2] + f[x, 2] + f[y, 2] + f[z, 2], f[w, 3] + f[x, 3]} ... based on observations In[3]:= Cases[expr, f[_, 2]] Out[3]= {f[w, 2], f[x, 2], f[y, 2], f[z, 2]} In[5]:= DeleteCases[expr, f[_, _]] Out[5]= a + b + c + x + y so this could work, but ugly: In[6]:= Head[expr] @@ Cases[expr, f[_, 2]] Out[6]= f[w, 2] + f[x, 2] + f[y, 2] + f[z, 2] perhaps more convenient, but ugly again at use of pattern matching: In[7]:= Select[expr, MatchQ[#, f[_, 2]] &] Out[7]= f[w, 2] + f[x, 2] + f[y, 2] + f[z, 2] negating DeleteCases, ugly same way: In[8]:= DeleteCases[expr, e_ /; ! MatchQ[e, f[_, 2]]] Out[8]= f[w, 2] + f[x, 2] + f[y, 2] + f[z, 2] Extracting gives same as Cases: In[9]:= Extract[expr, Position[expr, f[f_, 2]]] Out[9]= {f[w, 2], f[x, 2], f[y, 2], f[z, 2]} As does Take: In[10]:= Take[expr, #] & /@ Position[expr, f[f_, 2]] Out[10]= {f[w, 2], f[x, 2], f[y, 2], f[z, 2]} Delete is fine (as DeleteCases) In[12]:= Delete[expr, Complement[List /@ Range[Length[expr]], Position[expr, f[f_, 2]]]] Out[12]= f[w, 2] + f[x, 2] + f[y, 2] + f[z, 2] -- Hartmut Wolf