Duplicate the swap function

10

1

Because defining the function:

swap[x_, y_] := Module[{}, t = x; x = y; y = t; Return[]]

and writing:

swap[x, y]
{x, y}

I get:

{y, y}

and not {y, x} as I would like?

Thank you!

TeM

Posted 2017-02-07T20:52:11.573

Reputation: 3 933

2is swap meant to swap the values stored in x and y, or is it meant to symbolically swap the two expressions? – march – 2017-02-07T21:03:13.443

2What is the point of Module here? What is the point of Return? – Marius Ladegård Meyer – 2017-02-07T21:06:31.523

As to Module, you may want to read this, as to Return, you may want to read this.

– xzczd – 2017-02-10T11:51:12.093

Answers

14

Attributes[swap] = HoldAll;

swap[x_, y_] := {x, y} = {y, x};

x = 1;
y = 2;

swap[x, y];

{x, y}
{2, 1}

There are two characteristics of this code worth noting. The first is the HoldAll Attribute:

The second is the evaluation of {x, y} = {y, x} itself, which is related. Let us consider how else we might implement this. Essentially we need to store the present values of x and y before reassigning these Symbols to the opposite value. That might be done verbosely like this:

x1 = x;
y1 = y;
x = y1;
y = x1;

This requires that two additional Symbols be introduced which is less clean than ideal. Instead we can store the original values within the evaluation sequence itself. First understand that Set (short form =) has the HoldFirst attribute. This means that in the expression {x, y} = {y, x} (long form Set[{x, y}, {y, x}]) the second argument will be evaluated before Set does anything, but the first argument will be held in an unevaluated form. Indeed we find this in the output of TracePrint:

x = 1;  y = 2;

TracePrint[{x, y} = {y, x}];

  (* other print lines omitted*)

{x, y} = {2, 1}

Thanks to the fact that Set operates on lists this then performs the reassignment that we want. If it did not we could still perform this action without using intermediate (temporary) variables like x1 and y1 by using the same kind of evaluation control.

(x = #2; y = #1) &[x, y]

Here a Function is used which (by default) evaluates its arguments but holds the body of the function (x = #2; y = #1) unevaluated until its Slots are filled.

Mr.Wizard

Posted 2017-02-07T20:52:11.573

Reputation: 259 163

4@Manu You are welcome, and I am glad I can help. This really is not a stupid question as it requires some specific knowledge and understanding regarding evaluation semantics in Mathematica. It's actually a very nice minimal example of a couple of different properties. I suspect the question will end up being of use to other newish users. – Mr.Wizard – 2017-02-07T21:57:01.130

6

Just a reminder for advanced users, to show the complexity of the problem :

enter image description here

enter image description here

keywords : David Wagner power programming swap byname

andre314

Posted 2017-02-07T20:52:11.573

Reputation: 15 746