Go to the previous, next section.

Functions

A Lisp program is composed mainly of Lisp functions. This chapter explains what functions are, how they accept arguments, and how to define them.

What Is a Function?

In a general sense, a function is a rule for carrying on a computation given several values called arguments. The result of the computation is called the value of the function. The computation can also have side effects: lasting changes in the values of variables or the contents of data structures.

Here are important terms for functions in Emacs Lisp and for other function-like objects.

function
In Emacs Lisp, a function is anything that can be applied to arguments in a Lisp program. In some cases, we use it more specifically to mean a function written in Lisp. Special forms and macros are not functions.

primitive
A primitive is a function callable from Lisp that is written in C, such as car or append. These functions are also called built-in functions or subrs. (Special forms are also considered primitives.)

Usually the reason that a function is a primitives is because it is fundamental, or provides a low-level interface to operating system services, or because it needs to run fast. Primitives can be modified or added only by changing the C sources and recompiling the editor. See section Writing Emacs Primitives.

lambda expression
A lambda expression is a function written in Lisp. These are described in the following section.

special form
A special form is a primitive that is like a function but does not evaluate all of its arguments in the usual way. It may evaluate only some of the arguments, or may evaluate them in an unusual order, or several times. Many special forms are described in section Control Structures.

macro
A macro is a construct defined in Lisp by the programmer. It differs from a function in that it translates a Lisp expression that you write into an equivalent expression to be evaluated instead of the original expression. See section Macros, for how to define and use macros.

command
A command is an object that command-execute can invoke; it is a possible definition for a key sequence. Some functions are commands; a function written in Lisp is a command if it contains an interactive declaration (see section Defining Commands). Such a function can be called from Lisp expressions like other functions; in this case, the fact that the function is a command makes no difference.

Strings are commands also, even though they are not functions. A symbol is a command if its function definition is a command; such symbols can be invoked with M-x. The symbol is a function as well if the definition is a function. See section Command Loop Overview.

keystroke command
A keystroke command is a command that is bound to a key sequence (typically one to three keystrokes). The distinction is made here merely to avoid confusion with the meaning of "command" in non-Emacs editors; for programmers, the distinction is normally unimportant.

byte-code function
A byte-code function is a function that has been compiled by the byte compiler. See section Byte-Code Function Type.

Function: subrp object

This function returns t if object is a built-in function (i.e. a Lisp primitive).

