       Re: Exercise of Programming with Mathematica

• To: mathgroup at smc.vnet.net
• Subject: [mg131873] Re: Exercise of Programming with Mathematica
• From: Itai Seggev <itais at wolfram.com>
• Date: Sun, 20 Oct 2013 23:40:47 -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
• References: <20131018084528.A030C6A21@smc.vnet.net>

```On Fri, Oct 18, 2013 at 04:45:28AM -0400, 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}}

Nothing has gone wrong.  :)  Seriouly, You're entirely input is an ordered pair
with x -> {a,b} and y -> {c, d}.  The reason the first example works is that it
has 3 pairs, so the binding isn't possible.  Remember, ReplaceAll (/.)  always
looks for the larges subexpression it can match first.

> My solution is the most stupid one.
>
> {{a, b}, {c, d}}/.{{x_, y_}, {w_, t_}} :> {{y, x}, {t, w}}
>
> May I ask any elegant solutions?

With this pattern, x and y cannot themselves be lists:

In:= {{a, b}, {c, d}} /. {x : Except[_List],  y : Except[_List]} -> {y, x}

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

--
Itai Seggev
Mathematica Algorithms R&D
217-398-0700

```

• Prev by Date: Using same \$UserBaseDirectory for Mac & Windows versions
• Next by Date: Re: Exercise of Programming with Mathematica
• Previous by thread: Re: Exercise of Programming with Mathematica
• Next by thread: Re: Exercise of Programming with Mathematica