SWAPPING VALUES

Since all parameter-passing in Scheme is by value, it is not possible to write a procedure that will exchange the values of two given variables; a Pascal procedure such as

procedure swap (var alpha, beta: integer);
var temp: integer;
begin
    temp := alpha;
    alpha := beta;
    beta := temp
end;
has no exact counterpart in Scheme. Probably the best way to explain this algorithm to a student of Scheme is to invent a ``cell'' or ``reference'' data type that explicitly simulates the behavior of a Pascal variable:
(define cell
  (lambda (value)
    (vector value)))

(define cell-ref
  (lambda (c)
    (vector-ref c 0)))

(define cell-set!
  (lambda (c new-value)
    (vector-set! c 0 new-value)))
Here, then, is a Scheme procedure that exchanges the contents of two cells:
(define cell-swap!
  (lambda (alpha beta)
    (let ((temp (cell-ref alpha)))
      (cell-set! alpha (cell-ref beta))
      (cell-set! beta temp))))
A similar procedure is used for the (far more common) operation of swapping two elements of an array:
(define vector-swap!
  (lambda (v index-1 index-2)
    (let ((temp (vector-ref v index-1)))
      (vector-set! v index-1 (vector-ref v index-2))
      (vector-set! v index-2 temp))))


This document is available on the World Wide Web as

http://www.math.grin.edu/~stone/events/scheme-workshop/cellswap.html


created July 8, 1995
last revised June 24, 1996

John David Stone (stone@math.grin.edu)