Initial git import
[sxemacs] / info / lispref / eval.texi
1 @c -*-texinfo-*-
2 @c This is part of the SXEmacs Lisp Reference Manual.
3 @c Copyright (C) 1990, 1991, 1992, 1993, 1994 Free Software Foundation, Inc.
4 @c Copyright (C) 2005 Sebastian Freundt <hroptatyr@sxemacs.org>
5 @c See the file lispref.texi for copying conditions.
6 @setfilename ../../info/eval.info
7
8 @node Evaluation, Control Structures, Symbols, Top
9 @chapter Evaluation
10 @cindex evaluation
11 @cindex  interpreter
12 @cindex interpreter
13 @cindex value of expression
14
15   The @dfn{evaluation} of expressions in SXEmacs Lisp is performed by the
16 @dfn{Lisp interpreter}---a program that receives a Lisp object as input
17 and computes its @dfn{value as an expression}.  How it does this depends
18 on the data type of the object, according to rules described in this
19 chapter.  The interpreter runs automatically to evaluate portions of
20 your program, but can also be called explicitly via the Lisp primitive
21 function @code{eval}.
22
23 @ifnottex
24 @menu
25 * Intro Eval::  Evaluation in the scheme of things.
26 * Eval::        How to invoke the Lisp interpreter explicitly.
27 * Forms::       How various sorts of objects are evaluated.
28 * Quoting::     Avoiding evaluation (to put constants in the program).
29 @end menu
30
31
32 @node Intro Eval
33 @section Introduction to Evaluation
34
35   The Lisp interpreter, or evaluator, is the program that computes
36 the value of an expression that is given to it.  When a function
37 written in Lisp is called, the evaluator computes the value of the
38 function by evaluating the expressions in the function body.  Thus,
39 running any Lisp program really means running the Lisp interpreter.
40
41   How the evaluator handles an object depends primarily on the data
42 type of the object.
43 @end ifnottex
44
45 @cindex forms
46 @cindex expression
47   A Lisp object that is intended for evaluation is called an
48 @dfn{expression} or a @dfn{form}.  The fact that expressions are data
49 objects and not merely text is one of the fundamental differences
50 between Lisp-like languages and typical programming languages.  Any
51 object can be evaluated, but in practice only numbers, symbols, lists
52 and strings are evaluated very often.
53
54   It is very common to read a Lisp expression and then evaluate the
55 expression, but reading and evaluation are separate activities, and
56 either can be performed alone.  Reading per se does not evaluate
57 anything; it converts the printed representation of a Lisp object to the
58 object itself.  It is up to the caller of @code{read} whether this
59 object is a form to be evaluated, or serves some entirely different
60 purpose.  @xref{Input Functions}.
61
62   Do not confuse evaluation with command key interpretation.  The
63 editor command loop translates keyboard input into a command (an
64 interactively callable function) using the active keymaps, and then
65 uses @code{call-interactively} to invoke the command.  The execution of
66 the command itself involves evaluation if the command is written in
67 Lisp, but that is not a part of command key interpretation itself.
68 @xref{Command Loop}.
69
70 @cindex recursive evaluation
71   Evaluation is a recursive process.  That is, evaluation of a form may
72 call @code{eval} to evaluate parts of the form.  For example, evaluation
73 of a function call first evaluates each argument of the function call,
74 and then evaluates each form in the function body.  Consider evaluation
75 of the form @code{(car x)}: the subform @code{x} must first be evaluated
76 recursively, so that its value can be passed as an argument to the
77 function @code{car}.
78
79   Evaluation of a function call ultimately calls the function specified
80 in it.  @xref{Functions and Commands}.  The execution of the function may itself work
81 by evaluating the function definition; or the function may be a Lisp
82 primitive implemented in C, or it may be a byte-compiled function
83 (@pxref{Byte Compilation}).
84
85 @cindex environment
86   The evaluation of forms takes place in a context called the
87 @dfn{environment}, which consists of the current values and bindings of
88 all Lisp variables.@footnote{This definition of ``environment'' is
89 specifically not intended to include all the data that can affect the
90 result of a program.}  Whenever the form refers to a variable without
91 creating a new binding for it, the value of the binding in the current
92 environment is used.  @xref{Variables}.
93
94 @cindex side effect
95   Evaluation of a form may create new environments for recursive
96 evaluation by binding variables (@pxref{Local Variables}).  These
97 environments are temporary and vanish by the time evaluation of the form
98 is complete.  The form may also make changes that persist; these changes
99 are called @dfn{side effects}.  An example of a form that produces side
100 effects is @code{(setq foo 1)}.
101
102   The details of what evaluation means for each kind of form are
103 described below (@pxref{Forms}).
104
105 @node Eval
106 @section Eval
107 @c ??? Perhaps this should be the last section in the chapter.
108
109   Most often, forms are evaluated automatically, by virtue of their
110 occurrence in a program being run.  On rare occasions, you may need to
111 write code that evaluates a form that is computed at run time, such as
112 after reading a form from text being edited or getting one from a
113 property list.  On these occasions, use the @code{eval} function.
114
115   @strong{Please note:} it is generally cleaner and more flexible to call
116 functions that are stored in data structures, rather than to evaluate
117 expressions stored in data structures.  Using functions provides the
118 ability to pass information to them as arguments.
119
120   The functions and variables described in this section evaluate forms,
121 specify limits to the evaluation process, or record recently returned
122 values.  Loading a file also does evaluation (@pxref{Loading}).
123
124 @defun eval form
125 This is the basic function for performing evaluation.  It evaluates
126 @var{form} in the current environment and returns the result.  How the
127 evaluation proceeds depends on the type of the object (@pxref{Forms}).
128
129 Since @code{eval} is a function, the argument expression that appears
130 in a call to @code{eval} is evaluated twice: once as preparation before
131 @code{eval} is called, and again by the @code{eval} function itself.
132 Here is an example:
133
134 @example
135 @group
136 (setq foo 'bar)
137      @result{} bar
138 @end group
139 @group
140 (setq bar 'baz)
141      @result{} baz
142 ;; @r{@code{eval} receives argument @code{bar}, which is the value of @code{foo}}
143 (eval foo)
144      @result{} baz
145 (eval 'foo)
146      @result{} bar
147 @end group
148 @end example
149
150 The number of currently active calls to @code{eval} is limited to
151 @code{max-lisp-eval-depth} (see below).
152 @end defun
153
154 @deffn Command eval-region start end &optional stream
155 This function evaluates the forms in the current buffer in the region
156 defined by the positions @var{start} and @var{end}.  It reads forms from
157 the region and calls @code{eval} on them until the end of the region is
158 reached, or until an error is signaled and not handled.
159
160 If @var{stream} is supplied, @code{standard-output} is bound to it
161 during the evaluation.
162
163 You can use the variable @code{load-read-function} to specify a function
164 for @code{eval-region} to use instead of @code{read} for reading
165 expressions.  @xref{How Programs Do Loading}.
166
167 @code{eval-region} always returns @code{nil}.
168 @end deffn
169
170 @cindex evaluation of buffer contents
171 @deffn Command eval-buffer buffer &optional stream
172 This is like @code{eval-region} except that it operates on the whole
173 contents of @var{buffer}.
174 @end deffn
175
176 @defvar max-lisp-eval-depth
177 This variable defines the maximum depth allowed in calls to @code{eval},
178 @code{apply}, and @code{funcall} before an error is signaled (with error
179 message @code{"Lisp nesting exceeds max-lisp-eval-depth"}).  This counts
180 internal uses of those functions, such as for calling the functions
181 mentioned in Lisp expressions, and recursive evaluation of function call
182 arguments and function body forms.
183
184 This limit, with the associated error when it is exceeded, is one way
185 that Lisp avoids infinite recursion on an ill-defined function.
186 @cindex Lisp nesting error
187
188 The default value of this variable is 1000.  If you set it to a value
189 less than 100, Lisp will reset it to 100 if the given value is reached.
190
191 @code{max-specpdl-size} provides another limit on nesting.
192 @xref{Local Variables}.
193 @end defvar
194
195 @defvar values
196 The value of this variable is a list of the values returned by all the
197 expressions that were read from buffers (including the minibuffer),
198 evaluated, and printed.  The elements are ordered most recent first.
199
200 @example
201 @group
202 (setq x 1)
203      @result{} 1
204 @end group
205 @group
206 (list 'A (1+ 2) auto-save-default)
207      @result{} (A 3 t)
208 @end group
209 @group
210 values
211      @result{} ((A 3 t) 1 @dots{})
212 @end group
213 @end example
214
215 This variable is useful for referring back to values of forms recently
216 evaluated.  It is generally a bad idea to print the value of
217 @code{values} itself, since this may be very long.  Instead, examine
218 particular elements, like this:
219
220 @example
221 @group
222 ;; @r{Refer to the most recent evaluation result.}
223 (nth 0 values)
224      @result{} (A 3 t)
225 @end group
226 @group
227 ;; @r{That put a new element on,}
228 ;;   @r{so all elements move back one.}
229 (nth 1 values)
230      @result{} (A 3 t)
231 @end group
232 @group
233 ;; @r{This gets the element that was next-to-most-recent}
234 ;;   @r{before this example.}
235 (nth 3 values)
236      @result{} 1
237 @end group
238 @end example
239 @end defvar
240
241 @node Forms
242 @section Kinds of Forms
243
244   A Lisp object that is intended to be evaluated is called a @dfn{form}.
245 How SXEmacs evaluates a form depends on its data type.  SXEmacs has three
246 different kinds of form that are evaluated differently: symbols, lists,
247 and ``all other types''.  This section describes all three kinds,
248 starting with ``all other types'' which are self-evaluating forms.
249
250 @menu
251 * Self-Evaluating Forms::   Forms that evaluate to themselves.
252 * Symbol Forms::            Symbols evaluate as variables.
253 * Classifying Lists::       How to distinguish various sorts of list forms.
254 * Function Indirection::    When a symbol appears as the car of a list,
255                               we find the real function via the symbol.
256 * Function Forms::          Forms that call functions.
257 * Macro Forms::             Forms that call macros.
258 * Special Forms::           ``Special forms'' are idiosyncratic primitives,
259                               most of them extremely important.
260 * Autoloading::             Functions set up to load files
261                               containing their real definitions.
262 @end menu
263
264
265 @node Self-Evaluating Forms
266 @subsection Self-Evaluating Forms
267 @cindex vector evaluation
268 @cindex literal evaluation
269 @cindex self-evaluating form
270
271   A @dfn{self-evaluating form} is any form that is not a list or symbol.
272 Self-evaluating forms evaluate to themselves: the result of evaluation
273 is the same object that was evaluated.  Thus, the number 25 evaluates to
274 25, and the string @code{"foo"} evaluates to the string @code{"foo"}.
275 Likewise, evaluation of a vector does not cause evaluation of the
276 elements of the vector---it returns the same vector with its contents
277 unchanged.
278
279 @example
280 @group
281 '123               ; @r{An object, shown without evaluation.}
282      @result{} 123
283 @end group
284 @group
285 123                ; @r{Evaluated as usual---result is the same.}
286      @result{} 123
287 @end group
288 @group
289 (eval '123)        ; @r{Evaluated ``by hand''---result is the same.}
290      @result{} 123
291 @end group
292 @group
293 (eval (eval '123)) ; @r{Evaluating twice changes nothing.}
294      @result{} 123
295 @end group
296 @end example
297
298   It is common to write numbers, characters, strings, and even vectors
299 in Lisp code, taking advantage of the fact that they self-evaluate.
300 However, it is quite unusual to do this for types that lack a read
301 syntax, because there's no way to write them textually.  It is possible
302 to construct Lisp expressions containing these types by means of a Lisp
303 program.  Here is an example:
304
305 @example
306 @group
307 ;; @r{Build an expression containing a buffer object.}
308 (setq buffer (list 'print (current-buffer)))
309      @result{} (print #<buffer eval.texi>)
310 @end group
311 @group
312 ;; @r{Evaluate it.}
313 (eval buffer)
314      @print{} #<buffer eval.texi>
315      @result{} #<buffer eval.texi>
316 @end group
317 @end example
318
319
320 @node Symbol Forms
321 @subsection Symbol Forms
322 @cindex symbol evaluation
323
324   When a symbol is evaluated, it is treated as a variable.  The result
325 is the variable's value, if it has one.  If it has none (if its value
326 cell is void), an error is signaled.  For more information on the use of
327 variables, see @ref{Variables}.
328
329   In the following example, we set the value of a symbol with
330 @code{setq}.  Then we evaluate the symbol, and get back the value that
331 @code{setq} stored.
332
333 @example
334 @group
335 (setq a 123)
336      @result{} 123
337 @end group
338 @group
339 (eval 'a)
340      @result{} 123
341 @end group
342 @group
343 a
344      @result{} 123
345 @end group
346 @end example
347
348   The symbols @code{nil} and @code{t} are treated specially, so that the
349 value of @code{nil} is always @code{nil}, and the value of @code{t} is
350 always @code{t}; you cannot set or bind them to any other values.  Thus,
351 these two symbols act like self-evaluating forms, even though
352 @code{eval} treats them like any other symbol.
353
354
355 @node Classifying Lists
356 @subsection Classification of List Forms
357 @cindex list form evaluation
358
359   A form that is a nonempty list is either a function call, a macro
360 call, or a special form, according to its first element.  These three
361 kinds of forms are evaluated in different ways, described below.  The
362 remaining list elements constitute the @dfn{arguments} for the function,
363 macro, or special form.
364
365   The first step in evaluating a nonempty list is to examine its first
366 element.  This element alone determines what kind of form the list is
367 and how the rest of the list is to be processed.  The first element is
368 @emph{not} evaluated, as it would be in some Lisp dialects such as
369 Scheme.
370
371
372 @node Function Indirection
373 @subsection Symbol Function Indirection
374 @cindex symbol function indirection
375 @cindex indirection
376 @cindex void function
377
378   If the first element of the list is a symbol then evaluation examines
379 the symbol's function cell, and uses its contents instead of the
380 original symbol.  If the contents are another symbol, this process,
381 called @dfn{symbol function indirection}, is repeated until it obtains a
382 non-symbol.  @xref{Function Names}, for more information about using a
383 symbol as a name for a function stored in the function cell of the
384 symbol.
385
386   One possible consequence of this process is an infinite loop, in the
387 event that a symbol's function cell refers to the same symbol.  Or a
388 symbol may have a void function cell, in which case the subroutine
389 @code{symbol-function} signals a @code{void-function} error.  But if
390 neither of these things happens, we eventually obtain a non-symbol,
391 which ought to be a function or other suitable object.
392
393 @kindex invalid-function
394 @cindex invalid function
395   More precisely, we should now have a Lisp function (a lambda
396 expression), a byte-code function, a primitive function, a Lisp macro, a
397 special form, or an autoload object.  Each of these types is a case
398 described in one of the following sections.  If the object is not one of
399 these types, the error @code{invalid-function} is signaled.
400
401   The following example illustrates the symbol indirection process.  We
402 use @code{fset} to set the function cell of a symbol and
403 @code{symbol-function} to get the function cell contents
404 (@pxref{Function Cells}).  Specifically, we store the symbol @code{car}
405 into the function cell of @code{first}, and the symbol @code{first} into
406 the function cell of @code{erste}.
407
408 @smallexample
409 @group
410 ;; @r{Build this function cell linkage:}
411 ;;   -------------       -----        -------        -------
412 ;;  | #<subr car> | <-- | car |  <-- | first |  <-- | erste |
413 ;;   -------------       -----        -------        -------
414 @end group
415 @end smallexample
416
417 @smallexample
418 @group
419 (symbol-function 'car)
420      @result{} #<subr car>
421 @end group
422 @group
423 (fset 'first 'car)
424      @result{} car
425 @end group
426 @group
427 (fset 'erste 'first)
428      @result{} first
429 @end group
430 @group
431 (erste '(1 2 3))   ; @r{Call the function referenced by @code{erste}.}
432      @result{} 1
433 @end group
434 @end smallexample
435
436   By contrast, the following example calls a function without any symbol
437 function indirection, because the first element is an anonymous Lisp
438 function, not a symbol.
439
440 @smallexample
441 @group
442 ((lambda (arg) (erste arg))
443  '(1 2 3))
444      @result{} 1
445 @end group
446 @end smallexample
447
448 @noindent
449 Executing the function itself evaluates its body; this does involve
450 symbol function indirection when calling @code{erste}.
451
452   The built-in function @code{indirect-function} provides an easy way to
453 perform symbol function indirection explicitly.
454
455 @defun indirect-function object
456 This function returns the meaning of @var{object} as a function.  If
457 @var{object} is a symbol, then it finds @var{object}'s function
458 definition and starts over with that value.  If @var{object} is not a
459 symbol, then it returns @var{object} itself.
460
461 Here is how you could define @code{indirect-function} in Lisp:
462
463 @smallexample
464 (defun indirect-function (function)
465   (if (symbolp function)
466       (indirect-function (symbol-function function))
467     function))
468 @end smallexample
469 @end defun
470
471
472 @node Function Forms
473 @subsection Evaluation of Function Forms
474 @cindex function form evaluation
475 @cindex function call
476
477   If the first element of a list being evaluated is a Lisp function
478 object, byte-code object or primitive function object, then that list is
479 a @dfn{function call}.  For example, here is a call to the function
480 @code{+}:
481
482 @example
483 (+ 1 x)
484 @end example
485
486   The first step in evaluating a function call is to evaluate the
487 remaining elements of the list from left to right.  The results are the
488 actual argument values, one value for each list element.  The next step
489 is to call the function with this list of arguments, effectively using
490 the function @code{apply} (@pxref{Calling Functions}).
491
492 If the function is written in Lisp, the arguments are used to bind the
493 argument variables of the function (@pxref{Lambda Expressions}); then
494 the forms in the function body are evaluated in order, and the value of
495 the last body form becomes the value of the function call.
496
497
498 @node Macro Forms
499 @subsection Lisp Macro Evaluation
500 @cindex macro call evaluation
501
502   If the first element of a list being evaluated is a macro object, then
503 the list is a @dfn{macro call}.  When a macro call is evaluated, the
504 elements of the rest of the list are @emph{not} initially evaluated.
505 Instead, these elements themselves are used as the arguments of the
506 macro.  The macro definition computes a replacement form, called the
507 @dfn{expansion} of the macro, to be evaluated in place of the original
508 form.  The expansion may be any sort of form: a self-evaluating
509 constant, a symbol, or a list.  If the expansion is itself a macro call,
510 this process of expansion repeats until some other sort of form results.
511
512   Ordinary evaluation of a macro call finishes by evaluating the
513 expansion.  However, the macro expansion is not necessarily evaluated
514 right away, or at all, because other programs also expand macro calls,
515 and they may or may not evaluate the expansions.
516
517   Normally, the argument expressions are not evaluated as part of
518 computing the macro expansion, but instead appear as part of the
519 expansion, so they are computed when the expansion is computed.
520
521   For example, given a macro defined as follows:
522
523 @example
524 @group
525 (defmacro cadr (x)
526   (list 'car (list 'cdr x)))
527 @end group
528 @end example
529
530 @noindent
531 an expression such as @code{(cadr (assq 'handler list))} is a macro
532 call, and its expansion is:
533
534 @example
535 (car (cdr (assq 'handler list)))
536 @end example
537
538 @noindent
539 Note: The argument @code{(assq 'handler list)} appears in the
540 expansion.
541
542 @xref{Macros}, for a complete description of SXEmacs Lisp macros.
543
544
545 @node Special Forms
546 @subsection Special Forms
547 @cindex special form evaluation
548
549   A @dfn{special form} is a primitive function specially marked so that
550 its arguments are not all evaluated.  Most special forms define control
551 structures or perform variable bindings---things which functions cannot
552 do.
553
554   Each special form has its own rules for which arguments are evaluated
555 and which are used without evaluation.  Whether a particular argument is
556 evaluated may depend on the results of evaluating other arguments.
557
558   Here is a list, in alphabetical order, of all of the special forms in
559 SXEmacs Lisp with a reference to where each is described.
560
561 @table @code
562 @item and
563 @pxref{Combining Conditions}
564
565 @item catch
566 @pxref{Catch and Throw}
567
568 @item cond
569 @pxref{Conditionals}
570
571 @item condition-case
572 @pxref{Handling Errors}
573
574 @item defconst
575 @pxref{Defining Variables}
576
577 @item defmacro
578 @pxref{Defining Macros}
579
580 @item defun
581 @pxref{Defining Functions}
582
583 @item defvar
584 @pxref{Defining Variables}
585
586 @item function
587 @pxref{Anonymous Functions}
588
589 @item if
590 @pxref{Conditionals}
591
592 @item interactive
593 @pxref{Interactive Call}
594
595 @item let
596 @itemx let*
597 @pxref{Local Variables}
598
599 @item or
600 @pxref{Combining Conditions}
601
602 @item prog1
603 @itemx prog2
604 @itemx progn
605 @pxref{Sequencing}
606
607 @item quote
608 @pxref{Quoting}
609
610 @item save-current-buffer
611 @pxref{Excursions}
612
613 @item save-excursion
614 @pxref{Excursions}
615
616 @item save-restriction
617 @pxref{Narrowing}
618
619 @item save-selected-window
620 @pxref{Excursions}
621
622 @item save-window-excursion
623 @pxref{Window Configurations}
624
625 @item setq
626 @pxref{Setting Variables}
627
628 @item setq-default
629 @pxref{Creating Buffer-Local}
630
631 @item unwind-protect
632 @pxref{Nonlocal Exits}
633
634 @item while
635 @pxref{Iteration}
636
637 @item with-output-to-temp-buffer
638 @pxref{Temporary Displays}
639 @end table
640
641 @cindex CL note---special forms compared
642 @quotation
643 @b{Common Lisp note:} here are some comparisons of special forms in
644 SXEmacs Lisp and Common Lisp.  @code{setq}, @code{if}, and
645 @code{catch} are special forms in both SXEmacs Lisp and Common Lisp.
646 @code{defun} is a special form in SXEmacs Lisp, but a macro in Common
647 Lisp.  @code{save-excursion} is a special form in SXEmacs Lisp, but
648 does not exist in Common Lisp.  @code{throw} is a special form in
649 Common Lisp (because it must be able to throw multiple values), but it
650 is a function in SXEmacs Lisp (which doesn't have multiple
651 values).@refill
652 @end quotation
653
654
655 @node Autoloading
656 @subsection Autoloading
657
658   The @dfn{autoload} feature allows you to call a function or macro
659 whose function definition has not yet been loaded into SXEmacs.  It
660 specifies which file contains the definition.  When an autoload object
661 appears as a symbol's function definition, calling that symbol as a
662 function automatically loads the specified file; then it calls the real
663 definition loaded from that file.  @xref{Autoload}.
664
665
666 @node Quoting
667 @section Quoting
668 @cindex quoting
669
670   Quoting is a technique to modify the evaluation behaviour of
671 expressions.  This is achieved by wrapping the expression into a
672 special form.  The lisp reader will now evualate this special form
673 instead of the original expression.
674
675 SXEmacs basically knows about 3 quoting forms: @code{quote},
676 @code{function} and @code{backquote}.  Moreover, all of these possess
677 an alternative read syntax, @code{'}, @code{#'} and @code{`}
678 respectively.  In programs you will find almost exclusively the
679 abbreviated variants which also facilitate human reading of program
680 sources.  You can test yourself in the example section below. @c :)
681
682 @menu
683 * Quoting with quote::          The special form `quote' (')
684 * Quoting with function::       The special form `function' (#')
685 * Quoting with backquote::      The special form `backquote' (`)
686 * Nested quoting::              How to nest quoting forms
687 @end menu
688
689
690 @node Quoting with quote
691 @subsection Quoting with @code{quote}
692 @findex quote
693 @findex @samp{'}
694
695   The special form @code{quote} returns its single argument, as written,
696 without evaluating it.  This provides a way to include constant symbols
697 and lists, which are not self-evaluating objects, in a program.  (It is
698 not necessary to quote self-evaluating objects such as numbers, strings,
699 and vectors.)
700
701 @defspec quote object
702 This special form returns @var{object}, without evaluating it.
703 @end defspec
704
705 @cindex @samp{'} for quoting
706 @cindex quoting using apostrophe
707 @cindex apostrophe for quoting
708 @cindex quoting short forms
709   Because @code{quote} is used so often in programs, Lisp provides a
710 convenient read syntax for it.  An apostrophe character (@samp{'})
711 followed by a Lisp object (in read syntax) expands to a list whose
712 first element is @code{quote}, and whose second element is the object.
713 Thus, the read syntax @code{'x} is an abbreviation for
714 @code{(quote x)}.
715
716 Here are some examples of expressions that use @code{quote}:
717
718 @example
719 @group
720 (quote (+ 1 2))
721      @result{} (+ 1 2)
722 @end group
723 @group
724 (quote foo)
725      @result{} foo
726 @end group
727 @group
728 'foo
729      @result{} foo
730 @end group
731 @group
732 ''foo
733      @result{} (quote foo)
734 @end group
735 @group
736 '(quote foo)
737      @result{} (quote foo)
738 @end group
739 @group
740 ['foo]
741      @result{} [(quote foo)]
742 @end group
743 @end example
744
745   Numeric constants, indefinite symbols, string constants, character
746 constants and the special forms @code{t} and @code{nil} evaluate
747 themselves.  Quoting them is allowed but optional.  Vector constants
748 created with the bracket notation (@code{[ ]}) are also immune against
749 quoting.  @xref{Self-Evaluating Forms}.
750
751 @example
752 @group
753 '12
754   @result{} 12
755 '2.333
756   @result{} 2.333
757 '1/2
758   @result{} 1/2
759 '2+5Z
760   @result{} 2+5Z
761 'Z/12Z
762   @result{} Z/12Z
763 '1+2i
764   @result{} 1+2i
765 '0.5-0.5i
766   @result{} 0.50000-0.50000i
767 @end group
768
769 @group
770 '+infinity
771   @result{} +infinity
772 '-infinity
773   @result{} -infinity
774 'complex-infinity
775   @result{} complex-infinity
776 'not-a-number
777   @result{} not-a-number
778 @end group
779
780 @group
781 '"string"
782   @result{} "string"
783 (eval ''#r"\a\b\c")
784   @result{} "\\a\\b\\c"
785 @end group
786
787 @group
788 '?a
789   @result{} ?a
790 '?'
791   @result{} ?\'
792 @end group
793
794 @group
795 't
796   @result{} t
797 'nil
798   @result{} nil
799 @end group
800
801 @group
802 [a b c]
803   @result{} [a b c]
804 '[a b c]
805   @result{} [a b c]
806 @end group
807 @end example
808
809
810 @node Quoting with function
811 @subsection Quoting with @code{function}
812 @findex function
813 @findex @samp{#'}
814
815   The special form @code{function} returns its single argument, as
816 written, without evaluating it, and indicates thereby that this
817 argument is to be treated as function.  This is mandatory only if you
818 intend to compile your program and want the byte-compiler to
819 optimise your code accordingly.  Any other lisp code will accept both
820 the ordinarily quoted and the function-quoted form.  Because of this
821 SXEmacs does allow you to evaluate the value cell of a function-quoted
822 object.  However, this is bad style and may lead to problems in case
823 of byte-compilation.
824
825 @defspec function function-object
826 @cindex function quoting
827 This special form returns @var{function-object} without evaluating it.
828 In this, it is equivalent to @code{quote}.  However, it serves as a
829 note to the SXEmacs Lisp compiler that @var{function-object} is intended
830 to be used only as a function, and therefore can safely be compiled.
831 Contrast this with @code{quote}, in @ref{Quoting with quote}.
832 @end defspec
833
834 @cindex @samp{#'} for quoting
835 @cindex quoting short forms
836   As for @code{quote}, there is also an abbreviated read syntax for
837 @code{function}.  A sharpsign character followed by an apostrophe
838 (@samp{#'}) followed by a a Lisp object in read syntax expands to a
839 list whose first element is @code{function}, and whose second element
840 is the object.  Thus, the read syntax @code{#'y} is an abbreviation for
841 @code{(function y)}.
842
843   This effect can be used in macros to distinguish explicitly between
844 variable and function bindings, see example below, also
845 @pxref{Macros}.  However, since the rest of SXEmacs accepts both the
846 @code{quote}d and the @code{function}-quoted form equally and coerces
847 them to the desired form internally, macros or functions which diverge
848 from this norm should contain a clear remark in their docstring.
849
850 @noindent
851 Here are some examples of expressions that use @code{function}:
852 @example
853 @group
854 (function car)
855   @result{} car
856 @end group
857 @group
858 #'car
859   @result{} car
860 @end group
861 @group
862 '#'car
863   => (function car)
864 @end group
865 @group
866 (symbol-function #'funcall)
867   @result{} #<subr funcall>
868 (symbol-value #'nil)
869   @result{} nil
870 @end group
871 @end example
872
873 @noindent
874 As mentioned above, an example for a macro which distinguishes between
875 @samp{'} and @samp{#'}.
876
877 @example
878 @group
879 (defmacro picky-funcall (symbol &rest arguments)
880   (let ((type (car-safe symbol))
881         (name (car (cdr-safe symbol)))
882         (qargs (list 'quote arguments)))
883     (cond ((eq type 'function)
884            (list 'apply symbol qargs))
885           ((eq type 'quote)
886            (list 'apply name qargs))
887           (t
888            (error "I don't know what to do with `%s'." symbol)))))
889 @end group
890 @end example
891
892 @noindent
893 Now we define both a function with the name @samp{test} and a variable
894 with the name @samp{test}.  Afterwards we apply each to our
895 @code{picky-funcall}.
896
897 @example
898 @group
899 (defun test (a b)
900   (+ a b))
901   @result{} test
902 (defvar test '-)
903   @result{} test
904 @end group
905
906 @group
907 (picky-funcall #'test 4 2)
908   @result{} 6
909 (picky-funcall 'test 4 2)
910   @result{} 2
911 @end group
912
913 @group
914 (picky-funcall test 4 2)
915 @error{} Cannot decide if `test' contains a variable or function.
916 @end group
917 @end example
918
919   Again, the behaviour of @code{picky-funcall} is unusual in SXEmacs,
920 you should try to avoid it wherever you can.  In contrast, quoting
921 functions with @samp{#'} (or the @code{function} form) is usual and
922 even recommended because it clarifies your intention to both human
923 readers and the lisp expression reader.
924
925   Also note, in a function definition you have no definite chance to
926 distinguish between any of the quoting forms.  This would revert
927 function indirection anyway.  However, if you intend to treat
928 variables different from functions you could try to guess using
929 @code{symbol-name}, @code{symbol-function} and @code{symbol-value}
930 (@pxref{Symbols}).
931
932   As for quoting, self-evaluating forms are not affected by
933 function quotation.  However, function quoting such forms is most
934 likely wrong anyway so we will not give examples here.
935
936   Nonetheless there is a macro definition to turn lambda-lists
937 (@pxref{Anonymous Functions}) into self-evaluating objects.
938
939 @smallexample
940 @group
941 (lambda (x) (+ x x))
942   @result{} (lambda (x) (+ x x))
943 @end group
944 @end smallexample
945
946 @noindent
947 The true expansion of @code{(lambda @dots{})} is @code{(function (lambda @dots{}))}.
948
949
950 @node Quoting with backquote
951 @subsection Quoting with @code{`} (backquote)
952 @findex backquote
953 @findex @samp{`}
954 @cindex backquote (list substitution)
955 @cindex @samp{`} (list substitution)
956
957   While @code{'} quotes its expression completely it is very
958 complicated to quote, say, a list of several elements but leave one
959 element unquoted (i.e. evaluate it).  The result would probably look
960 like:
961 @smallexample
962 (setq e 5)
963 (list 'a 'b 'c 'd e 'e 'e 'e)
964   @result{} (a b c d 5 e e e)
965 @end smallexample
966
967   In this sense, a backquote is somewhat the reverse operation of a
968 @samp{'}.  Backquote allows you to quote the entire list, but
969 selectively evaluate elements of that list.  However, in the simplest
970 case, it is identical to @code{quote}.  These two forms yield
971 identical results:
972
973 @example
974 @group
975 `(a list of (+ 2 3) elements)
976   @result{} (a list of (+ 2 3) elements)
977 @end group
978 @group
979 '(a list of (+ 2 3) elements)
980   @result{} (a list of (+ 2 3) elements)
981 @end group
982 @end example
983
984   However, unlike @code{quote} which has a special read-syntax,
985 backquoting is implemented as macro and the routines @code{backquote}
986 and @code{`} do not coincide.
987
988 @unnumberedsubsec The @samp{,} marker
989 @findex @samp{,@@} @r{(with backquote)}
990 @cindex selective replace (with backquote)
991
992 The special marker @samp{,} can be used inside of the argument to
993 inhibit the quotation for this particular expression.  Thus the
994 backquote alternative of the motivation example above could be:
995
996 @smallexample
997 @group
998 (setq e 10)
999 `(a b c d ,e e e e)
1000   @result{} (a b c d 10 e e e)
1001 @end group
1002 @end smallexample
1003
1004   Please note, the comma is not treated specially by the lisp reader,
1005 thus it is a perfectly valid part of a symbol.  If you want to protect
1006 against strange behaviour @strong{do not use a leading @samp{,} in
1007 your variable or function names}.  In reality symbols with leading
1008 commas can be of great use in nested quoting constructions,
1009 @pxref{Nested quoting}.  However, make sure that none of such bindings
1010 escapes to the normal lisp environment.
1011
1012 @unnumberedsubsec The @samp{,@@} marker
1013 @findex @samp{,@@} @r{(with backquote)}
1014 @cindex splicing (with backquote)
1015
1016   With the special marker @samp{,@@} inside of a backquoted expression
1017 you can @dfn{splice} an evaluated value into the resulting list.  The
1018 elements of the spliced list become elements at the same level as the
1019 other elements of the resulting list.  The equivalent code without
1020 using @samp{`} is often unreadable.
1021
1022   Like the comma operator @samp{,@@} is not treated specially by the
1023 lisp reader either.  You will have to take care for symbol names with
1024 leading @samp{,@@} in foreign (i.e. non-backquoting) contexts and
1025 their bindings yourself.
1026
1027 @noindent
1028 Let us now look at a more pragmatic example of backquoting.
1029
1030 @example
1031 @group
1032 (defun interior (function fix-arg)
1033   "Return the insertion of FIX-ARG in FUNCTION,
1034 that is a function which is derived from FUNCTION by fixating the
1035 first argument to FIX-ARG and keeping the rest variable.
1036
1037 This process is often referred to as currying.
1038 Mathematically it is a special interior product (hence the name)."
1039   (let* ((body (indirect-function function))
1040          (args
1041           (cond ((subrp body)
1042                  (error "Error: Cannot handle built-in functions."))
1043                 ((compiled-function-p body)
1044                  (compiled-function-arglist body))
1045                 (t
1046                  (cadr body))))
1047          (newarglist
1048           (if args
1049               (cdr args)
1050             (error "Error: %s accepts no arguments." function)))
1051          (newargs
1052           (delq '&optional (copy-list newarglist))))
1053     `(lambda ,newarglist
1054        (,function ',fix-arg ,@@newargs))))
1055   @result{} interior
1056 @end group
1057 @end example
1058
1059   This definition is far from perfect but sufficient for our
1060 purposes.  Since we excluded built-in functions in the above code we
1061 define a simple lisp equivalent of the @code{list} function.
1062
1063 @example
1064 @group
1065 (defun list-demo (a b c d)
1066   "Return the list (A B C D)."
1067   (list a b c d))
1068   @result{} list-demo
1069 @end group
1070
1071 @group
1072 (list-demo 1 'a 2 t)
1073   @result{} (1 a 2 t)
1074 @end group
1075 @end example
1076
1077 @noindent
1078 Now we look at the interior product of @samp{?a} and
1079 @code{list-demo}.
1080
1081 @example
1082 @group
1083 (interior #'list-demo ?a)
1084   @result{} (lambda (b c d) (list-demo (quote ?a) b c d))
1085 @end group
1086 @end example
1087
1088   As you can see, @code{,function} and @code{,fix-arg} have been
1089 replaced with the according argument passed to @code{interior}.
1090 Additionally we quote the replace of @code{,fix-arg} to prevent
1091 another expansion of the replacement during the call of the resulting
1092 function.  Also note how the list in @var{newargs} which had the local
1093 binding @samp{(b c d)} within @code{interior} has been spliced into the
1094 function call expression.
1095
1096 @smallexample
1097 @group
1098 (fset #'list-demo-a (interior #'list-demo ?a))
1099   @result{} (lambda (b c d) (list-demo (quote ?a) b c d))
1100 (list-demo-a 'and 3 'args)
1101   => (?a and 3 args)
1102 @end group
1103 @end smallexample
1104
1105   Now let's have a glance at a prominent annoyance.  The
1106 @var{function} argument of the @code{mapcar} function is passed
1107 exactly one argument (an element of the given list).  Sometimes it is
1108 wishful to map a two-argument function whose first argument is
1109 constant during the mapping anyway.  In this scenario our
1110 @code{interior} comes in very handy.
1111
1112 @example
1113 @group
1114 (defvar demo-hook nil)
1115   => demo-hook
1116 (mapcar (interior #'add-hook 'demo-hook) '(first-fun another-fun))
1117   @result{} ((first-fun) (another-fun first-fun))
1118 demo-hook
1119   @result{} (another-fun first-fun)
1120 @end group
1121 @end example
1122
1123 @unnumberedsubsec The @samp{,.} marker
1124 @findex @samp{,.} @r{(with backquote)}
1125 @cindex destructive splicing (with backquote)
1126
1127   Instead of the splicing operator @samp{,@@} which internally uses
1128 @code{append} to splice an expression into the list at place, you can
1129 always use the destructive form @samp{,.} instead which internally
1130 uses @code{nconc}.  Refer to the documentation of @code{nconc} for
1131 more information, @pxref{Rearrangement}.
1132
1133 @example
1134 @group
1135 (setq test-list '(a b))
1136   @result{} (a b)
1137 @end group
1138
1139 @group
1140 `(,.test-list ,(+ 2 3))
1141   @result{} (a b 5)
1142 `(,.test-list ,(+ 3 4))
1143   @result{} (a b 5 7)
1144 @end group
1145
1146 @group
1147 test-list
1148   @result{} (a b 5 7)
1149 @end group
1150 @end example
1151
1152
1153 @node Nested quoting
1154 @subsection Nested quoting
1155
1156   Simple nested quotations have already been used throughout this
1157 section.  Indeed, function quoting and symbol quoting may be used
1158 combined in order and any nesting level.  Trying to quote of a
1159 self-evaluating or special form necessarily leads to double quoting
1160 it.  Thus @code{''?a} will become @code{(quote ?a)}.
1161
1162   Furthermore, we have already seen that backquoting empowers us to
1163 create a mixture of quoted and evaluated parts of an expression.  We
1164 shall now look at the various oddities which may arise particularly in
1165 nested quotation scenarios.
1166
1167 @example
1168 @group
1169 (setq y 'x
1170       x 'y)
1171 @end group
1172
1173 @group
1174 `(,y `(,y ,@@(+ 2 3)) ,@@(+ 2 3))
1175   @result{} (x (bq-list* y (+ 2 3)) . 5)
1176
1177 `(,y ,`(,y ,@@(+ 2 3)) ,@@(+ 2 3))
1178   => (x (x . 5) . 5)
1179
1180 `(,y ,'`(,y ,@@(+ 2 3)) ,@@(+ 2 3))
1181   @result{} (x (backquote ((\, y) (\,@ (+ 2 3)))) . 5)
1182 @end group
1183 @end example
1184
1185   In the first example, you can behold the dequoting strategy of
1186 nested backquotes.  Like other lisp implementations and dialects the
1187 nested structure is somewhat preserved.  Substitutions are made only
1188 for dequoted (or marked as such) elements appearing at the same
1189 nesting level as the outermost backquote.  But evaluation takes place
1190 at all nesting levels likewise.  Inner backquote lists are evaluated
1191 but remain quoted within the outer backquote list unless these are
1192 marked themselves for dequoting and substitution.  For your
1193 information, the @code{bq-list*} macro behaves like Common Lisp's
1194 @code{list*} form.
1195
1196 @noindent
1197 Evaluation of the inner expression yields:
1198 @smallexample
1199 @group
1200 (bq-list* y (+ 2 3))
1201   @result{} (x . 5)
1202 @end group
1203 @end smallexample
1204
1205 @noindent
1206 This evaluation explains the second example.
1207
1208   Sometimes it is useful to leave inner backquote lists entirely
1209 untouched, for example in macros which in turn define other macros
1210 which then use backquote lists in their definition.  Example 3
1211 demonstrates how this can be achieved.
1212
1213 @unnumberedsubsec Dequoting across nesting bounds
1214
1215   There is no definite concept (yet).  You will achieve what you want
1216 if you carefully quote your expressions.  Although you need to use the
1217 expanded names for @code{`}, @code{,}, @code{,@@} and @code{,.}.
1218
1219 @smallexample
1220 @group
1221 (let ((y 'x)
1222       (x 'y))
1223   `(,y (,'backquote (,y  ,',y))))
1224   @result{} (x (backquote (x (\, y))))
1225 @end group
1226 @end smallexample
1227
1228 @noindent
1229 With growing nesting complexity list constructors may well be more
1230 flexible.
1231
1232 @smallexample
1233 @group
1234 (let ((y 'x)
1235       (x 'y))
1236   (list y (list 'backquote (list y '(\, y)))))
1237   @result{} (x (backquote (x (\, y))))
1238 @end group
1239 @end smallexample
1240
1241   In the future we may provide a more comprehensible concept where the
1242 above scenario would simply read @code{`(,y ``(,y ,,y))}.  On the
1243 other hand you can create your own solutions of backquotations using
1244 -- better said abusing -- the comma read-syntax.  The idea is to
1245 locally make all variables self-evaluating and explicitly specify an
1246 expansion for commatised variables.  To get this right, this is one
1247 method out of many and it it a matter of personal taste.  The next
1248 (very) simple example merely demonstrates the idea and does not
1249 represent a concept nor a special elisp feature at all:
1250
1251 @smallexample
1252 (let* ((x 'x)
1253        (y 'y)
1254        (,x 'top-level)
1255        (,y x)
1256        (,,x ,x)
1257        (,,y ,x))
1258   (list x y ,x ,y ,,x ,,y))
1259 @end smallexample
1260