1 This is Info file ../info/lispref.info, produced by Makeinfo version
2 1.68 from the input file lispref/lispref.texi.
4 INFO-DIR-SECTION XEmacs Editor
6 * Lispref: (lispref). XEmacs Lisp Reference Manual.
11 GNU Emacs Lisp Reference Manual Second Edition (v2.01), May 1993 GNU
12 Emacs Lisp Reference Manual Further Revised (v2.02), August 1993 Lucid
13 Emacs Lisp Reference Manual (for 19.10) First Edition, March 1994
14 XEmacs Lisp Programmer's Manual (for 19.12) Second Edition, April 1995
15 GNU Emacs Lisp Reference Manual v2.4, June 1995 XEmacs Lisp
16 Programmer's Manual (for 19.13) Third Edition, July 1995 XEmacs Lisp
17 Reference Manual (for 19.14 and 20.0) v3.1, March 1996 XEmacs Lisp
18 Reference Manual (for 19.15 and 20.1, 20.2, 20.3) v3.2, April, May,
19 November 1997 XEmacs Lisp Reference Manual (for 21.0) v3.3, April 1998
21 Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995 Free Software
22 Foundation, Inc. Copyright (C) 1994, 1995 Sun Microsystems, Inc.
23 Copyright (C) 1995, 1996 Ben Wing.
25 Permission is granted to make and distribute verbatim copies of this
26 manual provided the copyright notice and this permission notice are
27 preserved on all copies.
29 Permission is granted to copy and distribute modified versions of
30 this manual under the conditions for verbatim copying, provided that the
31 entire resulting derived work is distributed under the terms of a
32 permission notice identical to this one.
34 Permission is granted to copy and distribute translations of this
35 manual into another language, under the above conditions for modified
36 versions, except that this permission notice may be stated in a
37 translation approved by the Foundation.
39 Permission is granted to copy and distribute modified versions of
40 this manual under the conditions for verbatim copying, provided also
41 that the section entitled "GNU General Public License" is included
42 exactly as in the original, and provided that the entire resulting
43 derived work is distributed under the terms of a permission notice
44 identical to this one.
46 Permission is granted to copy and distribute translations of this
47 manual into another language, under the above conditions for modified
48 versions, except that the section entitled "GNU General Public License"
49 may be included in a translation approved by the Free Software
50 Foundation instead of in the original English.
53 File: lispref.info, Node: Variable Aliases, Prev: Buffer-Local Variables, Up: Variables
58 You can define a variable as an "alias" for another. Any time you
59 reference the former variable, the current value of the latter is
60 returned. Any time you change the value of the former variable, the
61 value of the latter is actually changed. This is useful in cases where
62 you want to rename a variable but still make old code work (*note
65 - Function: defvaralias VARIABLE ALIAS
66 This function defines VARIABLE as an alias for ALIAS.
67 Thenceforth, any operations performed on VARIABLE will actually be
68 performed on ALIAS. Both VARIABLE and ALIAS should be symbols.
69 If ALIAS is `nil', remove any aliases for VARIABLE. ALIAS can
70 itself be aliased, and the chain of variable aliases will be
71 followed appropriately. If VARIABLE already has a value, this
72 value will be shadowed until the alias is removed, at which point
73 it will be restored. Currently VARIABLE cannot be a built-in
74 variable, a variable that has a buffer-local value in any buffer,
75 or the symbols `nil' or `t'.
77 - Function: variable-alias VARIABLE
78 If VARIABLE is aliased to another variable, this function returns
79 that variable. VARIABLE should be a symbol. If VARIABLE is not
80 aliased, this function returns `nil'.
82 - Function: indirect-variable OBJECT
83 This function returns the variable at the end of OBJECT's
84 variable-alias chain. If OBJECT is a symbol, follow all variable
85 aliases and return the final (non-aliased) symbol. If OBJECT is
86 not a symbol, just return it. Signal a
87 `cyclic-variable-indirection' error if there is a loop in the
88 variable chain of symbols.
91 File: lispref.info, Node: Functions, Next: Macros, Prev: Variables, Up: Top
96 A Lisp program is composed mainly of Lisp functions. This chapter
97 explains what functions are, how they accept arguments, and how to
102 * What Is a Function:: Lisp functions vs. primitives; terminology.
103 * Lambda Expressions:: How functions are expressed as Lisp objects.
104 * Function Names:: A symbol can serve as the name of a function.
105 * Defining Functions:: Lisp expressions for defining functions.
106 * Calling Functions:: How to use an existing function.
107 * Mapping Functions:: Applying a function to each element of a list, etc.
108 * Anonymous Functions:: Lambda expressions are functions with no names.
109 * Function Cells:: Accessing or setting the function definition
111 * Inline Functions:: Defining functions that the compiler will open code.
112 * Related Topics:: Cross-references to specific Lisp primitives
113 that have a special bearing on how functions work.
116 File: lispref.info, Node: What Is a Function, Next: Lambda Expressions, Up: Functions
121 In a general sense, a function is a rule for carrying on a
122 computation given several values called "arguments". The result of the
123 computation is called the value of the function. The computation can
124 also have side effects: lasting changes in the values of variables or
125 the contents of data structures.
127 Here are important terms for functions in XEmacs Lisp and for other
128 function-like objects.
131 In XEmacs Lisp, a "function" is anything that can be applied to
132 arguments in a Lisp program. In some cases, we use it more
133 specifically to mean a function written in Lisp. Special forms and
134 macros are not functions.
137 A "primitive" is a function callable from Lisp that is written in
138 C, such as `car' or `append'. These functions are also called
139 "built-in" functions or "subrs". (Special forms are also
140 considered primitives.)
142 Usually the reason that a function is a primitives is because it is
143 fundamental, because it provides a low-level interface to operating
144 system services, or because it needs to run fast. Primitives can
145 be modified or added only by changing the C sources and
146 recompiling the editor. See *Note Writing Lisp Primitives:
147 (internals)Writing Lisp Primitives.
150 A "lambda expression" is a function written in Lisp. These are
151 described in the following section. *Note Lambda Expressions::.
154 A "special form" is a primitive that is like a function but does
155 not evaluate all of its arguments in the usual way. It may
156 evaluate only some of the arguments, or may evaluate them in an
157 unusual order, or several times. Many special forms are described
158 in *Note Control Structures::.
161 A "macro" is a construct defined in Lisp by the programmer. It
162 differs from a function in that it translates a Lisp expression
163 that you write into an equivalent expression to be evaluated
164 instead of the original expression. Macros enable Lisp
165 programmers to do the sorts of things that special forms can do.
166 *Note Macros::, for how to define and use macros.
169 A "command" is an object that `command-execute' can invoke; it is
170 a possible definition for a key sequence. Some functions are
171 commands; a function written in Lisp is a command if it contains an
172 interactive declaration (*note Defining Commands::.). Such a
173 function can be called from Lisp expressions like other functions;
174 in this case, the fact that the function is a command makes no
177 Keyboard macros (strings and vectors) are commands also, even
178 though they are not functions. A symbol is a command if its
179 function definition is a command; such symbols can be invoked with
180 `M-x'. The symbol is a function as well if the definition is a
181 function. *Note Command Overview::.
184 A "keystroke command" is a command that is bound to a key sequence
185 (typically one to three keystrokes). The distinction is made here
186 merely to avoid confusion with the meaning of "command" in
187 non-Emacs editors; for Lisp programs, the distinction is normally
191 A "compiled function" is a function that has been compiled by the
192 byte compiler. *Note Compiled-Function Type::.
194 - Function: subrp OBJECT
195 This function returns `t' if OBJECT is a built-in function (i.e.,
198 (subrp 'message) ; `message' is a symbol,
199 => nil ; not a subr object.
200 (subrp (symbol-function 'message))
203 - Function: compiled-function-p OBJECT
204 This function returns `t' if OBJECT is a compiled function. For
207 (compiled-function-p (symbol-function 'next-line))
211 File: lispref.info, Node: Lambda Expressions, Next: Function Names, Prev: What Is a Function, Up: Functions
216 A function written in Lisp is a list that looks like this:
218 (lambda (ARG-VARIABLES...)
219 [DOCUMENTATION-STRING]
220 [INTERACTIVE-DECLARATION]
223 Such a list is called a "lambda expression". In XEmacs Lisp, it
224 actually is valid as an expression--it evaluates to itself. In some
225 other Lisp dialects, a lambda expression is not a valid expression at
226 all. In either case, its main use is not to be evaluated as an
227 expression, but to be called as a function.
231 * Lambda Components:: The parts of a lambda expression.
232 * Simple Lambda:: A simple example.
233 * Argument List:: Details and special features of argument lists.
234 * Function Documentation:: How to put documentation in a function.
237 File: lispref.info, Node: Lambda Components, Next: Simple Lambda, Up: Lambda Expressions
239 Components of a Lambda Expression
240 ---------------------------------
242 A function written in Lisp (a "lambda expression") is a list that
245 (lambda (ARG-VARIABLES...)
246 [DOCUMENTATION-STRING]
247 [INTERACTIVE-DECLARATION]
250 The first element of a lambda expression is always the symbol
251 `lambda'. This indicates that the list represents a function. The
252 reason functions are defined to start with `lambda' is so that other
253 lists, intended for other uses, will not accidentally be valid as
256 The second element is a list of symbols-the argument variable names.
257 This is called the "lambda list". When a Lisp function is called, the
258 argument values are matched up against the variables in the lambda
259 list, which are given local bindings with the values provided. *Note
262 The documentation string is a Lisp string object placed within the
263 function definition to describe the function for the XEmacs help
264 facilities. *Note Function Documentation::.
266 The interactive declaration is a list of the form `(interactive
267 CODE-STRING)'. This declares how to provide arguments if the function
268 is used interactively. Functions with this declaration are called
269 "commands"; they can be called using `M-x' or bound to a key.
270 Functions not intended to be called in this way should not have
271 interactive declarations. *Note Defining Commands::, for how to write
272 an interactive declaration.
274 The rest of the elements are the "body" of the function: the Lisp
275 code to do the work of the function (or, as a Lisp programmer would say,
276 "a list of Lisp forms to evaluate"). The value returned by the
277 function is the value returned by the last element of the body.
280 File: lispref.info, Node: Simple Lambda, Next: Argument List, Prev: Lambda Components, Up: Lambda Expressions
282 A Simple Lambda-Expression Example
283 ----------------------------------
285 Consider for example the following function:
287 (lambda (a b c) (+ a b c))
289 We can call this function by writing it as the CAR of an expression,
292 ((lambda (a b c) (+ a b c))
295 This call evaluates the body of the lambda expression with the variable
296 `a' bound to 1, `b' bound to 2, and `c' bound to 3. Evaluation of the
297 body adds these three numbers, producing the result 6; therefore, this
298 call to the function returns the value 6.
300 Note that the arguments can be the results of other function calls,
303 ((lambda (a b c) (+ a b c))
306 This evaluates the arguments `1', `(* 2 3)', and `(- 5 4)' from left to
307 right. Then it applies the lambda expression to the argument values 1,
308 6 and 1 to produce the value 8.
310 It is not often useful to write a lambda expression as the CAR of a
311 form in this way. You can get the same result, of making local
312 variables and giving them values, using the special form `let' (*note
313 Local Variables::.). And `let' is clearer and easier to use. In
314 practice, lambda expressions are either stored as the function
315 definitions of symbols, to produce named functions, or passed as
316 arguments to other functions (*note Anonymous Functions::.).
318 However, calls to explicit lambda expressions were very useful in the
319 old days of Lisp, before the special form `let' was invented. At that
320 time, they were the only way to bind and initialize local variables.
323 File: lispref.info, Node: Argument List, Next: Function Documentation, Prev: Simple Lambda, Up: Lambda Expressions
325 Advanced Features of Argument Lists
326 -----------------------------------
328 Our simple sample function, `(lambda (a b c) (+ a b c))', specifies
329 three argument variables, so it must be called with three arguments: if
330 you try to call it with only two arguments or four arguments, you get a
331 `wrong-number-of-arguments' error.
333 It is often convenient to write a function that allows certain
334 arguments to be omitted. For example, the function `substring' accepts
335 three arguments--a string, the start index and the end index--but the
336 third argument defaults to the LENGTH of the string if you omit it. It
337 is also convenient for certain functions to accept an indefinite number
338 of arguments, as the functions `list' and `+' do.
340 To specify optional arguments that may be omitted when a function is
341 called, simply include the keyword `&optional' before the optional
342 arguments. To specify a list of zero or more extra arguments, include
343 the keyword `&rest' before one final argument.
345 Thus, the complete syntax for an argument list is as follows:
348 [&optional OPTIONAL-VARS...]
351 The square brackets indicate that the `&optional' and `&rest' clauses,
352 and the variables that follow them, are optional.
354 A call to the function requires one actual argument for each of the
355 REQUIRED-VARS. There may be actual arguments for zero or more of the
356 OPTIONAL-VARS, and there cannot be any actual arguments beyond that
357 unless the lambda list uses `&rest'. In that case, there may be any
358 number of extra actual arguments.
360 If actual arguments for the optional and rest variables are omitted,
361 then they always default to `nil'. There is no way for the function to
362 distinguish between an explicit argument of `nil' and an omitted
363 argument. However, the body of the function is free to consider `nil'
364 an abbreviation for some other meaningful value. This is what
365 `substring' does; `nil' as the third argument to `substring' means to
366 use the length of the string supplied.
368 Common Lisp note: Common Lisp allows the function to specify what
369 default value to use when an optional argument is omitted; XEmacs
370 Lisp always uses `nil'.
372 For example, an argument list that looks like this:
374 (a b &optional c d &rest e)
376 binds `a' and `b' to the first two actual arguments, which are
377 required. If one or two more arguments are provided, `c' and `d' are
378 bound to them respectively; any arguments after the first four are
379 collected into a list and `e' is bound to that list. If there are only
380 two arguments, `c' is `nil'; if two or three arguments, `d' is `nil';
381 if four arguments or fewer, `e' is `nil'.
383 There is no way to have required arguments following optional
384 ones--it would not make sense. To see why this must be so, suppose
385 that `c' in the example were optional and `d' were required. Suppose
386 three actual arguments are given; which variable would the third
387 argument be for? Similarly, it makes no sense to have any more
388 arguments (either required or optional) after a `&rest' argument.
390 Here are some examples of argument lists and proper calls:
392 ((lambda (n) (1+ n)) ; One required:
393 1) ; requires exactly one argument.
395 ((lambda (n &optional n1) ; One required and one optional:
396 (if n1 (+ n n1) (1+ n))) ; 1 or 2 arguments.
399 ((lambda (n &rest ns) ; One required and one rest:
400 (+ n (apply '+ ns))) ; 1 or more arguments.
405 File: lispref.info, Node: Function Documentation, Prev: Argument List, Up: Lambda Expressions
407 Documentation Strings of Functions
408 ----------------------------------
410 A lambda expression may optionally have a "documentation string" just
411 after the lambda list. This string does not affect execution of the
412 function; it is a kind of comment, but a systematized comment which
413 actually appears inside the Lisp world and can be used by the XEmacs
414 help facilities. *Note Documentation::, for how the
415 DOCUMENTATION-STRING is accessed.
417 It is a good idea to provide documentation strings for all the
418 functions in your program, even those that are only called from within
419 your program. Documentation strings are like comments, except that they
420 are easier to access.
422 The first line of the documentation string should stand on its own,
423 because `apropos' displays just this first line. It should consist of
424 one or two complete sentences that summarize the function's purpose.
426 The start of the documentation string is usually indented in the
427 source file, but since these spaces come before the starting
428 double-quote, they are not part of the string. Some people make a
429 practice of indenting any additional lines of the string so that the
430 text lines up in the program source. *This is a mistake.* The
431 indentation of the following lines is inside the string; what looks
432 nice in the source code will look ugly when displayed by the help
435 You may wonder how the documentation string could be optional, since
436 there are required components of the function that follow it (the body).
437 Since evaluation of a string returns that string, without any side
438 effects, it has no effect if it is not the last form in the body.
439 Thus, in practice, there is no confusion between the first form of the
440 body and the documentation string; if the only body form is a string
441 then it serves both as the return value and as the documentation.
444 File: lispref.info, Node: Function Names, Next: Defining Functions, Prev: Lambda Expressions, Up: Functions
449 In most computer languages, every function has a name; the idea of a
450 function without a name is nonsensical. In Lisp, a function in the
451 strictest sense has no name. It is simply a list whose first element is
452 `lambda', or a primitive subr-object.
454 However, a symbol can serve as the name of a function. This happens
455 when you put the function in the symbol's "function cell" (*note Symbol
456 Components::.). Then the symbol itself becomes a valid, callable
457 function, equivalent to the list or subr-object that its function cell
458 refers to. The contents of the function cell are also called the
459 symbol's "function definition". The procedure of using a symbol's
460 function definition in place of the symbol is called "symbol function
461 indirection"; see *Note Function Indirection::.
463 In practice, nearly all functions are given names in this way and
464 referred to through their names. For example, the symbol `car' works
465 as a function and does what it does because the primitive subr-object
466 `#<subr car>' is stored in its function cell.
468 We give functions names because it is convenient to refer to them by
469 their names in Lisp expressions. For primitive subr-objects such as
470 `#<subr car>', names are the only way you can refer to them: there is
471 no read syntax for such objects. For functions written in Lisp, the
472 name is more convenient to use in a call than an explicit lambda
473 expression. Also, a function with a name can refer to itself--it can
474 be recursive. Writing the function's name in its own definition is much
475 more convenient than making the function definition point to itself
476 (something that is not impossible but that has various disadvantages in
479 We often identify functions with the symbols used to name them. For
480 example, we often speak of "the function `car'", not distinguishing
481 between the symbol `car' and the primitive subr-object that is its
482 function definition. For most purposes, there is no need to
485 Even so, keep in mind that a function need not have a unique name.
486 While a given function object *usually* appears in the function cell of
487 only one symbol, this is just a matter of convenience. It is easy to
488 store it in several symbols using `fset'; then each of the symbols is
489 equally well a name for the same function.
491 A symbol used as a function name may also be used as a variable;
492 these two uses of a symbol are independent and do not conflict.
495 File: lispref.info, Node: Defining Functions, Next: Calling Functions, Prev: Function Names, Up: Functions
500 We usually give a name to a function when it is first created. This
501 is called "defining a function", and it is done with the `defun'
504 - Special Form: defun NAME ARGUMENT-LIST BODY-FORMS
505 `defun' is the usual way to define new Lisp functions. It defines
506 the symbol NAME as a function that looks like this:
508 (lambda ARGUMENT-LIST . BODY-FORMS)
510 `defun' stores this lambda expression in the function cell of
511 NAME. It returns the value NAME, but usually we ignore this value.
513 As described previously (*note Lambda Expressions::.),
514 ARGUMENT-LIST is a list of argument names and may include the
515 keywords `&optional' and `&rest'. Also, the first two forms in
516 BODY-FORMS may be a documentation string and an interactive
519 There is no conflict if the same symbol NAME is also used as a
520 variable, since the symbol's value cell is independent of the
521 function cell. *Note Symbol Components::.
523 Here are some examples:
530 (defun bar (a &optional b &rest c)
538 error--> Wrong number of arguments.
540 (defun capitalize-backwards ()
541 "Upcase the last letter of a word."
547 => capitalize-backwards
549 Be careful not to redefine existing functions unintentionally.
550 `defun' redefines even primitive functions such as `car' without
551 any hesitation or notification. Redefining a function already
552 defined is often done deliberately, and there is no way to
553 distinguish deliberate redefinition from unintentional
556 - Function: define-function NAME DEFINITION
557 - Function: defalias NAME DEFINITION
558 These equivalent special forms define the symbol NAME as a
559 function, with definition DEFINITION (which can be any valid Lisp
562 The proper place to use `define-function' or `defalias' is where a
563 specific function name is being defined--especially where that
564 name appears explicitly in the source file being loaded. This is
565 because `define-function' and `defalias' record which file defined
566 the function, just like `defun'. (*note Unloading::.).
568 By contrast, in programs that manipulate function definitions for
569 other purposes, it is better to use `fset', which does not keep
572 See also `defsubst', which defines a function like `defun' and tells
573 the Lisp compiler to open-code it. *Note Inline Functions::.
576 File: lispref.info, Node: Calling Functions, Next: Mapping Functions, Prev: Defining Functions, Up: Functions
581 Defining functions is only half the battle. Functions don't do
582 anything until you "call" them, i.e., tell them to run. Calling a
583 function is also known as "invocation".
585 The most common way of invoking a function is by evaluating a list.
586 For example, evaluating the list `(concat "a" "b")' calls the function
587 `concat' with arguments `"a"' and `"b"'. *Note Evaluation::, for a
588 description of evaluation.
590 When you write a list as an expression in your program, the function
591 name is part of the program. This means that you choose which function
592 to call, and how many arguments to give it, when you write the program.
593 Usually that's just what you want. Occasionally you need to decide at
594 run time which function to call. To do that, use the functions
595 `funcall' and `apply'.
597 - Function: funcall FUNCTION &rest ARGUMENTS
598 `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
601 Since `funcall' is a function, all of its arguments, including
602 FUNCTION, are evaluated before `funcall' is called. This means
603 that you can use any expression to obtain the function to be
604 called. It also means that `funcall' does not see the expressions
605 you write for the ARGUMENTS, only their values. These values are
606 *not* evaluated a second time in the act of calling FUNCTION;
607 `funcall' enters the normal procedure for calling a function at the
608 place where the arguments have already been evaluated.
610 The argument FUNCTION must be either a Lisp function or a
611 primitive function. Special forms and macros are not allowed,
612 because they make sense only when given the "unevaluated" argument
613 expressions. `funcall' cannot provide these because, as we saw
614 above, it never knows them in the first place.
620 (funcall f 'x 'y '(z))
623 error--> Invalid function: #<subr and>
625 Compare these example with the examples of `apply'.
627 - Function: apply FUNCTION &rest ARGUMENTS
628 `apply' calls FUNCTION with ARGUMENTS, just like `funcall' but
629 with one difference: the last of ARGUMENTS is a list of arguments
630 to give to FUNCTION, rather than a single argument. We also say
631 that `apply' "spreads" this list so that each individual element
634 `apply' returns the result of calling FUNCTION. As with
635 `funcall', FUNCTION must either be a Lisp function or a primitive
636 function; special forms and macros do not make sense in `apply'.
641 error--> Wrong type argument: listp, z
642 (apply '+ 1 2 '(3 4))
644 (apply '+ '(1 2 3 4))
647 (apply 'append '((a b c) nil (x y z) nil))
650 For an interesting example of using `apply', see the description of
651 `mapcar', in *Note Mapping Functions::.
653 It is common for Lisp functions to accept functions as arguments or
654 find them in data structures (especially in hook variables and property
655 lists) and call them using `funcall' or `apply'. Functions that accept
656 function arguments are often called "functionals".
658 Sometimes, when you call a functional, it is useful to supply a no-op
659 function as the argument. Here are two different kinds of no-op
662 - Function: identity ARG
663 This function returns ARG and has no side effects.
665 - Function: ignore &rest ARGS
666 This function ignores any arguments and returns `nil'.
669 File: lispref.info, Node: Mapping Functions, Next: Anonymous Functions, Prev: Calling Functions, Up: Functions
674 A "mapping function" applies a given function to each element of a
675 list or other collection. XEmacs Lisp has several such functions;
676 `mapcar' and `mapconcat', which scan a list, are described here.
677 *Note Creating Symbols::, for the function `mapatoms' which maps over
678 the symbols in an obarray.
680 Mapping functions should never modify the sequence being mapped over.
681 The results are unpredictable.
683 - Function: mapcar FUNCTION SEQUENCE
684 `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and
685 returns a list of the results.
687 The argument SEQUENCE can be any kind of sequence; that is, a
688 list, a vector, a bit vector, or a string. The result is always a
689 list. The length of the result is the same as the length of
694 (mapcar 'car '((a b) (c d) (e f)))
698 (mapcar 'char-to-string "abc")
701 ;; Call each function in `my-hooks'.
702 (mapcar 'funcall my-hooks)
704 (defun mapcar* (f &rest args)
705 "Apply FUNCTION to successive cars of all ARGS.
706 Return the list of results."
707 ;; If no list is exhausted,
708 (if (not (memq 'nil args))
709 ;; apply function to CARs.
710 (cons (apply f (mapcar 'car args))
712 ;; Recurse for rest of elements.
713 (mapcar 'cdr args)))))
715 (mapcar* 'cons '(a b c) '(1 2 3 4))
716 => ((a . 1) (b . 2) (c . 3))
718 - Function: mapconcat FUNCTION SEQUENCE SEPARATOR
719 `mapconcat' applies FUNCTION to each element of SEQUENCE: the
720 results, which must be strings, are concatenated. Between each
721 pair of result strings, `mapconcat' inserts the string SEPARATOR.
722 Usually SEPARATOR contains a space or comma or other suitable
725 The argument FUNCTION must be a function that can take one
726 argument and return a string. The argument SEQUENCE can be any
727 kind of sequence; that is, a list, a vector, a bit vector, or a
730 (mapconcat 'symbol-name
731 '(The cat in the hat)
733 => "The cat in the hat"
735 (mapconcat (function (lambda (x) (format "%c" (1+ x))))
741 File: lispref.info, Node: Anonymous Functions, Next: Function Cells, Prev: Mapping Functions, Up: Functions
746 In Lisp, a function is a list that starts with `lambda', a byte-code
747 function compiled from such a list, or alternatively a primitive
748 subr-object; names are "extra". Although usually functions are defined
749 with `defun' and given names at the same time, it is occasionally more
750 concise to use an explicit lambda expression--an anonymous function.
751 Such a list is valid wherever a function name is.
753 Any method of creating such a list makes a valid function. Even
756 (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
757 => (lambda (x) (+ 12 x))
759 This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
760 it the value (*not* the function definition!) of `silly'.
762 Here is how we might call this function:
767 (It does *not* work to write `(silly 1)', because this function is not
768 the *function definition* of `silly'. We have not given `silly' any
769 function definition, just a value as a variable.)
771 Most of the time, anonymous functions are constants that appear in
772 your program. For example, you might want to pass one as an argument
773 to the function `mapcar', which applies any given function to each
774 element of a list. Here we pass an anonymous function that multiplies
777 (defun double-each (list)
778 (mapcar '(lambda (x) (* 2 x)) list))
780 (double-each '(2 11))
783 In such cases, we usually use the special form `function' instead of
784 simple quotation to quote the anonymous function.
786 - Special Form: function FUNCTION-OBJECT
787 This special form returns FUNCTION-OBJECT without evaluating it.
788 In this, it is equivalent to `quote'. However, it serves as a
789 note to the XEmacs Lisp compiler that FUNCTION-OBJECT is intended
790 to be used only as a function, and therefore can safely be
791 compiled. Contrast this with `quote', in *Note Quoting::.
793 Using `function' instead of `quote' makes a difference inside a
794 function or macro that you are going to compile. For example:
796 (defun double-each (list)
797 (mapcar (function (lambda (x) (* 2 x))) list))
799 (double-each '(2 11))
802 If this definition of `double-each' is compiled, the anonymous function
803 is compiled as well. By contrast, in the previous definition where
804 ordinary `quote' is used, the argument passed to `mapcar' is the
809 The Lisp compiler cannot assume this list is a function, even though it
810 looks like one, since it does not know what `mapcar' does with the
811 list. Perhaps `mapcar' will check that the CAR of the third element is
812 the symbol `*'! The advantage of `function' is that it tells the
813 compiler to go ahead and compile the constant function.
815 We sometimes write `function' instead of `quote' when quoting the
816 name of a function, but this usage is just a sort of comment.
818 (function SYMBOL) == (quote SYMBOL) == 'SYMBOL
820 See `documentation' in *Note Accessing Documentation::, for a
821 realistic example using `function' and an anonymous function.
824 File: lispref.info, Node: Function Cells, Next: Inline Functions, Prev: Anonymous Functions, Up: Functions
826 Accessing Function Cell Contents
827 ================================
829 The "function definition" of a symbol is the object stored in the
830 function cell of the symbol. The functions described here access, test,
831 and set the function cell of symbols.
833 See also the function `indirect-function' in *Note Function
836 - Function: symbol-function SYMBOL
837 This returns the object in the function cell of SYMBOL. If the
838 symbol's function cell is void, a `void-function' error is
841 This function does not check that the returned object is a
844 (defun bar (n) (+ n 2))
846 (symbol-function 'bar)
847 => (lambda (n) (+ n 2))
850 (symbol-function 'baz)
853 If you have never given a symbol any function definition, we say that
854 that symbol's function cell is "void". In other words, the function
855 cell does not have any Lisp object in it. If you try to call such a
856 symbol as a function, it signals a `void-function' error.
858 Note that void is not the same as `nil' or the symbol `void'. The
859 symbols `nil' and `void' are Lisp objects, and can be stored into a
860 function cell just as any other object can be (and they can be valid
861 functions if you define them in turn with `defun'). A void function
862 cell contains no object whatsoever.
864 You can test the voidness of a symbol's function definition with
865 `fboundp'. After you have given a symbol a function definition, you
866 can make it void once more using `fmakunbound'.
868 - Function: fboundp SYMBOL
869 This function returns `t' if the symbol has an object in its
870 function cell, `nil' otherwise. It does not check that the object
871 is a legitimate function.
873 - Function: fmakunbound SYMBOL
874 This function makes SYMBOL's function cell void, so that a
875 subsequent attempt to access this cell will cause a `void-function'
876 error. (See also `makunbound', in *Note Local Variables::.)
885 error--> Symbol's function definition is void: foo
887 - Function: fset SYMBOL OBJECT
888 This function stores OBJECT in the function cell of SYMBOL. The
889 result is OBJECT. Normally OBJECT should be a function or the
890 name of a function, but this is not checked.
892 There are three normal uses of this function:
894 * Copying one symbol's function definition to another. (In
895 other words, making an alternate name for a function.)
897 * Giving a symbol a function definition that is not a list and
898 therefore cannot be made with `defun'. For example, you can
899 use `fset' to give a symbol `s1' a function definition which
900 is another symbol `s2'; then `s1' serves as an alias for
901 whatever definition `s2' presently has.
903 * In constructs for defining or altering functions. If `defun'
904 were not a primitive, it could be written in Lisp (as a
907 Here are examples of the first two uses:
909 ;; Give `first' the same definition `car' has.
910 (fset 'first (symbol-function 'car))
915 ;; Make the symbol `car' the function definition of `xfirst'.
920 (symbol-function 'xfirst)
922 (symbol-function (symbol-function 'xfirst))
925 ;; Define a named keyboard macro.
926 (fset 'kill-two-lines "\^u2\^k")
929 See also the related functions `define-function' and `defalias',
930 in *Note Defining Functions::.
932 When writing a function that extends a previously defined function,
933 the following idiom is sometimes used:
935 (fset 'old-foo (symbol-function 'foo))
937 "Just like old-foo, except more so."
941 This does not work properly if `foo' has been defined to autoload. In
942 such a case, when `foo' calls `old-foo', Lisp attempts to define
943 `old-foo' by loading a file. Since this presumably defines `foo'
944 rather than `old-foo', it does not produce the proper results. The
945 only way to avoid this problem is to make sure the file is loaded
946 before moving aside the old definition of `foo'.
948 But it is unmodular and unclean, in any case, for a Lisp file to
949 redefine a function defined elsewhere.
952 File: lispref.info, Node: Inline Functions, Next: Related Topics, Prev: Function Cells, Up: Functions
957 You can define an "inline function" by using `defsubst' instead of
958 `defun'. An inline function works just like an ordinary function
959 except for one thing: when you compile a call to the function, the
960 function's definition is open-coded into the caller.
962 Making a function inline makes explicit calls run faster. But it
963 also has disadvantages. For one thing, it reduces flexibility; if you
964 change the definition of the function, calls already inlined still use
965 the old definition until you recompile them. Since the flexibility of
966 redefining functions is an important feature of XEmacs, you should not
967 make a function inline unless its speed is really crucial.
969 Another disadvantage is that making a large function inline can
970 increase the size of compiled code both in files and in memory. Since
971 the speed advantage of inline functions is greatest for small
972 functions, you generally should not make large functions inline.
974 It's possible to define a macro to expand into the same code that an
975 inline function would execute. But the macro would have a limitation:
976 you can use it only explicitly--a macro cannot be called with `apply',
977 `mapcar' and so on. Also, it takes some work to convert an ordinary
978 function into a macro. (*Note Macros::.) To convert it into an inline
979 function is very easy; simply replace `defun' with `defsubst'. Since
980 each argument of an inline function is evaluated exactly once, you
981 needn't worry about how many times the body uses the arguments, as you
982 do for macros. (*Note Argument Evaluation::.)
984 Inline functions can be used and open-coded later on in the same
985 file, following the definition, just like macros.
988 File: lispref.info, Node: Related Topics, Prev: Inline Functions, Up: Functions
990 Other Topics Related to Functions
991 =================================
993 Here is a table of several functions that do things related to
994 function calling and function definitions. They are documented
995 elsewhere, but we provide cross references here.
998 See *Note Calling Functions::.
1001 See *Note Autoload::.
1003 `call-interactively'
1004 See *Note Interactive Call::.
1007 See *Note Interactive Call::.
1010 See *Note Accessing Documentation::.
1016 See *Note Calling Functions::.
1019 See *Note Calling Functions::.
1022 See *Note Function Indirection::.
1025 See *Note Using Interactive::.
1028 See *Note Interactive Call::.
1031 See *Note Creating Symbols::.
1034 See *Note Mapping Functions::.
1037 See *Note Mapping Functions::.
1040 See *Note Key Lookup::.
1043 File: lispref.info, Node: Macros, Next: Loading, Prev: Functions, Up: Top
1048 "Macros" enable you to define new control constructs and other
1049 language features. A macro is defined much like a function, but instead
1050 of telling how to compute a value, it tells how to compute another Lisp
1051 expression which will in turn compute the value. We call this
1052 expression the "expansion" of the macro.
1054 Macros can do this because they operate on the unevaluated
1055 expressions for the arguments, not on the argument values as functions
1056 do. They can therefore construct an expansion containing these
1057 argument expressions or parts of them.
1059 If you are using a macro to do something an ordinary function could
1060 do, just for the sake of speed, consider using an inline function
1061 instead. *Note Inline Functions::.
1065 * Simple Macro:: A basic example.
1066 * Expansion:: How, when and why macros are expanded.
1067 * Compiling Macros:: How macros are expanded by the compiler.
1068 * Defining Macros:: How to write a macro definition.
1069 * Backquote:: Easier construction of list structure.
1070 * Problems with Macros:: Don't evaluate the macro arguments too many times.
1071 Don't hide the user's variables.
1074 File: lispref.info, Node: Simple Macro, Next: Expansion, Up: Macros
1076 A Simple Example of a Macro
1077 ===========================
1079 Suppose we would like to define a Lisp construct to increment a
1080 variable value, much like the `++' operator in C. We would like to
1081 write `(inc x)' and have the effect of `(setq x (1+ x))'. Here's a
1082 macro definition that does the job:
1085 (list 'setq var (list '1+ var)))
1087 When this is called with `(inc x)', the argument `var' has the value
1088 `x'--*not* the *value* of `x'. The body of the macro uses this to
1089 construct the expansion, which is `(setq x (1+ x))'. Once the macro
1090 definition returns this expansion, Lisp proceeds to evaluate it, thus
1094 File: lispref.info, Node: Expansion, Next: Compiling Macros, Prev: Simple Macro, Up: Macros
1096 Expansion of a Macro Call
1097 =========================
1099 A macro call looks just like a function call in that it is a list
1100 which starts with the name of the macro. The rest of the elements of
1101 the list are the arguments of the macro.
1103 Evaluation of the macro call begins like evaluation of a function
1104 call except for one crucial difference: the macro arguments are the
1105 actual expressions appearing in the macro call. They are not evaluated
1106 before they are given to the macro definition. By contrast, the
1107 arguments of a function are results of evaluating the elements of the
1110 Having obtained the arguments, Lisp invokes the macro definition just
1111 as a function is invoked. The argument variables of the macro are bound
1112 to the argument values from the macro call, or to a list of them in the
1113 case of a `&rest' argument. And the macro body executes and returns
1114 its value just as a function body does.
1116 The second crucial difference between macros and functions is that
1117 the value returned by the macro body is not the value of the macro call.
1118 Instead, it is an alternate expression for computing that value, also
1119 known as the "expansion" of the macro. The Lisp interpreter proceeds
1120 to evaluate the expansion as soon as it comes back from the macro.
1122 Since the expansion is evaluated in the normal manner, it may contain
1123 calls to other macros. It may even be a call to the same macro, though
1126 You can see the expansion of a given macro call by calling
1129 - Function: macroexpand FORM &optional ENVIRONMENT
1130 This function expands FORM, if it is a macro call. If the result
1131 is another macro call, it is expanded in turn, until something
1132 which is not a macro call results. That is the value returned by
1133 `macroexpand'. If FORM is not a macro call to begin with, it is
1136 Note that `macroexpand' does not look at the subexpressions of
1137 FORM (although some macro definitions may do so). Even if they
1138 are macro calls themselves, `macroexpand' does not expand them.
1140 The function `macroexpand' does not expand calls to inline
1141 functions. Normally there is no need for that, since a call to an
1142 inline function is no harder to understand than a call to an
1145 If ENVIRONMENT is provided, it specifies an alist of macro
1146 definitions that shadow the currently defined macros. Byte
1147 compilation uses this feature.
1150 (list 'setq var (list '1+ var)))
1153 (macroexpand '(inc r))
1156 (defmacro inc2 (var1 var2)
1157 (list 'progn (list 'inc var1) (list 'inc var2)))
1160 (macroexpand '(inc2 r s))
1161 => (progn (inc r) (inc s)) ; `inc' not expanded here.
1164 File: lispref.info, Node: Compiling Macros, Next: Defining Macros, Prev: Expansion, Up: Macros
1166 Macros and Byte Compilation
1167 ===========================
1169 You might ask why we take the trouble to compute an expansion for a
1170 macro and then evaluate the expansion. Why not have the macro body
1171 produce the desired results directly? The reason has to do with
1174 When a macro call appears in a Lisp program being compiled, the Lisp
1175 compiler calls the macro definition just as the interpreter would, and
1176 receives an expansion. But instead of evaluating this expansion, it
1177 compiles the expansion as if it had appeared directly in the program.
1178 As a result, the compiled code produces the value and side effects
1179 intended for the macro, but executes at full compiled speed. This would
1180 not work if the macro body computed the value and side effects
1181 itself--they would be computed at compile time, which is not useful.
1183 In order for compilation of macro calls to work, the macros must be
1184 defined in Lisp when the calls to them are compiled. The compiler has a
1185 special feature to help you do this: if a file being compiled contains a
1186 `defmacro' form, the macro is defined temporarily for the rest of the
1187 compilation of that file. To use this feature, you must define the
1188 macro in the same file where it is used and before its first use.
1190 Byte-compiling a file executes any `require' calls at top-level in
1191 the file. This is in case the file needs the required packages for
1192 proper compilation. One way to ensure that necessary macro definitions
1193 are available during compilation is to require the files that define
1194 them (*note Named Features::.). To avoid loading the macro definition
1195 files when someone *runs* the compiled program, write
1196 `eval-when-compile' around the `require' calls (*note Eval During
1200 File: lispref.info, Node: Defining Macros, Next: Backquote, Prev: Compiling Macros, Up: Macros
1205 A Lisp macro is a list whose CAR is `macro'. Its CDR should be a
1206 function; expansion of the macro works by applying the function (with
1207 `apply') to the list of unevaluated argument-expressions from the macro
1210 It is possible to use an anonymous Lisp macro just like an anonymous
1211 function, but this is never done, because it does not make sense to pass
1212 an anonymous macro to functionals such as `mapcar'. In practice, all
1213 Lisp macros have names, and they are usually defined with the special
1216 - Special Form: defmacro NAME ARGUMENT-LIST BODY-FORMS...
1217 `defmacro' defines the symbol NAME as a macro that looks like this:
1219 (macro lambda ARGUMENT-LIST . BODY-FORMS)
1221 This macro object is stored in the function cell of NAME. The
1222 value returned by evaluating the `defmacro' form is NAME, but
1223 usually we ignore this value.
1225 The shape and meaning of ARGUMENT-LIST is the same as in a
1226 function, and the keywords `&rest' and `&optional' may be used
1227 (*note Argument List::.). Macros may have a documentation string,
1228 but any `interactive' declaration is ignored since macros cannot be
1229 called interactively.