Re: Exercise of Programming with Mathematica
- To: mathgroup at smc.vnet.net
- Subject: [mg131859] Re: Exercise of Programming with Mathematica
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Sat, 19 Oct 2013 04:10:36 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-outx@smc.vnet.net
- Delivered-to: mathgroup-newsendx@smc.vnet.net
On 10/18/13 at 4:45 AM, infozyzhang at gmail.com (Zhenyi Zhang) wrote: >Here is a rule designed to switch the order of each pair of >expressions in a list. It works fine on the first example, but fails >on the second. >In[1]:= {{a, b}, {c, d}, {e, f}}/.{x_, y_} :> {y, x} >Out[1]= {{b, a}, {d, c}, {f, e}} >In[2]:= {{a, b}, {c, d}}/.{x_, y_} :> {y, x} >Out[2]= {{c, d}, {a, b}} >Explain what has gone wrong and >rewrite this rule to correct the situation, that is, so that the >second example returns {{b, a}, {d, c}} The pattern {x_, y_} matches any two element list. In the first case, the only two element lists are the pairs you want to change. But in the second case, you have three two element lists, the two pairs you want to change and the list of pairs since there are only two pairs. You can achieve what you want by using a more restrictive pattern, i.e., In[2]:= {{a, b}, {c, d}} /. {x_Symbol, y_} :> {y, x} Out[2]= {{b, a}, {d, c}} or if you did not want to change the order of the paired symbols, In[3]:= {{a, b}, {c, d}} /. {x_List, y_} :> {y, x} Out[3]= {{c, d}, {a, b}}