Search code examples
schemelispracketsicp

Is there a way of summing two vectors with different lengths in Scheme?


Am a beginner to Scheme a dialect of Lisp, am trying to implement a function sum-vector that takes two vectors of numbers as arguments and returns a vector with the sum of the corresponding elements of the input vectors.

I have tried the following code but i can't figure out how to sum two vectors with different lengths. Here is my current code

#lang scheme
(define sum-vector
  (lambda (vec-1 vec-2)
    (let* ((len (vector-length vec-1))
                                       
           (result (make-vector len)))
      (do ((index 0 (+ index 1)))
          ((= index len) result)
        (vector-set! result index
                     (+ (vector-ref vec-1 index)
                        (vector-ref vec-2 index)))))))

(sum-vector (vector 4 6 8 3) (vector 5 6 7))

When i run the above code it works perfectly for vectors with same lengths e.g (sum-vector (vector 4 6 8) (vector 5 6 7)) returns #(9 12 15) I want it to work similarly for different lengths e.g (sum-vector (vector 4 6 8 3) (vector 5 6 7)) should return #(9 11 15 3) but i can't figure out the logic for doing that.


Solution

  • One possible solution is to append zeros to each vector to make their lengths equal and then use vector-map:

    (define (zero-vector len)
      (make-vector len 0))
    
    (define (append-zeros vec max-len)
      (vector-append vec (zero-vector (- max-len (vector-length vec)))))
    
    (define (sum-vector v1 v2)
      (let ((max-len (max (vector-length v1)
                          (vector-length v2))))
        (vector-map +
                    (append-zeros v1 max-len)
                    (append-zeros v2 max-len))))
    

    Tests:

    > (sum-vector (vector 1 2 3) (vector 1 2 3 4 5 6))
    '#(2 4 6 4 5 6)
    > (sum-vector (vector) (vector 1 2 3 4 5 6 7 8))
    '#(1 2 3 4 5 6 7 8)