The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Inactive » comp.soft-sys.math.mathematica

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Exercise of Programming with Mathematica
Replies: 8   Last Post: Oct 23, 2013 11:33 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Ray Koopman

Posts: 3,383
Registered: 12/7/04
Re: Exercise of Programming with Mathematica
Posted: Oct 20, 2013 11:18 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

Instead of using ReplaceAll (/.), use Replace and specify the level.

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

In[2]:= Replace[{{a, b}, {c, d}}, {x_, y_} :> {y, x}, {0}]
Out[2]= {{c, d}, {a, b}}

----- 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}}
> 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.

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.