Develop a program that computes the scalar product of two vectors. The program must not accept vectors having different size (in such a case print an error message) For example:

>(scalar-product '# (1 2 3) '#(2 1 1))
7
>(scalar-product '#(1 2 3) '#(1 2 3 4 5))
ERROR: Different sizes of vectors!
>

a) Write the program in iterative style using the DO loop
b) Write the program using recursion.

Respuesta :

Answer:

Explanation:

a) using DO loop, we have the following code:

(define (scalar-product-1 list1 list2)

(do ((remainingList1 list1 (cdr remainingList1))

(remainingList2 list2 (cdr remainingList2))    

(final-answer 0 (+ final-answer (* (car remainingList1) (car remainingList2)))))

((null? remainingList1) final-answer)

))

(define (scalar-product list1 list2) (if (= (length list1) (length list2)) (scalar-product-1 list1 list2) (display "ERROR: Different sizes of vectors\n"))

b) using recursion, we have the following code

(define (scalar-product list1 list2)

(cond ((not(= (length list1)(length list2))) "ERROR: Different sizes of Vectors")

((null? list1) 0)    

(else (+(* (car list1) (car list2)) (scalar-product (cdr list1) (cdr list2))))

))

ACCESS MORE