Question

My vectors are defined as:

(x1, x2, …, xn) and (y1, y2, …yn)

I'm trying to calculate them like so:

sqrt((x1-y1)*(x1-y1) + (x2-y2)*(x2-y2) + … + (xn-yn)*(xn-yn))

I'm having trouble with vectors of more than 2 elements. I've been trying to use a for-each loop but I can't get the recursion to work right.

Also, I can get everything but the sqrt of the final number. I tried to define the final number as a variable, then take the sqrt of that variable, but my interpreter said something about "define not allowed in expression . . .".

My working code so far:

(define vectordistance 
  (lambda (v1 v2)
  (if 
   (null? v1) 0
      (+ 
      (*
      (- (car v1) (car v2))
      (- (car v1) (car v2))
      ) 
      (vectordistance (cdr v1) (cdr v2))
      )
  )
))
Was it helpful?

Solution

First, you're using lists - a vector is a different beast in Scheme. The key point for the solution is that you have to iterate over the lists, and somehow accumulate the answer until there are no more elements left. Also, a helper function will be useful here, because first we have to accumulate the addition and take the square root only at the end. Assuming that both lists have the same length:

; this is the same as yours, but better formatted
(define (helper v1 v2)
  (if (null? v1)
      0
      (+ (* (- (car v1) (car v2))
            (- (car v1) (car v2)))
         (helper (cdr v1) (cdr v2)))))

; call the above as a helper and take the square root of the result    
(define (vectordistance v1 v2)
  (sqrt (helper v1 v2)))

As a bonus (suggested by Chris) you can write the helper in a more idiomatic way by using a fold procedure. Check your interpreter's documentation, it might be called foldl or fold-left or simply fold, but this is how you'd use it - the idea is to avoid using explicit recursion and favoring the use of higher-order procedures:

(define (square x)
  (* x x))

(define (helper v1 v2)
  (foldl (lambda (e1 e2 r)
           (+ (square (- e1 e2)) r))
         0
         v1 v2))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top