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))