Search code examples
recursionlispcommon-lisp

Write a recursive LISP function that finds the dot product of two lists of numbers of same length


Just started to learn LISP and I'm trying to figure out how to write the following recursive function.

So should I have

(DOT-PRODUCT '(1 2) '(3 4)))

The output should be 11

I've written the following

(defun DOT-PRODUCT (a b)
  (if (or (null a) (null b))
      0
      (+ (* (first a) (first b))
         (DOT-PRODUCT (rest a) (rest b)))))

And everything seems to work; however, it still works with lists of different lengths. I want it to just work with lists of numbers that have the same length. Where should I add code that returns "invalid length" should we have such?


Solution

  • A simple way is to rewrite the function so that it checks different cases using the conditional form cond:

    (defun dot-product (a b)
      (cond ((null a) (if (null b) 0 (error "invalid length")))
            ((null b) (error "invalid length"))
            (t (+ (* (first a) (first b))
                  (dot-product (rest a) (rest b))))))
    

    In the first branch of the cond, if the first argument is NIL, the second one must be NIL as well, otherwise an error is generated. In the second branch, we already know that a is not NIL, so an error is immediately generated. Finally, the result is calculated.