The less-familiar parts of Lisp for beginners — fdefinition

We move on now to fdefinition.  This is a fairly short topic, but before reviewing it, you might want to read the article on fboundp, if you have not yet read it.

The fdefinition accessor provides a means for setting or reading the function object associated with a particular symbol in the function symbol table.  As such, it is, like fboundp, also unaffected by lexical functions or macros created with flet, labels, or macrolet.

The uses of this accessor are fairly esoteric.  It can certainly be used as part of the implementation of the defun macro, or in the implementations of functions that are passed function symbols, like apply, funcall, and mapcar.  It can also be used to sniff the type of function that is bound, after fboundp returns non-nil.  There might be some rare contexts in which the programmer needs the code to determine whether a particular passed symbol points to a function or macro, or to a generic function, and fdefinition is part of the means for answering that question.  In everyday programming, though, you are unlikely to need to use this feature.

CL-USER> (defun my-adder (x)
           (+ 1 x))
CL-USER> (my-adder 2)
CL-USER> (setf (fdefinition 'my-adder) #'(lambda (x) (+ x 10)))
#<FUNCTION (LAMBDA (X)) {100673943B}>
CL-USER> (my-adder 2)

An example of examining the type of a symbol:
(defun what-symbol (sym)
    ((fboundp sym)
     (typecase (fdefinition sym)
        (format t "~A is a generic function~%" sym))
        (format t "~A is a (non-generic) function~%" sym))
        (format t "~A is not a function~%"))))
     (format t "~A is not bound in the function symbol table.~%" sym))))

Edit #1:  2014-02-02

Please do not attach too much to the vague and possibly misleading “function symbol table” language I’ve used above.  Instead, look over this later article that I hope provides some more precise details on what is really happening.  It’s not merely a semantic distinction, the material there is important to understand when programming in Lisp.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.