#'
is just shorthand for function
, just as '
is shorthand for quote
.
You can use it anywhere where you want to indicate to the byte-compiler or the interpreter or a human reader that its argument is expected to be (is treated as) a function.
In many contexts the context determines how the argument is treated if, for example, you simply quote it (use quote
or '
) instead of using #'
(or function
). For example, in a context where a symbol is used only for its symbol-function
property, i.e., it is used as a function, you can just pass the symbol (e.g. by quoting it or passing a variable whose value is the symbol).
But sometimes code is clearer if you do use #'
in such contexts.
From (elisp) Anonymous Functions:
-- 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.