Re: A simple swap function

*To*: mathgroup at smc.vnet.net*Subject*: [mg2233] Re: [mg2132] A simple swap function*From*: mmcclure at liberty.uc.wlu.edu (Mark McClure)*Date*: Wed, 18 Oct 1995 01:53:03 -0400*Organization*: Washington & Lee University

Richard Mercer (richard at seuss.math.wright.edu) wrote: : > 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}]; Even if a and b have been assigned values, howabout swap[{a_,b_}] := {b,a} ? Mark mmcclure at wlu.edu http://wlu.edu/~mmcclure