Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #16091 > unrolled thread
| Started by | Itai Seggev <itais@wolfram.com> |
|---|---|
| First post | 2013-10-21 03:19 +0000 |
| Last post | 2013-10-21 03:19 +0000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.soft-sys.math.mathematica
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Exercise of Programming with Mathematica Itai Seggev <itais@wolfram.com> - 2013-10-21 03:19 +0000
| From | Itai Seggev <itais@wolfram.com> |
|---|---|
| Date | 2013-10-21 03:19 +0000 |
| Subject | Re: Exercise of Programming with Mathematica |
| Message-ID | <l426fo$le8$1@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[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}}
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[115]:= {{a, b}, {c, d}} /. {x : Except[_List], y : Except[_List]} -> {y, x}
Out[115]= {{b, a}, {d, c}}
--
Itai Seggev
Mathematica Algorithms R&D
217-398-0700
Back to top | Article view | comp.soft-sys.math.mathematica
csiph-web