]> code.delx.au - gnu-emacs/blob - lispref/functions.texi
@ifinto -> @ifnottex.
[gnu-emacs] / lispref / functions.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998, 1999
4 @c Free Software Foundation, Inc.
5 @c See the file elisp.texi for copying conditions.
6 @setfilename ../info/functions
7 @node Functions, Macros, Variables, Top
8 @chapter Functions
9
10 A Lisp program is composed mainly of Lisp functions. This chapter
11 explains what functions are, how they accept arguments, and how to
12 define them.
13
14 @menu
15 * What Is a Function:: Lisp functions vs. primitives; terminology.
16 * Lambda Expressions:: How functions are expressed as Lisp objects.
17 * Function Names:: A symbol can serve as the name of a function.
18 * Defining Functions:: Lisp expressions for defining functions.
19 * Calling Functions:: How to use an existing function.
20 * Mapping Functions:: Applying a function to each element of a list, etc.
21 * Anonymous Functions:: Lambda expressions are functions with no names.
22 * Function Cells:: Accessing or setting the function definition
23 of a symbol.
24 * Inline Functions:: Defining functions that the compiler will open code.
25 * Related Topics:: Cross-references to specific Lisp primitives
26 that have a special bearing on how functions work.
27 @end menu
28
29 @node What Is a Function
30 @section What Is a Function?
31
32 In a general sense, a function is a rule for carrying on a computation
33 given several values called @dfn{arguments}. The result of the
34 computation is called the value of the function. The computation can
35 also have side effects: lasting changes in the values of variables or
36 the contents of data structures.
37
38 Here are important terms for functions in Emacs Lisp and for other
39 function-like objects.
40
41 @table @dfn
42 @item function
43 @cindex function
44 In Emacs Lisp, a @dfn{function} is anything that can be applied to
45 arguments in a Lisp program. In some cases, we use it more
46 specifically to mean a function written in Lisp. Special forms and
47 macros are not functions.
48
49 @item primitive
50 @cindex primitive
51 @cindex subr
52 @cindex built-in function
53 A @dfn{primitive} is a function callable from Lisp that is written in C,
54 such as @code{car} or @code{append}. These functions are also called
55 @dfn{built-in} functions or @dfn{subrs}. (Special forms are also
56 considered primitives.)
57
58 Usually the reason we implement a function as a primitive is either
59 because it is fundamental, because it provides a low-level interface to
60 operating system services, or because it needs to run fast. Primitives
61 can be modified or added only by changing the C sources and recompiling
62 the editor. See @ref{Writing Emacs Primitives}.
63
64 @item lambda expression
65 A @dfn{lambda expression} is a function written in Lisp.
66 These are described in the following section.
67 @ifnottex
68 @xref{Lambda Expressions}.
69 @end ifnottex
70
71 @item special form
72 A @dfn{special form} is a primitive that is like a function but does not
73 evaluate all of its arguments in the usual way. It may evaluate only
74 some of the arguments, or may evaluate them in an unusual order, or
75 several times. Many special forms are described in @ref{Control
76 Structures}.
77
78 @item macro
79 @cindex macro
80 A @dfn{macro} is a construct defined in Lisp by the programmer. It
81 differs from a function in that it translates a Lisp expression that you
82 write into an equivalent expression to be evaluated instead of the
83 original expression. Macros enable Lisp programmers to do the sorts of
84 things that special forms can do. @xref{Macros}, for how to define and
85 use macros.
86
87 @item command
88 @cindex command
89 A @dfn{command} is an object that @code{command-execute} can invoke; it
90 is a possible definition for a key sequence. Some functions are
91 commands; a function written in Lisp is a command if it contains an
92 interactive declaration (@pxref{Defining Commands}). Such a function
93 can be called from Lisp expressions like other functions; in this case,
94 the fact that the function is a command makes no difference.
95
96 Keyboard macros (strings and vectors) are commands also, even though
97 they are not functions. A symbol is a command if its function
98 definition is a command; such symbols can be invoked with @kbd{M-x}.
99 The symbol is a function as well if the definition is a function.
100 @xref{Command Overview}.
101
102 @item keystroke command
103 @cindex keystroke command
104 A @dfn{keystroke command} is a command that is bound to a key sequence
105 (typically one to three keystrokes). The distinction is made here
106 merely to avoid confusion with the meaning of ``command'' in non-Emacs
107 editors; for Lisp programs, the distinction is normally unimportant.
108
109 @item byte-code function
110 A @dfn{byte-code function} is a function that has been compiled by the
111 byte compiler. @xref{Byte-Code Type}.
112 @end table
113
114 @defun functionp object
115 This function returns @code{t} if @var{object} is any kind of function,
116 or a special form or macro.
117 @end defun
118
119 @defun subrp object
120 This function returns @code{t} if @var{object} is a built-in function
121 (i.e., a Lisp primitive).
122
123 @example
124 @group
125 (subrp 'message) ; @r{@code{message} is a symbol,}
126 @result{} nil ; @r{not a subr object.}
127 @end group
128 @group
129 (subrp (symbol-function 'message))
130 @result{} t
131 @end group
132 @end example
133 @end defun
134
135 @defun byte-code-function-p object
136 This function returns @code{t} if @var{object} is a byte-code
137 function. For example:
138
139 @example
140 @group
141 (byte-code-function-p (symbol-function 'next-line))
142 @result{} t
143 @end group
144 @end example
145 @end defun
146
147 @node Lambda Expressions
148 @section Lambda Expressions
149 @cindex lambda expression
150
151 A function written in Lisp is a list that looks like this:
152
153 @example
154 (lambda (@var{arg-variables}@dots{})
155 @r{[}@var{documentation-string}@r{]}
156 @r{[}@var{interactive-declaration}@r{]}
157 @var{body-forms}@dots{})
158 @end example
159
160 @noindent
161 Such a list is called a @dfn{lambda expression}. In Emacs Lisp, it
162 actually is valid as an expression---it evaluates to itself. In some
163 other Lisp dialects, a lambda expression is not a valid expression at
164 all. In either case, its main use is not to be evaluated as an
165 expression, but to be called as a function.
166
167 @menu
168 * Lambda Components:: The parts of a lambda expression.
169 * Simple Lambda:: A simple example.
170 * Argument List:: Details and special features of argument lists.
171 * Function Documentation:: How to put documentation in a function.
172 @end menu
173
174 @node Lambda Components
175 @subsection Components of a Lambda Expression
176
177 @ifnottex
178
179 A function written in Lisp (a ``lambda expression'') is a list that
180 looks like this:
181
182 @example
183 (lambda (@var{arg-variables}@dots{})
184 [@var{documentation-string}]
185 [@var{interactive-declaration}]
186 @var{body-forms}@dots{})
187 @end example
188 @end ifnottex
189
190 @cindex lambda list
191 The first element of a lambda expression is always the symbol
192 @code{lambda}. This indicates that the list represents a function. The
193 reason functions are defined to start with @code{lambda} is so that
194 other lists, intended for other uses, will not accidentally be valid as
195 functions.
196
197 The second element is a list of symbols---the argument variable names.
198 This is called the @dfn{lambda list}. When a Lisp function is called,
199 the argument values are matched up against the variables in the lambda
200 list, which are given local bindings with the values provided.
201 @xref{Local Variables}.
202
203 The documentation string is a Lisp string object placed within the
204 function definition to describe the function for the Emacs help
205 facilities. @xref{Function Documentation}.
206
207 The interactive declaration is a list of the form @code{(interactive
208 @var{code-string})}. This declares how to provide arguments if the
209 function is used interactively. Functions with this declaration are called
210 @dfn{commands}; they can be called using @kbd{M-x} or bound to a key.
211 Functions not intended to be called in this way should not have interactive
212 declarations. @xref{Defining Commands}, for how to write an interactive
213 declaration.
214
215 @cindex body of function
216 The rest of the elements are the @dfn{body} of the function: the Lisp
217 code to do the work of the function (or, as a Lisp programmer would say,
218 ``a list of Lisp forms to evaluate''). The value returned by the
219 function is the value returned by the last element of the body.
220
221 @node Simple Lambda
222 @subsection A Simple Lambda-Expression Example
223
224 Consider for example the following function:
225
226 @example
227 (lambda (a b c) (+ a b c))
228 @end example
229
230 @noindent
231 We can call this function by writing it as the @sc{car} of an
232 expression, like this:
233
234 @example
235 @group
236 ((lambda (a b c) (+ a b c))
237 1 2 3)
238 @end group
239 @end example
240
241 @noindent
242 This call evaluates the body of the lambda expression with the variable
243 @code{a} bound to 1, @code{b} bound to 2, and @code{c} bound to 3.
244 Evaluation of the body adds these three numbers, producing the result 6;
245 therefore, this call to the function returns the value 6.
246
247 Note that the arguments can be the results of other function calls, as in
248 this example:
249
250 @example
251 @group
252 ((lambda (a b c) (+ a b c))
253 1 (* 2 3) (- 5 4))
254 @end group
255 @end example
256
257 @noindent
258 This evaluates the arguments @code{1}, @code{(* 2 3)}, and @code{(- 5
259 4)} from left to right. Then it applies the lambda expression to the
260 argument values 1, 6 and 1 to produce the value 8.
261
262 It is not often useful to write a lambda expression as the @sc{car} of
263 a form in this way. You can get the same result, of making local
264 variables and giving them values, using the special form @code{let}
265 (@pxref{Local Variables}). And @code{let} is clearer and easier to use.
266 In practice, lambda expressions are either stored as the function
267 definitions of symbols, to produce named functions, or passed as
268 arguments to other functions (@pxref{Anonymous Functions}).
269
270 However, calls to explicit lambda expressions were very useful in the
271 old days of Lisp, before the special form @code{let} was invented. At
272 that time, they were the only way to bind and initialize local
273 variables.
274
275 @node Argument List
276 @subsection Other Features of Argument Lists
277 @kindex wrong-number-of-arguments
278 @cindex argument binding
279 @cindex binding arguments
280
281 Our simple sample function, @code{(lambda (a b c) (+ a b c))},
282 specifies three argument variables, so it must be called with three
283 arguments: if you try to call it with only two arguments or four
284 arguments, you get a @code{wrong-number-of-arguments} error.
285
286 It is often convenient to write a function that allows certain
287 arguments to be omitted. For example, the function @code{substring}
288 accepts three arguments---a string, the start index and the end
289 index---but the third argument defaults to the @var{length} of the
290 string if you omit it. It is also convenient for certain functions to
291 accept an indefinite number of arguments, as the functions @code{list}
292 and @code{+} do.
293
294 @cindex optional arguments
295 @cindex rest arguments
296 @kindex &optional
297 @kindex &rest
298 To specify optional arguments that may be omitted when a function
299 is called, simply include the keyword @code{&optional} before the optional
300 arguments. To specify a list of zero or more extra arguments, include the
301 keyword @code{&rest} before one final argument.
302
303 Thus, the complete syntax for an argument list is as follows:
304
305 @example
306 @group
307 (@var{required-vars}@dots{}
308 @r{[}&optional @var{optional-vars}@dots{}@r{]}
309 @r{[}&rest @var{rest-var}@r{]})
310 @end group
311 @end example
312
313 @noindent
314 The square brackets indicate that the @code{&optional} and @code{&rest}
315 clauses, and the variables that follow them, are optional.
316
317 A call to the function requires one actual argument for each of the
318 @var{required-vars}. There may be actual arguments for zero or more of
319 the @var{optional-vars}, and there cannot be any actual arguments beyond
320 that unless the lambda list uses @code{&rest}. In that case, there may
321 be any number of extra actual arguments.
322
323 If actual arguments for the optional and rest variables are omitted,
324 then they always default to @code{nil}. There is no way for the
325 function to distinguish between an explicit argument of @code{nil} and
326 an omitted argument. However, the body of the function is free to
327 consider @code{nil} an abbreviation for some other meaningful value.
328 This is what @code{substring} does; @code{nil} as the third argument to
329 @code{substring} means to use the length of the string supplied.
330
331 @cindex CL note---default optional arg
332 @quotation
333 @b{Common Lisp note:} Common Lisp allows the function to specify what
334 default value to use when an optional argument is omitted; Emacs Lisp
335 always uses @code{nil}. Emacs Lisp does not support ``supplied-p''
336 variables that tell you whether an argument was explicitly passed.
337 @end quotation
338
339 For example, an argument list that looks like this:
340
341 @example
342 (a b &optional c d &rest e)
343 @end example
344
345 @noindent
346 binds @code{a} and @code{b} to the first two actual arguments, which are
347 required. If one or two more arguments are provided, @code{c} and
348 @code{d} are bound to them respectively; any arguments after the first
349 four are collected into a list and @code{e} is bound to that list. If
350 there are only two arguments, @code{c} is @code{nil}; if two or three
351 arguments, @code{d} is @code{nil}; if four arguments or fewer, @code{e}
352 is @code{nil}.
353
354 There is no way to have required arguments following optional
355 ones---it would not make sense. To see why this must be so, suppose
356 that @code{c} in the example were optional and @code{d} were required.
357 Suppose three actual arguments are given; which variable would the third
358 argument be for? Similarly, it makes no sense to have any more
359 arguments (either required or optional) after a @code{&rest} argument.
360
361 Here are some examples of argument lists and proper calls:
362
363 @smallexample
364 ((lambda (n) (1+ n)) ; @r{One required:}
365 1) ; @r{requires exactly one argument.}
366 @result{} 2
367 ((lambda (n &optional n1) ; @r{One required and one optional:}
368 (if n1 (+ n n1) (1+ n))) ; @r{1 or 2 arguments.}
369 1 2)
370 @result{} 3
371 ((lambda (n &rest ns) ; @r{One required and one rest:}
372 (+ n (apply '+ ns))) ; @r{1 or more arguments.}
373 1 2 3 4 5)
374 @result{} 15
375 @end smallexample
376
377 @node Function Documentation
378 @subsection Documentation Strings of Functions
379 @cindex documentation of function
380
381 A lambda expression may optionally have a @dfn{documentation string} just
382 after the lambda list. This string does not affect execution of the
383 function; it is a kind of comment, but a systematized comment which
384 actually appears inside the Lisp world and can be used by the Emacs help
385 facilities. @xref{Documentation}, for how the @var{documentation-string} is
386 accessed.
387
388 It is a good idea to provide documentation strings for all the
389 functions in your program, even those that are called only from within
390 your program. Documentation strings are like comments, except that they
391 are easier to access.
392
393 The first line of the documentation string should stand on its own,
394 because @code{apropos} displays just this first line. It should consist
395 of one or two complete sentences that summarize the function's purpose.
396
397 The start of the documentation string is usually indented in the source file,
398 but since these spaces come before the starting double-quote, they are not part of
399 the string. Some people make a practice of indenting any additional
400 lines of the string so that the text lines up in the program source.
401 @emph{This is a mistake.} The indentation of the following lines is
402 inside the string; what looks nice in the source code will look ugly
403 when displayed by the help commands.
404
405 You may wonder how the documentation string could be optional, since
406 there are required components of the function that follow it (the body).
407 Since evaluation of a string returns that string, without any side effects,
408 it has no effect if it is not the last form in the body. Thus, in
409 practice, there is no confusion between the first form of the body and the
410 documentation string; if the only body form is a string then it serves both
411 as the return value and as the documentation.
412
413 @node Function Names
414 @section Naming a Function
415 @cindex function definition
416 @cindex named function
417 @cindex function name
418
419 In most computer languages, every function has a name; the idea of a
420 function without a name is nonsensical. In Lisp, a function in the
421 strictest sense has no name. It is simply a list whose first element is
422 @code{lambda}, a byte-code function object, or a primitive subr-object.
423
424 However, a symbol can serve as the name of a function. This happens
425 when you put the function in the symbol's @dfn{function cell}
426 (@pxref{Symbol Components}). Then the symbol itself becomes a valid,
427 callable function, equivalent to the list or subr-object that its
428 function cell refers to. The contents of the function cell are also
429 called the symbol's @dfn{function definition}. The procedure of using a
430 symbol's function definition in place of the symbol is called
431 @dfn{symbol function indirection}; see @ref{Function Indirection}.
432
433 In practice, nearly all functions are given names in this way and
434 referred to through their names. For example, the symbol @code{car} works
435 as a function and does what it does because the primitive subr-object
436 @code{#<subr car>} is stored in its function cell.
437
438 We give functions names because it is convenient to refer to them by
439 their names in Lisp expressions. For primitive subr-objects such as
440 @code{#<subr car>}, names are the only way you can refer to them: there
441 is no read syntax for such objects. For functions written in Lisp, the
442 name is more convenient to use in a call than an explicit lambda
443 expression. Also, a function with a name can refer to itself---it can
444 be recursive. Writing the function's name in its own definition is much
445 more convenient than making the function definition point to itself
446 (something that is not impossible but that has various disadvantages in
447 practice).
448
449 We often identify functions with the symbols used to name them. For
450 example, we often speak of ``the function @code{car}'', not
451 distinguishing between the symbol @code{car} and the primitive
452 subr-object that is its function definition. For most purposes, there
453 is no need to distinguish.
454
455 Even so, keep in mind that a function need not have a unique name. While
456 a given function object @emph{usually} appears in the function cell of only
457 one symbol, this is just a matter of convenience. It is easy to store
458 it in several symbols using @code{fset}; then each of the symbols is
459 equally well a name for the same function.
460
461 A symbol used as a function name may also be used as a variable; these
462 two uses of a symbol are independent and do not conflict. (Some Lisp
463 dialects, such as Scheme, do not distinguish between a symbol's value
464 and its function definition; a symbol's value as a variable is also its
465 function definition.) If you have not given a symbol a function
466 definition, you cannot use it as a function; whether the symbol has a
467 value as a variable makes no difference to this.
468
469 @node Defining Functions
470 @section Defining Functions
471 @cindex defining a function
472
473 We usually give a name to a function when it is first created. This
474 is called @dfn{defining a function}, and it is done with the
475 @code{defun} special form.
476
477 @defspec defun name argument-list body-forms
478 @code{defun} is the usual way to define new Lisp functions. It
479 defines the symbol @var{name} as a function that looks like this:
480
481 @example
482 (lambda @var{argument-list} . @var{body-forms})
483 @end example
484
485 @code{defun} stores this lambda expression in the function cell of
486 @var{name}. It returns the value @var{name}, but usually we ignore this
487 value.
488
489 As described previously (@pxref{Lambda Expressions}),
490 @var{argument-list} is a list of argument names and may include the
491 keywords @code{&optional} and @code{&rest}. Also, the first two of the
492 @var{body-forms} may be a documentation string and an interactive
493 declaration.
494
495 There is no conflict if the same symbol @var{name} is also used as a
496 variable, since the symbol's value cell is independent of the function
497 cell. @xref{Symbol Components}.
498
499 Here are some examples:
500
501 @example
502 @group
503 (defun foo () 5)
504 @result{} foo
505 @end group
506 @group
507 (foo)
508 @result{} 5
509 @end group
510
511 @group
512 (defun bar (a &optional b &rest c)
513 (list a b c))
514 @result{} bar
515 @end group
516 @group
517 (bar 1 2 3 4 5)
518 @result{} (1 2 (3 4 5))
519 @end group
520 @group
521 (bar 1)
522 @result{} (1 nil nil)
523 @end group
524 @group
525 (bar)
526 @error{} Wrong number of arguments.
527 @end group
528
529 @group
530 (defun capitalize-backwards ()
531 "Upcase the last letter of a word."
532 (interactive)
533 (backward-word 1)
534 (forward-word 1)
535 (backward-char 1)
536 (capitalize-word 1))
537 @result{} capitalize-backwards
538 @end group
539 @end example
540
541 Be careful not to redefine existing functions unintentionally.
542 @code{defun} redefines even primitive functions such as @code{car}
543 without any hesitation or notification. Redefining a function already
544 defined is often done deliberately, and there is no way to distinguish
545 deliberate redefinition from unintentional redefinition.
546 @end defspec
547
548 @defun defalias name definition
549 This special form defines the symbol @var{name} as a function, with
550 definition @var{definition} (which can be any valid Lisp function).
551
552 The proper place to use @code{defalias} is where a specific function
553 name is being defined---especially where that name appears explicitly in
554 the source file being loaded. This is because @code{defalias} records
555 which file defined the function, just like @code{defun}
556 (@pxref{Unloading}).
557
558 By contrast, in programs that manipulate function definitions for other
559 purposes, it is better to use @code{fset}, which does not keep such
560 records.
561 @end defun
562
563 See also @code{defsubst}, which defines a function like @code{defun}
564 and tells the Lisp compiler to open-code it. @xref{Inline Functions}.
565
566 @node Calling Functions
567 @section Calling Functions
568 @cindex function invocation
569 @cindex calling a function
570
571 Defining functions is only half the battle. Functions don't do
572 anything until you @dfn{call} them, i.e., tell them to run. Calling a
573 function is also known as @dfn{invocation}.
574
575 The most common way of invoking a function is by evaluating a list.
576 For example, evaluating the list @code{(concat "a" "b")} calls the
577 function @code{concat} with arguments @code{"a"} and @code{"b"}.
578 @xref{Evaluation}, for a description of evaluation.
579
580 When you write a list as an expression in your program, the function
581 name it calls is written in your program. This means that you choose
582 which function to call, and how many arguments to give it, when you
583 write the program. Usually that's just what you want. Occasionally you
584 need to compute at run time which function to call. To do that, use the
585 function @code{funcall}. When you also need to determine at run time
586 how many arguments to pass, use @code{apply}.
587
588 @defun funcall function &rest arguments
589 @code{funcall} calls @var{function} with @var{arguments}, and returns
590 whatever @var{function} returns.
591
592 Since @code{funcall} is a function, all of its arguments, including
593 @var{function}, are evaluated before @code{funcall} is called. This
594 means that you can use any expression to obtain the function to be
595 called. It also means that @code{funcall} does not see the expressions
596 you write for the @var{arguments}, only their values. These values are
597 @emph{not} evaluated a second time in the act of calling @var{function};
598 @code{funcall} enters the normal procedure for calling a function at the
599 place where the arguments have already been evaluated.
600
601 The argument @var{function} must be either a Lisp function or a
602 primitive function. Special forms and macros are not allowed, because
603 they make sense only when given the ``unevaluated'' argument
604 expressions. @code{funcall} cannot provide these because, as we saw
605 above, it never knows them in the first place.
606
607 @example
608 @group
609 (setq f 'list)
610 @result{} list
611 @end group
612 @group
613 (funcall f 'x 'y 'z)
614 @result{} (x y z)
615 @end group
616 @group
617 (funcall f 'x 'y '(z))
618 @result{} (x y (z))
619 @end group
620 @group
621 (funcall 'and t nil)
622 @error{} Invalid function: #<subr and>
623 @end group
624 @end example
625
626 Compare these examples with the examples of @code{apply}.
627 @end defun
628
629 @defun apply function &rest arguments
630 @code{apply} calls @var{function} with @var{arguments}, just like
631 @code{funcall} but with one difference: the last of @var{arguments} is a
632 list of objects, which are passed to @var{function} as separate
633 arguments, rather than a single list. We say that @code{apply}
634 @dfn{spreads} this list so that each individual element becomes an
635 argument.
636
637 @code{apply} returns the result of calling @var{function}. As with
638 @code{funcall}, @var{function} must either be a Lisp function or a
639 primitive function; special forms and macros do not make sense in
640 @code{apply}.
641
642 @example
643 @group
644 (setq f 'list)
645 @result{} list
646 @end group
647 @group
648 (apply f 'x 'y 'z)
649 @error{} Wrong type argument: listp, z
650 @end group
651 @group
652 (apply '+ 1 2 '(3 4))
653 @result{} 10
654 @end group
655 @group
656 (apply '+ '(1 2 3 4))
657 @result{} 10
658 @end group
659
660 @group
661 (apply 'append '((a b c) nil (x y z) nil))
662 @result{} (a b c x y z)
663 @end group
664 @end example
665
666 For an interesting example of using @code{apply}, see the description of
667 @code{mapcar}, in @ref{Mapping Functions}.
668 @end defun
669
670 @cindex functionals
671 It is common for Lisp functions to accept functions as arguments or
672 find them in data structures (especially in hook variables and property
673 lists) and call them using @code{funcall} or @code{apply}. Functions
674 that accept function arguments are often called @dfn{functionals}.
675
676 Sometimes, when you call a functional, it is useful to supply a no-op
677 function as the argument. Here are two different kinds of no-op
678 function:
679
680 @defun identity arg
681 This function returns @var{arg} and has no side effects.
682 @end defun
683
684 @defun ignore &rest args
685 This function ignores any arguments and returns @code{nil}.
686 @end defun
687
688 @node Mapping Functions
689 @section Mapping Functions
690 @cindex mapping functions
691
692 A @dfn{mapping function} applies a given function to each element of a
693 list or other collection. Emacs Lisp has several such functions;
694 @code{mapcar} and @code{mapconcat}, which scan a list, are described
695 here. @xref{Creating Symbols}, for the function @code{mapatoms} which
696 maps over the symbols in an obarray. @xref{Hash Access}, for the
697 function @code{maphash} which maps over key/value associations in a
698 hash table.
699
700 These mapping functions do not allow char-tables because a char-table
701 is a sparse array whose nominal range of indices is very large. To map
702 over a char-table in a way that deals properly with its sparse nature,
703 use the function @code{map-char-table} (@pxref{Char-Tables}).
704
705 @defun mapcar function sequence
706 @code{mapcar} applies @var{function} to each element of @var{sequence}
707 in turn, and returns a list of the results.
708
709 The argument @var{sequence} can be any kind of sequence except a
710 char-table; that is, a list, a vector, a bool-vector, or a string. The
711 result is always a list. The length of the result is the same as the
712 length of @var{sequence}.
713
714 @smallexample
715 @group
716 @exdent @r{For example:}
717
718 (mapcar 'car '((a b) (c d) (e f)))
719 @result{} (a c e)
720 (mapcar '1+ [1 2 3])
721 @result{} (2 3 4)
722 (mapcar 'char-to-string "abc")
723 @result{} ("a" "b" "c")
724 @end group
725
726 @group
727 ;; @r{Call each function in @code{my-hooks}.}
728 (mapcar 'funcall my-hooks)
729 @end group
730
731 @group
732 (defun mapcar* (function &rest args)
733 "Apply FUNCTION to successive cars of all ARGS.
734 Return the list of results."
735 ;; @r{If no list is exhausted,}
736 (if (not (memq 'nil args))
737 ;; @r{apply function to @sc{car}s.}
738 (cons (apply function (mapcar 'car args))
739 (apply 'mapcar* function
740 ;; @r{Recurse for rest of elements.}
741 (mapcar 'cdr args)))))
742 @end group
743
744 @group
745 (mapcar* 'cons '(a b c) '(1 2 3 4))
746 @result{} ((a . 1) (b . 2) (c . 3))
747 @end group
748 @end smallexample
749 @end defun
750
751 @defun mapconcat function sequence separator
752 @code{mapconcat} applies @var{function} to each element of
753 @var{sequence}: the results, which must be strings, are concatenated.
754 Between each pair of result strings, @code{mapconcat} inserts the string
755 @var{separator}. Usually @var{separator} contains a space or comma or
756 other suitable punctuation.
757
758 The argument @var{function} must be a function that can take one
759 argument and return a string. The argument @var{sequence} can be any
760 kind of sequence except a char-table; that is, a list, a vector, a
761 bool-vector, or a string.
762
763 @smallexample
764 @group
765 (mapconcat 'symbol-name
766 '(The cat in the hat)
767 " ")
768 @result{} "The cat in the hat"
769 @end group
770
771 @group
772 (mapconcat (function (lambda (x) (format "%c" (1+ x))))
773 "HAL-8000"
774 "")
775 @result{} "IBM.9111"
776 @end group
777 @end smallexample
778 @end defun
779
780 @node Anonymous Functions
781 @section Anonymous Functions
782 @cindex anonymous function
783
784 In Lisp, a function is a list that starts with @code{lambda}, a
785 byte-code function compiled from such a list, or alternatively a
786 primitive subr-object; names are ``extra''. Although usually functions
787 are defined with @code{defun} and given names at the same time, it is
788 occasionally more concise to use an explicit lambda expression---an
789 anonymous function. Such a list is valid wherever a function name is.
790
791 Any method of creating such a list makes a valid function. Even this:
792
793 @smallexample
794 @group
795 (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
796 @result{} (lambda (x) (+ 12 x))
797 @end group
798 @end smallexample
799
800 @noindent
801 This computes a list that looks like @code{(lambda (x) (+ 12 x))} and
802 makes it the value (@emph{not} the function definition!) of
803 @code{silly}.
804
805 Here is how we might call this function:
806
807 @example
808 @group
809 (funcall silly 1)
810 @result{} 13
811 @end group
812 @end example
813
814 @noindent
815 (It does @emph{not} work to write @code{(silly 1)}, because this function
816 is not the @emph{function definition} of @code{silly}. We have not given
817 @code{silly} any function definition, just a value as a variable.)
818
819 Most of the time, anonymous functions are constants that appear in
820 your program. For example, you might want to pass one as an argument to
821 the function @code{mapcar}, which applies any given function to each
822 element of a list.
823
824 Here we define a function @code{change-property} which
825 uses a function as its third argument:
826
827 @example
828 @group
829 (defun change-property (symbol prop function)
830 (let ((value (get symbol prop)))
831 (put symbol prop (funcall function value))))
832 @end group
833 @end example
834
835 @noindent
836 Here we define a function that uses @code{change-property},
837 passing it a function to double a number:
838
839 @example
840 @group
841 (defun double-property (symbol prop)
842 (change-property symbol prop '(lambda (x) (* 2 x))))
843 @end group
844 @end example
845
846 @noindent
847 In such cases, we usually use the special form @code{function} instead
848 of simple quotation to quote the anonymous function, like this:
849
850 @example
851 @group
852 (defun double-property (symbol prop)
853 (change-property symbol prop
854 (function (lambda (x) (* 2 x)))))
855 @end group
856 @end example
857
858 Using @code{function} instead of @code{quote} makes a difference if you
859 compile the function @code{double-property}. For example, if you
860 compile the second definition of @code{double-property}, the anonymous
861 function is compiled as well. By contrast, if you compile the first
862 definition which uses ordinary @code{quote}, the argument passed to
863 @code{change-property} is the precise list shown:
864
865 @example
866 (lambda (x) (* x 2))
867 @end example
868
869 @noindent
870 The Lisp compiler cannot assume this list is a function, even though it
871 looks like one, since it does not know what @code{change-property} will
872 do with the list. Perhaps it will check whether the @sc{car} of the third
873 element is the symbol @code{*}! Using @code{function} tells the
874 compiler it is safe to go ahead and compile the constant function.
875
876 We sometimes write @code{function} instead of @code{quote} when
877 quoting the name of a function, but this usage is just a sort of
878 comment:
879
880 @example
881 (function @var{symbol}) @equiv{} (quote @var{symbol}) @equiv{} '@var{symbol}
882 @end example
883
884 @cindex @samp{#'} syntax
885 The read syntax @code{#'} is a short-hand for using @code{function}.
886 For example,
887
888 @example
889 #'(lambda (x) (* x x))
890 @end example
891
892 @noindent
893 is equivalent to
894
895 @example
896 (function (lambda (x) (* x x)))
897 @end example
898
899 @defspec function function-object
900 @cindex function quoting
901 This special form returns @var{function-object} without evaluating it.
902 In this, it is equivalent to @code{quote}. However, it serves as a
903 note to the Emacs Lisp compiler that @var{function-object} is intended
904 to be used only as a function, and therefore can safely be compiled.
905 Contrast this with @code{quote}, in @ref{Quoting}.
906 @end defspec
907
908 See @code{documentation} in @ref{Accessing Documentation}, for a
909 realistic example using @code{function} and an anonymous function.
910
911 @node Function Cells
912 @section Accessing Function Cell Contents
913
914 The @dfn{function definition} of a symbol is the object stored in the
915 function cell of the symbol. The functions described here access, test,
916 and set the function cell of symbols.
917
918 See also the function @code{indirect-function} in @ref{Function
919 Indirection}.
920
921 @defun symbol-function symbol
922 @kindex void-function
923 This returns the object in the function cell of @var{symbol}. If the
924 symbol's function cell is void, a @code{void-function} error is
925 signaled.
926
927 This function does not check that the returned object is a legitimate
928 function.
929
930 @example
931 @group
932 (defun bar (n) (+ n 2))
933 @result{} bar
934 @end group
935 @group
936 (symbol-function 'bar)
937 @result{} (lambda (n) (+ n 2))
938 @end group
939 @group
940 (fset 'baz 'bar)
941 @result{} bar
942 @end group
943 @group
944 (symbol-function 'baz)
945 @result{} bar
946 @end group
947 @end example
948 @end defun
949
950 @cindex void function cell
951 If you have never given a symbol any function definition, we say that
952 that symbol's function cell is @dfn{void}. In other words, the function
953 cell does not have any Lisp object in it. If you try to call such a symbol
954 as a function, it signals a @code{void-function} error.
955
956 Note that void is not the same as @code{nil} or the symbol
957 @code{void}. The symbols @code{nil} and @code{void} are Lisp objects,
958 and can be stored into a function cell just as any other object can be
959 (and they can be valid functions if you define them in turn with
960 @code{defun}). A void function cell contains no object whatsoever.
961
962 You can test the voidness of a symbol's function definition with
963 @code{fboundp}. After you have given a symbol a function definition, you
964 can make it void once more using @code{fmakunbound}.
965
966 @defun fboundp symbol
967 This function returns @code{t} if the symbol has an object in its
968 function cell, @code{nil} otherwise. It does not check that the object
969 is a legitimate function.
970 @end defun
971
972 @defun fmakunbound symbol
973 This function makes @var{symbol}'s function cell void, so that a
974 subsequent attempt to access this cell will cause a @code{void-function}
975 error. (See also @code{makunbound}, in @ref{Void Variables}.)
976
977 @example
978 @group
979 (defun foo (x) x)
980 @result{} foo
981 @end group
982 @group
983 (foo 1)
984 @result{}1
985 @end group
986 @group
987 (fmakunbound 'foo)
988 @result{} foo
989 @end group
990 @group
991 (foo 1)
992 @error{} Symbol's function definition is void: foo
993 @end group
994 @end example
995 @end defun
996
997 @defun fset symbol definition
998 This function stores @var{definition} in the function cell of
999 @var{symbol}. The result is @var{definition}. Normally
1000 @var{definition} should be a function or the name of a function, but
1001 this is not checked. The argument @var{symbol} is an ordinary evaluated
1002 argument.
1003
1004 There are three normal uses of this function:
1005
1006 @itemize @bullet
1007 @item
1008 Copying one symbol's function definition to another---in other words,
1009 making an alternate name for a function. (If you think of this as the
1010 definition of the new name, you should use @code{defalias} instead of
1011 @code{fset}; see @ref{Defining Functions}.)
1012
1013 @item
1014 Giving a symbol a function definition that is not a list and therefore
1015 cannot be made with @code{defun}. For example, you can use @code{fset}
1016 to give a symbol @code{s1} a function definition which is another symbol
1017 @code{s2}; then @code{s1} serves as an alias for whatever definition
1018 @code{s2} presently has. (Once again use @code{defalias} instead of
1019 @code{fset} if you think of this as the definition of @code{s1}.)
1020
1021 @item
1022 In constructs for defining or altering functions. If @code{defun}
1023 were not a primitive, it could be written in Lisp (as a macro) using
1024 @code{fset}.
1025 @end itemize
1026
1027 Here are examples of these uses:
1028
1029 @example
1030 @group
1031 ;; @r{Save @code{foo}'s definition in @code{old-foo}.}
1032 (fset 'old-foo (symbol-function 'foo))
1033 @end group
1034
1035 @group
1036 ;; @r{Make the symbol @code{car} the function definition of @code{xfirst}.}
1037 ;; @r{(Most likely, @code{defalias} would be better than @code{fset} here.)}
1038 (fset 'xfirst 'car)
1039 @result{} car
1040 @end group
1041 @group
1042 (xfirst '(1 2 3))
1043 @result{} 1
1044 @end group
1045 @group
1046 (symbol-function 'xfirst)
1047 @result{} car
1048 @end group
1049 @group
1050 (symbol-function (symbol-function 'xfirst))
1051 @result{} #<subr car>
1052 @end group
1053
1054 @group
1055 ;; @r{Define a named keyboard macro.}
1056 (fset 'kill-two-lines "\^u2\^k")
1057 @result{} "\^u2\^k"
1058 @end group
1059
1060 @group
1061 ;; @r{Here is a function that alters other functions.}
1062 (defun copy-function-definition (new old)
1063 "Define NEW with the same function definition as OLD."
1064 (fset new (symbol-function old)))
1065 @end group
1066 @end example
1067 @end defun
1068
1069 When writing a function that extends a previously defined function,
1070 the following idiom is sometimes used:
1071
1072 @example
1073 (fset 'old-foo (symbol-function 'foo))
1074 (defun foo ()
1075 "Just like old-foo, except more so."
1076 @group
1077 (old-foo)
1078 (more-so))
1079 @end group
1080 @end example
1081
1082 @noindent
1083 This does not work properly if @code{foo} has been defined to autoload.
1084 In such a case, when @code{foo} calls @code{old-foo}, Lisp attempts
1085 to define @code{old-foo} by loading a file. Since this presumably
1086 defines @code{foo} rather than @code{old-foo}, it does not produce the
1087 proper results. The only way to avoid this problem is to make sure the
1088 file is loaded before moving aside the old definition of @code{foo}.
1089
1090 But it is unmodular and unclean, in any case, for a Lisp file to
1091 redefine a function defined elsewhere. It is cleaner to use the advice
1092 facility (@pxref{Advising Functions}).
1093
1094 @node Inline Functions
1095 @section Inline Functions
1096 @cindex inline functions
1097
1098 @findex defsubst
1099 You can define an @dfn{inline function} by using @code{defsubst} instead
1100 of @code{defun}. An inline function works just like an ordinary
1101 function except for one thing: when you compile a call to the function,
1102 the function's definition is open-coded into the caller.
1103
1104 Making a function inline makes explicit calls run faster. But it also
1105 has disadvantages. For one thing, it reduces flexibility; if you change
1106 the definition of the function, calls already inlined still use the old
1107 definition until you recompile them. Since the flexibility of
1108 redefining functions is an important feature of Emacs, you should not
1109 make a function inline unless its speed is really crucial.
1110
1111 Another disadvantage is that making a large function inline can increase
1112 the size of compiled code both in files and in memory. Since the speed
1113 advantage of inline functions is greatest for small functions, you
1114 generally should not make large functions inline.
1115
1116 It's possible to define a macro to expand into the same code that an
1117 inline function would execute. (@xref{Macros}.) But the macro would be
1118 limited to direct use in expressions---a macro cannot be called with
1119 @code{apply}, @code{mapcar} and so on. Also, it takes some work to
1120 convert an ordinary function into a macro. To convert it into an inline
1121 function is very easy; simply replace @code{defun} with @code{defsubst}.
1122 Since each argument of an inline function is evaluated exactly once, you
1123 needn't worry about how many times the body uses the arguments, as you
1124 do for macros. (@xref{Argument Evaluation}.)
1125
1126 Inline functions can be used and open-coded later on in the same file,
1127 following the definition, just like macros.
1128
1129 @c Emacs versions prior to 19 did not have inline functions.
1130
1131 @node Related Topics
1132 @section Other Topics Related to Functions
1133
1134 Here is a table of several functions that do things related to
1135 function calling and function definitions. They are documented
1136 elsewhere, but we provide cross references here.
1137
1138 @table @code
1139 @item apply
1140 See @ref{Calling Functions}.
1141
1142 @item autoload
1143 See @ref{Autoload}.
1144
1145 @item call-interactively
1146 See @ref{Interactive Call}.
1147
1148 @item commandp
1149 See @ref{Interactive Call}.
1150
1151 @item documentation
1152 See @ref{Accessing Documentation}.
1153
1154 @item eval
1155 See @ref{Eval}.
1156
1157 @item funcall
1158 See @ref{Calling Functions}.
1159
1160 @item function
1161 See @ref{Anonymous Functions}.
1162
1163 @item ignore
1164 See @ref{Calling Functions}.
1165
1166 @item indirect-function
1167 See @ref{Function Indirection}.
1168
1169 @item interactive
1170 See @ref{Using Interactive}.
1171
1172 @item interactive-p
1173 See @ref{Interactive Call}.
1174
1175 @item mapatoms
1176 See @ref{Creating Symbols}.
1177
1178 @item mapcar
1179 See @ref{Mapping Functions}.
1180
1181 @item map-char-table
1182 See @ref{Char-Tables}.
1183
1184 @item mapconcat
1185 See @ref{Mapping Functions}.
1186
1187 @item undefined
1188 See @ref{Key Lookup}.
1189 @end table
1190