Question

I was wondering how to get the dot product of two vectors.

(check-expect (dot (vector 5 1 1) (vector 1 0 0)) (+ 5 0 0))
(check-expect (dot (vector 1 1 5) (vector 1 0 0)) (+ 1 0 0))

So essentially I'm trying to build a function (dot) that will satisfy these two check expects.

So far I have only started this by defining the function

(define (dot vec1 vec2)

I had previously defined a function (vfold) that is the same as foldl except that vfoldl works on vectors rather than lists, but am not sure if I have to use it for this new function.

; vfoldl: (X Y --> Y) Y [VectorOf X] --> Y
(define (vfoldl combine base avec)
  (local [(define imax (sub1 (vector-length avec)))
          (define (vaux combine avec index acc)
            (cond [(= index imax) (combine (vector-ref avec imax) acc)]
                  [else (vaux combine
                              avec
                              (add1 index)
                              (combine (vector-ref avec index)
                                       acc))]))]
   (vaux combine avec 0 base)))
Was it helpful?

Solution

Shouldn't the following work? (I don't have an interpreter on hand to test it, give me a minute to check.)

(define (dot a b)
    (apply + (vector->list (vector-map * a b)))
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top