1

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)))))
3
  • This is probably an easy answer, but I have not worked with vectors before and need to use them for plotting something. Commented Oct 11, 2013 at 13:35
  • What is the intended result? Commented Oct 11, 2013 at 16:08
  • I am trying to "zip" list X and Y into a list of data points. Commented Oct 11, 2013 at 16:11

2 Answers 2

3

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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))

1 Comment

If I replace '() with #() would that eliminate () altogether?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.