John Friedrich
John Friedrich

Reputation: 343

Vectors in Scheme

How would I write a vector-to-list function without using the built in (vector->list) function. Specifically I am looking to learn how to access values within vectors as I have not previously worked with them.

Is there a more straightforward implementation than this:

(define (vector-to-list vec)
 (define (helper k lst)
   (if (= k (vector-length vec))
        lst
       (helper (+ k 1) (cons (vector-ref vec k) lst))))
  (reverse (helper 0 '())))
 (vector-to-list #(1 2 3 4))

?

Upvotes: 1

Views: 490

Answers (1)

GoZoner
GoZoner

Reputation: 70135

No, that is a sound implementation. One could write it a bit more idiomatically using 'named-let' as:

(define (vector-to-list vec)
  (let ((len (vector-length vec)))
    (let looping ((k 0) (lst '())
      (if (= k len)
          (reverse lst)
          (looping (+ k 1)
                   (cons (vector-ref vec k) lst)))))

You could avoid the use of reverse by constructing the list from back to front:

(define (vector-to-list vec)
  (let looping ((k (- (vector-length vec) 1)) (lst '())
    (if (< k 0)
        lst
        (looping (- k 1)
                 (cons (vector-ref vec k) lst)))))

Upvotes: 4

Related Questions