Computing the Inner Product with Common Lisp

Over at iqool, Patrick Krusenotto asks how you would compute the inner product of two vectors using Common Lisp. He gives a number of solutions, all of which are interesting. You can look at this problem two ways:

  1. What is the most idiomatic way?
  2. What is the fastest way?

If I were writing a function to do this and speed was not an overriding concern, I would do something like

(defun inner-product (v1 v2)
  (reduce #'+ (mapcar #'* v1 v2)))

and Krusenotto agrees that this is what most Lispers would write.

If I was concerned about speed, I would want to avoid the consing from the mapcar and would do something like

(defun inner-product (v1 v2)
  (let ((sum 0))
    (mapc (lambda (e1 e2) (incf sum (* e1 e2))) v1 v2)
    sum))

That’s probably fast enough for almost all applications, especially if you add some declares to optimize code generation. There was a solution similar to this in the comments. To tell the truth, though, I might also use a tail recursive loop as in Krusenotto’s solution #2. I do love me some recursive programming.

If I was really concerned about speed, I would probably do something like Krusenotto’s solution #5, which uses an explicit go to speed the loop. With proper declarations, you probably can’t do much better.

It’s fun to think about how you might program simple problems like this. What solution(s) would you use?

This entry was posted in Programming and tagged , . Bookmark the permalink.