John Friedrich
John Friedrich

Reputation: 343

Scheme Vector Syntax

Am I using the bound "vector" function from scheme correctly here?

(define (zip2 list1 list2)
 (if (null? list1)
   '()
   (vector (vector (car list1) (car list2))
           (zip2 (cdr list1) (cdr list2)))))

Upvotes: 1

Views: 185

Answers (2)

Óscar López
Óscar López

Reputation: 235984

I don't think the result is correct. If we run the procedure in the question, this is what we get:

(zip2 '(1 2 3) '(4 5 6))
=> '#(#(1 4) #(#(2 5) #(#(3 6) ())))

As you can see, there are vectors nested within vectors, deeper than they should. The problem with your solution is that you can't just replace cons with vector and expect that things will work the same; cons is fine for building a list as you go, adding one element at a time, but for building a vector you need to know all the elements beforehand, because you can't add elements after its creation.

I'd rather solve the problem in terms of the "normal" zip operation (the one that uses lists) and then convert the result to vectors:

(define (zip list1 list2)
  (map list list1 list2))

(zip '(1 2 3) '(4 5 6))
=> '((1 4) (2 5) (3 6))

(define (zip2 list1 list2)
  (list->vector
   (map list->vector (zip list1 list2))))

(zip2 '(1 2 3) '(4 5 6))
=> '#(#(1 4) #(2 5) #(3 6))

Or equivalently, but without using zip as part of the solution:

(define (zip2 list1 list2)
  (list->vector
   (map vector list1 list2)))

(zip2 '(1 2 3) '(4 5 6))
=> '#(#(1 4) #(2 5) #(3 6))

Upvotes: 3

GoZoner
GoZoner

Reputation: 70135

Yes and no. In your if statement the consequent returns a list whereas the alternate returns a vector. That is unlikely to be correct. For example:

> (zip2 '(a b) '(1 2))
#(#(a 1) #(#(b 2) ()))

You notice the () in there? Not good... But, depends on your exact problem and you've not really stated that. The fix might be as simple as replacing '() with '#()

[Edit] Now that we know your need. This gets you there:

(define (zip2 list1 list2)
  (map vector list1 list2))

> (zip2 '(10 20) '(1 2)) 
(#(10 1) #(20 2))

Upvotes: 1

Related Questions