REVERSING THE ELEMENTS OF A VECTOR

Scheme provides a built-in reverse procedure, but it applies only to lists. Suppose one wants to reverse the order of the elements of a vector?

Actually, there are two variants of this problem. In the first, one wants to keep the container and move the contents around inside it. One algorithm that accomplishes this simply swaps elements that are equidistant from the ends, working from the outside towards the middle:

(define vector-reverse!
  (lambda (v)
    (let ((len (vector-length v)))
      (do ((left-index 0 (+ left-index 1))
           (right-index (- len 1) (- right-index 1)))
          ((<= right-index left-index))
        (vector-swap! v left-index right-index)))))
On the other hand, one may want to leave the original vector unchanged, building and returning a new vector with the same elements, but in the reverse order. This is a job for vector-generator, a procedure that creates a vector of a specified size in which each element is the result of applying a specified procedure to the position of the element. The version given here is lightly adapted from Program 9.21 in Scheme and the art of programming, by George Springer and Daniel P. Friedman (Cambridge, Massachusetts: MIT Press, 1989), p. 283.
(define vector-generator
  (lambda (generator size)
    (let ((vec (make-vector size)))
      (do ((index 0 (+ index 1)))
          ((= index size) vec)
        (vector-set! vec index (generator index))))))
Here, then, is the non-destructive vector reversal procedure:
(define vector-reverse
  (lambda (v)
    (let ((len (vector-length v)))
      (vector-generator (lambda (index)
                          (vector-ref v (- (- len 1) index)))
                        len))))


This document is available on the World Wide Web as

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


created July 11, 1995
last revised June 24, 1996

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