Why are some function symbols sharp-quoted?

#'symbol is short for (function symbol) , the same way ’symbol is short for (quote symbol) .

You’d use it to indicate to the byte-compiler or a human reader that a symbol is expected to be treated as a function (rather than a literal data value).

At runtime the sharp-quote serves no functional purpose like it does in other lisps. (funcall 'some-function) would work just as well as (funcall #'some-function). The sole difference is at compile-time: the byte-compiler will perform additional checks on function symbols, e.g. warn you if a function isn’t known to be defined where it is used.

In the wild, you’ll find snippets of Emacs Lisp where lambdas are sharp-quoted, like so: #'(lambda (x) (* x x)). This takes after a convention found in other lisps, but is unnecessary in Emacs Lisp. To quote the documentation for function:

– Special Form: function function-object

This special form returns FUNCTION-OBJECT without evaluating it.

In this, it is similar to quote (*note Quoting::). But unlike quote , it also serves as a note to the Emacs evaluator and byte-compiler that FUNCTION-OBJECT is intended to be used as a function. Assuming FUNCTION-OBJECT is a valid lambda expression, this has two effects:

• When the code is byte-compiled, FUNCTION-OBJECT is compiled into a byte-code function object (*note Byte Compilation::).

• When lexical binding is enabled, FUNCTION-OBJECT is converted into a closure. *Note Closures::.

The read syntax #' is a short-hand for using function . The following forms are all equivalent:

(lambda (x) (* x x))
(function (lambda (x) (* x x)))
#'(lambda (x) (* x x))

In the following example, we define a change-property function that takes a function as its third argument, followed by a double-property function that makes use of change-property by passing it an anonymous function:

(defun change-property (symbol prop function)
   (let ((value (get symbol prop)))
     (put symbol prop (funcall function value))))

(defun double-property (symbol prop)
   (change-property symbol prop (lambda (x) (* 2 x))))

Note that we do not quote the lambda form.

If you compile the above code, the anonymous function is also compiled. This would not happen if, say, you had constructed the anonymous function by quoting it as a list:

(defun double-property (symbol prop)
   (change-property symbol prop '(lambda (x) (* 2 x))))

In that case, the anonymous function is kept as a lambda expression in the compiled code. The byte-compiler cannot assume this list is a function, even though it looks like one, since it does not know that change-property intends to use it as a function.


More information about symbols in elisp: http://ergoemacs.org/emacs_manual/elisp/Symbol-Components.html