swapping the values of two variables

I had need of this recently, so posting the snippet here.

Say you have two variables “var1” and “var2”, and you want to swap their values so that “var1” takes the value of “var2” and vice verse. This requires creating a temporary variable. For example:

(setf temp var1)
(setf var1 var2)
(setf var2 temp)

While this works fine, if you need this code multiple times in the same script, it is less repetitious to write it as a macro:

(defmacro swap (x y)
  `(let ((temp ,x))
      (setf ,x ,y)
      (setf ,y temp)))

Then wherever we need to swap the values of two variables, we can simply write:

(swap var1 var2)

Here’s a demonstration that may be run in the Nyquist Prompt:

(defmacro swap (x y)
  `(let ((temp ,x))
      (setf ,x ,y)
      (setf ,y temp)))

(setf var1 1)
(setf var2 99)
(swap var1 var2)
(format nil "var1 = ~a   var2 = ~a" var1 var2)