This commit was generated by cvs2svn to compensate for changes in r5670,
[chise/xemacs-chise.git.1] / info / lispref.info-10
1 This is Info file ../../info/lispref.info, produced by Makeinfo version
2 1.68 from the input file lispref.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Lispref: (lispref).           XEmacs Lisp Reference Manual.
7 END-INFO-DIR-ENTRY
8
9    Edition History:
10
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
20
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.
24
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.
28
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.
33
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.
38
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.
45
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.
51
52 \1f
53 File: lispref.info,  Node: Variable Aliases,  Prev: Buffer-Local Variables,  Up: Variables
54
55 Variable Aliases
56 ================
57
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
63 Obsoleteness::.).
64
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'.
76
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'.
81
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.
89
90 \1f
91 File: lispref.info,  Node: Functions,  Next: Macros,  Prev: Variables,  Up: Top
92
93 Functions
94 *********
95
96    A Lisp program is composed mainly of Lisp functions.  This chapter
97 explains what functions are, how they accept arguments, and how to
98 define them.
99
100 * Menu:
101
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
110                             of a symbol.
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.
114
115 \1f
116 File: lispref.info,  Node: What Is a Function,  Next: Lambda Expressions,  Up: Functions
117
118 What Is a Function?
119 ===================
120
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.
126
127    Here are important terms for functions in XEmacs Lisp and for other
128 function-like objects.
129
130 "function"
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.
135
136 "primitive"
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.)
141
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.
148
149 "lambda expression"
150      A "lambda expression" is a function written in Lisp.  These are
151      described in the following section.  *Note Lambda Expressions::.
152
153 "special form"
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::.
159
160 "macro"
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.
167
168 "command"
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
175      difference.
176
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::.
182
183 "keystroke command"
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
188      unimportant.
189
190 "compiled function"
191      A "compiled function" is a function that has been compiled by the
192      byte compiler.  *Note Compiled-Function Type::.
193
194  - Function: subrp OBJECT
195      This function returns `t' if OBJECT is a built-in function (i.e.,
196      a Lisp primitive).
197
198           (subrp 'message)            ; `message' is a symbol,
199                => nil                 ;   not a subr object.
200           (subrp (symbol-function 'message))
201                => t
202
203  - Function: compiled-function-p OBJECT
204      This function returns `t' if OBJECT is a compiled function.  For
205      example:
206
207           (compiled-function-p (symbol-function 'next-line))
208                => t
209
210 \1f
211 File: lispref.info,  Node: Lambda Expressions,  Next: Function Names,  Prev: What Is a Function,  Up: Functions
212
213 Lambda Expressions
214 ==================
215
216    A function written in Lisp is a list that looks like this:
217
218      (lambda (ARG-VARIABLES...)
219        [DOCUMENTATION-STRING]
220        [INTERACTIVE-DECLARATION]
221        BODY-FORMS...)
222
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.
228
229 * Menu:
230
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.
235
236 \1f
237 File: lispref.info,  Node: Lambda Components,  Next: Simple Lambda,  Up: Lambda Expressions
238
239 Components of a Lambda Expression
240 ---------------------------------
241
242    A function written in Lisp (a "lambda expression") is a list that
243 looks like this:
244
245      (lambda (ARG-VARIABLES...)
246        [DOCUMENTATION-STRING]
247        [INTERACTIVE-DECLARATION]
248        BODY-FORMS...)
249
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
254 functions.
255
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
260 Local Variables::.
261
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::.
265
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.
273
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.
278
279 \1f
280 File: lispref.info,  Node: Simple Lambda,  Next: Argument List,  Prev: Lambda Components,  Up: Lambda Expressions
281
282 A Simple Lambda-Expression Example
283 ----------------------------------
284
285    Consider for example the following function:
286
287      (lambda (a b c) (+ a b c))
288
289 We can call this function by writing it as the CAR of an expression,
290 like this:
291
292      ((lambda (a b c) (+ a b c))
293       1 2 3)
294
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.
299
300    Note that the arguments can be the results of other function calls,
301 as in this example:
302
303      ((lambda (a b c) (+ a b c))
304       1 (* 2 3) (- 5 4))
305
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.
309
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::.).
317
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.
321
322 \1f
323 File: lispref.info,  Node: Argument List,  Next: Function Documentation,  Prev: Simple Lambda,  Up: Lambda Expressions
324
325 Advanced Features of Argument Lists
326 -----------------------------------
327
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.
332
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.
339
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.
344
345    Thus, the complete syntax for an argument list is as follows:
346
347      (REQUIRED-VARS...
348       [&optional OPTIONAL-VARS...]
349       [&rest REST-VAR])
350
351 The square brackets indicate that the `&optional' and `&rest' clauses,
352 and the variables that follow them, are optional.
353
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.
359
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.
367
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'.
371
372    For example, an argument list that looks like this:
373
374      (a b &optional c d &rest e)
375
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'.
382
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.
389
390    Here are some examples of argument lists and proper calls:
391
392      ((lambda (n) (1+ n))                ; One required:
393       1)                                 ; requires exactly one argument.
394           => 2
395      ((lambda (n &optional n1)           ; One required and one optional:
396               (if n1 (+ n n1) (1+ n)))   ; 1 or 2 arguments.
397       1 2)
398           => 3
399      ((lambda (n &rest ns)               ; One required and one rest:
400               (+ n (apply '+ ns)))       ; 1 or more arguments.
401       1 2 3 4 5)
402           => 15
403
404 \1f
405 File: lispref.info,  Node: Function Documentation,  Prev: Argument List,  Up: Lambda Expressions
406
407 Documentation Strings of Functions
408 ----------------------------------
409
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.
416
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.
421
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.
425
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
433 commands.
434
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.
442
443 \1f
444 File: lispref.info,  Node: Function Names,  Next: Defining Functions,  Prev: Lambda Expressions,  Up: Functions
445
446 Naming a Function
447 =================
448
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.
453
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::.
462
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.
467
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
477 practice).
478
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
483 distinguish.
484
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.
490
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.
493
494 \1f
495 File: lispref.info,  Node: Defining Functions,  Next: Calling Functions,  Prev: Function Names,  Up: Functions
496
497 Defining Functions
498 ==================
499
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'
502 special form.
503
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:
507
508           (lambda ARGUMENT-LIST . BODY-FORMS)
509
510      `defun' stores this lambda expression in the function cell of
511      NAME.  It returns the value NAME, but usually we ignore this value.
512
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
517      declaration.
518
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::.
522
523      Here are some examples:
524
525           (defun foo () 5)
526                => foo
527           (foo)
528                => 5
529           
530           (defun bar (a &optional b &rest c)
531               (list a b c))
532                => bar
533           (bar 1 2 3 4 5)
534                => (1 2 (3 4 5))
535           (bar 1)
536                => (1 nil nil)
537           (bar)
538           error--> Wrong number of arguments.
539           
540           (defun capitalize-backwards ()
541             "Upcase the last letter of a word."
542             (interactive)
543             (backward-word 1)
544             (forward-word 1)
545             (backward-char 1)
546             (capitalize-word 1))
547                => capitalize-backwards
548
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
554      redefinition.
555
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
560      function).
561
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::.).
567
568      By contrast, in programs that manipulate function definitions for
569      other purposes, it is better to use `fset', which does not keep
570      such records.
571
572    See also `defsubst', which defines a function like `defun' and tells
573 the Lisp compiler to open-code it.  *Note Inline Functions::.
574
575 \1f
576 File: lispref.info,  Node: Calling Functions,  Next: Mapping Functions,  Prev: Defining Functions,  Up: Functions
577
578 Calling Functions
579 =================
580
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".
584
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.
589
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'.
596
597  - Function: funcall FUNCTION &rest ARGUMENTS
598      `funcall' calls FUNCTION with ARGUMENTS, and returns whatever
599      FUNCTION returns.
600
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.
609
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.
615
616           (setq f 'list)
617                => list
618           (funcall f 'x 'y 'z)
619                => (x y z)
620           (funcall f 'x 'y '(z))
621                => (x y (z))
622           (funcall 'and t nil)
623           error--> Invalid function: #<subr and>
624
625      Compare these example with the examples of `apply'.
626
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
632      becomes an argument.
633
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'.
637
638           (setq f 'list)
639                => list
640           (apply f 'x 'y 'z)
641           error--> Wrong type argument: listp, z
642           (apply '+ 1 2 '(3 4))
643                => 10
644           (apply '+ '(1 2 3 4))
645                => 10
646           
647           (apply 'append '((a b c) nil (x y z) nil))
648                => (a b c x y z)
649
650      For an interesting example of using `apply', see the description of
651      `mapcar', in *Note Mapping Functions::.
652
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".
657
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
660 function:
661
662  - Function: identity ARG
663      This function returns ARG and has no side effects.
664
665  - Function: ignore &rest ARGS
666      This function ignores any arguments and returns `nil'.
667
668 \1f
669 File: lispref.info,  Node: Mapping Functions,  Next: Anonymous Functions,  Prev: Calling Functions,  Up: Functions
670
671 Mapping Functions
672 =================
673
674    A "mapping function" applies a given function to each element of a
675 list or other collection.  XEmacs Lisp has three such functions;
676 `mapcar' and `mapconcat', which scan a list, are described here.  For
677 the third mapping function, `mapatoms', see *Note Creating Symbols::.
678
679  - Function: mapcar FUNCTION SEQUENCE
680      `mapcar' applies FUNCTION to each element of SEQUENCE in turn, and
681      returns a list of the results.
682
683      The argument SEQUENCE may be a list, a vector, or a string.  The
684      result is always a list.  The length of the result is the same as
685      the length of SEQUENCE.
686
687      For example:
688
689           (mapcar 'car '((a b) (c d) (e f)))
690                => (a c e)
691           (mapcar '1+ [1 2 3])
692                => (2 3 4)
693           (mapcar 'char-to-string "abc")
694                => ("a" "b" "c")
695
696           ;; Call each function in `my-hooks'.
697           (mapcar 'funcall my-hooks)
698
699           (defun mapcar* (f &rest args)
700             "Apply FUNCTION to successive cars of all ARGS.
701           Return the list of results."
702             ;; If no list is exhausted,
703             (if (not (memq 'nil args))
704                 ;; apply function to CARs.
705                 (cons (apply f (mapcar 'car args))
706                       (apply 'mapcar* f
707                              ;; Recurse for rest of elements.
708                              (mapcar 'cdr args)))))
709
710           (mapcar* 'cons '(a b c) '(1 2 3 4))
711                => ((a . 1) (b . 2) (c . 3))
712
713  - Function: mapconcat FUNCTION SEQUENCE SEPARATOR
714      `mapconcat' applies FUNCTION to each element of SEQUENCE: the
715      results, which must be strings, are concatenated.  Between each
716      pair of result strings, `mapconcat' inserts the string SEPARATOR.
717      Usually SEPARATOR contains a space or comma or other suitable
718      punctuation.
719
720      The argument FUNCTION must be a function that can take one
721      argument and return a string.
722
723           (mapconcat 'symbol-name
724                      '(The cat in the hat)
725                      " ")
726                => "The cat in the hat"
727
728           (mapconcat (function (lambda (x) (format "%c" (1+ x))))
729                      "HAL-8000"
730                      "")
731                => "IBM.9111"
732
733 \1f
734 File: lispref.info,  Node: Anonymous Functions,  Next: Function Cells,  Prev: Mapping Functions,  Up: Functions
735
736 Anonymous Functions
737 ===================
738
739    In Lisp, a function is a list that starts with `lambda', a byte-code
740 function compiled from such a list, or alternatively a primitive
741 subr-object; names are "extra".  Although usually functions are defined
742 with `defun' and given names at the same time, it is occasionally more
743 concise to use an explicit lambda expression--an anonymous function.
744 Such a list is valid wherever a function name is.
745
746    Any method of creating such a list makes a valid function.  Even
747 this:
748
749      (setq silly (append '(lambda (x)) (list (list '+ (* 3 4) 'x))))
750      => (lambda (x) (+ 12 x))
751
752 This computes a list that looks like `(lambda (x) (+ 12 x))' and makes
753 it the value (*not* the function definition!) of `silly'.
754
755    Here is how we might call this function:
756
757      (funcall silly 1)
758      => 13
759
760 (It does *not* work to write `(silly 1)', because this function is not
761 the *function definition* of `silly'.  We have not given `silly' any
762 function definition, just a value as a variable.)
763
764    Most of the time, anonymous functions are constants that appear in
765 your program.  For example, you might want to pass one as an argument
766 to the function `mapcar', which applies any given function to each
767 element of a list.  Here we pass an anonymous function that multiplies
768 a number by two:
769
770      (defun double-each (list)
771        (mapcar '(lambda (x) (* 2 x)) list))
772      => double-each
773      (double-each '(2 11))
774      => (4 22)
775
776 In such cases, we usually use the special form `function' instead of
777 simple quotation to quote the anonymous function.
778
779  - Special Form: function FUNCTION-OBJECT
780      This special form returns FUNCTION-OBJECT without evaluating it.
781      In this, it is equivalent to `quote'.  However, it serves as a
782      note to the XEmacs Lisp compiler that FUNCTION-OBJECT is intended
783      to be used only as a function, and therefore can safely be
784      compiled.  Contrast this with `quote', in *Note Quoting::.
785
786    Using `function' instead of `quote' makes a difference inside a
787 function or macro that you are going to compile.  For example:
788
789      (defun double-each (list)
790        (mapcar (function (lambda (x) (* 2 x))) list))
791      => double-each
792      (double-each '(2 11))
793      => (4 22)
794
795 If this definition of `double-each' is compiled, the anonymous function
796 is compiled as well.  By contrast, in the previous definition where
797 ordinary `quote' is used, the argument passed to `mapcar' is the
798 precise list shown:
799
800      (lambda (x) (* x 2))
801
802 The Lisp compiler cannot assume this list is a function, even though it
803 looks like one, since it does not know what `mapcar' does with the
804 list.  Perhaps `mapcar' will check that the CAR of the third element is
805 the symbol `*'!  The advantage of `function' is that it tells the
806 compiler to go ahead and compile the constant function.
807
808    We sometimes write `function' instead of `quote' when quoting the
809 name of a function, but this usage is just a sort of comment.
810
811      (function SYMBOL) == (quote SYMBOL) == 'SYMBOL
812
813    See `documentation' in *Note Accessing Documentation::, for a
814 realistic example using `function' and an anonymous function.
815
816 \1f
817 File: lispref.info,  Node: Function Cells,  Next: Inline Functions,  Prev: Anonymous Functions,  Up: Functions
818
819 Accessing Function Cell Contents
820 ================================
821
822    The "function definition" of a symbol is the object stored in the
823 function cell of the symbol.  The functions described here access, test,
824 and set the function cell of symbols.
825
826    See also the function `indirect-function' in *Note Function
827 Indirection::.
828
829  - Function: symbol-function SYMBOL
830      This returns the object in the function cell of SYMBOL.  If the
831      symbol's function cell is void, a `void-function' error is
832      signaled.
833
834      This function does not check that the returned object is a
835      legitimate function.
836
837           (defun bar (n) (+ n 2))
838                => bar
839           (symbol-function 'bar)
840                => (lambda (n) (+ n 2))
841           (fset 'baz 'bar)
842                => bar
843           (symbol-function 'baz)
844                => bar
845
846    If you have never given a symbol any function definition, we say that
847 that symbol's function cell is "void".  In other words, the function
848 cell does not have any Lisp object in it.  If you try to call such a
849 symbol as a function, it signals a `void-function' error.
850
851    Note that void is not the same as `nil' or the symbol `void'.  The
852 symbols `nil' and `void' are Lisp objects, and can be stored into a
853 function cell just as any other object can be (and they can be valid
854 functions if you define them in turn with `defun').  A void function
855 cell contains no object whatsoever.
856
857    You can test the voidness of a symbol's function definition with
858 `fboundp'.  After you have given a symbol a function definition, you
859 can make it void once more using `fmakunbound'.
860
861  - Function: fboundp SYMBOL
862      This function returns `t' if the symbol has an object in its
863      function cell, `nil' otherwise.  It does not check that the object
864      is a legitimate function.
865
866  - Function: fmakunbound SYMBOL
867      This function makes SYMBOL's function cell void, so that a
868      subsequent attempt to access this cell will cause a `void-function'
869      error.  (See also `makunbound', in *Note Local Variables::.)
870
871           (defun foo (x) x)
872                => x
873           (foo 1)
874                =>1
875           (fmakunbound 'foo)
876                => x
877           (foo 1)
878           error--> Symbol's function definition is void: foo
879
880  - Function: fset SYMBOL OBJECT
881      This function stores OBJECT in the function cell of SYMBOL.  The
882      result is OBJECT.  Normally OBJECT should be a function or the
883      name of a function, but this is not checked.
884
885      There are three normal uses of this function:
886
887         * Copying one symbol's function definition to another.  (In
888           other words, making an alternate name for a function.)
889
890         * Giving a symbol a function definition that is not a list and
891           therefore cannot be made with `defun'.  For example, you can
892           use `fset' to give a symbol `s1' a function definition which
893           is another symbol `s2'; then `s1' serves as an alias for
894           whatever definition `s2' presently has.
895
896         * In constructs for defining or altering functions.  If `defun'
897           were not a primitive, it could be written in Lisp (as a
898           macro) using `fset'.
899
900      Here are examples of the first two uses:
901
902           ;; Give `first' the same definition `car' has.
903           (fset 'first (symbol-function 'car))
904                => #<subr car>
905           (first '(1 2 3))
906                => 1
907           
908           ;; Make the symbol `car' the function definition of `xfirst'.
909           (fset 'xfirst 'car)
910                => car
911           (xfirst '(1 2 3))
912                => 1
913           (symbol-function 'xfirst)
914                => car
915           (symbol-function (symbol-function 'xfirst))
916                => #<subr car>
917           
918           ;; Define a named keyboard macro.
919           (fset 'kill-two-lines "\^u2\^k")
920                => "\^u2\^k"
921
922      See also the related functions `define-function' and `defalias',
923      in *Note Defining Functions::.
924
925    When writing a function that extends a previously defined function,
926 the following idiom is sometimes used:
927
928      (fset 'old-foo (symbol-function 'foo))
929      (defun foo ()
930        "Just like old-foo, except more so."
931        (old-foo)
932        (more-so))
933
934 This does not work properly if `foo' has been defined to autoload.  In
935 such a case, when `foo' calls `old-foo', Lisp attempts to define
936 `old-foo' by loading a file.  Since this presumably defines `foo'
937 rather than `old-foo', it does not produce the proper results.  The
938 only way to avoid this problem is to make sure the file is loaded
939 before moving aside the old definition of `foo'.
940
941    But it is unmodular and unclean, in any case, for a Lisp file to
942 redefine a function defined elsewhere.
943
944 \1f
945 File: lispref.info,  Node: Inline Functions,  Next: Related Topics,  Prev: Function Cells,  Up: Functions
946
947 Inline Functions
948 ================
949
950    You can define an "inline function" by using `defsubst' instead of
951 `defun'.  An inline function works just like an ordinary function
952 except for one thing: when you compile a call to the function, the
953 function's definition is open-coded into the caller.
954
955    Making a function inline makes explicit calls run faster.  But it
956 also has disadvantages.  For one thing, it reduces flexibility; if you
957 change the definition of the function, calls already inlined still use
958 the old definition until you recompile them.  Since the flexibility of
959 redefining functions is an important feature of XEmacs, you should not
960 make a function inline unless its speed is really crucial.
961
962    Another disadvantage is that making a large function inline can
963 increase the size of compiled code both in files and in memory.  Since
964 the speed advantage of inline functions is greatest for small
965 functions, you generally should not make large functions inline.
966
967    It's possible to define a macro to expand into the same code that an
968 inline function would execute.  But the macro would have a limitation:
969 you can use it only explicitly--a macro cannot be called with `apply',
970 `mapcar' and so on.  Also, it takes some work to convert an ordinary
971 function into a macro.  (*Note Macros::.)  To convert it into an inline
972 function is very easy; simply replace `defun' with `defsubst'.  Since
973 each argument of an inline function is evaluated exactly once, you
974 needn't worry about how many times the body uses the arguments, as you
975 do for macros.  (*Note Argument Evaluation::.)
976
977    Inline functions can be used and open-coded later on in the same
978 file, following the definition, just like macros.
979
980 \1f
981 File: lispref.info,  Node: Related Topics,  Prev: Inline Functions,  Up: Functions
982
983 Other Topics Related to Functions
984 =================================
985
986    Here is a table of several functions that do things related to
987 function calling and function definitions.  They are documented
988 elsewhere, but we provide cross references here.
989
990 `apply'
991      See *Note Calling Functions::.
992
993 `autoload'
994      See *Note Autoload::.
995
996 `call-interactively'
997      See *Note Interactive Call::.
998
999 `commandp'
1000      See *Note Interactive Call::.
1001
1002 `documentation'
1003      See *Note Accessing Documentation::.
1004
1005 `eval'
1006      See *Note Eval::.
1007
1008 `funcall'
1009      See *Note Calling Functions::.
1010
1011 `ignore'
1012      See *Note Calling Functions::.
1013
1014 `indirect-function'
1015      See *Note Function Indirection::.
1016
1017 `interactive'
1018      See *Note Using Interactive::.
1019
1020 `interactive-p'
1021      See *Note Interactive Call::.
1022
1023 `mapatoms'
1024      See *Note Creating Symbols::.
1025
1026 `mapcar'
1027      See *Note Mapping Functions::.
1028
1029 `mapconcat'
1030      See *Note Mapping Functions::.
1031
1032 `undefined'
1033      See *Note Key Lookup::.
1034
1035 \1f
1036 File: lispref.info,  Node: Macros,  Next: Loading,  Prev: Functions,  Up: Top
1037
1038 Macros
1039 ******
1040
1041    "Macros" enable you to define new control constructs and other
1042 language features.  A macro is defined much like a function, but instead
1043 of telling how to compute a value, it tells how to compute another Lisp
1044 expression which will in turn compute the value.  We call this
1045 expression the "expansion" of the macro.
1046
1047    Macros can do this because they operate on the unevaluated
1048 expressions for the arguments, not on the argument values as functions
1049 do.  They can therefore construct an expansion containing these
1050 argument expressions or parts of them.
1051
1052    If you are using a macro to do something an ordinary function could
1053 do, just for the sake of speed, consider using an inline function
1054 instead.  *Note Inline Functions::.
1055
1056 * Menu:
1057
1058 * Simple Macro::            A basic example.
1059 * Expansion::               How, when and why macros are expanded.
1060 * Compiling Macros::        How macros are expanded by the compiler.
1061 * Defining Macros::         How to write a macro definition.
1062 * Backquote::               Easier construction of list structure.
1063 * Problems with Macros::    Don't evaluate the macro arguments too many times.
1064                               Don't hide the user's variables.
1065
1066 \1f
1067 File: lispref.info,  Node: Simple Macro,  Next: Expansion,  Up: Macros
1068
1069 A Simple Example of a Macro
1070 ===========================
1071
1072    Suppose we would like to define a Lisp construct to increment a
1073 variable value, much like the `++' operator in C.  We would like to
1074 write `(inc x)' and have the effect of `(setq x (1+ x))'.  Here's a
1075 macro definition that does the job:
1076
1077      (defmacro inc (var)
1078         (list 'setq var (list '1+ var)))
1079
1080    When this is called with `(inc x)', the argument `var' has the value
1081 `x'--*not* the *value* of `x'.  The body of the macro uses this to
1082 construct the expansion, which is `(setq x (1+ x))'.  Once the macro
1083 definition returns this expansion, Lisp proceeds to evaluate it, thus
1084 incrementing `x'.
1085
1086 \1f
1087 File: lispref.info,  Node: Expansion,  Next: Compiling Macros,  Prev: Simple Macro,  Up: Macros
1088
1089 Expansion of a Macro Call
1090 =========================
1091
1092    A macro call looks just like a function call in that it is a list
1093 which starts with the name of the macro.  The rest of the elements of
1094 the list are the arguments of the macro.
1095
1096    Evaluation of the macro call begins like evaluation of a function
1097 call except for one crucial difference: the macro arguments are the
1098 actual expressions appearing in the macro call.  They are not evaluated
1099 before they are given to the macro definition.  By contrast, the
1100 arguments of a function are results of evaluating the elements of the
1101 function call list.
1102
1103    Having obtained the arguments, Lisp invokes the macro definition just
1104 as a function is invoked.  The argument variables of the macro are bound
1105 to the argument values from the macro call, or to a list of them in the
1106 case of a `&rest' argument.  And the macro body executes and returns
1107 its value just as a function body does.
1108
1109    The second crucial difference between macros and functions is that
1110 the value returned by the macro body is not the value of the macro call.
1111 Instead, it is an alternate expression for computing that value, also
1112 known as the "expansion" of the macro.  The Lisp interpreter proceeds
1113 to evaluate the expansion as soon as it comes back from the macro.
1114
1115    Since the expansion is evaluated in the normal manner, it may contain
1116 calls to other macros.  It may even be a call to the same macro, though
1117 this is unusual.
1118
1119    You can see the expansion of a given macro call by calling
1120 `macroexpand'.
1121
1122  - Function: macroexpand FORM &optional ENVIRONMENT
1123      This function expands FORM, if it is a macro call.  If the result
1124      is another macro call, it is expanded in turn, until something
1125      which is not a macro call results.  That is the value returned by
1126      `macroexpand'.  If FORM is not a macro call to begin with, it is
1127      returned as given.
1128
1129      Note that `macroexpand' does not look at the subexpressions of
1130      FORM (although some macro definitions may do so).  Even if they
1131      are macro calls themselves, `macroexpand' does not expand them.
1132
1133      The function `macroexpand' does not expand calls to inline
1134      functions.  Normally there is no need for that, since a call to an
1135      inline function is no harder to understand than a call to an
1136      ordinary function.
1137
1138      If ENVIRONMENT is provided, it specifies an alist of macro
1139      definitions that shadow the currently defined macros.  Byte
1140      compilation uses this feature.
1141
1142           (defmacro inc (var)
1143               (list 'setq var (list '1+ var)))
1144                => inc
1145
1146           (macroexpand '(inc r))
1147                => (setq r (1+ r))
1148
1149           (defmacro inc2 (var1 var2)
1150               (list 'progn (list 'inc var1) (list 'inc var2)))
1151                => inc2
1152
1153           (macroexpand '(inc2 r s))
1154                => (progn (inc r) (inc s))  ; `inc' not expanded here.
1155
1156 \1f
1157 File: lispref.info,  Node: Compiling Macros,  Next: Defining Macros,  Prev: Expansion,  Up: Macros
1158
1159 Macros and Byte Compilation
1160 ===========================
1161
1162    You might ask why we take the trouble to compute an expansion for a
1163 macro and then evaluate the expansion.  Why not have the macro body
1164 produce the desired results directly?  The reason has to do with
1165 compilation.
1166
1167    When a macro call appears in a Lisp program being compiled, the Lisp
1168 compiler calls the macro definition just as the interpreter would, and
1169 receives an expansion.  But instead of evaluating this expansion, it
1170 compiles the expansion as if it had appeared directly in the program.
1171 As a result, the compiled code produces the value and side effects
1172 intended for the macro, but executes at full compiled speed.  This would
1173 not work if the macro body computed the value and side effects
1174 itself--they would be computed at compile time, which is not useful.
1175
1176    In order for compilation of macro calls to work, the macros must be
1177 defined in Lisp when the calls to them are compiled.  The compiler has a
1178 special feature to help you do this: if a file being compiled contains a
1179 `defmacro' form, the macro is defined temporarily for the rest of the
1180 compilation of that file.  To use this feature, you must define the
1181 macro in the same file where it is used and before its first use.
1182
1183    Byte-compiling a file executes any `require' calls at top-level in
1184 the file.  This is in case the file needs the required packages for
1185 proper compilation.  One way to ensure that necessary macro definitions
1186 are available during compilation is to require the files that define
1187 them (*note Named Features::.).  To avoid loading the macro definition
1188 files when someone *runs* the compiled program, write
1189 `eval-when-compile' around the `require' calls (*note Eval During
1190 Compile::.).
1191
1192 \1f
1193 File: lispref.info,  Node: Defining Macros,  Next: Backquote,  Prev: Compiling Macros,  Up: Macros
1194
1195 Defining Macros
1196 ===============
1197
1198    A Lisp macro is a list whose CAR is `macro'.  Its CDR should be a
1199 function; expansion of the macro works by applying the function (with
1200 `apply') to the list of unevaluated argument-expressions from the macro
1201 call.
1202
1203    It is possible to use an anonymous Lisp macro just like an anonymous
1204 function, but this is never done, because it does not make sense to pass
1205 an anonymous macro to functionals such as `mapcar'.  In practice, all
1206 Lisp macros have names, and they are usually defined with the special
1207 form `defmacro'.
1208
1209  - Special Form: defmacro NAME ARGUMENT-LIST BODY-FORMS...
1210      `defmacro' defines the symbol NAME as a macro that looks like this:
1211
1212           (macro lambda ARGUMENT-LIST . BODY-FORMS)
1213
1214      This macro object is stored in the function cell of NAME.  The
1215      value returned by evaluating the `defmacro' form is NAME, but
1216      usually we ignore this value.
1217
1218      The shape and meaning of ARGUMENT-LIST is the same as in a
1219      function, and the keywords `&rest' and `&optional' may be used
1220      (*note Argument List::.).  Macros may have a documentation string,
1221      but any `interactive' declaration is ignored since macros cannot be
1222      called interactively.
1223