Search code examples
lispcommon-lisplisp-2funcall

Common Lisp, "defined but never used"


This function compiles with warnings, fn is defined and never used in the first line, and that fn is an undefined function in the second line:

(defun test-function (fn)
  (funcall #'fn))

Why? A general explanation or a link to it would be great.

PD: Complete log:

test.lisp:9:1:                                                                             
  style-warning:                                                                           
    The variable FN is defined but never used.                                             
    --> PROGN SB-IMPL::%DEFUN SB-IMPL::%DEFUN SB-INT:NAMED-LAMBDA                          
    ==>                                                                                    
      #'(SB-INT:NAMED-LAMBDA TEST-FUNCTION                                                          
            (FN)                                                                           
          (BLOCK TEST-FUNCTION (FUNCALL #'FN)))                                                     


test.lisp:10:3:                                                                            
  style-warning:                                                                           
    undefined function: FN                                                                 
    ==>                                                                                    
      (SB-C::%FUNCALL #'FN)

Solution

  • If you want to call a function passed as parameter, or assigned to a variable, simply use the variable or parameter as first argument to funcall:

    (defun test-function(fn)
      (funcall fn))
    
    (test-function #'+)
    ;; => 0
    

    The notation #'X is an abbreviation for (function X), (see the manual), where X must be the name of a function, for instance defined with a defun or labels or flet, or a lambda expression. So, #'fn does not work since fn is not the name of a function, but a variable (in this case, a parameter).

    Common-Lisp is a Lisp-2, that is the namespace of functions is different from that of other variables. So the names of the functions are specials in the sense that you can call them directly in a form, while, if a function is assigned to a variable, it must be called with (funcall name-of-the-variable arguments).