next up previous contents
Next: Conditionals and the Up: CHAPTER.3: PROCEDURES AND Previous: Removing unwanted items

Swapping items using the stack

As described earlier, the following swaps the values of X and Y:

    x, y -> (y, x);
And this is equivalent to

    x, y -> x -> y;
The statement:

    -> (y, x); x, y;
has a rather different meaning. Effectively, it swaps the top two elements of the stack and as a side-effect stores the top two items in x and y. E.g.

    1, 2, 3, 4;
    -> (y, x); x, y;

    ** 1 2 4 3

    x, y =>
    ** 4 3
If we wanted to swap the first (ie top) and third elements of the stack we could do:

    vars x, y, z;
    -> x -> y -> z; x, y, z;
or, more clearly,

    -> (z, y, x); x, y, z;

Aaron Sloman
Fri Jan 2 03:17:44 GMT 1998