MathGroup Archive 1995

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

Search the Archive

Re: A simple swap function

  • To: mathgroup at
  • Subject: [mg2226] Re: [mg2132] A simple swap function
  • From: wagner at (Dave Wagner)
  • Date: Tue, 17 Oct 1995 02:34:35 -0400
  • Organization: University of Colorado, Boulder

In article <45cvu4$5tc at>,
Richard Mercer  <richard at> 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!

Following up to my earlier posting on this topic, which was done while
on the road and in some haste, I can now elaborate.  Fleck showed that
it was impossible to write a correct swap function in Algol using the
call-by-name parameter transmission mechanism:

    A.C. Fleck, 1976. On the impossibility of content exchange through
    the by-name parameter transmission mechanism. ACM SIGPLAN Notices

Here is an example of what kinds of problems occur, using the
Mathematica-specific mechanism suggested by Richard Mercer above:

    s = {3,1,2};
    i = 2;
    {i, s}


    {i, s[[i]]} = {s[[i]], i};
    {i, s}


The result ought to be {1, {3, 2, 2}}.

After some reflection I think that may be oversimplifying to conclude
that something that's impossible to do in Algol is also impossible to
do in Mathematica.  I've thought about trying to write a correct swap
function using constructs such as Hold and With to "freeze" the
expressions being swapped.  Unfortunately, you can only scope symbols,
not entire expressions, so my strategy would fail when trying to swap
s[[i]] with s[[s[[i]]]], for example.  So while I won't go so far as to
state that this is impossible to do in Mathematica, it seems to be very
hard, and given Fleck's result I wouldn't waste too much time on it.

This is not to say, of course, that the {a,b} = {b,a} trick isn't useful,
as long as you realize its shortcomings.

		Dave Wagner
		Principia Consulting
		(303) 786-8371
		dbwagner at

  • Prev by Date: Mma & ANOVA : package for calculating sums of squares????
  • Next by Date: Re: Mathlink & Graphics....
  • Previous by thread: Re: A simple swap function
  • Next by thread: Re: A simple swap function