MathGroup Archive 2001

[Date Index] [Thread Index] [Author Index]

Search the Archive

RE: Replacement Rule

  • To: mathgroup at smc.vnet.net
  • Subject: [mg32075] RE: [mg32064] Replacement Rule
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.de>
  • Date: Sat, 22 Dec 2001 04:22:48 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

> -----Original Message-----
> From: bghiggins at ucdavis.edu [mailto:bghiggins at ucdavis.edu]
To: mathgroup at smc.vnet.net
> Sent: Friday, December 21, 2001 9:58 AM
> To: mathgroup at smc.vnet.net
> Subject: [mg32075] [mg32064] Replacement Rule
> 
> 
> I have the following list
> 
> l1={{1,2},{3,4},{5,6}};
> 
> and then I operate on it with the following pattern/replacement rule
> 
> In[3]:= l1 /. {x_, y_} -> x
> 
> Out[3]= {1, 3, 5}
> 
> This is what I would expect. Now consider the following list
> 
> In[4]:= l2 = {{3, 4}, {5, 6}};
> 
> Then I use the same pattern/replacement rule 
> 
> In[5]:=l2 /. {x_, y_} -> x
> 
> Out[5]= {3, 4}
> 
> I was hoping to get
> 
> {3,5}
> 
> What am I missing? The FullForm of l2 is basically the same structure
> as l1, as far as I can tell....
> 
> Brian
> 
There is no mystery here, but a match you didn't reckon with. To see all
possible matches look at

In[2]:= Position[{{3, 4}, {5, 6}}, {x_, _}]
Out[2]= {{1}, {2}, {}}

at positions 1 and 2 of the list (the ones you liked), plus one additional,
indicated by {} which means the total expression. If you compare with

In[3]:= Position[{{3, 4}, {5, 6}}, {x_Integer, _}]
Out[3]= {{1}, {2}}

the pattern now cannot math the total expression any longer. These are the
ways out of your dilemma: be more specific with your patter, or direct the
matching process. Some examples

In[4]:= {{3, 4}, {5, 6}} /. {x_Integer, _} :> x
Out[4]= {3, 5}

In[5]:=
anotherHead[{3, 4}, {5, 6}] /. {x_, _} :> x /. anotherHead -> List
Out[5]= {3, 5}

In[7]:=
Replace[{{3, 4}, {5, 6}}, {x_, _} :> x, {1}]
Out[7]= {3, 5}
compare with
In[6]:=
(# /. {x_, _} :> x &) /@ {{3, 4}, {5, 6}}
Out[6]= {3, 5}

In[8]:=
Replace[{{3, 4}, {5, 6}}, {x_, _} :> x, Infinity]
Out[8]= {3, 5}

However
In[9]:=
Replace[{{3, 4}, {5, 6}}, {x_, _} :> x, {0, Infinity}]
Out[9]= 3
compare with
In[10]:=
Replace[#, {x_, _} :> x] & //@ {{3, 4}, {5, 6}}
Out[10]= 3

So we might say ReplaceAll works top down, Replace bottom up. Make shure you
understand these cases.

Hartmut



  • Prev by Date: Re: Font problems w SuSE 7.3 / Partial Solution
  • Next by Date: Re: symbolic calculations with complex numbers
  • Previous by thread: Re: Replacement Rule
  • Next by thread: Solutions that are not solutions