opening it up with Common Lisp

Favorite weblogs

Lisp Related

Bill Clementson

Finding Lisp


Planet Lisp



Talking Points Memo

This Modern World

Working for Change

Other home


Recent Readings

Book review: Darwinia
Reviewed: Friday, August 11, 2006

Summer reading: Spin
Reviewed: Saturday, August 5, 2006

Reviewed: Tuesday, July 18, 2006

the Omnivoire's Delimma
Reviewed: Wednesday, July 12, 2006

the Golem's Eye
Reviewed: Wednesday, May 31, 2006


When not to apply yourself
Saturday, April 3, 2004

Apply is cool but don't use it unless you need to. I recently found this definition of #'mean:

(defun mean (list) (/ (apply #'+ list)   
  (length list)))

Which is certainly clean and succinct. Think about what happens, however, when this is called with a really big list (e.g., 100,000 elements): apply is called with 100,000 arguments. All of these need to be pushed onto the stack and, generally speaking, there won't be room. Note that Lisp has two implementation dependent constants (lambda-parameters-limit and call-arguments-limit) which proclaim how many arguments the implementation feels it can support when defining and calling functions. To get around this, you can use reduce:

(defun mean (list) (float (/ (reduce #'+ list) (length list))))

or even an a new fangled iteration construct:

(defun mean (list)
  (let ((sum 0) (count 0))
    (loop for x in list do
          (incf sum x)
          (incf count))
    (float (/ sum count))))

The #'reduce method is slightly slower in this case because we also need to get the length of the list (two passes) rather than computing both in one pass. I've added the call to #'float because we probably don't want to be trafficking in ratios.


Home | About | Quotes | Recent | Archives

Copyright -- Gary Warren King, 2004 - 2006