root/branches/2.1/info/cl-1

Revision 3212, 43.0 kB (checked in by miyoshi, 5 years ago)

Sync up with Emacs-21.3.

Line 
1 This is ../info/cl, produced by makeinfo version 4.2 from cl.texi.
2
3 INFO-DIR-SECTION Emacs
4 START-INFO-DIR-ENTRY
5 * CL: (cl).             Partial Common Lisp support for Emacs Lisp.
6 END-INFO-DIR-ENTRY
7
8    This file documents the GNU Emacs Common Lisp emulation package.
9
10    Copyright (C) 1993 Free Software Foundation, Inc.
11
12    Permission is granted to copy, distribute and/or modify this document
13 under the terms of the GNU Free Documentation License, Version 1.1 or
14 any later version published by the Free Software Foundation; with no
15 Invariant Sections, with the Front-Cover texts being "A GNU Manual",
16 and with the Back-Cover Texts as in (a) below.  A copy of the license
17 is included in the section entitled "GNU Free Documentation License" in
18 the Emacs manual.
19
20    (a) The FSF's Back-Cover Text is: "You have freedom to copy and
21 modify this GNU Manual, like GNU software.  Copies published by the Free
22 Software Foundation raise funds for GNU development."
23
24    This document is part of a collection distributed under the GNU Free
25 Documentation License.  If you want to distribute this document
26 separately from the collection, you can do so by adding a copy of the
27 license to the document, as described in section 6 of the license.
28
29 
30 File: cl,  Node: Top,  Next: Overview,  Prev: (dir),  Up: (dir)
31
32 Common Lisp Extensions
33 **********************
34
35 This document describes a set of Emacs Lisp facilities borrowed from
36 Common Lisp.  All the facilities are described here in detail.  While
37 this document does not assume any prior knowledge of Common Lisp, it
38 does assume a basic familiarity with Emacs Lisp.
39
40 * Menu:
41
42 * Overview::             Installation, usage, etc.
43 * Program Structure::    Arglists, `eval-when', `defalias'
44 * Predicates::           `typep', `eql', and `equalp'
45 * Control Structure::    `setf', `do', `loop', etc.
46 * Macros::               Destructuring, `define-compiler-macro'
47 * Declarations::         `proclaim', `declare', etc.
48 * Symbols::              Property lists, `gensym'
49 * Numbers::              Predicates, functions, random numbers
50 * Sequences::            Mapping, functions, searching, sorting
51 * Lists::                `cadr', `sublis', `member*', `assoc*', etc.
52 * Structures::           `defstruct'
53 * Assertions::           `check-type', `assert', `ignore-errors'.
54
55 * Efficiency Concerns::         Hints and techniques
56 * Common Lisp Compatibility::   All known differences with Steele
57 * Old CL Compatibility::        All known differences with old cl.el
58 * Porting Common Lisp::         Hints for porting Common Lisp code
59
60 * Function Index::
61 * Variable Index::
62
63 
64 File: cl,  Node: Overview,  Next: Program Structure,  Prev: Top,  Up: Top
65
66 Overview
67 ********
68
69 Common Lisp is a huge language, and Common Lisp systems tend to be
70 massive and extremely complex.  Emacs Lisp, by contrast, is rather
71 minimalist in the choice of Lisp features it offers the programmer.  As
72 Emacs Lisp programmers have grown in number, and the applications they
73 write have grown more ambitious, it has become clear that Emacs Lisp
74 could benefit from many of the conveniences of Common Lisp.
75
76    The "CL" package adds a number of Common Lisp functions and control
77 structures to Emacs Lisp.  While not a 100% complete implementation of
78 Common Lisp, "CL" adds enough functionality to make Emacs Lisp
79 programming significantly more convenient.
80
81    Some Common Lisp features have been omitted from this package for
82 various reasons:
83
84    * Some features are too complex or bulky relative to their benefit
85      to Emacs Lisp programmers.  CLOS and Common Lisp streams are fine
86      examples of this group.
87
88    * Other features cannot be implemented without modification to the
89      Emacs Lisp interpreter itself, such as multiple return values,
90      lexical scoping, case-insensitive symbols, and complex numbers.
91      The "CL" package generally makes no attempt to emulate these
92      features.
93
94    * Some features conflict with existing things in Emacs Lisp.  For
95      example, Emacs' `assoc' function is incompatible with the Common
96      Lisp `assoc'.  In such cases, this package usually adds the suffix
97      `*' to the function name of the Common Lisp version of the
98      function (e.g., `assoc*').
99
100    The package described here was written by Dave Gillespie,
101 `daveg@synaptics.com'.  It is a total rewrite of the original 1986
102 `cl.el' package by Cesar Quiroz.  Most features of the the Quiroz
103 package have been retained; any incompatibilities are noted in the
104 descriptions below.  Care has been taken in this version to ensure that
105 each function is defined efficiently, concisely, and with minimal
106 impact on the rest of the Emacs environment.
107
108 * Menu:
109
110 * Usage::                How to use the CL package
111 * Organization::         The package's five component files
112 * Installation::         Compiling and installing CL
113 * Naming Conventions::   Notes on CL function names
114
115 
116 File: cl,  Node: Usage,  Next: Organization,  Prev: Overview,  Up: Overview
117
118 Usage
119 =====
120
121 Lisp code that uses features from the "CL" package should include at
122 the beginning:
123
124      (require 'cl)
125
126 If you want to ensure that the new (Gillespie) version of "CL" is the
127 one that is present, add an additional `(require 'cl-19)' call:
128
129      (require 'cl)
130      (require 'cl-19)
131
132 The second call will fail (with "`cl-19.el' not found") if the old
133 `cl.el' package was in use.
134
135    It is safe to arrange to load "CL" at all times, e.g., in your
136 `.emacs' file.  But it's a good idea, for portability, to `(require
137 'cl)' in your code even if you do this.
138
139 
140 File: cl,  Node: Organization,  Next: Installation,  Prev: Usage,  Up: Overview
141
142 Organization
143 ============
144
145 The Common Lisp package is organized into four files:
146
147 `cl.el'
148      This is the "main" file, which contains basic functions and
149      information about the package.  This file is relatively
150      compact--about 700 lines.
151
152 `cl-extra.el'
153      This file contains the larger, more complex or unusual functions.
154      It is kept separate so that packages which only want to use Common
155      Lisp fundamentals like the `cadr' function won't need to pay the
156      overhead of loading the more advanced functions.
157
158 `cl-seq.el'
159      This file contains most of the advanced functions for operating on
160      sequences or lists, such as `delete-if' and `assoc*'.
161
162 `cl-macs.el'
163      This file contains the features of the packages which are macros
164      instead of functions.  Macros expand when the caller is compiled,
165      not when it is run, so the macros generally only need to be
166      present when the byte-compiler is running (or when the macros are
167      used in uncompiled code such as a `.emacs' file).  Most of the
168      macros of this package are isolated in `cl-macs.el' so that they
169      won't take up memory unless you are compiling.
170
171    The file `cl.el' includes all necessary `autoload' commands for the
172 functions and macros in the other three files.  All you have to do is
173 `(require 'cl)', and `cl.el' will take care of pulling in the other
174 files when they are needed.
175
176    There is another file, `cl-compat.el', which defines some routines
177 from the older `cl.el' package that are no longer present in the new
178 package.  This includes internal routines like `setelt' and
179 `zip-lists', deprecated features like `defkeyword', and an emulation of
180 the old-style multiple-values feature.  *Note Old CL Compatibility::.
181
182 
183 File: cl,  Node: Installation,  Next: Naming Conventions,  Prev: Organization,  Up: Overview
184
185 Installation
186 ============
187
188 Installation of the "CL" package is simple:  Just put the byte-compiled
189 files `cl.elc', `cl-extra.elc', `cl-seq.elc', `cl-macs.elc', and
190 `cl-compat.elc' into a directory on your `load-path'.
191
192    There are no special requirements to compile this package: The files
193 do not have to be loaded before they are compiled, nor do they need to
194 be compiled in any particular order.
195
196    You may choose to put the files into your main `lisp/' directory,
197 replacing the original `cl.el' file there.  Or, you could put them into
198 a directory that comes before `lisp/' on your `load-path' so that the
199 old `cl.el' is effectively hidden.
200
201    Also, format the `cl.texinfo' file and put the resulting Info files
202 in the `info/' directory or another suitable place.
203
204    You may instead wish to leave this package's components all in their
205 own directory, and then add this directory to your `load-path' and
206 `Info-directory-list'.  Add the directory to the front of the list so
207 the old "CL" package and its documentation are hidden.
208
209 
210 File: cl,  Node: Naming Conventions,  Prev: Installation,  Up: Overview
211
212 Naming Conventions
213 ==================
214
215 Except where noted, all functions defined by this package have the same
216 names and calling conventions as their Common Lisp counterparts.
217
218    Following is a complete list of functions whose names were changed
219 from Common Lisp, usually to avoid conflicts with Emacs.  In each case,
220 a `*' has been appended to the Common Lisp name to obtain the Emacs
221 name:
222
223      defun*        defsubst*     defmacro*     function*
224      member*       assoc*        rassoc*       get*
225      remove*       delete*       mapcar*       sort*
226      floor*        ceiling*      truncate*     round*
227      mod*          rem*          random*
228
229    Internal function and variable names in the package are prefixed by
230 `cl-'.  Here is a complete list of functions _not_ prefixed by `cl-'
231 which were not taken from Common Lisp:
232
233      floatp-safe   lexical-let   lexical-let*
234      callf         callf2        letf          letf*
235      defsubst*
236
237    The following simple functions and macros are defined in `cl.el';
238 they do not cause other components like `cl-extra' to be loaded.
239
240      eql           floatp-safe   endp
241      evenp         oddp          plusp         minusp
242      caaar .. cddddr
243      list*         ldiff         rest          first .. tenth
244      copy-list     subst         mapcar* [2]
245      adjoin [3]    acons         pairlis       pop [4]
246      push [4]      pushnew [3,4] incf [4]      decf [4]
247      proclaim      declaim
248
249 [2] Only for one sequence argument or two list arguments.
250
251 [3] Only if `:test' is `eq', `equal', or unspecified, and `:key' is not
252 used.
253
254 [4] Only when PLACE is a plain variable name.
255
256 
257 File: cl,  Node: Program Structure,  Next: Predicates,  Prev: Overview,  Up: Top
258
259 Program Structure
260 *****************
261
262 This section describes features of the "CL" package which have to do
263 with programs as a whole: advanced argument lists for functions, and
264 the `eval-when' construct.
265
266 * Menu:
267
268 * Argument Lists::       `&key', `&aux', `defun*', `defmacro*'.
269 * Time of Evaluation::   The `eval-when' construct.
270
271 
272 File: cl,  Node: Argument Lists,  Next: Time of Evaluation,  Prev: Program Structure,  Up: Program Structure
273
274 Argument Lists
275 ==============
276
277 Emacs Lisp's notation for argument lists of functions is a subset of
278 the Common Lisp notation.  As well as the familiar `&optional' and
279 `&rest' markers, Common Lisp allows you to specify default values for
280 optional arguments, and it provides the additional markers `&key' and
281 `&aux'.
282
283    Since argument parsing is built-in to Emacs, there is no way for
284 this package to implement Common Lisp argument lists seamlessly.
285 Instead, this package defines alternates for several Lisp forms which
286 you must use if you need Common Lisp argument lists.
287
288  - Special Form: defun* name arglist body...
289      This form is identical to the regular `defun' form, except that
290      ARGLIST is allowed to be a full Common Lisp argument list.  Also,
291      the function body is enclosed in an implicit block called NAME;
292      *note Blocks and Exits::.
293
294  - Special Form: defsubst* name arglist body...
295      This is just like `defun*', except that the function that is
296      defined is automatically proclaimed `inline', i.e., calls to it
297      may be expanded into in-line code by the byte compiler.  This is
298      analogous to the `defsubst' form; `defsubst*' uses a different
299      method (compiler macros) which works in all version of Emacs, and
300      also generates somewhat more efficient inline expansions.  In
301      particular, `defsubst*' arranges for the processing of keyword
302      arguments, default values, etc., to be done at compile-time
303      whenever possible.
304
305  - Special Form: defmacro* name arglist body...
306      This is identical to the regular `defmacro' form, except that
307      ARGLIST is allowed to be a full Common Lisp argument list.  The
308      `&environment' keyword is supported as described in Steele.  The
309      `&whole' keyword is supported only within destructured lists (see
310      below); top-level `&whole' cannot be implemented with the current
311      Emacs Lisp interpreter.  The macro expander body is enclosed in an
312      implicit block called NAME.
313
314  - Special Form: function* symbol-or-lambda
315      This is identical to the regular `function' form, except that if
316      the argument is a `lambda' form then that form may use a full
317      Common Lisp argument list.
318
319    Also, all forms (such as `defsetf' and `flet') defined in this
320 package that include ARGLISTs in their syntax allow full Common Lisp
321 argument lists.
322
323    Note that it is _not_ necessary to use `defun*' in order to have
324 access to most "CL" features in your function.  These features are
325 always present; `defun*''s only difference from `defun' is its more
326 flexible argument lists and its implicit block.
327
328    The full form of a Common Lisp argument list is
329
330      (VAR...
331       &optional (VAR INITFORM SVAR)...
332       &rest VAR
333       &key ((KEYWORD VAR) INITFORM SVAR)...
334       &aux (VAR INITFORM)...)
335
336    Each of the five argument list sections is optional.  The SVAR,
337 INITFORM, and KEYWORD parts are optional; if they are omitted, then
338 `(VAR)' may be written simply `VAR'.
339
340    The first section consists of zero or more "required" arguments.
341 These arguments must always be specified in a call to the function;
342 there is no difference between Emacs Lisp and Common Lisp as far as
343 required arguments are concerned.
344
345    The second section consists of "optional" arguments.  These
346 arguments may be specified in the function call; if they are not,
347 INITFORM specifies the default value used for the argument.  (No
348 INITFORM means to use `nil' as the default.)  The INITFORM is evaluated
349 with the bindings for the preceding arguments already established; `(a
350 &optional (b (1+ a)))' matches one or two arguments, with the second
351 argument defaulting to one plus the first argument.  If the SVAR is
352 specified, it is an auxiliary variable which is bound to `t' if the
353 optional argument was specified, or to `nil' if the argument was
354 omitted.  If you don't use an SVAR, then there will be no way for your
355 function to tell whether it was called with no argument, or with the
356 default value passed explicitly as an argument.
357
358    The third section consists of a single "rest" argument.  If more
359 arguments were passed to the function than are accounted for by the
360 required and optional arguments, those extra arguments are collected
361 into a list and bound to the "rest" argument variable.  Common Lisp's
362 `&rest' is equivalent to that of Emacs Lisp.  Common Lisp accepts
363 `&body' as a synonym for `&rest' in macro contexts; this package
364 accepts it all the time.
365
366    The fourth section consists of "keyword" arguments.  These are
367 optional arguments which are specified by name rather than positionally
368 in the argument list.  For example,
369
370      (defun* foo (a &optional b &key c d (e 17)))
371
372 defines a function which may be called with one, two, or more
373 arguments.  The first two arguments are bound to `a' and `b' in the
374 usual way.  The remaining arguments must be pairs of the form `:c',
375 `:d', or `:e' followed by the value to be bound to the corresponding
376 argument variable.  (Symbols whose names begin with a colon are called
377 "keywords", and they are self-quoting in the same way as `nil' and `t'.)
378
379    For example, the call `(foo 1 2 :d 3 :c 4)' sets the five arguments
380 to 1, 2, 4, 3, and 17, respectively.  If the same keyword appears more
381 than once in the function call, the first occurrence takes precedence
382 over the later ones.  Note that it is not possible to specify keyword
383 arguments without specifying the optional argument `b' as well, since
384 `(foo 1 :c 2)' would bind `b' to the keyword `:c', then signal an error
385 because `2' is not a valid keyword.
386
387    If a KEYWORD symbol is explicitly specified in the argument list as
388 shown in the above diagram, then that keyword will be used instead of
389 just the variable name prefixed with a colon.  You can specify a
390 KEYWORD symbol which does not begin with a colon at all, but such
391 symbols will not be self-quoting; you will have to quote them
392 explicitly with an apostrophe in the function call.
393
394    Ordinarily it is an error to pass an unrecognized keyword to a
395 function, e.g., `(foo 1 2 :c 3 :goober 4)'.  You can ask Lisp to ignore
396 unrecognized keywords, either by adding the marker `&allow-other-keys'
397 after the keyword section of the argument list, or by specifying an
398 `:allow-other-keys' argument in the call whose value is non-`nil'.  If
399 the function uses both `&rest' and `&key' at the same time, the "rest"
400 argument is bound to the keyword list as it appears in the call.  For
401 example:
402
403      (defun* find-thing (thing &rest rest &key need &allow-other-keys)
404        (or (apply 'member* thing thing-list :allow-other-keys t rest)
405            (if need (error "Thing not found"))))
406
407 This function takes a `:need' keyword argument, but also accepts other
408 keyword arguments which are passed on to the `member*' function.
409 `allow-other-keys' is used to keep both `find-thing' and `member*' from
410 complaining about each others' keywords in the arguments.
411
412    The fifth section of the argument list consists of "auxiliary
413 variables".  These are not really arguments at all, but simply
414 variables which are bound to `nil' or to the specified INITFORMS during
415 execution of the function.  There is no difference between the
416 following two functions, except for a matter of stylistic taste:
417
418      (defun* foo (a b &aux (c (+ a b)) d)
419        BODY)
420      
421      (defun* foo (a b)
422        (let ((c (+ a b)) d)
423          BODY))
424
425    Argument lists support "destructuring".  In Common Lisp,
426 destructuring is only allowed with `defmacro'; this package allows it
427 with `defun*' and other argument lists as well.  In destructuring, any
428 argument variable (VAR in the above diagram) can be replaced by a list
429 of variables, or more generally, a recursive argument list.  The
430 corresponding argument value must be a list whose elements match this
431 recursive argument list.  For example:
432
433      (defmacro* dolist ((var listform &optional resultform)
434                         &rest body)
435        ...)
436
437    This says that the first argument of `dolist' must be a list of two
438 or three items; if there are other arguments as well as this list, they
439 are stored in `body'.  All features allowed in regular argument lists
440 are allowed in these recursive argument lists.  In addition, the clause
441 `&whole VAR' is allowed at the front of a recursive argument list.  It
442 binds VAR to the whole list being matched; thus `(&whole all a b)'
443 matches a list of two things, with `a' bound to the first thing, `b'
444 bound to the second thing, and `all' bound to the list itself.  (Common
445 Lisp allows `&whole' in top-level `defmacro' argument lists as well,
446 but Emacs Lisp does not support this usage.)
447
448    One last feature of destructuring is that the argument list may be
449 dotted, so that the argument list `(a b . c)' is functionally
450 equivalent to `(a b &rest c)'.
451
452    If the optimization quality `safety' is set to 0 (*note
453 Declarations::), error checking for wrong number of arguments and
454 invalid keyword arguments is disabled.  By default, argument lists are
455 rigorously checked.
456
457 
458 File: cl,  Node: Time of Evaluation,  Prev: Argument Lists,  Up: Program Structure
459
460 Time of Evaluation
461 ==================
462
463 Normally, the byte-compiler does not actually execute the forms in a
464 file it compiles.  For example, if a file contains `(setq foo t)', the
465 act of compiling it will not actually set `foo' to `t'.  This is true
466 even if the `setq' was a top-level form (i.e., not enclosed in a
467 `defun' or other form).  Sometimes, though, you would like to have
468 certain top-level forms evaluated at compile-time.  For example, the
469 compiler effectively evaluates `defmacro' forms at compile-time so that
470 later parts of the file can refer to the macros that are defined.
471
472  - Special Form: eval-when (situations...) forms...
473      This form controls when the body FORMS are evaluated.  The
474      SITUATIONS list may contain any set of the symbols `compile',
475      `load', and `eval' (or their long-winded ANSI equivalents,
476      `:compile-toplevel', `:load-toplevel', and `:execute').
477
478      The `eval-when' form is handled differently depending on whether
479      or not it is being compiled as a top-level form.  Specifically, it
480      gets special treatment if it is being compiled by a command such
481      as `byte-compile-file' which compiles files or buffers of code,
482      and it appears either literally at the top level of the file or
483      inside a top-level `progn'.
484
485      For compiled top-level `eval-when's, the body FORMS are executed
486      at compile-time if `compile' is in the SITUATIONS list, and the
487      FORMS are written out to the file (to be executed at load-time) if
488      `load' is in the SITUATIONS list.
489
490      For non-compiled-top-level forms, only the `eval' situation is
491      relevant.  (This includes forms executed by the interpreter, forms
492      compiled with `byte-compile' rather than `byte-compile-file', and
493      non-top-level forms.)  The `eval-when' acts like a `progn' if
494      `eval' is specified, and like `nil' (ignoring the body FORMS) if
495      not.
496
497      The rules become more subtle when `eval-when's are nested; consult
498      Steele (second edition) for the gruesome details (and some
499      gruesome examples).
500
501      Some simple examples:
502
503           ;; Top-level forms in foo.el:
504           (eval-when (compile)           (setq foo1 'bar))
505           (eval-when (load)              (setq foo2 'bar))
506           (eval-when (compile load)      (setq foo3 'bar))
507           (eval-when (eval)              (setq foo4 'bar))
508           (eval-when (eval compile)      (setq foo5 'bar))
509           (eval-when (eval load)         (setq foo6 'bar))
510           (eval-when (eval compile load) (setq foo7 'bar))
511
512      When `foo.el' is compiled, these variables will be set during the
513      compilation itself:
514
515           foo1  foo3  foo5  foo7      ; `compile'
516
517      When `foo.elc' is loaded, these variables will be set:
518
519           foo2  foo3  foo6  foo7      ; `load'
520
521      And if `foo.el' is loaded uncompiled, these variables will be set:
522
523           foo4  foo5  foo6  foo7      ; `eval'
524
525      If these seven `eval-when's had been, say, inside a `defun', then
526      the first three would have been equivalent to `nil' and the last
527      four would have been equivalent to the corresponding `setq's.
528
529      Note that `(eval-when (load eval) ...)' is equivalent to `(progn
530      ...)' in all contexts.  The compiler treats certain top-level
531      forms, like `defmacro' (sort-of) and `require', as if they were
532      wrapped in `(eval-when (compile load eval) ...)'.
533
534    Emacs includes two special forms related to `eval-when'.  One of
535 these, `eval-when-compile', is not quite equivalent to any `eval-when'
536 construct and is described below.
537
538    The other form, `(eval-and-compile ...)', is exactly equivalent to
539 `(eval-when (compile load eval) ...)' and so is not itself defined by
540 this package.
541
542  - Special Form: eval-when-compile forms...
543      The FORMS are evaluated at compile-time; at execution time, this
544      form acts like a quoted constant of the resulting value.  Used at
545      top-level, `eval-when-compile' is just like `eval-when (compile
546      eval)'.  In other contexts, `eval-when-compile' allows code to be
547      evaluated once at compile-time for efficiency or other reasons.
548
549      This form is similar to the `#.' syntax of true Common Lisp.
550
551  - Special Form: load-time-value form
552      The FORM is evaluated at load-time; at execution time, this form
553      acts like a quoted constant of the resulting value.
554
555      Early Common Lisp had a `#,' syntax that was similar to this, but
556      ANSI Common Lisp replaced it with `load-time-value' and gave it
557      more well-defined semantics.
558
559      In a compiled file, `load-time-value' arranges for FORM to be
560      evaluated when the `.elc' file is loaded and then used as if it
561      were a quoted constant.  In code compiled by `byte-compile' rather
562      than `byte-compile-file', the effect is identical to
563      `eval-when-compile'.  In uncompiled code, both `eval-when-compile'
564      and `load-time-value' act exactly like `progn'.
565
566           (defun report ()
567             (insert "This function was executed on: "
568                     (current-time-string)
569                     ", compiled on: "
570                     (eval-when-compile (current-time-string))
571                     ;; or '#.(current-time-string) in real Common Lisp
572                     ", and loaded on: "
573                     (load-time-value (current-time-string))))
574
575      Byte-compiled, the above defun will result in the following code
576      (or its compiled equivalent, of course) in the `.elc' file:
577
578           (setq --temp-- (current-time-string))
579           (defun report ()
580             (insert "This function was executed on: "
581                     (current-time-string)
582                     ", compiled on: "
583                     '"Wed Jun 23 18:33:43 1993"
584                     ", and loaded on: "
585                     --temp--))
586
587 
588 File: cl,  Node: Predicates,  Next: Control Structure,  Prev: Program Structure,  Up: Top
589
590 Predicates
591 **********
592
593 This section describes functions for testing whether various facts are
594 true or false.
595
596 * Menu:
597
598 * Type Predicates::      `typep', `deftype', and `coerce'
599 * Equality Predicates::  `eql' and `equalp'
600
601 
602 File: cl,  Node: Type Predicates,  Next: Equality Predicates,  Prev: Predicates,  Up: Predicates
603
604 Type Predicates
605 ===============
606
607 The "CL" package defines a version of the Common Lisp `typep' predicate.
608
609  - Function: typep object type
610      Check if OBJECT is of type TYPE, where TYPE is a (quoted) type
611      name of the sort used by Common Lisp.  For example, `(typep foo
612      'integer)' is equivalent to `(integerp foo)'.
613
614    The TYPE argument to the above function is either a symbol or a list
615 beginning with a symbol.
616
617    * If the type name is a symbol, Emacs appends `-p' to the symbol
618      name to form the name of a predicate function for testing the
619      type.  (Built-in predicates whose names end in `p' rather than
620      `-p' are used when appropriate.)
621
622    * The type symbol `t' stands for the union of all types.  `(typep
623      OBJECT t)' is always true.  Likewise, the type symbol `nil' stands
624      for nothing at all, and `(typep OBJECT nil)' is always false.
625
626    * The type symbol `null' represents the symbol `nil'.  Thus `(typep
627      OBJECT 'null)' is equivalent to `(null OBJECT)'.
628
629    * The type symbol `real' is a synonym for `number', and `fixnum' is
630      a synonym for `integer'.
631
632    * The type symbols `character' and `string-char' match integers in
633      the range from 0 to 255.
634
635    * The type symbol `float' uses the `floatp-safe' predicate defined
636      by this package rather than `floatp', so it will work correctly
637      even in Emacs versions without floating-point support.
638
639    * The type list `(integer LOW HIGH)' represents all integers between
640      LOW and HIGH, inclusive.  Either bound may be a list of a single
641      integer to specify an exclusive limit, or a `*' to specify no
642      limit.  The type `(integer * *)' is thus equivalent to `integer'.
643
644    * Likewise, lists beginning with `float', `real', or `number'
645      represent numbers of that type falling in a particular range.
646
647    * Lists beginning with `and', `or', and `not' form combinations of
648      types.  For example, `(or integer (float 0 *))' represents all
649      objects that are integers or non-negative floats.
650
651    * Lists beginning with `member' or `member*' represent objects `eql'
652      to any of the following values.  For example, `(member 1 2 3 4)'
653      is equivalent to `(integer 1 4)', and `(member nil)' is equivalent
654      to `null'.
655
656    * Lists of the form `(satisfies PREDICATE)' represent all objects
657      for which PREDICATE returns true when called with that object as
658      an argument.
659
660    The following function and macro (not technically predicates) are
661 related to `typep'.
662
663  - Function: coerce object type
664      This function attempts to convert OBJECT to the specified TYPE.
665      If OBJECT is already of that type as determined by `typep', it is
666      simply returned.  Otherwise, certain types of conversions will be
667      made:  If TYPE is any sequence type (`string', `list', etc.) then
668      OBJECT will be converted to that type if possible.  If TYPE is
669      `character', then strings of length one and symbols with
670      one-character names can be coerced.  If TYPE is `float', then
671      integers can be coerced in versions of Emacs that support floats.
672      In all other circumstances, `coerce' signals an error.
673
674  - Special Form: deftype name arglist forms...
675      This macro defines a new type called NAME.  It is similar to
676      `defmacro' in many ways; when NAME is encountered as a type name,
677      the body FORMS are evaluated and should return a type specifier
678      that is equivalent to the type.  The ARGLIST is a Common Lisp
679      argument list of the sort accepted by `defmacro*'.  The type
680      specifier `(NAME ARGS...)' is expanded by calling the expander
681      with those arguments; the type symbol `NAME' is expanded by
682      calling the expander with no arguments.  The ARGLIST is processed
683      the same as for `defmacro*' except that optional arguments without
684      explicit defaults use `*' instead of `nil' as the "default"
685      default.  Some examples:
686
687           (deftype null () '(satisfies null))    ; predefined
688           (deftype list () '(or null cons))      ; predefined
689           (deftype unsigned-byte (&optional bits)
690             (list 'integer 0 (if (eq bits '*) bits (1- (lsh 1 bits)))))
691           (unsigned-byte 8)  ==  (integer 0 255)
692           (unsigned-byte)  ==  (integer 0 *)
693           unsigned-byte  ==  (integer 0 *)
694
695      The last example shows how the Common Lisp `unsigned-byte' type
696      specifier could be implemented if desired; this package does not
697      implement `unsigned-byte' by default.
698
699    The `typecase' and `check-type' macros also use type names.  *Note
700 Conditionals::.  *Note Assertions::.  The `map', `concatenate', and
701 `merge' functions take type-name arguments to specify the type of
702 sequence to return.  *Note Sequences::.
703
704 
705 File: cl,  Node: Equality Predicates,  Prev: Type Predicates,  Up: Predicates
706
707 Equality Predicates
708 ===================
709
710 This package defines two Common Lisp predicates, `eql' and `equalp'.
711
712  - Function: eql a b
713      This function is almost the same as `eq', except that if A and B
714      are numbers of the same type, it compares them for numeric
715      equality (as if by `equal' instead of `eq').  This makes a
716      difference only for versions of Emacs that are compiled with
717      floating-point support.  Emacs floats are allocated objects just
718      like cons cells, which means that `(eq 3.0 3.0)' will not
719      necessarily be true--if the two `3.0's were allocated separately,
720      the pointers will be different even though the numbers are the
721      same.  But `(eql 3.0 3.0)' will always be true.
722
723      The types of the arguments must match, so `(eql 3 3.0)' is still
724      false.
725
726      Note that Emacs integers are "direct" rather than allocated, which
727      basically means `(eq 3 3)' will always be true.  Thus `eq' and
728      `eql' behave differently only if floating-point numbers are
729      involved, and are indistinguishable on Emacs versions that don't
730      support floats.
731
732      There is a slight inconsistency with Common Lisp in the treatment
733      of positive and negative zeros.  Some machines, notably those with
734      IEEE standard arithmetic, represent `+0' and `-0' as distinct
735      values.  Normally this doesn't matter because the standard
736      specifies that `(= 0.0 -0.0)' should always be true, and this is
737      indeed what Emacs Lisp and Common Lisp do.  But the Common Lisp
738      standard states that `(eql 0.0 -0.0)' and `(equal 0.0 -0.0)' should
739      be false on IEEE-like machines; Emacs Lisp does not do this, and in
740      fact the only known way to distinguish between the two zeros in
741      Emacs Lisp is to `format' them and check for a minus sign.
742
743  - Function: equalp a b
744      This function is a more flexible version of `equal'.  In
745      particular, it compares strings case-insensitively, and it compares
746      numbers without regard to type (so that `(equalp 3 3.0)' is true).
747      Vectors and conses are compared recursively.  All other objects
748      are compared as if by `equal'.
749
750      This function differs from Common Lisp `equalp' in several
751      respects.  First, Common Lisp's `equalp' also compares
752      _characters_ case-insensitively, which would be impractical in
753      this package since Emacs does not distinguish between integers and
754      characters.  In keeping with the idea that strings are less
755      vector-like in Emacs Lisp, this package's `equalp' also will not
756      compare strings against vectors of integers.
757
758    Also note that the Common Lisp functions `member' and `assoc' use
759 `eql' to compare elements, whereas Emacs Lisp follows the MacLisp
760 tradition and uses `equal' for these two functions.  In Emacs, use
761 `member*' and `assoc*' to get functions which use `eql' for comparisons.
762
763 
764 File: cl,  Node: Control Structure,  Next: Macros,  Prev: Predicates,  Up: Top
765
766 Control Structure
767 *****************
768
769 The features described in the following sections implement various
770 advanced control structures, including the powerful `setf' facility and
771 a number of looping and conditional constructs.
772
773 * Menu:
774
775 * Assignment::             The `psetq' form
776 * Generalized Variables::  `setf', `incf', `push', etc.
777 * Variable Bindings::      `progv', `lexical-let', `flet', `macrolet'
778 * Conditionals::           `case', `typecase'
779 * Blocks and Exits::       `block', `return', `return-from'
780 * Iteration::              `do', `dotimes', `dolist', `do-symbols'
781 * Loop Facility::          The Common Lisp `loop' macro
782 * Multiple Values::        `values', `multiple-value-bind', etc.
783
784 
785 File: cl,  Node: Assignment,  Next: Generalized Variables,  Prev: Control Structure,  Up: Control Structure
786
787 Assignment
788 ==========
789
790 The `psetq' form is just like `setq', except that multiple assignments
791 are done in parallel rather than sequentially.
792
793  - Special Form: psetq [symbol form]...
794      This special form (actually a macro) is used to assign to several
795      variables simultaneously.  Given only one SYMBOL and FORM, it has
796      the same effect as `setq'.  Given several SYMBOL and FORM pairs,
797      it evaluates all the FORMs in advance and then stores the
798      corresponding variables afterwards.
799
800           (setq x 2 y 3)
801           (setq x (+ x y)  y (* x y))
802           x
803                => 5
804           y                     ; `y' was computed after `x' was set.
805                => 15
806           (setq x 2 y 3)
807           (psetq x (+ x y)  y (* x y))
808           x
809                => 5
810           y                     ; `y' was computed before `x' was set.
811                => 6
812
813      The simplest use of `psetq' is `(psetq x y y x)', which exchanges
814      the values of two variables.  (The `rotatef' form provides an even
815      more convenient way to swap two variables; *note Modify Macros::.)
816
817      `psetq' always returns `nil'.
818
819 
820 File: cl,  Node: Generalized Variables,  Next: Variable Bindings,  Prev: Assignment,  Up: Control Structure
821
822 Generalized Variables
823 =====================
824
825 A "generalized variable" or "place form" is one of the many places in
826 Lisp memory where values can be stored.  The simplest place form is a
827 regular Lisp variable.  But the cars and cdrs of lists, elements of
828 arrays, properties of symbols, and many other locations are also places
829 where Lisp values are stored.
830
831    The `setf' form is like `setq', except that it accepts arbitrary
832 place forms on the left side rather than just symbols.  For example,
833 `(setf (car a) b)' sets the car of `a' to `b', doing the same operation
834 as `(setcar a b)' but without having to remember two separate functions
835 for setting and accessing every type of place.
836
837    Generalized variables are analogous to "lvalues" in the C language,
838 where `x = a[i]' gets an element from an array and `a[i] = x' stores an
839 element using the same notation.  Just as certain forms like `a[i]' can
840 be lvalues in C, there is a set of forms that can be generalized
841 variables in Lisp.
842
843 * Menu:
844
845 * Basic Setf::         `setf' and place forms
846 * Modify Macros::      `incf', `push', `rotatef', `letf', `callf', etc.
847 * Customizing Setf::   `define-modify-macro', `defsetf', `define-setf-method'
848
849 
850 File: cl,  Node: Basic Setf,  Next: Modify Macros,  Prev: Generalized Variables,  Up: Generalized Variables
851
852 Basic Setf
853 ----------
854
855 The `setf' macro is the most basic way to operate on generalized
856 variables.
857
858  - Special Form: setf [place form]...
859      This macro evaluates FORM and stores it in PLACE, which must be a
860      valid generalized variable form.  If there are several PLACE and
861      FORM pairs, the assignments are done sequentially just as with
862      `setq'.  `setf' returns the value of the last FORM.
863
864      The following Lisp forms will work as generalized variables, and
865      so may legally appear in the PLACE argument of `setf':
866
867         * A symbol naming a variable.  In other words, `(setf x y)' is
868           exactly equivalent to `(setq x y)', and `setq' itself is
869           strictly speaking redundant now that `setf' exists.  Many
870           programmers continue to prefer `setq' for setting simple
871           variables, though, purely for stylistic or historical reasons.
872           The macro `(setf x y)' actually expands to `(setq x y)', so
873           there is no performance penalty for using it in compiled code.
874
875         * A call to any of the following Lisp functions:
876
877                car                 cdr                 caar .. cddddr
878                nth                 rest                first .. tenth
879                aref                elt                 nthcdr
880                symbol-function     symbol-value        symbol-plist
881                get                 get*                getf
882                gethash             subseq
883
884           Note that for `nthcdr' and `getf', the list argument of the
885           function must itself be a valid PLACE form.  For example,
886           `(setf (nthcdr 0 foo) 7)' will set `foo' itself to 7.  Note
887           that `push' and `pop' on an `nthcdr' place can be used to
888           insert or delete at any position in a list.  The use of
889           `nthcdr' as a PLACE form is an extension to standard Common
890           Lisp.
891
892         * The following Emacs-specific functions are also `setf'-able.
893
894                buffer-file-name                  marker-position
895                buffer-modified-p                 match-data
896                buffer-name                       mouse-position
897                buffer-string                     overlay-end
898                buffer-substring                  overlay-get
899                current-buffer                    overlay-start
900                current-case-table                point
901                current-column                    point-marker
902                current-global-map                point-max
903                current-input-mode                point-min
904                current-local-map                 process-buffer
905                current-window-configuration      process-filter
906                default-file-modes                process-sentinel
907                default-value                     read-mouse-position
908                documentation-property            screen-height
909                extent-data                       screen-menubar
910                extent-end-position               screen-width
911                extent-start-position             selected-window
912                face-background                   selected-screen
913                face-background-pixmap            selected-frame
914                face-font                         standard-case-table
915                face-foreground                   syntax-table
916                face-underline-p                  window-buffer
917                file-modes                        window-dedicated-p
918                frame-height                      window-display-table
919                frame-parameters                  window-height
920                frame-visible-p                   window-hscroll
921                frame-width                       window-point
922                get-register                      window-start
923                getenv                            window-width
924                global-key-binding                x-get-cut-buffer
925                keymap-parent                     x-get-cutbuffer
926                local-key-binding                 x-get-secondary-selection
927                mark                              x-get-selection
928                mark-marker
929
930           Most of these have directly corresponding "set" functions,
931           like `use-local-map' for `current-local-map', or `goto-char'
932           for `point'.  A few, like `point-min', expand to longer
933           sequences of code when they are `setf''d (`(narrow-to-region
934           x (point-max))' in this case).
935
936         * A call of the form `(substring SUBPLACE N [M])', where
937           SUBPLACE is itself a legal generalized variable whose current
938           value is a string, and where the value stored is also a
939           string.  The new string is spliced into the specified part of
940           the destination string.  For example:
941
942                (setq a (list "hello" "world"))
943                     => ("hello" "world")
944                (cadr a)
945                     => "world"
946                (substring (cadr a) 2 4)
947                     => "rl"
948                (setf (substring (cadr a) 2 4) "o")
949                     => "o"
950                (cadr a)
951                     => "wood"
952                a
953                     => ("hello" "wood")
954
955           The generalized variable `buffer-substring', listed above,
956           also works in this way by replacing a portion of the current
957           buffer.
958
959         * A call of the form `(apply 'FUNC ...)' or `(apply (function
960           FUNC) ...)', where FUNC is a `setf'-able function whose store
961           function is "suitable" in the sense described in Steele's
962           book; since none of the standard Emacs place functions are
963           suitable in this sense, this feature is only interesting when
964           used with places you define yourself with
965           `define-setf-method' or the long form of `defsetf'.
966
967         * A macro call, in which case the macro is expanded and `setf'
968           is applied to the resulting form.
969
970         * Any form for which a `defsetf' or `define-setf-method' has
971           been made.
972
973      Using any forms other than these in the PLACE argument to `setf'
974      will signal an error.
975
976      The `setf' macro takes care to evaluate all subforms in the proper
977      left-to-right order; for example,
978
979           (setf (aref vec (incf i)) i)
980
981      looks like it will evaluate `(incf i)' exactly once, before the
982      following access to `i'; the `setf' expander will insert temporary
983      variables as necessary to ensure that it does in fact work this
984      way no matter what setf-method is defined for `aref'.  (In this
985      case, `aset' would be used and no such steps would be necessary
986      since `aset' takes its arguments in a convenient order.)
987
988      However, if the PLACE form is a macro which explicitly evaluates
989      its arguments in an unusual order, this unusual order will be
990      preserved.  Adapting an example from Steele, given
991
992           (defmacro wrong-order (x y) (list 'aref y x))
993
994      the form `(setf (wrong-order A B) 17)' will evaluate B first, then
995      A, just as in an actual call to `wrong-order'.
996
Note: See TracBrowser for help on using the browser.