Needs to be done in DrRacket
Write a function dotProduct which takes two lists of
numbers representing vectors, and produces their dot product (or
reports their incompatibility).
E.g., (dotProduct '(1 2) '(3 4) ) -> 11
(dotProduct '(1 2 3) '(4 5 6)) -> 32
(dotProduct '(1 2 3) '(4 5)) -> *incompatible*
We can write a recursive function which accepts two lists and in each recursion it picks the first element of both lists multiply them and return the sum of this product with recursive call on remaining list, base condition will be when both list have no elements and in that case we will return 0.
note - car returns the head(first element) of a given list, example - car '(1 2 3) returns 1.
cdr returns the tail of a given list (remaining list after removing head element). example - cdr '(1 2 3) returns '(2 3).
Racket Code -
#lang racket
(define (dotProduct l1 l2) ; two paremeters as list l1 and list
l2
(cond ((not (equal? (length l1) (length l2))) (print
"*incompatible*")) ;codititon to check if length of both list is
same or not, if not then print incompatible otherwise contnue
(else
(cond ((null? l1) 0) ;base case, when both lists have 0 elements
left.
(else
(+ (* (car l1) (car l2)) ;pick first element of both list, multiply
them and add to the result of recursive call on remaining list(in
next line).
(dotProduct (cdr l1) (cdr l2))))))))
Screenshots -
Get Answers For Free
Most questions answered within 1 hours.