Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #16079 > unrolled thread

Re: Exercise of Programming with Mathematica

Started byBill Rowe <readnews@sbcglobal.net>
First post2013-10-19 07:47 +0000
Last post2013-10-19 07:47 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.soft-sys.math.mathematica


Contents

  Re: Exercise of Programming with Mathematica Bill Rowe <readnews@sbcglobal.net> - 2013-10-19 07:47 +0000

#16079 — Re: Exercise of Programming with Mathematica

FromBill Rowe <readnews@sbcglobal.net>
Date2013-10-19 07:47 +0000
SubjectRe: Exercise of Programming with Mathematica
Message-ID<l3tdea$9ti$1@smc.vnet.net>
On 10/18/13 at 4:45 AM, infozyzhang@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}}

[toc] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web