Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1995
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1995

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: A simple swap function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg2151] Re: [mg2132] A simple swap function
  • From: Richard Mercer <richard at seuss.math.wright.edu>
  • Date: Tue, 10 Oct 1995 02:36:40 -0400

 >   I think I must be missing something straightforward.
>  I want a function to swap the values of 2 lists.  I
>  defined ab={a,b}, and ba={b,a}, and
>  swap[v1_,v2_]:=Module[{temp=v1},v1=v2;v2=temp;], and I
>  get an Iteration limit exceeded error.  When I look at
>  ab, it looks like {Hold[a],Hold[b]} (or maybe
>  {Hold[b],Hold[a], I don't remember), and ba looks
>  opposite.  When I tried to use the same function on
>  numbers, it didn't work either.  What's wrong with what
>  I'm doing, and how can I do what I want to do?

All of this is unnecessary.
Assuming the variables a and b have been assigned values, 

the assignment

{a,b} = {b,a}

works. Try it! I do NOT recommend this if a and b have not been  
assigned values!

If you want to be ultracareful, you could use

swap[v1_Symbol,v2_Symbol]:= 

  If[ValueQ[v1] & ValueQ[v2], {v1,v2} = {v2,v1}];

Richard Mercer


Richard Mercer


  • Prev by Date: Re: Constructing Expressions from List Elements
  • Next by Date: Re: X-crashing!
  • Previous by thread: Re: A simple swap function
  • Next by thread: Re: A simple swap function