       Re: Exercise of Programming with Mathematica

• To: mathgroup at smc.vnet.net
• Subject: [mg131857] Re: Exercise of Programming with Mathematica
• From: Sseziwa Mukasa <mukasa at gmail.com>
• Date: Sat, 19 Oct 2013 04:09:56 -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>

```I can't determine a pattern that represents a pair which does not also match {{a,b},{c,d}}, but I can think of two options.  The first is not to use pattern matching at all, which may be more efficient anyway:

In:= {{a, b}, {c, d}, {e, f}}[[All, {2, 1}]]
{{a, b}, {c, d}}[[All, {2, 1}]]
Out= {{b, a}, {d, c}, {f, e}}
Out= {{b, a}, {d, c}}

The other is to limit the pattern matching to the appropriate level:

In:= Replace[{{a, b}, {c, d}, {e, f}}, {x_, y_} -> {y, x}, {1}]
Replace[{{a, b}, {c, d}}, {x_, y_} -> {y, x}, {1}]
Out= {{b, a}, {d, c}, {f, e}}
Out= {{b, a}, {d, c}}

Elegance as always is in the eye of the beholder,

Sseziwa

On Oct 18, 2013, at 4:45 AM, Zhenyi Zhang <infozyzhang at gmail.com> 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}}
>
> 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?
>
> Thanks.
>

```

• Prev by Date: Re: Version 9 Trial contaminates Version 8 running paid version
• Next by Date: Re: Exercise of Programming with Mathematica
• Previous by thread: Exercise of Programming with Mathematica
• Next by thread: Re: Exercise of Programming with Mathematica