       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:= {{a, b}, {c, d}, {e, f}}/.{x_, y_} :> {y, x}
>Out= {{b, a}, {d, c}, {f, e}}
>In:= {{a, b}, {c, d}}/.{x_, y_} :> {y, x}
>Out= {{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:= {{a, b}, {c, d}} /. {x_Symbol, y_} :> {y, x}

Out= {{b, a}, {d, c}}

or if you did not want to change the order of the paired symbols,

In:= {{a, b}, {c, d}} /. {x_List, y_} :> {y, x}

Out= {{c, d}, {a, b}}

```

• Prev by Date: Re: Exercise of Programming with Mathematica
• Next by Date: Re: Help with Manipulate
• Previous by thread: Re: Exercise of Programming with Mathematica
• Next by thread: Re: Exercise of Programming with Mathematica