(subrp 'message)            ; message is a symbol,
     => nil                 ;   not a subr object.
(subrp (symbol-function 'message))
     => t

Function: byte-code-function-p object

This function returns t if object is a byte-code function. For example:

(byte-code-function-p (symbol-function 'next-line))
     => t

Lambda Expressions

A function written in Lisp is a list that looks like this:

(lambda (arg-variables...)
  [documentation-string]
  [interactive-declaration]
  body-forms...)

(Such a list is called a lambda expression for historical reasons, even though it is not really an expression at all--it is not a form that can be evaluated meaningfully.)

Components of a Lambda Expression

The first element of a lambda expression is always the symbol lambda. This indicates that the list represents a function. The reason functions are defined to start with lambda is so that other lists, intended for other uses, will not accidentally be valid as functions.

The second element is a list of argument variable names (symbols). This is called the lambda list. When a Lisp function is called, the argument values are matched up against the variables in the lambda list, which are given local bindings with the values provided. See section Local Variables.

The documentation string is an actual string that serves to describe the function for the Emacs help facilities. See section Documentation Strings of Functions.

The interactive declaration is a list of the form (interactive code-string). This declares how to provide arguments if the function is used interactively. Functions with this declaration are called commands; they can be called using M-x or bound to a key. Functions not intended to be called in this way should not have interactive declarations. See section Defining Commands, for how to write an interactive declaration.

The rest of the elements are the body of the function: the Lisp code to do the work of the function (or, as a Lisp programmer would say, "a list of Lisp forms to evaluate"). The value returned by the function is the value returned by the last element of the body.

A Simple Lambda-Expression Example

Consider for example the following function:

(lambda (a b c) (+ a b c))

We can call this function by writing it as the CAR of an expression, like this:

((lambda (a b c) (+ a b c))
 1 2 3)

The body of this lambda expression is evaluated with the variable a bound to 1, b bound to 2, and c bound to 3. Evaluation of the body adds these three numbers, producing the result 6; therefore, this call to the function returns the value 6.

Note that the arguments can be the results of other function calls, as in this example:

((lambda (a b c) (+ a b c))
 1 (* 2 3) (- 5 4))

Here all the arguments 1, (* 2 3), and (- 5 4) are evaluated, left to right. Then the lambda expression is applied to the argument values 1, 6 and 1 to produce the value 8.

It is not often useful to write a lambda expression as the CAR of a form in this way. You can get the same result, of making local variables and giving them values, using the special form let (see section Local Variables). And let is clearer and easier to use. In practice, lambda expressions are either stored as the function definitions of symbols, to produce named functions, or passed as arguments to other functions (see section Anonymous Functions).

However, calls to explicit lambda expressions were very useful in the old days of Lisp, before the special form let was invented. At that time, they were the only way to bind and initialize local variables.

Advanced Features of Argument Lists

Our simple sample function, (lambda (a b c) (+ a b c)), specifies three argument variables, so it must be called with three arguments: if you try to call it with only two arguments or four arguments, you get a wrong-number-of-arguments error.

It is often convenient to write a function that allows certain arguments to be omitted. For example, the function substring accepts three arguments--a string, the start index and the end index--but the third argument defaults to the end of the string if you omit it. It is also convenient for certain functions to accept an indefinite number of arguments, as the functions and and + do.

To specify optional arguments that may be omitted when a function is called, simply include the keyword &optional before the optional arguments. To specify a list of zero or more extra arguments, include the keyword &rest before one final argument.

Thus, the complete syntax for an argument list is as follows:

(required-vars...
 [&optional optional-vars...]
 [&rest rest-var])

The square brackets indicate that the &optional and &rest clauses, and the variables that follow them, are optional.

A call to the function requires one actual argument for each of the required-vars. There may be actual arguments for zero or more of the optional-vars, and there cannot be any more actual arguments than these unless &rest exists. In that case, there may be any number of extra actual arguments.

If actual arguments for the optional and rest variables are omitted, then they always default to nil. However, the body of the function is free to consider nil an abbreviation for some other meaningful value. This is what substring does; nil as the third argument means to use the length of the string supplied. There is no way for the function to distinguish between an explicit argument of nil and an omitted argument.

Common Lisp note: Common Lisp allows the function to specify what default value to use when an optional argument is omitted; GNU Emacs Lisp always uses nil.

For example, an argument list that looks like this:

(a b &optional c d &rest e)

binds a and b to the first two actual arguments, which are required. If one or two more arguments are provided, c and d are bound to them respectively; any arguments after the first four are collected into a list and e is bound to that list. If there are only two arguments, c is nil; if two or three arguments, d is nil; if four arguments or fewer, e is nil.

There is no way to have required arguments following optional ones--it would not make sense. To see why this must be so, suppose that c in the example were optional and d were required. If three actual arguments are given; then which variable would the third argument be for? Similarly, it makes no sense to have any more arguments (either required or optional) after a &rest argument.

Here are some examples of argument lists and proper calls:

((lambda (n) (1+ n))                ; One required:
 1)                                 ; requires exactly one argument.
     => 2
((lambda (n &optional n1)           ; One required and one optional:
         (if n1 (+ n n1) (1+ n)))   ; 1 or 2 arguments.
 1 2)
     => 3
((lambda (n &rest ns)               ; One required and one rest:
         (+ n (apply '+ ns)))       ; 1 or more arguments.
 1 2 3 4 5)
     => 15

Documentation Strings of Functions

A lambda expression may optionally have a documentation string just after the lambda list. This string does not affect execution of the function; it is a kind of comment, but a systematized comment which actually appears inside the Lisp world and can be used by the Emacs help facilities. See section Documentation, for how the documentation-string is accessed.

It is a good idea to provide documentation strings for all commands, and for all other functions in your program that users of your program should know about; internal functions might as well have only comments, since comments don't take up any room when your program is loaded.

The first line of the documentation string should stand on its own, because apropos displays just this first line. It should consist of one or two complete sentences that summarize the function's purpose.

The start of the documentation string is usually indented, but since these spaces come before the starting double-quote, they are not part of the string. Some people make a practice of indenting any additional lines of the string so that the text lines up. This is a mistake. The indentation of the following lines is inside the string; what looks nice in the source code will look ugly when displayed by the help commands.

You may wonder how the documentation string could be optional, since there are required components of the function that follow it (the body). Since evaluation of a string returns that string, without any side effects, it has no effect if it is not the last form in the body. Thus, in practice, there is no confusion between the first form of the body and the documentation string; if the only body form is a string then it serves both as the return value and as the documentation.

Naming a Function

In most computer languages, every function has a name; the idea of a function without a name is nonsensical. In Lisp, a function in the strictest sense has no name. It is simply a list whose first element is lambda, or a primitive subr-object.

However, a symbol can serve as the name of a function. This happens when you put the function in the symbol's function cell (see section Symbol Components). Then the symbol itself becomes a valid, callable function, equivalent to the list or subr-object that its function cell refers to. The contents of the function cell are also called the symbol's function definition. When the evaluator finds the function definition to use in place of the symbol, we call that symbol function indirection; see section Symbol Function Indirection.

In practice, nearly all functions are given names in this way and referred to through their names. For example, the symbol car works as a function and does what it does because the primitive subr-object #<subr car> is stored in its function cell.

We give functions names because it is more convenient to refer to them by their names in other functions. For primitive subr-objects such as #<subr car>, names are the only way you can refer to them: there is no read syntax for such objects. For functions written in Lisp, the name is more convenient to use in a call than an explicit lambda expression. Also, a function with a name can refer to itself--it can be recursive. Writing the function's name in its own definition is much more convenient than making the function definition point to itself (something that is not impossible but that has various disadvantages in practice).

Functions are often identified with the symbols used to name them. For example, we often speak of "the function car", not distinguishing between the symbol car and the primitive subr-object that is its function definition. For most purposes, there is no need to distinguish.

Even so, keep in mind that a function need not have a unique name. While a given function object usually appears in the function cell of only one symbol, this is just a matter of convenience. It is easy to store it in several symbols using fset; then each of the symbols is equally well a name for the same function.

A symbol used as a function name may also be used as a variable; these two uses of a symbol are independent and do not conflict.

Defining Named Functions

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.

Special Form: defun name argument-list body-forms

defun is 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)

This lambda expression is stored in the function cell of name. The value returned by evaluating the defun form is name, but usually we ignore this value.

As described previously (see section Lambda Expressions), argument-list is a list of argument names and may include the keywords &optional and &rest. Also, the first two forms in body-forms may be a documentation string and an interactive declaration.

Note that the same symbol name may also be used as a global variable, since the value cell is independent of the function cell.

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-backwards

Be careful not to redefine existing functions unintentionally. defun redefines even primitive functions such as car without 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.

Calling Functions

Defining functions is only half the battle. Functions don't do anything until you call them, i.e., tell them to run. This process is also known as invocation.

The most common way of invoking a function is by evaluating a list. For example, evaluating the list (concat "a" "b") calls the function concat. See section Evaluation, for a description of evaluation.

When you write a list as an expression in your program, the function name is part of the program. This means that the choice of which function to call is made when you write the program. Usually that's just what you want. Occasionally you need to decide at run time which function to call. Then you can use the functions funcall and apply.

Function: funcall function &rest arguments

funcall calls function with arguments, and returns whatever function returns.

Since funcall is a function, all of its arguments, including function, are evaluated before funcall is called. This means that you can use any expression to obtain the function to be called. It also means that funcall does not see the expressions you write for the arguments, only their values. These values are not evaluated a second time in the act of calling function; funcall enters the normal procedure for calling a function at the place where the arguments have already been evaluated.

The argument function must be either a Lisp function or a primitive function. Special forms and macros are not allowed, because they make sense only when given the "unevaluated" argument expressions. funcall cannot provide these because, as we saw above, it never knows them in the first place.

(setq f 'list)
     => list
(funcall f 'x 'y 'z)
     => (x y z)
(funcall f 'x 'y '(z))
     => (x y (z))
(funcall 'and t nil)
error--> Invalid function: #<subr and>

Compare this example with that of apply.

Function: apply function &rest arguments

apply calls function with arguments, just like funcall but with one difference: the last of arguments is a list of arguments to give to function, rather than a single argument. We also say that this list is appended to the other arguments.

apply returns the result of calling function. As with funcall, function must either be a Lisp function or a primitive function; special forms and macros do not make sense in apply.

(setq f 'list)
     => list
(apply f 'x 'y 'z)
error--> Wrong type argument: listp, z
(apply '+ 1 2 '(3 4))
     => 10
(apply '+ '(1 2 3 4))
     => 10

(apply 'append '((a b c) nil (x y z) nil))
     => (a b c x y z)

An interesting example of using apply is found in the description of mapcar; see the following section.

It is common for Lisp functions to accept functions as arguments or find them in data structures (especially in hook variables and property lists) and call them using funcall or apply. Functions that accept function arguments are often called functionals.

Sometimes, when you call such a function, it is useful to supply a no-op function as the argument. Here are two different kinds of no-op function:

Function: identity arg

This function returns arg and has no side effects.

Function: ignore &rest args

This function ignores any arguments and returns nil.

Mapping Functions

A mapping function applies a given function to each element of a list or other collection. Emacs Lisp has three such functions; mapcar and mapconcat, which scan a list, are described here. For the third mapping function, mapatoms, see section Creating and Interning Symbols.

Function: mapcar function sequence

mapcar applies function to each element of sequence in turn. The results are made into a nil-terminated list.

The argument sequence may be a list, a vector or a string. The result is always a list. The length of the result is the same as the length of sequence.

For example:

(mapcar 'car '((a b) (c d) (e f)))
     => (a c e)
(mapcar '1+ [1 2 3])
     => (2 3 4)
(mapcar 'char-to-string "abc")
     => ("a" "b" "c")

;; Call each function in my-hooks.
(mapcar 'funcall my-hooks)

(defun mapcar* (f &rest args)
  "Apply FUNCTION to successive cars of all ARGS, until one
ends.  Return the list of results."
  ;; If no list is exhausted,
  (if (not (memq 'nil args))              
      ;; Apply function to CARs.
      (cons (apply f (mapcar 'car args))  
            (apply 'mapcar* f             
                   ;; Recurse for rest of elements.
                   (mapcar 'cdr args)))))

(mapcar* 'cons '(a b c) '(1 2 3 4))
     => ((a . 1) (b . 2) (c . 3))

Function: mapconcat function sequence separator

mapconcat applies function to each element of sequence: the results, which must be strings, are concatenated. Between each pair of result strings, mapconcat inserts the string separator. Usually separator contains a space or comma or other suitable punctuation.

The argument function must be a function that can take one argument and returns a string.

(mapconcat 'symbol-name
           '(The cat in the hat)
           " ")
     => "The cat in the hat"

(mapconcat (function (lambda (x) (format "%c" (1+ x))))
           "HAL-8000"
           "")
     => "IBM.9111"

Anonymous Functions

In Lisp, a function is a list that starts with lambda (or alternatively a primitive subr-object); names are "extra". Although usually functions are defined with defun and given names at the same time, it is occasionally more concise to use an explicit lambda expression--an anonymous function. Such a list is valid wherever a function name is.

Any method of creating such a list makes a valid function. Even this:

(setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
     => (lambda (x) (+ 12 x))

This computes a list that looks like (lambda (x) (+ 12 x)) and makes it the value (not the function definition!) of silly.

Here is how we might call this function:

(funcall silly 1)
     => 13

(It does not work to write (silly 1), because this function is not the function definition of silly. We have not given silly any function definition, just a value as a variable.)

Most of the time, anonymous functions are constants that appear in your program. For example, you might want to pass one as an argument to the function mapcar, which applies any given function to each element of a list. Here we pass an anonymous function that multiplies a number by two:

(defun double-each (list)
  (mapcar '(lambda (x) (* 2 x)) list))
     => double-each
(double-each '(2 11))
     => (4 22)

In such cases, we usually use the special form function instead of simple quotation to quote the anonymous function.

Special Form: function function-object

This special form returns function-object without evaluating it. In this, it is equivalent to quote. However, it serves as a note to the Emacs Lisp compiler that function-object is intended to be used only as a function, and therefore can safely be compiled. See section Quoting, for comparison.

Using function instead of quote makes a difference inside a function or macro that you are going to compile. For example:

(defun double-each (list)
  (mapcar (function (lambda (x) (* 2 x))) list))
     => double-each
(double-each '(2 11))
     => (4 22)

If this definition of double-each is compiled, the anonymous function is compiled as well. By contrast, in the previous definition where ordinary quote is used, the argument passed to mapcar is the precise list shown:

(lambda (arg) (+ arg 5))

The Lisp compiler cannot assume this list is a function, even though it looks like one, since it does not know what mapcar does with the list. Perhaps mapcar will check that the CAR of the third element is the symbol +! The advantage of function is that it tells the compiler to go ahead and compile the constant function.

We sometimes write function instead of quote when quoting the name of a function, but this usage is just a sort of comment.

(function symbol) == (quote symbol) == 'symbol

See documentation in section Access to Documentation Strings, for a realistic example using function and an anonymous function.

Accessing Function Cell Contents

The function definition of a symbol is the object stored in the function cell of the symbol. The functions described here access, test, and set the function cell of symbols.

Function: symbol-function symbol

This returns the object in the function cell of symbol. If the symbol's function cell is void, a void-function error is signaled.

This function does not check that the returned object is a legitimate function.

(defun bar (n) (+ n 2))
     => bar
(symbol-function 'bar)
     => (lambda (n) (+ n 2))
(fset 'baz 'bar)
     => bar
(symbol-function 'baz)
     => bar

If you have never given a symbol any function definition, we say that that symbol's function cell is void. In other words, the function cell does not have any Lisp object in it. If you try to call such a symbol as a function, it signals a void-function error.

Note that void is not the same as nil or the symbol void. The symbols nil and void are Lisp objects, and can be stored into a function cell just as any other object can be (and they can be valid functions if you define them in turn with defun); but nil or void is an object. A void function cell contains no object whatsoever.

You can test the voidness of a symbol's function definition with fboundp. After you have given a symbol a function definition, you can make it void once more using fmakunbound.

Function: fboundp symbol

Returns t if the symbol has an object in its function cell, nil otherwise. It does not check that the object is a legitimate function.

Function: fmakunbound symbol

This function makes symbol's function cell void, so that a subsequent attempt to access this cell will cause a void-function error. (See also makunbound, in section Local Variables.)

(defun foo (x) x)
     => x
(fmakunbound 'foo)
     => x
(foo 1)
error--> Symbol's function definition is void: foo

Function: fset symbol object

This function stores object in the function cell of symbol. The result is object. Normally object should be a function or the name of a function, but this is not checked.

There are three normal uses of this function:

Here are examples of the first two uses:

;; Give first the same definition car has.
(fset 'first (symbol-function 'car))
     => #<subr car>
(first '(1 2 3))
     => 1

;; Make the symbol car the function definition of xfirst.
(fset 'xfirst 'car)
     => car
(xfirst '(1 2 3))
     => 1
(symbol-function 'xfirst)
     => car
(symbol-function (symbol-function 'xfirst))
     => #<subr car>

;; Define a named keyboard macro.
(fset 'kill-two-lines "\^u2\^k")
     => "\^u2\^k"

When writing a function that extends a previously defined function, the following idiom is often used:

(fset 'old-foo (symbol-function 'foo))

(defun foo ()
  "Just like old-foo, except more so."
  (old-foo)
  (more-so))

This does not work properly if foo has been defined to autoload. In such a case, when foo calls old-foo, Lisp attempts to define old-foo by loading a file. Since this presumably defines foo rather than old-foo, it does not produce the proper results. The only way to avoid this problem is to make sure the file is loaded before moving aside the old definition of foo.

See also the function indirect-function in section Symbol Function Indirection.

Inline Functions

You can define an inline function by using defsubst instead of defun. An inline function works just like an ordinary function except for one thing: when you compile a call to the function, the function's definition is open-coded into the caller.

Making a function inline makes explicit calls run faster. But it also has disadvantages. For one thing, it reduces flexibility; if you change the definition of the function, calls already inlined still use the old definition until you recompile them.

Another disadvantage is that making a large function inline can increase the size of compiled code both in files and in memory. Since the advantages of inline functions are greatest for small functions, you generally should not make large functions inline.

It's possible to define a macro to expand into the same code that an inline function would execute. But the macro would have a limitation: you can use it only explicitly--a macro cannot be called with apply, mapcar and so on. Also, it takes some work to convert an ordinary function into a macro. (See section Macros.) To convert it into an inline function is very easy; simply replace defun with defsubst.

Inline functions can be used and open coded later on in the same file, following the definition, just like macros.

Emacs versions prior to 19 did not have inline functions.

Other Topics Related to Functions

Here is a table of several functions that do things related to function calling and function definitions. They are documented elsewhere, but we provide cross references here.

apply
See section Calling Functions.

autoload
See section Autoload.

call-interactively
See section Interactive Call.

commandp
See section Interactive Call.

documentation
See section Access to Documentation Strings.

eval
See section Eval.

funcall
See section Calling Functions.

ignore
See section Calling Functions.

indirect-function
See section Symbol Function Indirection.

interactive
See section Using interactive.

interactive-p
See section Interactive Call.

mapatoms
See section Creating and Interning Symbols.

mapcar
See section Mapping Functions.

mapconcat
See section Mapping Functions.

undefined
See section Key Lookup.

Go to the previous, next section.