We usually give a name to a function when it is first created. This
is called defining a function, and it is done with the
defun special form.
defunis the usual way to define new Lisp functions. It defines the symbol name as a function that looks like this:(lambda argument-list . body-forms)
defunstores this lambda expression in the function cell of name. It returns the value name, but usually we ignore this value.As described previously, argument-list is a list of argument names and may include the keywords
&optionaland&rest(see Lambda Expressions). Also, the first two of the body-forms may be a documentation string and an interactive declaration.There is no conflict if the same symbol name is also used as a variable, since the symbol's value cell is independent of the function cell. See Symbol Components.
Here are some examples:
(defun foo () 5) ⇒ foo (foo) ⇒ 5 (defun bar (a &optional b &rest c) (list a b c)) ⇒ bar (bar 1 2 3 4 5) ⇒ (1 2 (3 4 5)) (bar 1) ⇒ (1 nil nil) (bar) error--> Wrong number of arguments. (defun capitalize-backwards () "Upcase the last letter of a word." (interactive) (backward-word 1) (forward-word 1) (backward-char 1) (capitalize-word 1)) ⇒ capitalize-backwardsBe careful not to redefine existing functions unintentionally.
defunredefines even primitive functions such ascarwithout any hesitation or notification. Redefining a function already defined is often done deliberately, and there is no way to distinguish deliberate redefinition from unintentional redefinition.
This special form defines the symbol name as a function, with definition definition (which can be any valid Lisp function). It returns definition.
If docstring is non-
nil, it becomes the function documentation of name. Otherwise, any documentation provided by definition is used.The proper place to use
defaliasis where a specific function name is being defined—especially where that name appears explicitly in the source file being loaded. This is becausedefaliasrecords which file defined the function, just likedefun(see Unloading).By contrast, in programs that manipulate function definitions for other purposes, it is better to use
fset, which does not keep such records. See Function Cells.
You cannot create a new primitive function with defun or
defalias, but you can use them to change the function definition of
any symbol, even one such as car or x-popup-menu whose
normal definition is a primitive. However, this is risky: for
instance, it is next to impossible to redefine car without
breaking Lisp completely. Redefining an obscure function such as
x-popup-menu is less dangerous, but it still may not work as
you expect. If there are calls to the primitive from C code, they
call the primitive's C definition directly, so changing the symbol's
definition will have no effect on them.
See also defsubst, which defines a function like defun
and tells the Lisp compiler to open-code it. See Inline Functions.