I was tasked to write a recursive euclidean distance. I have been googling around but could not find any sample. I understand the function of euclidean distance and has no problem writing it in an iterative manner as shown below. Is there anyone who could advise me on how I should start for the recursive function? The requirement is the same as the iterative version. Thanks.
(defun euclidean-distance-it (p q)
(cond
((or (null p) (null q)) nil) ;return nil if either list is null
((or (atom p) (atom q)) nil) ;return nil if either list is an atom
((or (null (cdr p)) (null (cdr q))) nil);return nil if either list contains less than two inputs
((or (not (null (car(cdr(cdr p))))) (not (null (car(cdr(cdr q)))))) nil) ;return nil if either list contains more than two inputs
((or (or (not (numberp (car p))) (not (numberp (cadr p)))) (or (not (numberp (car q))) (not (numberp (cadr q))))) nil);return nil if any of the four entires aren't numbers
(T (sqrt (+ (expt (- (car p) (car q)) 2)
(expt (- (cadr p) (cadr q)) 2)))))) ;Calculate the euclidean distance
The only time recursive algorithm for this would be sensible if the input are two vectors (represented by lists) of any dimension, not only 2 or 3. In this case this will compute the square of the distance:
(defun sq-euclid-distance (p q)
(cond ((or (null p) (null q)) 0)
(t (+ (expt (- (car p) (car q)) 2)
(sq-euclid-distance (cdr p) (cdr q))))))
To get SQRT
out of it you would need to make it into a auxiliary helper and make a driver computing the square root.
(defun euclid-distance (p q) (sqrt sq-euclid-distance p q))
PS. I am not checking if p
and q
are atoms, but they can be treated as 1-dimensional vectors. Returning NIL
from the function that is expected to provide a numerical value is not a great idea.