Variable name for a function

For a change, here’s something that actually does what it’s supposed to, to wit, an anonymous function that computes the median of a list of numbers. The details of this function are unimportant, so for the main point of this article see the next paragraph.

(LAMBDA (NUMBERS)
  (LET* ((SORTED (SORT (COPY-SEQ NUMBERS) #'<))
         (SIZE (LENGTH SORTED))
         (MIDDLE-NUMBERS (NTHCDR (FLOOR (1- SIZE) 2)
                                 SORTED)))
    (IF (ODDP SIZE)
        (FIRST MIDDLE-NUMBERS)
        (/ (+ (FIRST MIDDLE-NUMBERS) (SECOND MIDDLE-NUMBERS))
           2))))

The following expression binds the local variable name (not function name!) MEDIAN to the function. As a result, all but one of the calls to MEDIAN are errors:

(LET ((MEDIAN paste-the-above-lambda-expression-here))
  (LIST (MEDIAN '(2))
        (FUNCALL MEDIAN '(6 2 8 4))
        (FUNCALL 'MEDIAN '(2 4 6 8   1 3 5 7 9))
        (FUNCALL #'MEDIAN '(2 4 6 8   1 3 5 7 9   0))))
Filed under  //   control flow   evaluation  

About

A growing compendium of erroneous Common Lisp code snippets by Ismail Ikram.

Lisp novices might try to correct these as a learning exercise. Need some help or just feel like nitpicking? Do post a comment and let me know.

Twitter