'How can i compute the summation of two vectors in scheme(Dr Racket)

I would like to implement my function sum-of-vectors , such that it takes two vectors of different numbers as arguments and it returns a vector with the summation of the corresponding elements of the captured vectors . This is how it should be executed to test for the summation of the vectors where vector 1 is (vector 4 6 8 3) , and vector 2 is : (vector 5 6 7)

Testing Expression: (sum-vector (vector 4 6 8 3) (vector 5 6 7)) => #(9 11 15 3)

SIMILAR QUESTION : There is a close solution to this which is on URL , Is there a way of summing two vectors with different lengths in Scheme?

but the difference is that , it displays '#(2 4 6 4 5 6) with a comma the start of the question , yet the actual output from my requirement should not have an apostrophe(') in the output vector. it should be #(9 11 15 3)



Solution 1:[1]

A function to process corresponding elements of two lists which may differ in length is easily written down: write a stub, with signature and purpose, and a minimal example:

(define (sum-of-lists l1 l2) ;; ListOfNumber ListOfNumber -> ListOfNumber
  ;; produce list of sums of corresponding elements of l1, l2
  ;; length of result is greater of lengths of l1, l2
  '#())

(check-expect (sum-of-lists '() '()) '())

Add the next examples and fill out the function:

(check-expect (sum-of-lists '()  '(1)) `(1))
(check-expect (sum-of-lists '(2) '())  `(2))
(check-expect (sum-of-lists '(3) '(4)) `(7))

(define (sum-of-lists l1 l2) ;; ListOfNumber ListOfNumber -> ListOfNumber
  ;; produce list of sums of corresponding elements of l1, l2
  ;; length of result is greater of lengths of l1, l2
  (cond
    [(and (empty? l1) (empty? l2)) empty ]
    [(empty? l1) (cons (first l2) (sum-of-lists l1 (rest l2))) ]
    [(empty? l2) (cons (first l1) (sum-of-lists (rest l1) l2)) ]
    [else (cons (+ (first l1) (first l2)) (sum-of-lists (rest l1) (rest l2))) ]))

(note how the 4 arms of the cond echo the 4 examples)

Now the required sum-of-vectors is just:

(define (sum-of-vectors von1 von2) ;; VectorOfNumber VectorOfNumber -> VectorOfNumber
  ;; produce vector of sums of corresponding elements of von1, von2
  ;; length of result is greater of lengths of von1, von2
  (list->vector (sum-of-lists (vector->list von1) (vector->list von2))))

(check-expect (sum-of-vectors (vector 4 6 8 3) (vector 5 6 7)) (vector 9 12 15 3))

Welcome to DrRacket, version 8.4 [cs].
Language: Advanced Student.
All 5 tests passed!
> (sum-of-vectors '#(1 2 3) '#(1 2 3 4 5 6))
(vector 2 4 6 4 5 6)
> 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mnemenaut