Re: A simple swap function

• To: mathgroup at smc.vnet.net
• Subject: [mg2167] Re: A simple swap function
• From: wagner at bullwinkle.cs.Colorado.EDU (Dave Wagner)
• Date: Wed, 11 Oct 1995 01:59:02 -0400
• Organization: University of Colorado, Boulder

```In article <44qj8g\$s22 at ralph.vnet.net>,
William F. Campbell <valentin at wam.umd.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?

The short answer is, you need to give your function the attribute HoldAll
using "SetAttributes[swap, HoldAll]".

The long answer is, don't do it.  Held parameters have call-by-name
semantics.  (Look it up in a programming languages book if you don't
know what that means.)  To see why what you're doing is a bad idea, try
evaluating "a = {1,3,2}; i = 2; swap[i, a[[i]]]" or "swap[a[[i]],
[i]]".  One of them will break horribly.  It's been proven that there
is no way to write a swap function using call-by-name parameters.

Sorry that this reply is so terse, or that I can't give you references,
but I'm doing this over a long-distance line at the moment.

Dave Wagner
Principia Consulting
(303) 786-8371
dbwagner at princon.com
http://www.princon.com/princon

```

• Prev by Date: RE: Labeling Lines on a multiple plot
• Next by Date: Comparison of overlapping numbers
• Previous by thread: Re: A simple swap function
• Next by thread: Re: A simple swap function