2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1994, 1998, 2001-2018 Free Software Foundation,
5 @c See the file elisp.texi for copying conditions.
11 @cindex value of expression
13 The @dfn{evaluation} of expressions in Emacs Lisp is performed by the
14 @dfn{Lisp interpreter}---a program that receives a Lisp object as input
15 and computes its @dfn{value as an expression}. How it does this depends
16 on the data type of the object, according to rules described in this
17 chapter. The interpreter runs automatically to evaluate portions of
18 your program, but can also be called explicitly via the Lisp primitive
23 * Intro Eval:: Evaluation in the scheme of things.
24 * Forms:: How various sorts of objects are evaluated.
25 * Quoting:: Avoiding evaluation (to put constants in the program).
26 * Backquote:: Easier construction of list structure.
27 * Eval:: How to invoke the Lisp interpreter explicitly.
28 * Deferred Eval:: Deferred and lazy evaluation of forms.
32 @section Introduction to Evaluation
34 The Lisp interpreter, or evaluator, is the part of Emacs that
35 computes the value of an expression that is given to it. When a
36 function written in Lisp is called, the evaluator computes the value
37 of the function by evaluating the expressions in the function body.
38 Thus, running any Lisp program really means running the Lisp
46 A Lisp object that is intended for evaluation is called a @dfn{form}
47 or @dfn{expression}@footnote{It is sometimes also referred to as an
48 @dfn{S-expression} or @dfn{sexp}, but we generally do not use this
49 terminology in this manual.}. The fact that forms are data objects
50 and not merely text is one of the fundamental differences between
51 Lisp-like languages and typical programming languages. Any object can
52 be evaluated, but in practice only numbers, symbols, lists and strings
53 are evaluated very often.
55 In subsequent sections, we will describe the details of what
56 evaluation means for each kind of form.
58 It is very common to read a Lisp form and then evaluate the form,
59 but reading and evaluation are separate activities, and either can be
60 performed alone. Reading per se does not evaluate anything; it
61 converts the printed representation of a Lisp object to the object
62 itself. It is up to the caller of @code{read} to specify whether this
63 object is a form to be evaluated, or serves some entirely different
64 purpose. @xref{Input Functions}.
66 @cindex recursive evaluation
67 Evaluation is a recursive process, and evaluating a form often
68 involves evaluating parts within that form. For instance, when you
69 evaluate a @dfn{function call} form such as @code{(car x)}, Emacs
70 first evaluates the argument (the subform @code{x}). After evaluating
71 the argument, Emacs @dfn{executes} the function (@code{car}), and if
72 the function is written in Lisp, execution works by evaluating the
73 @dfn{body} of the function (in this example, however, @code{car} is
74 not a Lisp function; it is a primitive function implemented in C).
75 @xref{Functions}, for more information about functions and function
79 Evaluation takes place in a context called the @dfn{environment},
80 which consists of the current values and bindings of all Lisp
81 variables (@pxref{Variables}).@footnote{This definition of
82 ``environment'' is specifically not intended to include all the data
83 that can affect the result of a program.} Whenever a form refers to a
84 variable without creating a new binding for it, the variable evaluates
85 to the value given by the current environment. Evaluating a form may
86 also temporarily alter the environment by binding variables
87 (@pxref{Local Variables}).
90 Evaluating a form may also make changes that persist; these changes
91 are called @dfn{side effects}. An example of a form that produces a
92 side effect is @code{(setq foo 1)}.
94 Do not confuse evaluation with command key interpretation. The
95 editor command loop translates keyboard input into a command (an
96 interactively callable function) using the active keymaps, and then
97 uses @code{call-interactively} to execute that command. Executing the
98 command usually involves evaluation, if the command is written in
99 Lisp; however, this step is not considered a part of command key
100 interpretation. @xref{Command Loop}.
103 @section Kinds of Forms
105 A Lisp object that is intended to be evaluated is called a
106 @dfn{form} (or an @dfn{expression}). How Emacs evaluates a form
107 depends on its data type. Emacs has three different kinds of form
108 that are evaluated differently: symbols, lists, and all other
109 types. This section describes all three kinds, one by one, starting
110 with the other types, which are self-evaluating forms.
113 * Self-Evaluating Forms:: Forms that evaluate to themselves.
114 * Symbol Forms:: Symbols evaluate as variables.
115 * Classifying Lists:: How to distinguish various sorts of list forms.
116 * Function Indirection:: When a symbol appears as the car of a list,
117 we find the real function via the symbol.
118 * Function Forms:: Forms that call functions.
119 * Macro Forms:: Forms that call macros.
120 * Special Forms:: Special forms are idiosyncratic primitives,
121 most of them extremely important.
122 * Autoloading:: Functions set up to load files
123 containing their real definitions.
126 @node Self-Evaluating Forms
127 @subsection Self-Evaluating Forms
128 @cindex vector evaluation
129 @cindex literal evaluation
130 @cindex self-evaluating form
132 A @dfn{self-evaluating form} is any form that is not a list or
133 symbol. Self-evaluating forms evaluate to themselves: the result of
134 evaluation is the same object that was evaluated. Thus, the number 25
135 evaluates to 25, and the string @code{"foo"} evaluates to the string
136 @code{"foo"}. Likewise, evaluating a vector does not cause evaluation
137 of the elements of the vector---it returns the same vector with its
142 '123 ; @r{A number, shown without evaluation.}
146 123 ; @r{Evaluated as usual---result is the same.}
150 (eval '123) ; @r{Evaluated "by hand"---result is the same.}
154 (eval (eval '123)) ; @r{Evaluating twice changes nothing.}
159 It is common to write numbers, characters, strings, and even vectors
160 in Lisp code, taking advantage of the fact that they self-evaluate.
161 However, it is quite unusual to do this for types that lack a read
162 syntax, because there's no way to write them textually. It is possible
163 to construct Lisp expressions containing these types by means of a Lisp
164 program. Here is an example:
168 ;; @r{Build an expression containing a buffer object.}
169 (setq print-exp (list 'print (current-buffer)))
170 @result{} (print #<buffer eval.texi>)
175 @print{} #<buffer eval.texi>
176 @result{} #<buffer eval.texi>
181 @subsection Symbol Forms
182 @cindex symbol evaluation
184 When a symbol is evaluated, it is treated as a variable. The result
185 is the variable's value, if it has one. If the symbol has no value as
186 a variable, the Lisp interpreter signals an error. For more
187 information on the use of variables, see @ref{Variables}.
189 In the following example, we set the value of a symbol with
190 @code{setq}. Then we evaluate the symbol, and get back the value that
208 The symbols @code{nil} and @code{t} are treated specially, so that the
209 value of @code{nil} is always @code{nil}, and the value of @code{t} is
210 always @code{t}; you cannot set or bind them to any other values. Thus,
211 these two symbols act like self-evaluating forms, even though
212 @code{eval} treats them like any other symbol. A symbol whose name
213 starts with @samp{:} also self-evaluates in the same way; likewise,
214 its value ordinarily cannot be changed. @xref{Constant Variables}.
216 @node Classifying Lists
217 @subsection Classification of List Forms
218 @cindex list form evaluation
220 A form that is a nonempty list is either a function call, a macro
221 call, or a special form, according to its first element. These three
222 kinds of forms are evaluated in different ways, described below. The
223 remaining list elements constitute the @dfn{arguments} for the function,
224 macro, or special form.
226 The first step in evaluating a nonempty list is to examine its first
227 element. This element alone determines what kind of form the list is
228 and how the rest of the list is to be processed. The first element is
229 @emph{not} evaluated, as it would be in some Lisp dialects such as
232 @node Function Indirection
233 @subsection Symbol Function Indirection
234 @cindex symbol function indirection
235 @cindex indirection for functions
236 @cindex void function
238 If the first element of the list is a symbol then evaluation
239 examines the symbol's function cell, and uses its contents instead of
240 the original symbol. If the contents are another symbol, this
241 process, called @dfn{symbol function indirection}, is repeated until
242 it obtains a non-symbol. @xref{Function Names}, for more information
243 about symbol function indirection.
245 One possible consequence of this process is an infinite loop, in the
246 event that a symbol's function cell refers to the same symbol.
247 Otherwise, we eventually obtain a non-symbol, which ought to be a
248 function or other suitable object.
250 @kindex invalid-function
251 More precisely, we should now have a Lisp function (a lambda
252 expression), a byte-code function, a primitive function, a Lisp macro,
253 a special form, or an autoload object. Each of these types is a case
254 described in one of the following sections. If the object is not one
255 of these types, Emacs signals an @code{invalid-function} error.
257 The following example illustrates the symbol indirection process.
258 We use @code{fset} to set the function cell of a symbol and
259 @code{symbol-function} to get the function cell contents
260 (@pxref{Function Cells}). Specifically, we store the symbol
261 @code{car} into the function cell of @code{first}, and the symbol
262 @code{first} into the function cell of @code{erste}.
266 ;; @r{Build this function cell linkage:}
267 ;; ------------- ----- ------- -------
268 ;; | #<subr car> | <-- | car | <-- | first | <-- | erste |
269 ;; ------------- ----- ------- -------
272 (symbol-function 'car)
273 @result{} #<subr car>
284 (erste '(1 2 3)) ; @r{Call the function referenced by @code{erste}.}
289 By contrast, the following example calls a function without any symbol
290 function indirection, because the first element is an anonymous Lisp
291 function, not a symbol.
295 ((lambda (arg) (erste arg))
302 Executing the function itself evaluates its body; this does involve
303 symbol function indirection when calling @code{erste}.
305 This form is rarely used and is now deprecated. Instead, you should write it
310 (funcall (lambda (arg) (erste arg))
317 (let ((arg '(1 2 3))) (erste arg))
321 The built-in function @code{indirect-function} provides an easy way to
322 perform symbol function indirection explicitly.
325 @defun indirect-function function &optional noerror
326 @anchor{Definition of indirect-function}
327 This function returns the meaning of @var{function} as a function. If
328 @var{function} is a symbol, then it finds @var{function}'s function
329 definition and starts over with that value. If @var{function} is not a
330 symbol, then it returns @var{function} itself.
332 This function returns @code{nil} if the final symbol is unbound. It
333 signals a @code{cyclic-function-indirection} error if there is a loop
334 in the chain of symbols.
336 The optional argument @var{noerror} is obsolete, kept for backward
337 compatibility, and has no effect.
339 Here is how you could define @code{indirect-function} in Lisp:
342 (defun indirect-function (function)
343 (if (symbolp function)
344 (indirect-function (symbol-function function))
350 @subsection Evaluation of Function Forms
351 @cindex function form evaluation
352 @cindex function call
354 If the first element of a list being evaluated is a Lisp function
355 object, byte-code object or primitive function object, then that list is
356 a @dfn{function call}. For example, here is a call to the function
363 The first step in evaluating a function call is to evaluate the
364 remaining elements of the list from left to right. The results are the
365 actual argument values, one value for each list element. The next step
366 is to call the function with this list of arguments, effectively using
367 the function @code{apply} (@pxref{Calling Functions}). If the function
368 is written in Lisp, the arguments are used to bind the argument
369 variables of the function (@pxref{Lambda Expressions}); then the forms
370 in the function body are evaluated in order, and the value of the last
371 body form becomes the value of the function call.
374 @subsection Lisp Macro Evaluation
375 @cindex macro call evaluation
377 If the first element of a list being evaluated is a macro object, then
378 the list is a @dfn{macro call}. When a macro call is evaluated, the
379 elements of the rest of the list are @emph{not} initially evaluated.
380 Instead, these elements themselves are used as the arguments of the
381 macro. The macro definition computes a replacement form, called the
382 @dfn{expansion} of the macro, to be evaluated in place of the original
383 form. The expansion may be any sort of form: a self-evaluating
384 constant, a symbol, or a list. If the expansion is itself a macro call,
385 this process of expansion repeats until some other sort of form results.
387 Ordinary evaluation of a macro call finishes by evaluating the
388 expansion. However, the macro expansion is not necessarily evaluated
389 right away, or at all, because other programs also expand macro calls,
390 and they may or may not evaluate the expansions.
392 Normally, the argument expressions are not evaluated as part of
393 computing the macro expansion, but instead appear as part of the
394 expansion, so they are computed when the expansion is evaluated.
396 For example, given a macro defined as follows:
401 (list 'car (list 'cdr x)))
406 an expression such as @code{(cadr (assq 'handler list))} is a macro
407 call, and its expansion is:
410 (car (cdr (assq 'handler list)))
414 Note that the argument @code{(assq 'handler list)} appears in the
417 @xref{Macros}, for a complete description of Emacs Lisp macros.
420 @subsection Special Forms
421 @cindex special forms
422 @cindex evaluation of special forms
424 A @dfn{special form} is a primitive function specially marked so that
425 its arguments are not all evaluated. Most special forms define control
426 structures or perform variable bindings---things which functions cannot
429 Each special form has its own rules for which arguments are evaluated
430 and which are used without evaluation. Whether a particular argument is
431 evaluated may depend on the results of evaluating other arguments.
433 If an expression's first symbol is that of a special form, the
434 expression should follow the rules of that special form; otherwise,
435 Emacs's behavior is not well-defined (though it will not crash). For
436 example, @code{((lambda (x) x . 3) 4)} contains a subexpression that
437 begins with @code{lambda} but is not a well-formed @code{lambda}
438 expression, so Emacs may signal an error, or may return 3 or 4 or
439 @code{nil}, or may behave in other ways.
441 @defun special-form-p object
442 This predicate tests whether its argument is a special form, and
443 returns @code{t} if so, @code{nil} otherwise.
446 Here is a list, in alphabetical order, of all of the special forms in
447 Emacs Lisp with a reference to where each is described.
451 @pxref{Combining Conditions}
454 @pxref{Catch and Throw}
460 @pxref{Handling Errors}
463 @pxref{Defining Variables}
466 @pxref{Defining Variables}
469 @pxref{Anonymous Functions}
475 @pxref{Interactive Call}
478 @pxref{Lambda Expressions}
482 @pxref{Local Variables}
485 @pxref{Combining Conditions}
495 @item save-current-buffer
496 @pxref{Current Buffer}
501 @item save-restriction
505 @pxref{Setting Variables}
508 @pxref{Creating Buffer-Local}
511 @pxref{Mouse Tracking}
514 @pxref{Nonlocal Exits}
520 @cindex CL note---special forms compared
522 @b{Common Lisp note:} Here are some comparisons of special forms in
523 GNU Emacs Lisp and Common Lisp. @code{setq}, @code{if}, and
524 @code{catch} are special forms in both Emacs Lisp and Common Lisp.
525 @code{save-excursion} is a special form in Emacs Lisp, but
526 doesn't exist in Common Lisp. @code{throw} is a special form in
527 Common Lisp (because it must be able to throw multiple values), but it
528 is a function in Emacs Lisp (which doesn't have multiple
533 @subsection Autoloading
535 The @dfn{autoload} feature allows you to call a function or macro
536 whose function definition has not yet been loaded into Emacs. It
537 specifies which file contains the definition. When an autoload object
538 appears as a symbol's function definition, calling that symbol as a
539 function automatically loads the specified file; then it calls the
540 real definition loaded from that file. The way to arrange for an
541 autoload object to appear as a symbol's function definition is
542 described in @ref{Autoload}.
547 The special form @code{quote} returns its single argument, as written,
548 without evaluating it. This provides a way to include constant symbols
549 and lists, which are not self-evaluating objects, in a program. (It is
550 not necessary to quote self-evaluating objects such as numbers, strings,
553 @defspec quote object
554 This special form returns @var{object}, without evaluating it.
557 @cindex @samp{'} for quoting
558 @cindex quoting using apostrophe
559 @cindex apostrophe for quoting
560 Because @code{quote} is used so often in programs, Lisp provides a
561 convenient read syntax for it. An apostrophe character (@samp{'})
562 followed by a Lisp object (in read syntax) expands to a list whose first
563 element is @code{quote}, and whose second element is the object. Thus,
564 the read syntax @code{'x} is an abbreviation for @code{(quote x)}.
566 Here are some examples of expressions that use @code{quote}:
595 Other quoting constructs include @code{function} (@pxref{Anonymous
596 Functions}), which causes an anonymous lambda expression written in Lisp
597 to be compiled, and @samp{`} (@pxref{Backquote}), which is used to quote
598 only part of a list, while computing and substituting other parts.
602 @cindex backquote (list substitution)
603 @cindex ` (list substitution)
606 @dfn{Backquote constructs} allow you to quote a list, but
607 selectively evaluate elements of that list. In the simplest case, it
608 is identical to the special form @code{quote}
612 (described in the previous section; @pxref{Quoting}).
614 For example, these two forms yield identical results:
618 `(a list of (+ 2 3) elements)
619 @result{} (a list of (+ 2 3) elements)
622 '(a list of (+ 2 3) elements)
623 @result{} (a list of (+ 2 3) elements)
627 @findex , @r{(with backquote)}
628 The special marker @samp{,} inside of the argument to backquote
629 indicates a value that isn't constant. The Emacs Lisp evaluator
630 evaluates the argument of @samp{,}, and puts the value in the list
635 `(a list of ,(+ 2 3) elements)
636 @result{} (a list of 5 elements)
641 Substitution with @samp{,} is allowed at deeper levels of the list
642 structure also. For example:
647 @result{} (1 2 (3 9))
651 @findex ,@@ @r{(with backquote)}
652 @cindex splicing (with backquote)
653 You can also @dfn{splice} an evaluated value into the resulting list,
654 using the special marker @samp{,@@}. The elements of the spliced list
655 become elements at the same level as the other elements of the resulting
656 list. The equivalent code without using @samp{`} is often unreadable.
657 Here are some examples:
661 (setq some-list '(2 3))
665 (cons 1 (append some-list '(4) some-list))
666 @result{} (1 2 3 4 2 3)
669 `(1 ,@@some-list 4 ,@@some-list)
670 @result{} (1 2 3 4 2 3)
674 (setq list '(hack foo bar))
675 @result{} (hack foo bar)
680 (cons 'words (append (cdr list) '(as elements)))))
681 @result{} (use the words foo bar as elements)
684 `(use the words ,@@(cdr list) as elements)
685 @result{} (use the words foo bar as elements)
693 Most often, forms are evaluated automatically, by virtue of their
694 occurrence in a program being run. On rare occasions, you may need to
695 write code that evaluates a form that is computed at run time, such as
696 after reading a form from text being edited or getting one from a
697 property list. On these occasions, use the @code{eval} function.
698 Often @code{eval} is not needed and something else should be used instead.
699 For example, to get the value of a variable, while @code{eval} works,
700 @code{symbol-value} is preferable; or rather than store expressions
701 in a property list that then need to go through @code{eval}, it is better to
702 store functions instead that are then passed to @code{funcall}.
704 The functions and variables described in this section evaluate forms,
705 specify limits to the evaluation process, or record recently returned
706 values. Loading a file also does evaluation (@pxref{Loading}).
708 It is generally cleaner and more flexible to store a function in a
709 data structure, and call it with @code{funcall} or @code{apply}, than
710 to store an expression in the data structure and evaluate it. Using
711 functions provides the ability to pass information to them as
714 @defun eval form &optional lexical
715 This is the basic function for evaluating an expression. It evaluates
716 @var{form} in the current environment, and returns the result. The
717 type of the @var{form} object determines how it is evaluated.
720 The argument @var{lexical} specifies the scoping rule for local
721 variables (@pxref{Variable Scoping}). If it is omitted or @code{nil},
722 that means to evaluate @var{form} using the default dynamic scoping
723 rule. If it is @code{t}, that means to use the lexical scoping rule.
724 The value of @var{lexical} can also be a non-empty alist specifying a
725 particular @dfn{lexical environment} for lexical bindings; however,
726 this feature is only useful for specialized purposes, such as in Emacs
727 Lisp debuggers. @xref{Lexical Binding}.
729 Since @code{eval} is a function, the argument expression that appears
730 in a call to @code{eval} is evaluated twice: once as preparation before
731 @code{eval} is called, and again by the @code{eval} function itself.
742 ;; @r{Here @code{eval} receives argument @code{foo}}
745 ;; @r{Here @code{eval} receives argument @code{bar}, which is the value of @code{foo}}
751 The number of currently active calls to @code{eval} is limited to
752 @code{max-lisp-eval-depth} (see below).
755 @deffn Command eval-region start end &optional stream read-function
756 @anchor{Definition of eval-region}
757 This function evaluates the forms in the current buffer in the region
758 defined by the positions @var{start} and @var{end}. It reads forms from
759 the region and calls @code{eval} on them until the end of the region is
760 reached, or until an error is signaled and not handled.
762 By default, @code{eval-region} does not produce any output. However,
763 if @var{stream} is non-@code{nil}, any output produced by output
764 functions (@pxref{Output Functions}), as well as the values that
765 result from evaluating the expressions in the region are printed using
766 @var{stream}. @xref{Output Streams}.
768 If @var{read-function} is non-@code{nil}, it should be a function,
769 which is used instead of @code{read} to read expressions one by one.
770 This function is called with one argument, the stream for reading
771 input. You can also use the variable @code{load-read-function}
772 (@pxref{Definition of load-read-function,, How Programs Do Loading})
773 to specify this function, but it is more robust to use the
774 @var{read-function} argument.
776 @code{eval-region} does not move point. It always returns @code{nil}.
779 @cindex evaluation of buffer contents
780 @deffn Command eval-buffer &optional buffer-or-name stream filename unibyte print
781 This is similar to @code{eval-region}, but the arguments provide
782 different optional features. @code{eval-buffer} operates on the
783 entire accessible portion of buffer @var{buffer-or-name}
784 (@pxref{Narrowing,,, emacs, The GNU Emacs Manual}).
785 @var{buffer-or-name} can be a buffer, a buffer name (a string), or
786 @code{nil} (or omitted), which means to use the current buffer.
787 @var{stream} is used as in @code{eval-region}, unless @var{stream} is
788 @code{nil} and @var{print} non-@code{nil}. In that case, values that
789 result from evaluating the expressions are still discarded, but the
790 output of the output functions is printed in the echo area.
791 @var{filename} is the file name to use for @code{load-history}
792 (@pxref{Unloading}), and defaults to @code{buffer-file-name}
793 (@pxref{Buffer File Name}). If @var{unibyte} is non-@code{nil},
794 @code{read} converts strings to unibyte whenever possible.
796 @findex eval-current-buffer
797 @code{eval-current-buffer} is an alias for this command.
800 @defopt max-lisp-eval-depth
801 @anchor{Definition of max-lisp-eval-depth}
802 This variable defines the maximum depth allowed in calls to @code{eval},
803 @code{apply}, and @code{funcall} before an error is signaled (with error
804 message @code{"Lisp nesting exceeds max-lisp-eval-depth"}).
806 This limit, with the associated error when it is exceeded, is one way
807 Emacs Lisp avoids infinite recursion on an ill-defined function. If
808 you increase the value of @code{max-lisp-eval-depth} too much, such
809 code can cause stack overflow instead. On some systems, this overflow
810 can be handled. In that case, normal Lisp evaluation is interrupted
811 and control is transferred back to the top level command loop
812 (@code{top-level}). Note that there is no way to enter Emacs Lisp
813 debugger in this situation. @xref{Error Debugging}.
815 @cindex Lisp nesting error
817 The depth limit counts internal uses of @code{eval}, @code{apply}, and
818 @code{funcall}, such as for calling the functions mentioned in Lisp
819 expressions, and recursive evaluation of function call arguments and
820 function body forms, as well as explicit calls in Lisp code.
822 The default value of this variable is 800. If you set it to a value
823 less than 100, Lisp will reset it to 100 if the given value is
824 reached. Entry to the Lisp debugger increases the value, if there is
825 little room left, to make sure the debugger itself has room to
828 @code{max-specpdl-size} provides another limit on nesting.
829 @xref{Definition of max-specpdl-size,, Local Variables}.
833 The value of this variable is a list of the values returned by all the
834 expressions that were read, evaluated, and printed from buffers
835 (including the minibuffer) by the standard Emacs commands which do
836 this. (Note that this does @emph{not} include evaluation in
837 @file{*ielm*} buffers, nor evaluation using @kbd{C-j}, @kbd{C-x C-e},
838 and similar evaluation commands in @code{lisp-interaction-mode}.) The
839 elements are ordered most recent first.
847 (list 'A (1+ 2) auto-save-default)
852 @result{} ((A 3 t) 1 @dots{})
856 This variable is useful for referring back to values of forms recently
857 evaluated. It is generally a bad idea to print the value of
858 @code{values} itself, since this may be very long. Instead, examine
859 particular elements, like this:
863 ;; @r{Refer to the most recent evaluation result.}
868 ;; @r{That put a new element on,}
869 ;; @r{so all elements move back one.}
874 ;; @r{This gets the element that was next-to-most-recent}
875 ;; @r{before this example.}
883 @section Deferred and Lazy Evaluation
885 @cindex deferred evaluation
886 @cindex lazy evaluation
889 Sometimes it is useful to delay the evaluation of an expression, for
890 example if you want to avoid performing a time-consuming calculation
891 if it turns out that the result is not needed in the future of the
892 program. The @file{thunk} library provides the following functions
893 and macros to support such @dfn{deferred evaluation}:
896 @defmac thunk-delay forms@dots{}
897 Return a @dfn{thunk} for evaluating the @var{forms}. A thunk is a
898 closure (@pxref{Closures}) that inherits the lexical environment of the
899 @code{thunk-delay} call. Using this macro requires
900 @code{lexical-binding}.
903 @defun thunk-force thunk
904 Force @var{thunk} to perform the evaluation of the forms specified in
905 the @code{thunk-delay} that created the thunk. The result of the
906 evaluation of the last form is returned. The @var{thunk} also
907 ``remembers'' that it has been forced: Any further calls of
908 @code{thunk-force} with the same @var{thunk} will just return the same
909 result without evaluating the forms again.
912 @defmac thunk-let (bindings@dots{}) forms@dots{}
913 This macro is analogous to @code{let} but creates ``lazy'' variable
914 bindings. Any binding has the form @w{@code{(@var{symbol}
915 @var{value-form})}}. Unlike @code{let}, the evaluation of any
916 @var{value-form} is deferred until the binding of the according
917 @var{symbol} is used for the first time when evaluating the
918 @var{forms}. Any @var{value-form} is evaluated at most once. Using
919 this macro requires @code{lexical-binding}.
927 (thunk-let ((derived-number
928 (progn (message "Calculating 1 plus 2 times %d" number)
942 @print{} Calculating 1 plus 2 times 12
948 Because of the special nature of lazily bound variables, it is an error
949 to set them (e.g.@: with @code{setq}).
952 @defmac thunk-let* (bindings@dots{}) forms@dots{}
953 This is like @code{thunk-let} but any expression in @var{bindings} is allowed
954 to refer to preceding bindings in this @code{thunk-let*} form. Using
955 this macro requires @code{lexical-binding}.
960 (thunk-let* ((x (prog2 (message "Calculating x...")
962 (message "Finished calculating x")))
963 (y (prog2 (message "Calculating y...")
965 (message "Finished calculating y")))
966 (z (prog2 (message "Calculating z...")
968 (message "Finished calculating z")))
969 (a (prog2 (message "Calculating a...")
971 (message "Finished calculating a"))))
974 @print{} Calculating z...
975 @print{} Calculating y...
976 @print{} Calculating x...
977 @print{} Finished calculating x
978 @print{} Finished calculating y
979 @print{} Finished calculating z
985 @code{thunk-let} and @code{thunk-let*} use thunks implicitly: their
986 expansion creates helper symbols and binds them to thunks wrapping the
987 binding expressions. All references to the original variables in the
988 body @var{forms} are then replaced by an expression that calls
989 @code{thunk-force} with the according helper variable as the argument.
990 So, any code using @code{thunk-let} or @code{thunk-let*} could be
991 rewritten to use thunks, but in many cases using these macros results
992 in nicer code than using thunks explicitly.