This is gcl.info, produced by makeinfo version 6.7 from gcl.texi.

This is a Texinfo GNU Common Lisp Manual based on the draft ANSI
standard for Common Lisp.

   Copyright 1994 William F. Schelter

INFO-DIR-SECTION GNU Common Lisp
START-INFO-DIR-ENTRY
* gcl: (gcl.info). GNU Common Lisp Manual
END-INFO-DIR-ENTRY


File: gcl.info,  Node: VALUES Forms as Places,  Next: THE Forms as Places,  Prev: Function Call Forms as Places,  Up: Kinds of Places

5.1.2.3 VALUES Forms as Places
..............................

A values form can be used as a place, provided that each of its subforms
is also a place form.

   A form such as

   (setf (values place-1 \dots place-n) values-form)

   does the following:

1.
     The subforms of each nested place are evaluated in left-to-right
     order.
2.
     The values-form is evaluated, and the first store variable from
     each place is bound to its return values as if by
     multiple-value-bind.
3.
     If the setf expansion for any place involves more than one store
     variable, then the additional store variables are bound to nil.
4.
     The storing forms for each place are evaluated in left-to-right
     order.

   The storing form in the setf expansion of values returns as multiple
values_2 the values of the store variables in step 2.  That is, the
number of values returned is the same as the number of place forms.
This may be more or fewer values than are produced by the values-form.


File: gcl.info,  Node: THE Forms as Places,  Next: APPLY Forms as Places,  Prev: VALUES Forms as Places,  Up: Kinds of Places

5.1.2.4 THE Forms as Places
...........................

A the form can be used as a place, in which case the declaration is
transferred to the newvalue form, and the resulting setf is analyzed.
For example,

      (setf (the integer (cadr x)) (+ y 3))

   is processed as if it were

      (setf (cadr x) (the integer (+ y 3)))


File: gcl.info,  Node: APPLY Forms as Places,  Next: Setf Expansions and Places,  Prev: THE Forms as Places,  Up: Kinds of Places

5.1.2.5 APPLY Forms as Places
.............................

The following situations involving setf of apply must be supported:

*
     (setf (apply #'aref array {subscript}* more-subscripts)
     new-element)
*
     (setf (apply #'bit array {subscript}* more-subscripts) new-element)
*
     (setf (apply #'sbit array {subscript}* more-subscripts)
     new-element)

   In all three cases, the element of array designated by the
concatenation of subscripts and more-subscripts (i.e., the same element
which would be read by the call to apply if it were not part of a setf
form) is changed to have the value given by new-element.

   For these usages, the function name (aref, bit, or sbit) must refer
to the global function definition, rather than a locally defined
function.

   No other standardized function is required to be supported, but an
implementation may define such support.  An implementation may also
define support for implementation-defined operators.

   If a user-defined function is used in this context, the following
equivalence is true, except that care is taken to preserve proper
left-to-right evaluation of argument subforms:

      (setf (apply #'name {arg}*) val)
      == (apply #'(setf name) val {arg}*)


File: gcl.info,  Node: Setf Expansions and Places,  Next: Macro Forms as Places,  Prev: APPLY Forms as Places,  Up: Kinds of Places

5.1.2.6 Setf Expansions and Places
..................................

Any compound form for which the operator has a

   setf expander

   defined can be used as a place.

   The operator must refer to the global function definition, rather
than a locally defined function or macro.


File: gcl.info,  Node: Macro Forms as Places,  Next: Symbol Macros as Places,  Prev: Setf Expansions and Places,  Up: Kinds of Places

5.1.2.7 Macro Forms as Places
.............................

A macro form can be used as a place, in which case Common Lisp expands
the macro form

   as if by macroexpand-1

   and then uses the macro expansion in place of the original place.

   Such macro expansion is attempted only after exhausting all other
possibilities other than expanding into a call to a function named (setf
reader).


File: gcl.info,  Node: Symbol Macros as Places,  Next: Other Compound Forms as Places,  Prev: Macro Forms as Places,  Up: Kinds of Places

5.1.2.8 Symbol Macros as Places
...............................

A reference to a symbol that has been established as a symbol macro can
be used as a place.  In this case, setf expands the reference and then
analyzes the resulting form.


File: gcl.info,  Node: Other Compound Forms as Places,  Prev: Symbol Macros as Places,  Up: Kinds of Places

5.1.2.9 Other Compound Forms as Places
......................................

For any other compound form for which the operator is a symbol f, the
setf form expands into a call to the function named (setf f).  The first
argument in the newly constructed function form is newvalue and the
remaining arguments are the remaining elements of place.  This expansion
occurs regardless of whether f or (setf f) is defined as a function
locally, globally, or not at all.  For example,

   (setf (f arg1 arg2 ...) new-value)

   expands into a form with the same effect and value as

      (let ((#:temp-1 arg1)          ;force correct order of evaluation
            (#:temp-2 arg2)
            ...
            (#:temp-0 new-value))
        (funcall (function (setf f)) #:temp-0 #:temp-1 #:temp-2...))

   A function named (setf f) must return its first argument as its only
value in order to preserve the semantics of setf.


File: gcl.info,  Node: Treatment of Other Macros Based on SETF,  Prev: Kinds of Places,  Up: Generalized Reference

5.1.3 Treatment of Other Macros Based on SETF
---------------------------------------------

For each of the "read-modify-write" operators in Figure 5-9, and for any
additional macros defined by the programmer using define-modify-macro,
an exception is made to the normal rule of left-to-right evaluation of
arguments.  Evaluation of argument forms occurs in left-to-right order,
with the exception that for the place argument, the actual read of the
"old value" from that place happens after all of the argument form
evaluations, and just before a "new value" is computed and written back
into the place.

   Specifically, each of these operators can be viewed as involving a
form with the following general syntax:

      (operator {preceding-form}* place {following-form}*)

   The evaluation of each such form proceeds like this:

1.
     Evaluate each of the preceding-forms, in left-to-right order.
2.
     Evaluate the subforms of the place, in the order specified by the
     second value of the setf expansion for that place.
3.
     Evaluate each of the following-forms, in left-to-right order.
4.
     Read the old value from place.
5.
     Compute the new value.
6.
     Store the new value into place.

  decf  pop   pushnew  
  incf  push  remf     

  Figure 5-9: Read-Modify-Write Macros



File: gcl.info,  Node: Transfer of Control to an Exit Point,  Next: Data and Control Flow Dictionary,  Prev: Generalized Reference,  Up: Data and Control Flow

5.2 Transfer of Control to an Exit Point
========================================

When a transfer of control is initiated by go, return-from, or throw the
following events occur in order to accomplish the transfer of control.
Note that for go, the exit point is the form within the tagbody that is
being executed at the time the go is performed; for return-from, the
exit point is the corresponding block form; and for throw, the exit
point is the corresponding catch form.

1.
     Intervening exit points are "abandoned" (i.e., their extent ends
     and it is no longer valid to attempt to transfer control through
     them).

2.
     The cleanup clauses of any intervening unwind-protect clauses are
     evaluated.

3.
     Intervening dynamic bindings of special variables, catch tags,
     condition handlers, and restarts are undone.

4.
     The extent of the exit point being invoked ends, and control is
     passed to the target.

   The extent of an exit being "abandoned" because it is being passed
over ends as soon as the transfer of control is initiated.  That is,
event 1 occurs at the beginning of the initiation of the transfer of
control.  The consequences are undefined if an attempt is made to
transfer control to an exit point whose dynamic extent has ended.

   Events 2 and 3 are actually performed interleaved, in the order
corresponding to the reverse order in which they were established.  The
effect of this is that the cleanup clauses of an unwind-protect see the
same dynamic bindings of variables and catch tags as were visible when
the unwind-protect was entered.

   Event 4 occurs at the end of the transfer of control.


File: gcl.info,  Node: Data and Control Flow Dictionary,  Prev: Transfer of Control to an Exit Point,  Up: Data and Control Flow

5.3 Data and Control Flow Dictionary
====================================

* Menu:

* apply::
* defun::
* fdefinition::
* fboundp::
* fmakunbound::
* flet::
* funcall::
* function (Special Operator)::
* function-lambda-expression::
* functionp::
* compiled-function-p::
* call-arguments-limit::
* lambda-list-keywords::
* lambda-parameters-limit::
* defconstant::
* defparameter::
* destructuring-bind::
* let::
* progv::
* setq::
* psetq::
* block::
* catch::
* go::
* return-from::
* return::
* tagbody::
* throw::
* unwind-protect::
* nil::
* not::
* t::
* eq::
* eql::
* equal::
* equalp::
* identity::
* complement::
* constantly::
* every::
* and::
* cond::
* if::
* or::
* when::
* case::
* typecase::
* multiple-value-bind::
* multiple-value-call::
* multiple-value-list::
* multiple-value-prog1::
* multiple-value-setq::
* values::
* values-list::
* multiple-values-limit::
* nth-value::
* prog::
* prog1::
* progn::
* define-modify-macro::
* defsetf::
* define-setf-expander::
* get-setf-expansion::
* setf::
* shiftf::
* rotatef::
* control-error::
* program-error::
* undefined-function::


File: gcl.info,  Node: apply,  Next: defun,  Prev: Data and Control Flow Dictionary,  Up: Data and Control Flow Dictionary

5.3.1 apply [Function]
----------------------

'apply' function &rest args^+ => {result}*

Arguments and Values::
......................

function--a function designator.

   args--a spreadable argument list designator.

   results--the values returned by function.

Description::
.............

Applies the function to the args.

   When the function receives its arguments via &rest, it is permissible
(but not required) for the implementation to bind the rest parameter to
an object that shares structure with the last argument to apply.
Because a function can neither detect whether it was called via apply
nor whether (if so) the last argument to apply was a constant,
conforming programs must neither rely on the list structure of a rest
list to be freshly consed, nor modify that list structure.

   setf can be used with apply in certain circumstances; see *note APPLY
Forms as Places::.

Examples::
..........

      (setq f '+) =>  +
      (apply f '(1 2)) =>  3
      (setq f #'-) =>  #<FUNCTION ->
      (apply f '(1 2)) =>  -1
      (apply #'max 3 5 '(2 7 3)) =>  7
      (apply 'cons '((+ 2 3) 4)) =>  ((+ 2 3) . 4)
      (apply #'+ '()) =>  0

      (defparameter *some-list* '(a b c))
      (defun strange-test (&rest x) (eq x *some-list*))
      (apply #'strange-test *some-list*) =>  implementation-dependent

      (defun bad-boy (&rest x) (rplacd x 'y))
      (bad-boy 'a 'b 'c) has undefined consequences.
      (apply #'bad-boy *some-list*) has undefined consequences.

      (defun foo (size &rest keys &key double &allow-other-keys)
        (let ((v (apply #'make-array size :allow-other-keys t keys)))
          (if double (concatenate (type-of v) v v) v)))
      (foo 4 :initial-contents '(a b c d) :double t)
         =>  #(A B C D A B C D)

See Also::
..........

*note funcall:: , *note fdefinition:: , function, *note Evaluation::,
*note APPLY Forms as Places::


File: gcl.info,  Node: defun,  Next: fdefinition,  Prev: apply,  Up: Data and Control Flow Dictionary

5.3.2 defun [Macro]
-------------------

'defun' function-name lambda-list [[{declaration}* | documentation]]
{form}*
=> function-name

Arguments and Values::
......................

function-name--a function name.

   lambda-list--an ordinary lambda list.

   declaration--a declare expression; not evaluated.

   documentation--a string; not evaluated.

   forms--an implicit progn.

   block-name--the function block name of the function-name.

Description::
.............

Defines a new function named function-name in the global environment.
The body of the function defined by defun consists of forms; they are
executed as an implicit progn when the function is called.  defun can be
used to define a new function, to install a corrected version of an
incorrect definition, to redefine an already-defined function, or to
redefine a macro as a function.

   defun implicitly puts a block named block-name around the body forms

   (but not the forms in the lambda-list)

   of the function defined.

   Documentation is attached as a documentation string to name (as kind
function) and to the function object.

   Evaluating defun causes function-name to be a global name for the
function specified by the lambda expression

      (lambda lambda-list
        [[{declaration}* | documentation]]
        (block block-name {form}*))

   processed in the lexical environment in which defun was executed.

   (None of the arguments are evaluated at macro expansion time.)

   defun is not required to perform any compile-time side effects.  In
particular, defun does not make the function definition available at
compile time.  An implementation may choose to store information about
the function for the purposes of compile-time error-checking (such as
checking the number of arguments on calls), or to enable the function to
be expanded inline.

Examples::
..........

      (defun recur (x)
       (when (> x 0)
         (recur (1- x)))) =>  RECUR
      (defun ex (a b &optional c (d 66) &rest keys &key test (start 0))
         (list a b c d keys test start)) =>  EX
      (ex 1 2) =>  (1 2 NIL 66 NIL NIL 0)
      (ex 1 2 3 4 :test 'equal :start 50)
     =>  (1 2 3 4 (:TEST EQUAL :START 50) EQUAL 50)
      (ex :test 1 :start 2) =>  (:TEST 1 :START 2 NIL NIL 0)

      ;; This function assumes its callers have checked the types of the
      ;; arguments, and authorizes the compiler to build in that assumption.
      (defun discriminant (a b c)
        (declare (number a b c))
        "Compute the discriminant for a quadratic equation."
        (- (* b b) (* 4 a c))) =>  DISCRIMINANT
      (discriminant 1 2/3 -2) =>  76/9

      ;; This function assumes its callers have not checked the types of the
      ;; arguments, and performs explicit type checks before making any assumptions.
      (defun careful-discriminant (a b c)
        "Compute the discriminant for a quadratic equation."
        (check-type a number)
        (check-type b number)
        (check-type c number)
        (locally (declare (number a b c))
          (- (* b b) (* 4 a c)))) =>  CAREFUL-DISCRIMINANT
      (careful-discriminant 1 2/3 -2) =>  76/9

See Also::
..........

*note flet:: , labels, *note block:: , *note return-from:: , declare,
*note documentation:: , *note Evaluation::, *note Ordinary Lambda
Lists::, *note Syntactic Interaction of Documentation Strings and
Declarations::

Notes::
.......

return-from can be used to return prematurely from a function defined by
defun.

   Additional side effects might take place when additional information
(typically debugging information) about the function definition is
recorded.


File: gcl.info,  Node: fdefinition,  Next: fboundp,  Prev: defun,  Up: Data and Control Flow Dictionary

5.3.3 fdefinition [Accessor]
----------------------------

'fdefinition' function-name => definition

   (setf (' fdefinition' function-name) new-definition)

Arguments and Values::
......................

function-name--a function name.

   In the non-setf case, the name must be fbound in the global
environment.

   definition--Current global function definition named by
function-name.

   new-definition--a function.

Description::
.............

fdefinition accesses the current global function definition named by
function-name.  The definition may be a function or may be an object
representing a special form or macro.

   The value returned by fdefinition when fboundp returns true but the
function-name denotes a macro or special form is not well-defined, but
fdefinition does not signal an error.

Exceptional Situations::
........................

Should signal an error of type type-error if function-name is not a
function name.

   An error of type undefined-function is signaled in the non-setf case
if function-name is not fbound.

See Also::
..........

*note fboundp:: , *note fmakunbound:: , *note macro-function:: ,

   *note special-operator-p:: ,

   *note symbol-function::

Notes::
.......

fdefinition cannot access the value of a lexical function name produced
by flet or labels; it can access only the global function value.

   setf can be used with fdefinition to replace a global function
definition when the function-name's function definition does not
represent a special form.

   setf of fdefinition requires a function as the new value.  It is an
error to set the fdefinition of a function-name to a symbol, a list, or
the value returned by fdefinition on the name of a macro or special
form.


File: gcl.info,  Node: fboundp,  Next: fmakunbound,  Prev: fdefinition,  Up: Data and Control Flow Dictionary

5.3.4 fboundp [Function]
------------------------

'fboundp' name => generalized-boolean

Pronunciation::
...............

pronounced ,ef 'baund p\=e

Arguments and Values::
......................

name--a function name.

   generalized-boolean--a generalized boolean.

Description::
.............

Returns true if name is fbound; otherwise, returns false.

Examples::
..........

      (fboundp 'car) =>  true
      (fboundp 'nth-value) =>  false
      (fboundp 'with-open-file) =>  true
      (fboundp 'unwind-protect) =>  true
      (defun my-function (x) x) =>  MY-FUNCTION
      (fboundp 'my-function) =>  true
      (let ((saved-definition (symbol-function 'my-function)))
        (unwind-protect (progn (fmakunbound 'my-function)
                               (fboundp 'my-function))
          (setf (symbol-function 'my-function) saved-definition)))
     =>  false
      (fboundp 'my-function) =>  true
      (defmacro my-macro (x) `',x) =>  MY-MACRO
      (fboundp 'my-macro) =>  true
      (fmakunbound 'my-function) =>  MY-FUNCTION
      (fboundp 'my-function) =>  false
      (flet ((my-function (x) x))
        (fboundp 'my-function)) =>  false

Exceptional Situations::
........................

Should signal an error of type type-error if name is not a function
name.

See Also::
..........

*note symbol-function:: , *note fmakunbound:: , *note fdefinition::

Notes::
.......

It is permissible to call symbol-function on any symbol that is fbound.

   fboundp is sometimes used to "guard" an access to the function cell,
as in:
     (if (fboundp x) (symbol-function x))

   Defining a setf expander F does not cause the setf function (setf F)
to become defined.


File: gcl.info,  Node: fmakunbound,  Next: flet,  Prev: fboundp,  Up: Data and Control Flow Dictionary

5.3.5 fmakunbound [Function]
----------------------------

'fmakunbound' name => name

Pronunciation::
...............

pronounced ,ef 'mak e n,baund or pronounced ,ef 'm\=a k e n,baund

Arguments and Values::
......................

name--a function name.

Description::
.............

Removes the function or macro definition, if any, of name in the global
environment.

Examples::
..........

     (defun add-some (x) (+ x 19)) =>  ADD-SOME
      (fboundp 'add-some) =>  true
      (flet ((add-some (x) (+ x 37)))
         (fmakunbound 'add-some)
         (add-some 1)) =>  38
      (fboundp 'add-some) =>  false

Exceptional Situations::
........................

Should signal an error of type type-error if name is not a function
name.

   The consequences are undefined if name is a special operator.

See Also::
..........

*note fboundp:: , *note makunbound::


File: gcl.info,  Node: flet,  Next: funcall,  Prev: fmakunbound,  Up: Data and Control Flow Dictionary

5.3.6 flet, labels, macrolet [Special Operator]
-----------------------------------------------

'flet' ({(function-name lambda-list [[{local-declaration}* |
local-documentation]] {local-form}*)}*) {declaration}* {form}*
=> {result}*

   'labels' ({(function-name lambda-list [[{local-declaration}* |
local-documentation]] {local-form}*)}*) {declaration}* {form}*
=> {result}*

   'macrolet' ({(name lambda-list [[{local-declaration}* |
local-documentation]] {local-form}*)}*) {declaration}* {form}*
=> {result}*

Arguments and Values::
......................

function-name--a function name.

   name--a symbol.

   lambda-list--a lambda list; for flet and labels, it is an ordinary
lambda list; for macrolet, it is a macro lambda list.

   local-declaration--a declare expression; not evaluated.

   declaration--a declare expression; not evaluated.

   local-documentation--a string; not evaluated.

   local-forms, forms--an implicit progn.

   results--the values of the forms.

Description::
.............

flet, labels, and macrolet define local functions and macros, and
execute forms using the local definitions.  Forms are executed in order
of occurrence.

   The body forms (but not the lambda list)

   of each function created by flet and labels and each macro created by
macrolet are enclosed in an implicit block whose name is the function
block name of the function-name or name, as appropriate.

   The scope of the declarations between the list of local
function/macro definitions and the body forms in flet and labels does
not include the bodies of the locally defined functions, except that for
labels, any inline, notinline, or ftype declarations that refer to the
locally defined functions do apply to the local function bodies.  That
is, their scope is the same as the function name that they affect.

   The scope of these declarations does not include the bodies of the
macro expander functions defined by macrolet.

flet
     flet defines locally named functions and executes a series of forms
     with these definition bindings.  Any number of such local functions
     can be defined.

     The scope of the name binding encompasses only the body.  Within
     the body of flet, function-names matching those defined by flet
     refer to the locally defined functions rather than to the global
     function definitions of the same name.

     Also, within the scope of flet, global setf expander definitions of
     the function-name defined by flet do not apply.  Note that this
     applies to (defsetf f ...), not (defmethod (setf f) ...).

     The names of functions defined by flet are in the lexical
     environment; they retain their local definitions only within the
     body of flet.  The function definition bindings are visible only in
     the body of flet, not the definitions themselves.  Within the
     function definitions, local function names that match those being
     defined refer to functions or macros defined outside the flet.
     flet can locally shadow a global function name, and the new
     definition can refer to the global definition.

     Any local-documentation is attached to the corresponding local
     function (if one is actually created) as a documentation string.

labels
     labels is equivalent to flet except that the scope of the defined
     function names for labels encompasses the function definitions
     themselves as well as the body.

macrolet
     macrolet establishes local macro definitions, using the same format
     used by defmacro.

     Within the body of macrolet, global setf expander definitions of
     the names defined by the macrolet do not apply; rather, setf
     expands the macro form and recursively process the resulting form.

     The macro-expansion functions defined by macrolet are defined in
     the

     lexical environment in which the macrolet form appears.
     Declarations and macrolet and symbol-macrolet definitions affect
     the local macro definitions in a macrolet, but the consequences are
     undefined if the local macro definitions reference any local
     variable or function bindings that are visible in that lexical
     environment.

     Any local-documentation is attached to the corresponding local
     macro function as a documentation string.

Examples::
..........

      (defun foo (x flag)
        (macrolet ((fudge (z)
                      ;The parameters x and flag are not accessible
                      ; at this point; a reference to flag would be to
                      ; the global variable of that name.
                      ` (if flag (* ,z ,z) ,z)))
         ;The parameters x and flag are accessible here.
          (+ x
             (fudge x)
             (fudge (+ x 1)))))
      ==
      (defun foo (x flag)
        (+ x
           (if flag (* x x) x)
           (if flag (* (+ x 1) (+ x 1)) (+ x 1))))

   after macro expansion.  The occurrences of x and flag legitimately
refer to the parameters of the function foo because those parameters are
visible at the site of the macro call which produced the expansion.

      (flet ((flet1 (n) (+ n n)))
         (flet ((flet1 (n) (+ 2 (flet1 n))))
           (flet1 2))) =>  6

      (defun dummy-function () 'top-level) =>  DUMMY-FUNCTION
      (funcall #'dummy-function) =>  TOP-LEVEL
      (flet ((dummy-function () 'shadow))
           (funcall #'dummy-function)) =>  SHADOW
      (eq (funcall #'dummy-function) (funcall 'dummy-function))
     =>  true
      (flet ((dummy-function () 'shadow))
        (eq (funcall #'dummy-function)
            (funcall 'dummy-function)))
     =>  false

      (defun recursive-times (k n)
        (labels ((temp (n)
                   (if (zerop n) 0 (+ k (temp (1- n))))))
          (temp n))) =>  RECURSIVE-TIMES
      (recursive-times 2 3) =>  6

      (defmacro mlets (x &environment env)
         (let ((form `(babbit ,x)))
           (macroexpand form env))) =>  MLETS
      (macrolet ((babbit (z) `(+ ,z ,z))) (mlets 5)) =>  10

      (flet ((safesqrt (x) (sqrt (abs x))))
       ;; The safesqrt function is used in two places.
        (safesqrt (apply #'+ (map 'list #'safesqrt '(1 2 3 4 5 6)))))
     =>  3.291173

      (defun integer-power (n k)
        (declare (integer n))
        (declare (type (integer 0 *) k))
        (labels ((expt0 (x k a)
                   (declare (integer x a) (type (integer 0 *) k))
                   (cond ((zerop k) a)
                         ((evenp k) (expt1 (* x x) (floor k 2) a))
                         (t (expt0 (* x x) (floor k 2) (* x a)))))
                 (expt1 (x k a)
                   (declare (integer x a) (type (integer 0 *) k))
                   (cond ((evenp k) (expt1 (* x x) (floor k 2) a))
                         (t (expt0 (* x x) (floor k 2) (* x a))))))
         (expt0 n k 1))) =>  INTEGER-POWER

      (defun example (y l)
        (flet ((attach (x)
                 (setq l (append l (list x)))))
          (declare (inline attach))
          (dolist (x y)
            (unless (null (cdr x))
              (attach x)))
          l))

      (example '((a apple apricot) (b banana) (c cherry) (d) (e))
               '((1) (2) (3) (4 2) (5) (6 3 2)))
     =>  ((1) (2) (3) (4 2) (5) (6 3 2) (A APPLE APRICOT) (B BANANA) (C CHERRY))

See Also::
..........

declare, *note defmacro:: , *note defun:: , *note documentation:: ,
*note let:: , *note Evaluation::, *note Syntactic Interaction of
Documentation Strings and Declarations::

Notes::
.......

It is not possible to define recursive functions with flet.  labels can
be used to define mutually recursive functions.

   If a macrolet form is a top level form, the body forms are also
processed as top level forms.  See *note File Compilation::.


File: gcl.info,  Node: funcall,  Next: function (Special Operator),  Prev: flet,  Up: Data and Control Flow Dictionary

5.3.7 funcall [Function]
------------------------

'funcall' function &rest args => {result}*

Arguments and Values::
......................

function--a function designator.

   args--arguments to the function.

   results--the values returned by the function.

Description::
.............

funcall applies function to args.

   If function is a symbol, it is coerced to a function as if by finding
its functional value in the global environment.

Examples::
..........

      (funcall #'+ 1 2 3) =>  6
      (funcall 'car '(1 2 3)) =>  1
      (funcall 'position 1 '(1 2 3 2 1) :start 1) =>  4
      (cons 1 2) =>  (1 . 2)
      (flet ((cons (x y) `(kons ,x ,y)))
        (let ((cons (symbol-function '+)))
          (funcall #'cons
                   (funcall 'cons 1 2)
                   (funcall cons 1 2))))
     =>  (KONS (1 . 2) 3)

Exceptional Situations::
........................

An error of type undefined-function should be signaled if function is a
symbol that does not have a global definition as a function or that has
a global definition as a macro or a special operator.

See Also::
..........

*note apply:: , function, *note Evaluation::

Notes::
.......

      (funcall function arg1 arg2 ...)
      == (apply function arg1 arg2 ... nil)
      == (apply function (list arg1 arg2 ...))

   The difference between funcall and an ordinary function call is that
in the former case the function is obtained by ordinary evaluation of a
form, and in the latter case it is obtained by the special
interpretation of the function position that normally occurs.


File: gcl.info,  Node: function (Special Operator),  Next: function-lambda-expression,  Prev: funcall,  Up: Data and Control Flow Dictionary

5.3.8 function [Special Operator]
---------------------------------

'function' name => function

Arguments and Values::
......................

name--a function name or lambda expression.

   function--a function object.

Description::
.............

The value of function is the functional value of name in the current
lexical environment.

   If name is a function name, the functional definition of that name is
that established by the innermost lexically enclosing flet, labels, or
macrolet form, if there is one.  Otherwise the global functional
definition of the function name is returned.

   If name is a lambda expression, then a lexical closure is returned.
In situations where a closure over the same set of bindings might be
produced more than once, the various resulting closures might or might
not be eq.

   It is an error to use function on a function name that does not
denote a function in the lexical environment in which the function form
appears.  Specifically, it is an error to use function on a symbol that
denotes a macro or special form.  An implementation may choose not to
signal this error for performance reasons, but implementations are
forbidden from defining the failure to signal an error as a useful
behavior.

Examples::
..........

      (defun adder (x) (function (lambda (y) (+ x y))))

   The result of (adder 3) is a function that adds 3 to its argument:

      (setq add3 (adder 3))
      (funcall add3 5) =>  8

   This works because function creates a closure of the lambda
expression that is able to refer to the value 3 of the variable x even
after control has returned from the function adder.

See Also::
..........

*note defun:: , *note fdefinition:: , *note flet:: , labels, *note
symbol-function:: , *note Symbols as Forms::, *note Sharpsign
Single-Quote::, *note Printing Other Objects::

Notes::
.......

The notation #'name may be used as an abbreviation for (function name).


File: gcl.info,  Node: function-lambda-expression,  Next: functionp,  Prev: function (Special Operator),  Up: Data and Control Flow Dictionary

5.3.9 function-lambda-expression [Function]
-------------------------------------------

'function-lambda-expression' function
=> lambda-expression, closure-p, name

Arguments and Values::
......................

function--a function.

   lambda-expression--a lambda expression or nil.

   closure-p--a generalized boolean.

   name--an object.

Description::
.............

Returns information about function as follows:

   The primary value, lambda-expression, is function's defining lambda
expression, or nil if the information is not available.  The lambda
expression may have been pre-processed in some ways, but it should
remain a suitable argument to compile or function.  Any implementation
may legitimately return nil as the lambda-expression of any function.

   The secondary value, closure-p, is nil if function's definition was
enclosed in the null lexical environment or something non-nil if
function's definition might have been enclosed in some non-null lexical
environment.  Any implementation may legitimately return true as the
closure-p of any function.

   The tertiary value, name, is the "name" of function.  The name is
intended for debugging only and is not necessarily one that would be
valid for use as a name in defun or function, for example.  By
convention, nil is used to mean that function has no name.  Any
implementation may legitimately return nil as the name of any function.

Examples::
..........

The following examples illustrate some possible return values, but are
not intended to be exhaustive:

      (function-lambda-expression #'(lambda (x) x))
     =>  NIL, false, NIL
     OR=> NIL, true, NIL
     OR=> (LAMBDA (X) X), true, NIL
     OR=> (LAMBDA (X) X), false, NIL

      (function-lambda-expression
         (funcall #'(lambda () #'(lambda (x) x))))
     =>  NIL, false, NIL
     OR=> NIL, true, NIL
     OR=> (LAMBDA (X) X), true, NIL
     OR=> (LAMBDA (X) X), false, NIL

      (function-lambda-expression
         (funcall #'(lambda (x) #'(lambda () x)) nil))
     =>  NIL, true, NIL
     OR=> (LAMBDA () X), true, NIL
     NOT=> NIL, false, NIL
     NOT=> (LAMBDA () X), false, NIL

      (flet ((foo (x) x))
        (setf (symbol-function 'bar) #'foo)
        (function-lambda-expression #'bar))
     =>  NIL, false, NIL
     OR=> NIL, true, NIL
     OR=> (LAMBDA (X) (BLOCK FOO X)), true, NIL
     OR=> (LAMBDA (X) (BLOCK FOO X)), false, FOO
     OR=> (SI::BLOCK-LAMBDA FOO (X) X), false, FOO

      (defun foo ()
        (flet ((bar (x) x))
          #'bar))
      (function-lambda-expression (foo))
     =>  NIL, false, NIL
     OR=> NIL, true, NIL
     OR=> (LAMBDA (X) (BLOCK BAR X)), true, NIL
     OR=> (LAMBDA (X) (BLOCK BAR X)), true, (:INTERNAL FOO 0 BAR)
     OR=> (LAMBDA (X) (BLOCK BAR X)), false, "BAR in FOO"

Notes::
.......

Although implementations are free to return "nil, true, nil" in all
cases, they are encouraged to return a lambda expression as the primary
value in the case where the argument was created by a call to compile or
eval (as opposed to being created by loading a compiled file).


File: gcl.info,  Node: functionp,  Next: compiled-function-p,  Prev: function-lambda-expression,  Up: Data and Control Flow Dictionary

5.3.10 functionp [Function]
---------------------------

'functionp' object => generalized-boolean

Arguments and Values::
......................

object--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

Returns true if object is of type function; otherwise, returns false.

Examples::
..........

      (functionp 'append) =>  false
      (functionp #'append) =>  true
      (functionp (symbol-function 'append)) =>  true
      (flet ((f () 1)) (functionp #'f)) =>  true
      (functionp (compile nil '(lambda () 259))) =>  true
      (functionp nil) =>  false
      (functionp 12) =>  false
      (functionp '(lambda (x) (* x x))) =>  false
      (functionp #'(lambda (x) (* x x))) =>  true

Notes::
.......

      (functionp object) == (typep object 'function)


File: gcl.info,  Node: compiled-function-p,  Next: call-arguments-limit,  Prev: functionp,  Up: Data and Control Flow Dictionary

5.3.11 compiled-function-p [Function]
-------------------------------------

'compiled-function-p' object => generalized-boolean

Arguments and Values::
......................

object--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

Returns true if object is of type compiled-function; otherwise, returns
false.

Examples::
..........

      (defun f (x) x) =>  F
      (compiled-function-p #'f)
     =>  false
     OR=> true
      (compiled-function-p 'f) =>  false
      (compile 'f) =>  F
      (compiled-function-p #'f) =>  true
      (compiled-function-p 'f) =>  false
      (compiled-function-p (compile nil '(lambda (x) x)))
     =>  true
      (compiled-function-p #'(lambda (x) x))
     =>  false
     OR=> true
      (compiled-function-p '(lambda (x) x)) =>  false

See Also::
..........

*note compile:: , *note compile-file:: , *note compiled-function::

Notes::
.......

      (compiled-function-p object) == (typep object 'compiled-function)


File: gcl.info,  Node: call-arguments-limit,  Next: lambda-list-keywords,  Prev: compiled-function-p,  Up: Data and Control Flow Dictionary

5.3.12 call-arguments-limit [Constant Variable]
-----------------------------------------------

Constant Value::
................

An integer not smaller than 50 and at least as great as the value of
lambda-parameters-limit, the exact magnitude of which is
implementation-dependent.

Description::
.............

The upper exclusive bound on the number of arguments that may be passed
to a function.

See Also::
..........

*note lambda-parameters-limit:: , *note multiple-values-limit::


File: gcl.info,  Node: lambda-list-keywords,  Next: lambda-parameters-limit,  Prev: call-arguments-limit,  Up: Data and Control Flow Dictionary

5.3.13 lambda-list-keywords [Constant Variable]
-----------------------------------------------

Constant Value::
................

a list, the elements of which are implementation-dependent, but which
must contain at least the symbols &allow-other-keys, &aux, &body,
&environment, &key, &optional, &rest, and &whole.

Description::
.............

A list of all the lambda list keywords used in the implementation,
including the additional ones used only by macro definition forms.

See Also::
..........

*note defun:: , *note flet:: , *note defmacro:: , macrolet, *note The
Evaluation Model::


File: gcl.info,  Node: lambda-parameters-limit,  Next: defconstant,  Prev: lambda-list-keywords,  Up: Data and Control Flow Dictionary

5.3.14 lambda-parameters-limit [Constant Variable]
--------------------------------------------------

Constant Value::
................

implementation-dependent, but not smaller than 50.

Description::
.............

A positive integer that is the upper exclusive bound on the number of
parameter names that can appear in a single lambda list.

See Also::
..........

*note call-arguments-limit::

Notes::
.......

Implementors are encouraged to make the value of lambda-parameters-limit
as large as possible.


File: gcl.info,  Node: defconstant,  Next: defparameter,  Prev: lambda-parameters-limit,  Up: Data and Control Flow Dictionary

5.3.15 defconstant [Macro]
--------------------------

'defconstant' name initial-value [documentation] => name

Arguments and Values::
......................

name--a symbol; not evaluated.

   initial-value--a form; evaluated.

   documentation--a string; not evaluated.

Description::
.............

defconstant causes the global variable named by name to be given a value
that is the result of evaluating initial-value.

   A constant defined by defconstant can be redefined with defconstant.
However, the consequences are undefined if an attempt is made to assign
a value to the symbol using another operator, or to assign it to a
different value using a subsequent defconstant.

   If documentation is supplied, it is attached to name as a
documentation string of kind variable.

   defconstant normally appears as a top level form, but it is
meaningful for it to appear as a non-top-level form.  However, the
compile-time side effects described below only take place when
defconstant appears as a top level form.

   The consequences are undefined if there are any bindings of the
variable named by name at the time defconstant is executed or if the
value is not eql to the value of initial-value.

   The consequences are undefined when constant symbols are rebound as
either lexical or dynamic variables.  In other words, a reference to a
symbol declared with defconstant always refers to its global value.

   The side effects of the execution of defconstant must be equivalent
to at least the side effects of the execution of the following code:

      (setf (symbol-value 'name) initial-value)
      (setf (documentation 'name 'variable) 'documentation)

   If a defconstant form appears as a top level form, the compiler must
recognize that name names a constant variable.  An implementation may
choose to evaluate the value-form at compile time, load time, or both.
Therefore, users must ensure that the initial-value can be evaluated at
compile time (regardless of whether or not references to name appear in
the file) and that it always evaluates to the same value.

   [Editorial Note by KMP: Does "same value" here mean eql or similar?]

   [Reviewer Note by Moon: Probably depends on whether load time is
compared to compile time, or two compiles.]

Examples::
..........

      (defconstant this-is-a-constant 'never-changing "for a test") =>  THIS-IS-A-CONSTANT
     this-is-a-constant =>  NEVER-CHANGING
      (documentation 'this-is-a-constant 'variable) =>  "for a test"
      (constantp 'this-is-a-constant) =>  true

See Also::
..........

*note declaim:: , *note defparameter:: , defvar, *note documentation:: ,
*note proclaim:: , *note Constant Variables::, *note Compilation::


File: gcl.info,  Node: defparameter,  Next: destructuring-bind,  Prev: defconstant,  Up: Data and Control Flow Dictionary

5.3.16 defparameter, defvar [Macro]
-----------------------------------

'defparameter' name initial-value [documentation] => name

   'defvar' name [initial-value [documentation]] => name

Arguments and Values::
......................

name--a symbol; not evaluated.

   initial-value--a form; for defparameter, it is always evaluated, but
for defvar it is evaluated only if name is not already bound.

   documentation--a string; not evaluated.

Description::
.............

defparameter and defvar establish name as a dynamic variable.

   defparameter unconditionally assigns the initial-value to the dynamic
variable named name.  defvar, by contrast, assigns initial-value (if
supplied) to the dynamic variable named name only if name is not already
bound.

   If no initial-value is supplied, defvar leaves the value cell of the
dynamic variable named name undisturbed; if name was previously bound,
its old value persists, and if it was previously unbound, it remains
unbound.

   If documentation is supplied, it is attached to name as a
documentation string of kind variable.

   defparameter and defvar normally appear as a top level form, but it
is meaningful for them to appear as non-top-level forms.  However, the
compile-time side effects described below only take place when they
appear as top level forms.

Examples::
..........

      (defparameter *p* 1) =>  *P*
      *p* =>  1
      (constantp '*p*) =>  false
      (setq *p* 2) =>  2
      (defparameter *p* 3) =>  *P*
      *p* =>  3

      (defvar *v* 1) =>  *V*
      *v* =>  1
      (constantp '*v*) =>  false
      (setq *v* 2) =>  2
      (defvar *v* 3) =>  *V*
      *v* =>  2

      (defun foo ()
        (let ((*p* 'p) (*v* 'v))
          (bar))) =>  FOO
      (defun bar () (list *p* *v*)) =>  BAR
      (foo) =>  (P V)

   The principal operational distinction between defparameter and defvar
is that defparameter makes an unconditional assignment to name, while
defvar makes a conditional one.  In practice, this means that
defparameter is useful in situations where loading or reloading the
definition would want to pick up a new value of the variable, while
defvar is used in situations where the old value would want to be
retained if the file were loaded or reloaded.  For example, one might
create a file which contained:

      (defvar *the-interesting-numbers* '())
      (defmacro define-interesting-number (name n)
        `(progn (defvar ,name ,n)
                (pushnew ,name *the-interesting-numbers*)
                ',name))
      (define-interesting-number *my-height* 168) ;cm
      (define-interesting-number *my-weight* 13)  ;stones

   Here the initial value, (), for the variable
*the-interesting-numbers* is just a seed that we are never likely to
want to reset to something else once something has been grown from it.
As such, we have used defvar to avoid having the *interesting-numbers*
information reset if the file is loaded a second time.  It is true that
the two calls to define-interesting-number here would be reprocessed,
but if there were additional calls in another file, they would not be
and that information would be lost.  On the other hand, consider the
following code:

      (defparameter *default-beep-count* 3)
      (defun beep (&optional (n *default-beep-count*))
        (dotimes (i n) (si:

   Here we could easily imagine editing the code to change the initial
value of *default-beep-count*, and then reloading the file to pick up
the new value.  In order to make value updating easy, we have used
defparameter.

   On the other hand, there is potential value to using defvar in this
situation.  For example, suppose that someone had predefined an
alternate value for *default-beep-count*, or had loaded the file and
then manually changed the value.  In both cases, if we had used defvar
instead of defparameter, those user preferences would not be overridden
by (re)loading the file.

   The choice of whether to use defparameter or defvar has visible
consequences to programs, but is nevertheless often made for subjective
reasons.

Side Effects::
..............

If a defvar or defparameter form appears as a top level form, the
compiler must recognize that the name has been proclaimed special.
However, it must neither evaluate the initial-value form nor assign the
dynamic variable named name at compile time.

   There may be additional (implementation-defined) compile-time or
run-time side effects, as long as such effects do not interfere with the
correct operation of conforming programs.

Affected By::
.............

defvar is affected by whether name is already bound.

See Also::
..........

*note declaim:: , *note defconstant:: , *note documentation:: , *note
Compilation::

Notes::
.......

It is customary to name dynamic variables with an asterisk at the
beginning and end of the name.  e.g., *foo* is a good name for a dynamic
variable, but not for a lexical variable; foo is a good name for a
lexical variable, but not for a dynamic variable.  This naming
convention is observed for all defined names in Common Lisp; however,
neither conforming programs nor conforming implementations are obliged
to adhere to this convention.

   The intent of the permission for additional side effects is to allow
implementations to do normal "bookkeeping" that accompanies definitions.
For example, the macro expansion of a defvar or defparameter form might
include code that arranges to record the name of the source file in
which the definition occurs.

   defparameter and defvar might be defined as follows:

      (defmacro defparameter (name initial-value
                              &optional (documentation nil documentation-p))
        `(progn (declaim (special ,name))
                (setf (symbol-value ',name) ,initial-value)
                ,(when documentation-p
                   `(setf (documentation ',name 'variable) ',documentation))
                ',name))
      (defmacro defvar (name &optional
                             (initial-value nil initial-value-p)
                             (documentation nil documentation-p))
        `(progn (declaim (special ,name))
                ,(when initial-value-p
                   `(unless (boundp ',name)
                      (setf (symbol-value ',name) ,initial-value)))
                ,(when documentation-p
                   `(setf (documentation ',name 'variable) ',documentation))
                ',name))


File: gcl.info,  Node: destructuring-bind,  Next: let,  Prev: defparameter,  Up: Data and Control Flow Dictionary

5.3.17 destructuring-bind [Macro]
---------------------------------

'destructuring-bind' lambda-list expression {declaration}* {form}*
=> {result}*

Arguments and Values::
......................

lambda-list--a destructuring lambda list.

   expression--a form.

   declaration--a declare expression; not evaluated.

   forms--an implicit progn.

   results--the values returned by the forms.

Description::
.............

destructuring-bind binds the variables specified in lambda-list to the
corresponding values in the tree structure resulting from the evaluation
of expression; then destructuring-bind evaluates forms.

   The lambda-list supports destructuring as described in *note
Destructuring Lambda Lists::.

Examples::
..........

      (defun iota (n) (loop for i from 1 to n collect i))       ;helper
      (destructuring-bind ((a &optional (b 'bee)) one two three)
          `((alpha) ,@(iota 3))
        (list a b three two one)) =>  (ALPHA BEE 3 2 1)

Exceptional Situations::
........................

If the result of evaluating the expression does not match the
destructuring pattern, an error of type error should be signaled.

See Also::
..........

macrolet, *note defmacro::


File: gcl.info,  Node: let,  Next: progv,  Prev: destructuring-bind,  Up: Data and Control Flow Dictionary

5.3.18 let, let* [Special Operator]
-----------------------------------

'let' ({var | (var [init-form])}*) {declaration}* {form}* => {result}*

   'let*' ({var | (var [init-form])}*) {declaration}* {form}* =>
{result}*

Arguments and Values::
......................

var--a symbol.

   init-form--a form.

   declaration--a declare expression; not evaluated.

   form--a form.

   results--the values returned by the forms.

Description::
.............

let and let* create new variable bindings and execute a series of forms
that use these bindings.  let performs the bindings in parallel and let*
does them sequentially.

   The form

      (let ((var1 init-form-1)
            (var2 init-form-2)
            ...
            (varm init-form-m))
        declaration1
        declaration2
        ...
        declarationp
        form1
        form2
        ...
        formn)

   first evaluates the expressions init-form-1, init-form-2, and so on,

   in that order, saving the resulting values.  Then all of the
variables varj are bound to the corresponding values; each binding is
lexical unless there is a special declaration to the contrary.  The
expressions formk are then evaluated in order; the values of all but the
last are discarded (that is, the body of a let is an implicit progn).

   let* is similar to let, but the bindings of variables are performed
sequentially rather than in parallel.  The expression for the init-form
of a var can refer to vars previously bound in the let*.

   The form

      (let* ((var1 init-form-1)
             (var2 init-form-2)
             ...
             (varm init-form-m))
        declaration1
        declaration2
        ...
        declarationp
        form1
        form2
        ...
        formn)

   first evaluates the expression init-form-1, then binds the variable
var1 to that value; then it evaluates init-form-2 and binds

   var2, and so on.  The expressions formj are then evaluated in order;
the values of all but the last are discarded (that is, the body of let*
is an implicit progn).

   For both let and let*, if there is not an init-form associated with a
var, var is initialized to nil.

   The special form let has the property that the scope of the name
binding does not include any initial value form.  For let*, a variable's
scope also includes the remaining initial value forms for subsequent
variable bindings.

Examples::
..........

      (setq a 'top) =>  TOP
      (defun dummy-function () a) =>  DUMMY-FUNCTION
      (let ((a 'inside) (b a))
         (format nil "~S ~S ~S" a b (dummy-function))) =>  "INSIDE TOP TOP"
      (let* ((a 'inside) (b a))
         (format nil "~S ~S ~S" a b (dummy-function))) =>  "INSIDE INSIDE TOP"
      (let ((a 'inside) (b a))
         (declare (special a))
         (format nil "~S ~S ~S" a b (dummy-function))) =>  "INSIDE TOP INSIDE"

   The code

      (let (x)
        (declare (integer x))
        (setq x (gcd y z))
        ...)

   is incorrect; although x is indeed set before it is used, and is set
to a value of the declared type integer, nevertheless x initially takes
on the value nil in violation of the type declaration.

See Also::
..........

*note progv::


File: gcl.info,  Node: progv,  Next: setq,  Prev: let,  Up: Data and Control Flow Dictionary

5.3.19 progv [Special Operator]
-------------------------------

'progv' symbols values {form}* => {result}*

Arguments and Values::
......................

symbols--a list of symbols; evaluated.

   values--a list of objects; evaluated.

   forms--an implicit progn.

   results--the values returned by the forms.

Description::
.............

progv creates new dynamic variable bindings and executes each form using
those bindings.  Each form is evaluated in order.

   progv allows binding one or more dynamic variables whose names may be
determined at run time.  Each form is evaluated in order with the
dynamic variables whose names are in symbols bound to corresponding
values.  If too few values are supplied, the remaining symbols are bound
and then made to have no value.  If too many values are supplied, the
excess values are ignored.  The bindings of the dynamic variables are
undone on exit from progv.

Examples::
..........

      (setq *x* 1) =>  1
      (progv '(*x*) '(2) *x*) =>  2
      *x* =>  1

     Assuming *x* is not globally special,

      (let ((*x* 3))
         (progv '(*x*) '(4)
           (list *x* (symbol-value '*x*)))) =>  (3 4)

See Also::
..........

*note let:: , *note Evaluation::

Notes::
.......

Among other things, progv is useful when writing interpreters for
languages embedded in Lisp; it provides a handle on the mechanism for
binding dynamic variables.


File: gcl.info,  Node: setq,  Next: psetq,  Prev: progv,  Up: Data and Control Flow Dictionary

5.3.20 setq [Special Form]
--------------------------

'setq' {!pair}* => result

   pair ::=var form

Pronunciation::
...............

pronounced 'set ,ky\"u

Arguments and Values::
......................

var--a symbol naming a variable other than a constant variable.

   form--a form.

   result--the primary value of the last form, or nil if no pairs were
supplied.

Description::
.............

Assigns values to variables.

   (setq var1 form1 var2 form2 ...) is the simple variable assignment
statement of Lisp.  First form1 is evaluated and the result is stored in
the variable var1, then form2 is evaluated and the result stored in
var2, and so forth.  setq may be used for assignment of both lexical and
dynamic variables.

   If any var refers to a binding made by symbol-macrolet, then that var
is treated as if setf (not setq) had been used.

Examples::
..........

      ;; A simple use of SETQ to establish values for variables.
      (setq a 1 b 2 c 3) =>  3
      a =>  1
      b =>  2
      c =>  3

      ;; Use of SETQ to update values by sequential assignment.
      (setq a (1+ b) b (1+ a) c (+ a b)) =>  7
      a =>  3
      b =>  4
      c =>  7

      ;; This illustrates the use of SETQ on a symbol macro.
      (let ((x (list 10 20 30)))
        (symbol-macrolet ((y (car x)) (z (cadr x)))
          (setq y (1+ z) z (1+ y))
          (list x y z)))
     =>  ((21 22 30) 21 22)

Side Effects::
..............

The primary value of each form is assigned to the corresponding var.

See Also::
..........

*note psetq:: , *note set:: , *note setf::


File: gcl.info,  Node: psetq,  Next: block,  Prev: setq,  Up: Data and Control Flow Dictionary

5.3.21 psetq [Macro]
--------------------

'psetq' {!pair}* => nil

   pair ::=var form

Pronunciation::
...............

psetq: pronounced

Arguments and Values::
......................

var--a symbol naming a variable other than a constant variable.

   form--a form.

Description::
.............

Assigns values to variables.

   This is just like setq, except that the assignments happen "in
parallel."  That is, first all of the forms are evaluated, and only then
are the variables set to the resulting values.  In this way, the
assignment to one variable does not affect the value computation of
another in the way that would occur with setq's sequential assignment.

   If any var refers to a binding made by symbol-macrolet, then that var
is treated as if psetf (not psetq) had been used.

Examples::
..........

      ;; A simple use of PSETQ to establish values for variables.
      ;; As a matter of style, many programmers would prefer SETQ
      ;; in a simple situation like this where parallel assignment
      ;; is not needed, but the two have equivalent effect.
      (psetq a 1 b 2 c 3) =>  NIL
      a =>  1
      b =>  2
      c =>  3

      ;; Use of PSETQ to update values by parallel assignment.
      ;; The effect here is very different than if SETQ had been used.
      (psetq a (1+ b) b (1+ a) c (+ a b)) =>  NIL
      a =>  3
      b =>  2
      c =>  3

      ;; Use of PSETQ on a symbol macro.
      (let ((x (list 10 20 30)))
        (symbol-macrolet ((y (car x)) (z (cadr x)))
          (psetq y (1+ z) z (1+ y))
          (list x y z)))
     =>  ((21 11 30) 21 11)

      ;; Use of parallel assignment to swap values of A and B.
      (let ((a 1) (b 2))
        (psetq a b  b a)
        (values a b))
     =>  2, 1

Side Effects::
..............

The values of forms are assigned to vars.

See Also::
..........

psetf, *note setq::


File: gcl.info,  Node: block,  Next: catch,  Prev: psetq,  Up: Data and Control Flow Dictionary

5.3.22 block [Special Operator]
-------------------------------

'block' name form* => {result}*

Arguments and Values::
......................

name--a symbol.

   form--a form.

   results--the values of the forms if a normal return occurs, or else,
if an explicit return occurs, the values that were transferred.

Description::
.............

block establishes a block named name and then evaluates forms as an
implicit progn.

   The special operators block and return-from work together to provide
a structured, lexical, non-local exit facility.  At any point lexically
contained within forms, return-from can be used with the given name to
return control and values from the block form, except when an
intervening block with the same name has been established, in which case
the outer block is shadowed by the inner one.

   The block named name has lexical scope and dynamic extent.

   Once established, a block may only be exited once, whether by normal
return or explicit return.

Examples::
..........

      (block empty) =>  NIL
      (block whocares (values 1 2) (values 3 4)) =>  3, 4
      (let ((x 1))
        (block stop (setq x 2) (return-from stop) (setq x 3))
        x) =>  2
      (block early (return-from early (values 1 2)) (values 3 4)) =>  1, 2
      (block outer (block inner (return-from outer 1)) 2) =>  1
      (block twin (block twin (return-from twin 1)) 2) =>  2
      ;; Contrast behavior of this example with corresponding example of CATCH.
      (block b
        (flet ((b1 () (return-from b 1)))
          (block b (b1) (print 'unreachable))
          2)) =>  1

See Also::
..........

*note return:: , *note return-from:: , *note Evaluation::

Notes::
.......


File: gcl.info,  Node: catch,  Next: go,  Prev: block,  Up: Data and Control Flow Dictionary

5.3.23 catch [Special Operator]
-------------------------------

'catch' tag {form}* => {result}*

Arguments and Values::
......................

tag--a catch tag; evaluated.

   forms--an implicit progn.

   results--if the forms exit normally, the values returned by the
forms; if a throw occurs to the tag, the values that are thrown.

Description::
.............

catch is used as the destination of a non-local control transfer by
throw.  Tags are used to find the catch to which a throw is transferring
control.  (catch 'foo form) catches a (throw 'foo form) but not a (throw
'bar form).

   The order of execution of catch follows:

1.
     Tag is evaluated.  It serves as the name of the catch.

2.
     Forms are then evaluated as an implicit progn, and the results of
     the last form are returned unless a throw occurs.

3.
     If a throw occurs during the execution of one of the forms, control
     is transferred to the catch form whose tag is eq to the tag
     argument of the throw and which is the most recently established
     catch with that tag.  No further evaluation of forms occurs.

4.
     The tag established by catch is disestablished just before the
     results are returned.

   If during the execution of one of the forms, a throw is executed
whose tag is eq to the catch tag, then the values specified by the throw
are returned as the result of the dynamically most recently established
catch form with that tag.

   The mechanism for catch and throw works even if throw is not within
the lexical scope of catch.  throw must occur within the dynamic extent
of the evaluation of the body of a catch with a corresponding tag.

Examples::
..........

      (catch 'dummy-tag 1 2 (throw 'dummy-tag 3) 4) =>  3
      (catch 'dummy-tag 1 2 3 4) =>  4
      (defun throw-back (tag) (throw tag t)) =>  THROW-BACK
      (catch 'dummy-tag (throw-back 'dummy-tag) 2) =>  T

      ;; Contrast behavior of this example with corresponding example of BLOCK.
      (catch 'c
        (flet ((c1 () (throw 'c 1)))
          (catch 'c (c1) (print 'unreachable))
          2)) =>  2

Exceptional Situations::
........................

An error of type control-error is signaled if throw is done when there
is no suitable catch tag.

See Also::
..........

*note throw:: , *note Evaluation::

Notes::
.......

It is customary for symbols to be used as tags, but any object is
permitted.  However, numbers should not be used because the comparison
is done using eq.

   catch differs from block in that catch tags have dynamic scope while
block names have lexical scope.


File: gcl.info,  Node: go,  Next: return-from,  Prev: catch,  Up: Data and Control Flow Dictionary

5.3.24 go [Special Operator]
----------------------------

'go' tag => #<NoValue>

Arguments and Values::
......................

tag--a go tag.

Description::
.............

go transfers control to the point in the body of an enclosing tagbody
form labeled by a tag eql to tag.  If there is no such tag in the body,
the bodies of lexically containing tagbody forms (if any) are examined
as well.  If several tags are eql to tag, control is transferred to
whichever matching tag is contained in the innermost tagbody form that
contains the go.  The consequences are undefined if there is no matching
tag lexically visible to the point of the go.

   The transfer of control initiated by go is performed as described in
*note Transfer of Control to an Exit Point::.

Examples::
..........

      (tagbody
        (setq val 2)
        (go lp)
        (incf val 3)
        lp (incf val 4)) =>  NIL
      val =>  6

   The following is in error because there is a normal exit of the
tagbody before the go is executed.

      (let ((a nil))
        (tagbody t (setq a #'(lambda () (go t))))
        (funcall a))

   The following is in error because the tagbody is passed over before
the go form is executed.

      (funcall (block nil
                 (tagbody a (return #'(lambda () (go a))))))

See Also::
..........

*note tagbody::


File: gcl.info,  Node: return-from,  Next: return,  Prev: go,  Up: Data and Control Flow Dictionary

5.3.25 return-from [Special Operator]
-------------------------------------

'return-from' name [result] => #<NoValue>

Arguments and Values::
......................

name--a block tag; not evaluated.

   result--a form; evaluated.  The default is nil.

Description::
.............

Returns control and multiple values_2 from a lexically enclosing block.

   A block form named name must lexically enclose the occurrence of
return-from; any values yielded by the evaluation of result are
immediately returned from the innermost such lexically enclosing block.

   The transfer of control initiated by return-from is performed as
described in *note Transfer of Control to an Exit Point::.

Examples::
..........

      (block alpha (return-from alpha) 1) =>  NIL
      (block alpha (return-from alpha 1) 2) =>  1
      (block alpha (return-from alpha (values 1 2)) 3) =>  1, 2
      (let ((a 0))
         (dotimes (i 10) (incf a) (when (oddp i) (return)))
         a) =>  2
      (defun temp (x)
         (if x (return-from temp 'dummy))
         44) =>  TEMP
      (temp nil) =>  44
      (temp t) =>  DUMMY
      (block out
        (flet ((exit (n) (return-from out n)))
          (block out (exit 1)))
        2) =>  1
      (block nil
        (unwind-protect (return-from nil 1)
          (return-from nil 2)))
     =>  2
      (dolist (flag '(nil t))
        (block nil
          (let ((x 5))
            (declare (special x))
            (unwind-protect (return-from nil)
              (print x))))
        (print 'here))
      |>  5
      |>  HERE
      |>  5
      |>  HERE
     =>  NIL
      (dolist (flag '(nil t))
        (block nil
          (let ((x 5))
            (declare (special x))
            (unwind-protect
                (if flag (return-from nil))
              (print x))))
        (print 'here))
      |>  5
      |>  HERE
      |>  5
      |>  HERE
     =>  NIL

   The following has undefined consequences because the block form exits
normally before the return-from form is attempted.

      (funcall (block nil #'(lambda () (return-from nil)))) is an error.

See Also::
..........

*note block:: , *note return:: , *note Evaluation::


File: gcl.info,  Node: return,  Next: tagbody,  Prev: return-from,  Up: Data and Control Flow Dictionary

5.3.26 return [Macro]
---------------------

'return' [result] => #<NoValue>

Arguments and Values::
......................

result--a form; evaluated.  The default is nil.

Description::
.............

Returns, as if by return-from, from the block named nil.

Examples::
..........

      (block nil (return) 1) =>  NIL
      (block nil (return 1) 2) =>  1
      (block nil (return (values 1 2)) 3) =>  1, 2
      (block nil (block alpha (return 1) 2)) =>  1
      (block alpha (block nil (return 1)) 2) =>  2
      (block nil (block nil (return 1) 2)) =>  1

See Also::
..........

*note block:: , *note return-from:: , *note Evaluation::

Notes::
.......

      (return) == (return-from nil)
      (return form) == (return-from nil form)

   The implicit blocks established by macros such as do are often named
nil, so that return can be used to exit from such forms.


File: gcl.info,  Node: tagbody,  Next: throw,  Prev: return,  Up: Data and Control Flow Dictionary

5.3.27 tagbody [Special Operator]
---------------------------------

'tagbody' {tag | statement}* => nil

Arguments and Values::
......................

tag--a go tag; not evaluated.

   statement--a compound form; evaluated as described below.

Description::
.............

Executes zero or more statements in a lexical environment that provides
for control transfers to labels indicated by the tags.

   The statements in a tagbody are evaluated in order from left to
right, and their values are discarded.  If at any time there are no
remaining statements, tagbody returns nil.  However, if (go tag) is
evaluated, control jumps to the part of the body labeled with the tag.
(Tags are compared with eql.)

   A tag established by tagbody has lexical scope and has dynamic
extent.  Once tagbody has been exited, it is no longer valid to go to a
tag in its body.  It is permissible for go to jump to a tagbody that is
not the innermost tagbody containing that go; the tags established by a
tagbody only shadow other tags of like name.

   The determination of which elements of the body are tags and which
are statements is made prior to any macro expansion of that element.  If
a statement is a macro form and its macro expansion is an atom, that
atom is treated as a statement, not a tag.

Examples::
..........

      (let (val)
         (tagbody
           (setq val 1)
           (go point-a)
           (incf val 16)
          point-c
           (incf val 04)
           (go point-b)
           (incf val 32)
          point-a
           (incf val 02)
           (go point-c)
           (incf val 64)
          point-b
           (incf val 08))
         val)
     =>  15
      (defun f1 (flag)
        (let ((n 1))
          (tagbody
            (setq n (f2 flag #'(lambda () (go out))))
           out
            (prin1 n))))
     =>  F1
      (defun f2 (flag escape)
        (if flag (funcall escape) 2))
     =>  F2
      (f1 nil)
      |>  2
     =>  NIL
      (f1 t)
      |>  1
     =>  NIL

See Also::
..........

*note go::

Notes::
.......

The macros in Figure 5-10 have implicit tagbodies.

  do              do-external-symbols  dotimes  
  do*             do-symbols           prog     
  do-all-symbols  dolist               prog*    

  Figure 5-10: Macros that have implicit tagbodies.



File: gcl.info,  Node: throw,  Next: unwind-protect,  Prev: tagbody,  Up: Data and Control Flow Dictionary

5.3.28 throw [Special Operator]
-------------------------------

'throw' tag result-form => #<NoValue>

Arguments and Values::
......................

tag--a catch tag; evaluated.

   result-form--a form; evaluated as described below.

Description::
.............

throw causes a non-local control transfer to a catch whose tag is eq to
tag.

   Tag is evaluated first to produce an object called the throw tag;
then result-form is evaluated, and its results are saved.  If the
result-form produces multiple values, then all the values are saved.
The most recent outstanding catch whose tag is eq to the throw tag is
exited; the saved results are returned as the value or values of catch.

   The transfer of control initiated by throw is performed as described
in *note Transfer of Control to an Exit Point::.

Examples::
..........

      (catch 'result
         (setq i 0 j 0)
         (loop (incf j 3) (incf i)
               (if (= i 3) (throw 'result (values i j))))) =>  3, 9


      (catch nil
        (unwind-protect (throw nil 1)
          (throw nil 2))) =>  2

   The consequences of the following are undefined because the catch of
b is passed over by the first throw, hence portable programs must assume
that its dynamic extent is terminated.  The binding of the catch tag is
not yet disestablished and therefore it is the target of the second
throw.

      (catch 'a
        (catch 'b
          (unwind-protect (throw 'a 1)
            (throw 'b 2))))

   The following prints "The inner catch returns :SECOND-THROW" and then
returns :outer-catch.

      (catch 'foo
              (format t "The inner catch returns ~s.~
                      (catch 'foo
                          (unwind-protect (throw 'foo :first-throw)
                              (throw 'foo :second-throw))))
              :outer-catch)
      |>  The inner catch returns :SECOND-THROW
     =>  :OUTER-CATCH

Exceptional Situations::
........................

If there is no outstanding catch tag that matches the throw tag, no
unwinding of the stack is performed, and an error of type control-error
is signaled.  When the error is signaled, the dynamic environment is
that which was in force at the point of the throw.

See Also::
..........

*note block:: , *note catch:: , *note return-from:: , *note
unwind-protect:: , *note Evaluation::

Notes::
.......

catch and throw are normally used when the exit point must have dynamic
scope (e.g., the throw is not lexically enclosed by the catch), while
block and return are used when lexical scope is sufficient.


File: gcl.info,  Node: unwind-protect,  Next: nil,  Prev: throw,  Up: Data and Control Flow Dictionary

5.3.29 unwind-protect [Special Operator]
----------------------------------------

'unwind-protect' protected-form {cleanup-form}* => {result}*

Arguments and Values::
......................

protected-form--a form.

   cleanup-form--a form.

   results--the values of the protected-form.

Description::
.............

unwind-protect evaluates protected-form and guarantees that
cleanup-forms are executed before unwind-protect exits, whether it
terminates normally or is aborted by a control transfer of some kind.
unwind-protect is intended to be used to make sure that certain side
effects take place after the evaluation of protected-form.

   If a non-local exit occurs during execution of cleanup-forms, no
special action is taken.  The cleanup-forms of unwind-protect are not
protected by that unwind-protect.

   unwind-protect protects against all attempts to exit from
protected-form, including go, handler-case, ignore-errors, restart-case,
return-from, throw, and with-simple-restart.

   Undoing of handler and restart bindings during an exit happens in
parallel with the undoing of the bindings of dynamic variables and catch
tags, in the reverse order in which they were established.  The effect
of this is that cleanup-form sees the same handler and restart bindings,
as well as dynamic variable bindings and catch tags, as were visible
when the unwind-protect was entered.

Examples::
..........

      (tagbody
        (let ((x 3))
          (unwind-protect
            (if (numberp x) (go out))
            (print x)))
       out
        ...)

   When go is executed, the call to print is executed first, and then
the transfer of control to the tag out is completed.

      (defun dummy-function (x)
         (setq state 'running)
         (unless (numberp x) (throw 'abort 'not-a-number))
         (setq state (1+ x))) =>  DUMMY-FUNCTION
      (catch 'abort (dummy-function 1)) =>  2
      state =>  2
      (catch 'abort (dummy-function 'trash)) =>  NOT-A-NUMBER
      state =>  RUNNING
      (catch 'abort (unwind-protect (dummy-function 'trash)
                       (setq state 'aborted))) =>  NOT-A-NUMBER
      state =>  ABORTED

   The following code is not correct:

      (unwind-protect
        (progn (incf *access-count*)
               (perform-access))
        (decf *access-count*))

   If an exit occurs before completion of incf, the decf form is
executed anyway, resulting in an incorrect value for *access-count*.
The correct way to code this is as follows:

      (let ((old-count *access-count*))
        (unwind-protect
          (progn (incf *access-count*)
                 (perform-access))
          (setq *access-count* old-count)))

     ;;; The following returns 2.
      (block nil
        (unwind-protect (return 1)
          (return 2)))

     ;;; The following has undefined consequences.
      (block a
        (block b
          (unwind-protect (return-from a 1)
            (return-from b 2))))

     ;;; The following returns 2.
      (catch nil
        (unwind-protect (throw nil 1)
          (throw nil 2)))

     ;;; The following has undefined consequences because the catch of B is
     ;;; passed over by the first THROW, hence portable programs must assume
     ;;; its dynamic extent is terminated.  The binding of the catch tag is not
     ;;; yet disestablished and therefore it is the target of the second throw.
      (catch 'a
        (catch 'b
          (unwind-protect (throw 'a 1)
            (throw 'b 2))))

     ;;; The following prints "The inner catch returns :SECOND-THROW"
     ;;; and then returns :OUTER-CATCH.
      (catch 'foo
              (format t "The inner catch returns ~s.~
                      (catch 'foo
                          (unwind-protect (throw 'foo :first-throw)
                              (throw 'foo :second-throw))))
              :outer-catch)

     ;;; The following returns 10. The inner CATCH of A is passed over, but
     ;;; because that CATCH is disestablished before the THROW to A is executed,
     ;;; it isn't seen.
      (catch 'a
        (catch 'b
          (unwind-protect (1+ (catch 'a (throw 'b 1)))
            (throw 'a 10))))

     ;;; The following has undefined consequences because the extent of
     ;;; the (CATCH 'BAR ...) exit ends when the (THROW 'FOO ...)
     ;;; commences.
      (catch 'foo
        (catch 'bar
            (unwind-protect (throw 'foo 3)
              (throw 'bar 4)
              (print 'xxx))))

     ;;; The following returns 4; XXX is not printed.
     ;;; The (THROW 'FOO ...) has no effect on the scope of the BAR
     ;;; catch tag or the extent of the (CATCH 'BAR ...) exit.
      (catch 'bar
        (catch 'foo
            (unwind-protect (throw 'foo 3)
              (throw 'bar 4)
              (print 'xxx))))

     ;;; The following prints 5.
      (block nil
        (let ((x 5))
          (declare (special x))
          (unwind-protect (return)
            (print x))))

See Also::
..........

*note catch:: , *note go:: , *note handler-case:: , *note restart-case::
, *note return:: , *note return-from:: , *note throw:: , *note
Evaluation::


File: gcl.info,  Node: nil,  Next: not,  Prev: unwind-protect,  Up: Data and Control Flow Dictionary

5.3.30 nil [Constant Variable]
------------------------------

Constant Value::
................

nil.

Description::
.............

nil represents both boolean (and generalized boolean) false and the
empty list.

Examples::
..........

      nil =>  NIL

See Also::
..........

*note t::


File: gcl.info,  Node: not,  Next: t,  Prev: nil,  Up: Data and Control Flow Dictionary

5.3.31 not [Function]
---------------------

'not' x => boolean

Arguments and Values::
......................

x--a generalized boolean (i.e., any object).

   boolean--a boolean.

Description::
.............

Returns t if x is false; otherwise, returns nil.

Examples::
..........

      (not nil) =>  T
      (not '()) =>  T
      (not (integerp 'sss)) =>  T
      (not (integerp 1)) =>  NIL
      (not 3.7) =>  NIL
      (not 'apple) =>  NIL

See Also::
..........

*note null::

Notes::
.......

not is intended to be used to invert the 'truth value' of a boolean (or
generalized boolean) whereas null is intended to be used to test for the
empty list.  Operationally, not and null compute the same result; which
to use is a matter of style.


File: gcl.info,  Node: t,  Next: eq,  Prev: not,  Up: Data and Control Flow Dictionary

5.3.32 t [Constant Variable]
----------------------------

Constant Value::
................

t.

Description::
.............

The boolean representing true, and the canonical generalized boolean
representing true.  Although any object other than nil is considered
true, t is generally used when there is no special reason to prefer one
such object over another.

   The symbol t is also sometimes used for other purposes as well.  For
example, as the name of a class, as a designator (e.g., a stream
designator) or as a special symbol for some syntactic reason (e.g., in
case and typecase to label the otherwise-clause).

Examples::
..........

      t =>  T
      (eq t 't) =>  true
      (find-class 't) =>  #<CLASS T 610703333>
      (case 'a (a 1) (t 2)) =>  1
      (case 'b (a 1) (t 2)) =>  2
      (prin1 'hello t)
      |>  HELLO
     =>  HELLO

See Also::
..........

*note NIL::


File: gcl.info,  Node: eq,  Next: eql,  Prev: t,  Up: Data and Control Flow Dictionary

5.3.33 eq [Function]
--------------------

'eq' x y => generalized-boolean

Arguments and Values::
......................

x--an object.

   y--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

Returns true if its arguments are the same, identical object; otherwise,
returns false.

Examples::
..........

      (eq 'a 'b) =>  false
      (eq 'a 'a) =>  true
      (eq 3 3)
     =>  true
     OR=> false
      (eq 3 3.0) =>  false
      (eq 3.0 3.0)
     =>  true
     OR=> false
      (eq #c(3 -4) #c(3 -4))
     =>  true
     OR=> false
      (eq #c(3 -4.0) #c(3 -4)) =>  false
      (eq (cons 'a 'b) (cons 'a 'c)) =>  false
      (eq (cons 'a 'b) (cons 'a 'b)) =>  false
      (eq '(a . b) '(a . b))
     =>  true
     OR=> false
      (progn (setq x (cons 'a 'b)) (eq x x)) =>  true
      (progn (setq x '(a . b)) (eq x x)) =>  true
      (eq #\A #\A)
     =>  true
     OR=> false
      (let ((x "Foo")) (eq x x)) =>  true
      (eq "Foo" "Foo")
     =>  true
     OR=> false
      (eq "Foo" (copy-seq "Foo")) =>  false
      (eq "FOO" "foo") =>  false
      (eq "string-seq" (copy-seq "string-seq")) =>  false
      (let ((x 5)) (eq x x))
     =>  true
     OR=> false

See Also::
..........

*note eql:: , *note equal:: , *note equalp:: , *note =:: , *note
Compilation::

Notes::
.......

Objects that appear the same when printed are not necessarily eq to each
other.  Symbols that print the same usually are eq to each other because
of the use of the intern function.  However, numbers with the same value
need not be eq, and two similar lists are usually not identical.

   An implementation is permitted to make "copies" of characters and
numbers at any time.  The effect is that Common Lisp makes no guarantee
that eq is true even when both its arguments are "the same thing" if
that thing is a character or number.

   Most Common Lisp operators use eql rather than eq to compare objects,
or else they default to eql and only use eq if specifically requested to
do so.  However, the following operators are defined to use eq rather
than eql in a way that cannot be overridden by the code which employs
them:

  catch           getf     throw  
  get             remf            
  get-properties  remprop  

  Figure 5-11: Operators that always prefer EQ over EQL



File: gcl.info,  Node: eql,  Next: equal,  Prev: eq,  Up: Data and Control Flow Dictionary

5.3.34 eql [Function]
---------------------

'eql' x y => generalized-boolean

Arguments and Values::
......................

x--an object.

   y--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

The value of eql is true of two objects, x and y, in the folowing cases:

1.
     If x and y are eq.
2.
     If x and y are both numbers of the same type and the same value.
3.
     If they are both characters that represent the same character.

   Otherwise the value of eql is false.

   If an implementation supports positive and negative zeros as distinct
values, then (eql 0.0 -0.0) returns false.  Otherwise, when the syntax
-0.0 is read it is interpreted as the value 0.0, and so (eql 0.0 -0.0)
returns true.

Examples::
..........

      (eql 'a 'b) =>  false
      (eql 'a 'a) =>  true
      (eql 3 3) =>  true
      (eql 3 3.0) =>  false
      (eql 3.0 3.0) =>  true
      (eql #c(3 -4) #c(3 -4)) =>  true
      (eql #c(3 -4.0) #c(3 -4)) =>  false
      (eql (cons 'a 'b) (cons 'a 'c)) =>  false
      (eql (cons 'a 'b) (cons 'a 'b)) =>  false
      (eql '(a . b) '(a . b))
     =>  true
     OR=> false
      (progn (setq x (cons 'a 'b)) (eql x x)) =>  true
      (progn (setq x '(a . b)) (eql x x)) =>  true
      (eql #\A #\A) =>  true
      (eql "Foo" "Foo")
     =>  true
     OR=> false
      (eql "Foo" (copy-seq "Foo")) =>  false
      (eql "FOO" "foo") =>  false

   Normally (eql 1.0s0 1.0d0) is false, under the assumption that 1.0s0
and 1.0d0 are of distinct data types.  However, implementations that do
not provide four distinct floating-point formats are permitted to
"collapse" the four formats into some smaller number of them; in such an
implementation (eql 1.0s0 1.0d0) might be true.

See Also::
..........

*note eq:: , *note equal:: , *note equalp:: , *note =:: , *note char=::

Notes::
.......

eql is the same as eq, except that if the arguments are characters or
numbers of the same type then their values are compared.  Thus eql tells
whether two objects are conceptually the same, whereas eq tells whether
two objects are implementationally identical.  It is for this reason
that eql, not eq, is the default comparison predicate for operators that
take sequences as arguments.

   eql may not be true of two floats even when they represent the same
value.  = is used to compare mathematical values.

   Two complex numbers are considered to be eql if their real parts are
eql and their imaginary parts are eql.  For example, (eql #C(4 5) #C(4
5)) is true and (eql #C(4 5) #C(4.0 5.0)) is false.  Note that while
(eql #C(5.0 0.0) 5.0) is false, (eql #C(5 0) 5) is true.  In the case of
(eql #C(5.0 0.0) 5.0) the two arguments are of different types, and so
cannot satisfy eql.  In the case of (eql #C(5 0) 5), #C(5 0) is not a
complex number, but is automatically reduced to the integer 5.


File: gcl.info,  Node: equal,  Next: equalp,  Prev: eql,  Up: Data and Control Flow Dictionary

5.3.35 equal [Function]
-----------------------

'equal' x y => generalized-boolean

Arguments and Values::
......................

x--an object.

   y--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

Returns true if x and y are structurally similar (isomorphic) objects.
Objects are treated as follows by equal.

Symbols, Numbers, and Characters
     equal is true of two objects if they are symbols that are eq, if
     they are numbers that are eql, or if they are characters that are
     eql.

Conses
     For conses, equal is defined recursively as the two cars being
     equal and the two cdrs being equal.

Arrays
     Two arrays are equal only if they are eq, with one exception:
     strings and bit vectors are compared element-by-element (using
     eql).  If either x or y has a fill pointer, the fill pointer limits
     the number of elements examined by equal.  Uppercase and lowercase
     letters in strings are considered by equal to be different.

Pathnames
     Two pathnames are equal if and only if all the corresponding
     components (host, device, and so on) are equivalent.  Whether or
     not uppercase and lowercase letters are considered equivalent in
     strings appearing in components is implementation-dependent.
     pathnames that are equal should be functionally equivalent.

Other (Structures, hash-tables, instances, ...)
     Two other objects are equal only if they are eq.

   equal does not descend any objects other than the ones explicitly
specified above.  Figure 5-12 summarizes the information given in the
previous list.  In addition, the figure specifies the priority of the
behavior of equal, with upper entries taking priority over lower ones.

  Type          Behavior                   
  number        uses eql                   
  character     uses eql                   
  cons          descends                   
  bit vector    descends                   
  string        descends                   
  pathname      "functionally equivalent"  
  structure     uses eq                    
  Other array   uses eq                    
  hash table    uses eq                    
  Other object  uses eq                    

  Figure 5-12: Summary and priorities of behavior of equal


   Any two objects that are eql are also equal.

   equal may fail to terminate if x or y is circular.

Examples::
..........

      (equal 'a 'b) =>  false
      (equal 'a 'a) =>  true
      (equal 3 3) =>  true
      (equal 3 3.0) =>  false
      (equal 3.0 3.0) =>  true
      (equal #c(3 -4) #c(3 -4)) =>  true
      (equal #c(3 -4.0) #c(3 -4)) =>  false
      (equal (cons 'a 'b) (cons 'a 'c)) =>  false
      (equal (cons 'a 'b) (cons 'a 'b)) =>  true
      (equal #\A #\A) =>  true
      (equal #\A #\a) =>  false
      (equal "Foo" "Foo") =>  true
      (equal "Foo" (copy-seq "Foo")) =>  true
      (equal "FOO" "foo") =>  false
      (equal "This-string" "This-string") =>  true
      (equal "This-string" "this-string") =>  false

See Also::
..........

*note eq:: , *note eql:: , *note equalp:: , *note =:: , *note string=::
, string-equal, *note char=:: , char-equal, *note tree-equal::

Notes::
.......

Object equality is not a concept for which there is a uniquely
determined correct algorithm.  The appropriateness of an equality
predicate can be judged only in the context of the needs of some
particular program.  Although these functions take any type of argument
and their names sound very generic, equal and equalp are not appropriate
for every application.

   A rough rule of thumb is that two objects are equal if and only if
their printed representations are the same.


File: gcl.info,  Node: equalp,  Next: identity,  Prev: equal,  Up: Data and Control Flow Dictionary

5.3.36 equalp [Function]
------------------------

'equalp' x y => generalized-boolean

Arguments and Values::
......................

x--an object.

   y--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

Returns true if x and y are equal, or if they have components that are
of the same type as each other and if those components are equalp;
specifically, equalp returns true in the following cases:

Characters
     If two characters are char-equal.

Numbers
     If two numbers are the same under =.

Conses
     If the two cars in the conses are equalp and the two cdrs in the
     conses are equalp.

Arrays
     If two arrays have the same number of dimensions, the dimensions
     match, and the corresponding active elements are equalp.  The types
     for which the arrays are specialized need not match; for example, a
     string and a general array that happens to contain the same
     characters are equalp.  Because equalp performs element-by-element
     comparisons of strings and ignores the case of characters, case
     distinctions are ignored when equalp compares strings.

Structures
     If two structures S_1 and S_2 have the same class and the value of
     each slot in S_1 is the same under equalp as the value of the
     corresponding slot in S_2.

Hash Tables
     equalp descends hash-tables by first comparing the count of entries
     and the :test function; if those are the same, it compares the keys
     of the tables using the :test function and then the values of the
     matching keys using equalp recursively.

   equalp does not descend any objects other than the ones explicitly
specified above.  Figure 5-13 summarizes the information given in the
previous list.  In addition, the figure specifies the priority of the
behavior of equalp, with upper entries taking priority over lower ones.

  Type          Behavior                      
  number        uses =                        
  character     uses char-equal               
  cons          descends                      
  bit vector    descends                      
  string        descends                      
  pathname      same as equal                 
  structure     descends, as described above  
  Other array   descends                      
  hash table    descends, as described above  
  Other object  uses eq                       

  Figure 5-13: Summary and priorities of behavior of equalp


Examples::
..........

      (equalp 'a 'b) =>  false
      (equalp 'a 'a) =>  true
      (equalp 3 3) =>  true
      (equalp 3 3.0) =>  true
      (equalp 3.0 3.0) =>  true
      (equalp #c(3 -4) #c(3 -4)) =>  true
      (equalp #c(3 -4.0) #c(3 -4)) =>  true
      (equalp (cons 'a 'b) (cons 'a 'c)) =>  false
      (equalp (cons 'a 'b) (cons 'a 'b)) =>  true
      (equalp #\A #\A) =>  true
      (equalp #\A #\a) =>  true
      (equalp "Foo" "Foo") =>  true
      (equalp "Foo" (copy-seq "Foo")) =>  true
      (equalp "FOO" "foo") =>  true

      (setq array1 (make-array 6 :element-type 'integer
                                 :initial-contents '(1 1 1 3 5 7)))
     =>  #(1 1 1 3 5 7)
      (setq array2 (make-array 8 :element-type 'integer
                                 :initial-contents '(1 1 1 3 5 7 2 6)
                                 :fill-pointer 6))
     =>  #(1 1 1 3 5 7)
      (equalp array1 array2) =>  true
      (setq vector1 (vector 1 1 1 3 5 7)) =>  #(1 1 1 3 5 7)
      (equalp array1 vector1) =>  true

See Also::
..........

*note eq:: , *note eql:: , *note equal:: , *note =:: , *note string=:: ,
string-equal, *note char=:: , char-equal

Notes::
.......

Object equality is not a concept for which there is a uniquely
determined correct algorithm.  The appropriateness of an equality
predicate can be judged only in the context of the needs of some
particular program.  Although these functions take any type of argument
and their names sound very generic, equal and equalp are not appropriate
for every application.


File: gcl.info,  Node: identity,  Next: complement,  Prev: equalp,  Up: Data and Control Flow Dictionary

5.3.37 identity [Function]
--------------------------

'identity' object => object

Arguments and Values::
......................

object--an object.

Description::
.............

Returns its argument object.

Examples::
..........

      (identity 101) =>  101
      (mapcan #'identity (list (list 1 2 3) '(4 5 6))) =>  (1 2 3 4 5 6)

Notes::
.......

identity is intended for use with functions that require a function as
an argument.

   (eql x (identity x)) returns true for all possible values of x, but
(eq x (identity x)) might return false when x is a number or character.

   identity could be defined by

     (defun identity (x) x)


File: gcl.info,  Node: complement,  Next: constantly,  Prev: identity,  Up: Data and Control Flow Dictionary

5.3.38 complement [Function]
----------------------------

'complement' function => complement-function

Arguments and Values::
......................

function--a function.

   complement-function--a function.

Description::
.............

Returns a function that takes the same arguments as function, and has
the same side-effect behavior as function, but returns only a single
value: a generalized boolean with the opposite truth value of that which
would be returned as the primary value of function.  That is, when the
function would have returned true as its primary value the
complement-function returns false, and when the function would have
returned false as its primary value the complement-function returns
true.

Examples::
..........

      (funcall (complement #'zerop) 1) =>  true
      (funcall (complement #'characterp) #\A) =>  false
      (funcall (complement #'member) 'a '(a b c)) =>  false
      (funcall (complement #'member) 'd '(a b c)) =>  true

See Also::
..........

*note not::

Notes::
.......

      (complement x) == #'(lambda (&rest arguments) (not (apply x arguments)))

   In Common Lisp, functions with names like "xxx-if-not" are related to
functions with names like "xxx-if" in that

     (xxx-if-not f . arguments) == (xxx-if (complement f) . arguments)

   For example,

      (find-if-not #'zerop '(0 0 3)) ==
      (find-if (complement #'zerop) '(0 0 3)) =>  3

   Note that since the "xxx-if-not" functions and the :test-not
arguments have been deprecated, uses of "xxx-if" functions or :test
arguments with complement are preferred.


File: gcl.info,  Node: constantly,  Next: every,  Prev: complement,  Up: Data and Control Flow Dictionary

5.3.39 constantly [Function]
----------------------------

'constantly' value => function

Arguments and Values::
......................

value--an object.

   function--a function.

Description::
.............

constantly returns a function that accepts any number of arguments, that
has no side-effects, and that always returns value.

Examples::
..........

      (mapcar (constantly 3) '(a b c d)) =>  (3 3 3 3)
      (defmacro with-vars (vars &body forms)
        `((lambda ,vars ,@forms) ,@(mapcar (constantly nil) vars)))
     =>  WITH-VARS
      (macroexpand '(with-vars (a b) (setq a 3 b (* a a)) (list a b)))
     =>  ((LAMBDA (A B) (SETQ A 3 B (* A A)) (LIST A B)) NIL NIL), true

See Also::
..........

*note not::

Notes::
.......

constantly could be defined by:

      (defun constantly (object)
        #'(lambda (&rest arguments) object))


File: gcl.info,  Node: every,  Next: and,  Prev: constantly,  Up: Data and Control Flow Dictionary

5.3.40 every, some, notevery, notany [Function]
-----------------------------------------------

'every' predicate &rest sequences^+ => generalized-boolean

   'some' predicate &rest sequences^+ => result

   'notevery' predicate &rest sequences^+ => generalized-boolean

   'notany' predicate &rest sequences^+ => generalized-boolean

Arguments and Values::
......................

predicate--a designator for a function of as many arguments as there are
sequences.

   sequence--a sequence.

   result--an object.

   generalized-boolean--a generalized boolean.

Description::
.............

every, some, notevery, and notany test elements of sequences for
satisfaction of a given predicate.  The first argument to predicate is
an element of the first sequence; each succeeding argument is an element
of a succeeding sequence.

   Predicate is first applied to the elements with index 0 in each of
the sequences, and possibly then to the elements with index 1, and so
on, until a termination criterion is met or the end of the shortest of
the sequences is reached.

   every returns false as soon as any invocation of predicate returns
false.  If the end of a sequence is reached, every returns true.  Thus,
every returns true if and only if every invocation of predicate returns
true.

   some returns the first non-nil value which is returned by an
invocation of predicate.  If the end of a sequence is reached without
any invocation of the predicate returning true, some returns false.
Thus, some returns true if and only if some invocation of predicate
returns true.

   notany returns false as soon as any invocation of predicate returns
true.  If the end of a sequence is reached, notany returns true.  Thus,
notany returns true if and only if it is not the case that any
invocation of predicate returns true.

   notevery returns true as soon as any invocation of predicate returns
false.  If the end of a sequence is reached, notevery returns false.
Thus, notevery returns true if and only if it is not the case that every
invocation of predicate returns true.

Examples::
..........

      (every #'characterp "abc") =>  true
      (some #'= '(1 2 3 4 5) '(5 4 3 2 1)) =>  true
      (notevery #'< '(1 2 3 4) '(5 6 7 8) '(9 10 11 12)) =>  false
      (notany #'> '(1 2 3 4) '(5 6 7 8) '(9 10 11 12)) =>  true

Exceptional Situations::
........................

Should signal type-error if its first argument is neither a symbol nor a
function or if any subsequent argument is not a proper sequence.

   Other exceptional situations are possible, depending on the nature of
the predicate.

See Also::
..........

*note and:: , *note or:: ,

   *note Traversal Rules and Side Effects::

Notes::
.......

      (notany predicate {sequence}*) == (not (some predicate {sequence}*))
      (notevery predicate {sequence}*) == (not (every predicate {sequence}*))


File: gcl.info,  Node: and,  Next: cond,  Prev: every,  Up: Data and Control Flow Dictionary

5.3.41 and [Macro]
------------------

'and' {form}* => {result}*

Arguments and Values::
......................

form--a form.

   results--the values resulting from the evaluation of the last form,
or the symbols nil or t.

Description::
.............

The macro and evaluates each form one at a time from left to right.  As
soon as any form evaluates to nil, and returns nil without evaluating
the remaining forms.  If all forms but the last evaluate to true values,
and returns the results produced by evaluating the last form.

   If no forms are supplied, (and) returns t.

   and passes back multiple values from the last subform but not from
subforms other than the last.

Examples::
..........

      (if (and (>= n 0)
               (< n (length a-simple-vector))
               (eq (elt a-simple-vector n) 'foo))
          (princ "Foo!"))

   The above expression prints Foo! if element n of a-simple-vector is
the symbol foo, provided also that n is indeed a valid index for
a-simple-vector.  Because and guarantees left-to-right testing of its
parts, elt is not called if n is out of range.

      (setq temp1 1 temp2 1 temp3 1) =>  1
      (and (incf temp1) (incf temp2) (incf temp3)) =>  2
      (and (eql 2 temp1) (eql 2 temp2) (eql 2 temp3)) =>  true
      (decf temp3) =>  1
      (and (decf temp1) (decf temp2) (eq temp3 'nil) (decf temp3)) =>  NIL
      (and (eql temp1 temp2) (eql temp2 temp3)) =>  true
      (and) =>  T

See Also::
..........

*note cond:: , *note every:: , *note if:: , *note or:: , *note when::

Notes::
.......

      (and form) == (let () form)
      (and form1 form2 ...) == (when form1 (and form2 ...))


File: gcl.info,  Node: cond,  Next: if,  Prev: and,  Up: Data and Control Flow Dictionary

5.3.42 cond [Macro]
-------------------

'cond' {!clause}* => {result}*

   clause ::=(test-form {form}*)

Arguments and Values::
......................

test-form--a form.

   forms--an implicit progn.

   results--the values of the forms in the first clause whose test-form
yields true, or the primary value of the test-form if there are no forms
in that clause, or else nil if no test-form yields true.

Description::
.............

cond allows the execution of forms to be dependent on test-form.

   Test-forms are evaluated one at a time in the order in which they are
given in the argument list until a test-form is found that evaluates to
true.

   If there are no forms in that clause, the primary value of the
test-form is returned by the cond form.  Otherwise, the forms associated
with this test-form are evaluated in order, left to right, as an
implicit progn, and the values returned by the last form are returned by
the cond form.

   Once one test-form has yielded true, no additional test-forms are
evaluated.  If no test-form yields true, nil is returned.

Examples::
..........

      (defun select-options ()
        (cond ((= a 1) (setq a 2))
              ((= a 2) (setq a 3))
              ((and (= a 3) (floor a 2)))
              (t (floor a 3)))) =>  SELECT-OPTIONS
      (setq a 1) =>  1
      (select-options) =>  2
      a =>  2
      (select-options) =>  3
      a =>  3
      (select-options) =>  1
      (setq a 5) =>  5
      (select-options) =>  1, 2

See Also::
..........

*note if:: , *note case:: .


File: gcl.info,  Node: if,  Next: or,  Prev: cond,  Up: Data and Control Flow Dictionary

5.3.43 if [Special Operator]
----------------------------

'if' test-form then-form [else-form] => {result}*

Arguments and Values::
......................

Test-form--a form.

   Then-form--a form.

   Else-form--a form.  The default is nil.

   results--if the test-form yielded true, the values returned by the
then-form; otherwise, the values returned by the else-form.

Description::
.............

if allows the execution of a form to be dependent on a single test-form.

   First test-form is evaluated.  If the result is true, then then-form
is selected; otherwise else-form is selected.  Whichever form is
selected is then evaluated.

Examples::
..........

      (if t 1) =>  1
      (if nil 1 2) =>  2
      (defun test ()
        (dolist (truth-value '(t nil 1 (a b c)))
          (if truth-value (print 'true) (print 'false))
          (prin1 truth-value))) =>  TEST
      (test)
      |>  TRUE T
      |>  FALSE NIL
      |>  TRUE 1
      |>  TRUE (A B C)
     =>  NIL

See Also::
..........

*note cond:: , unless, *note when::

Notes::
.......

      (if test-form then-form else-form)
      == (cond (test-form then-form) (t else-form))


File: gcl.info,  Node: or,  Next: when,  Prev: if,  Up: Data and Control Flow Dictionary

5.3.44 or [Macro]
-----------------

'or' {form}* => {results}*

Arguments and Values::
......................

form--a form.

   results--the values or primary value (see below) resulting from the
evaluation of the last form executed or nil.

Description::
.............

or evaluates each form, one at a time, from left to right.  The
evaluation of all forms terminates when a form evaluates to true (i.e.,
something other than nil).

   If the evaluation of any form other than the last returns a primary
value that is true, or immediately returns that value (but no additional
values) without evaluating the remaining forms.  If every form but the
last returns false as its primary value, or returns all values returned
by the last form.  If no forms are supplied, or returns nil.

Examples::
..........

      (or) =>  NIL
      (setq temp0 nil temp1 10 temp2 20 temp3 30) =>  30
      (or temp0 temp1 (setq temp2 37)) =>  10
      temp2 =>  20
      (or (incf temp1) (incf temp2) (incf temp3)) =>  11
      temp1 =>  11
      temp2 =>  20
      temp3 =>  30
      (or (values) temp1) =>  11
      (or (values temp1 temp2) temp3) =>  11
      (or temp0 (values temp1 temp2)) =>  11, 20
      (or (values temp0 temp1) (values temp2 temp3)) =>  20, 30

See Also::
..........

*note and:: , some, unless


File: gcl.info,  Node: when,  Next: case,  Prev: or,  Up: Data and Control Flow Dictionary

5.3.45 when, unless [Macro]
---------------------------

'when' test-form {form}* => {result}*

   'unless' test-form {form}* => {result}*

Arguments and Values::
......................

test-form--a form.

   forms--an implicit progn.

   results--the values of the forms in a when form if the test-form
yields true or in an unless form if the test-form yields false;
otherwise nil.

Description::
.............

when and unless allow the execution of forms to be dependent on a single
test-form.

   In a when form, if the test-form yields true, the forms are evaluated
in order from left to right and the values returned by the forms are
returned from the when form.  Otherwise, if the test-form yields false,
the forms are not evaluated, and the when form returns nil.

   In an unless form, if the test-form yields false, the forms are
evaluated in order from left to right and the values returned by the
forms are returned from the unless form.  Otherwise, if the test-form
yields false, the forms are not evaluated, and the unless form returns
nil.

Examples::
..........

      (when t 'hello) =>  HELLO
      (unless t 'hello) =>  NIL
      (when nil 'hello) =>  NIL
      (unless nil 'hello) =>  HELLO
      (when t) =>  NIL
      (unless nil) =>  NIL
      (when t (prin1 1) (prin1 2) (prin1 3))
      |>  123
     =>  3
      (unless t (prin1 1) (prin1 2) (prin1 3)) =>  NIL
      (when nil (prin1 1) (prin1 2) (prin1 3)) =>  NIL
      (unless nil (prin1 1) (prin1 2) (prin1 3))
      |>  123
     =>  3
      (let ((x 3))
        (list (when (oddp x) (incf x) (list x))
              (when (oddp x) (incf x) (list x))
              (unless (oddp x) (incf x) (list x))
              (unless (oddp x) (incf x) (list x))
              (if (oddp x) (incf x) (list x))
              (if (oddp x) (incf x) (list x))
              (if (not (oddp x)) (incf x) (list x))
              (if (not (oddp x)) (incf x) (list x))))
     =>  ((4) NIL (5) NIL 6 (6) 7 (7))

See Also::
..........

*note and:: , *note cond:: , *note if:: , *note or::

Notes::
.......

      (when test {form}^+) == (and test (progn {form}^+))
      (when test {form}^+) == (cond (test {form}^+))
      (when test {form}^+) == (if test (progn {form}^+) nil)
      (when test {form}^+) == (unless (not test) {form}^+)
      (unless test {form}^+) == (cond ((not test) {form}^+))
      (unless test {form}^+) == (if test nil (progn {form}^+))
      (unless test {form}^+) == (when (not test) {form}^+)


File: gcl.info,  Node: case,  Next: typecase,  Prev: when,  Up: Data and Control Flow Dictionary

5.3.46 case, ccase, ecase [Macro]
---------------------------------

'case' keyform {!normal-clause}* [!otherwise-clause] => {result}*

   'ccase' keyplace {!normal-clause}* => {result}*

   'ecase' keyform {!normal-clause}* => {result}*

   normal-clause ::=(keys {form}*)

   otherwise-clause ::=({otherwise | t} {form}*)

   clause ::=normal-clause | otherwise-clause

Arguments and Values::
......................

keyform--a form; evaluated to produce a test-key.

   keyplace--a form; evaluated initially to produce a test-key.
Possibly also used later as a place if no keys match.

   test-key--an object produced by evaluating keyform or keyplace.

   keys--a designator for a list of objects.  In the case of case, the
symbols t and otherwise may not be used as the keys designator.  To
refer to these symbols by themselves as keys, the designators (t) and
(otherwise), respectively, must be used instead.

   forms--an implicit progn.

   results--the values returned by the forms in the matching clause.

Description::
.............

These macros allow the conditional execution of a body of forms in a
clause that is selected by matching the test-key on the basis of its
identity.

   The keyform or keyplace is evaluated to produce the test-key.

   Each of the normal-clauses is then considered in turn.  If the
test-key is the same as any key for that clause, the forms in that
clause are evaluated as an implicit progn, and the values it returns are
returned as the value of the case, ccase, or ecase form.

   These macros differ only in their behavior when no normal-clause
matches; specifically:

case
     If no normal-clause matches, and there is an otherwise-clause, then
     that otherwise-clause automatically matches; the forms in that
     clause are evaluated as an implicit progn, and the values it
     returns are returned as the value of the case.

     If there is no otherwise-clause, case returns nil.

ccase
     If no normal-clause matches, a correctable error of type type-error
     is signaled.  The offending datum is the test-key and the expected
     type is type equivalent to (member key1 key2 ...).  The store-value
     restart can be used to correct the error.

     If the store-value restart is invoked, its argument becomes the new
     test-key, and is stored in keyplace as if by (setf keyplace
     test-key).  Then ccase starts over, considering each clause anew.

     [Reviewer Note by Barmar: Will it prompt for multiple values if
     keyplace is a VALUES general ref?]

     The subforms of keyplace might be evaluated again if none of the
     cases holds.

ecase
     If no normal-clause matches, a non-correctable error of type
     type-error is signaled.  The offending datum is the test-key and
     the expected type is type equivalent to (member key1 key2 ...).

     Note that in contrast with ccase, the caller of ecase may rely on
     the fact that ecase does not return if a normal-clause does not
     match.

Examples::
..........

      (dolist (k '(1 2 3 :four #\v () t 'other))
         (format t "~S "
            (case k ((1 2) 'clause1)
                    (3 'clause2)
                    (nil 'no-keys-so-never-seen)
                    ((nil) 'nilslot)
                    ((:four #\v) 'clause4)
                    ((t) 'tslot)
                    (otherwise 'others))))
      |>  CLAUSE1 CLAUSE1 CLAUSE2 CLAUSE4 CLAUSE4 NILSLOT TSLOT OTHERS
     =>  NIL
      (defun add-em (x) (apply #'+ (mapcar #'decode x)))
     =>  ADD-EM
      (defun decode (x)
        (ccase x
          ((i uno) 1)
          ((ii dos) 2)
          ((iii tres) 3)
          ((iv cuatro) 4)))
     =>  DECODE
      (add-em '(uno iii)) =>  4
      (add-em '(uno iiii))
      |>  Error: The value of X, IIII, is not I, UNO, II, DOS, III,
      |>         TRES, IV, or CUATRO.
      |>   1: Supply a value to use instead.
      |>   2: Return to Lisp Toplevel.
      |>  Debug> |>>:CONTINUE 1<<|
      |>  Value to evaluate and use for X: |>>'IV<<|
     =>  5

Side Effects::
..............

The debugger might be entered.  If the store-value restart is invoked,
the value of keyplace might be changed.

Affected By::
.............

ccase and ecase, since they might signal an error, are potentially
affected by existing handlers and *debug-io*.

Exceptional Situations::
........................

ccase and ecase signal an error of type type-error if no normal-clause
matches.

See Also::
..........

*note cond:: , *note typecase:: , *note setf:: , *note Generalized
Reference::

Notes::
.......

     (case test-key
       {(({key}*) {form}*)}*)
     ==
     (let ((#1=#:g0001 test-key))
       (cond {((member #1# '({key}*)) {form}*)}*))

   The specific error message used by ecase and ccase can vary between
implementations.  In situations where control of the specific wording of
the error message is important, it is better to use case with an
otherwise-clause that explicitly signals an error with an appropriate
message.


File: gcl.info,  Node: typecase,  Next: multiple-value-bind,  Prev: case,  Up: Data and Control Flow Dictionary

5.3.47 typecase, ctypecase, etypecase [Macro]
---------------------------------------------

'typecase' keyform {!normal-clause}* [!otherwise-clause] => {result}*

   'ctypecase' keyplace {!normal-clause}* => {result}*

   'etypecase' keyform {!normal-clause}* => {result}*

   normal-clause ::=(type {form}*)

   otherwise-clause ::=({otherwise | t} {form}*)

   clause ::=normal-clause | otherwise-clause

Arguments and Values::
......................

keyform--a form; evaluated to produce a test-key.

   keyplace--a form; evaluated initially to produce a test-key.
Possibly also used later as a place if no types match.

   test-key--an object produced by evaluating keyform or keyplace.

   type--a type specifier.

   forms--an implicit progn.

   results--the values returned by the forms in the matching clause.

Description::
.............

These macros allow the conditional execution of a body of forms in a
clause that is selected by matching the test-key on the basis of its
type.

   The keyform or keyplace is evaluated to produce the test-key.

   Each of the normal-clauses is then considered in turn.  If the
test-key is of the type given by the clauses's type, the forms in that
clause are evaluated as an implicit progn, and the values it returns are
returned as the value of the typecase, ctypecase, or etypecase form.

   These macros differ only in their behavior when no normal-clause
matches; specifically:

typecase
     If no normal-clause matches, and there is an otherwise-clause, then
     that otherwise-clause automatically matches; the forms in that
     clause are evaluated as an implicit progn, and the values it
     returns are returned as the value of the typecase.

     If there is no otherwise-clause, typecase returns nil.

ctypecase
     If no normal-clause matches, a correctable error of type type-error
     is signaled.  The offending datum is the test-key and the expected
     type is type equivalent to (or type1 type2 ...).  The store-value
     restart can be used to correct the error.

     If the store-value restart is invoked, its argument becomes the new
     test-key, and is stored in keyplace as if by (setf keyplace
     test-key).  Then ctypecase starts over, considering each clause
     anew.

     If the store-value restart is invoked interactively, the user is
     prompted for a new test-key to use.

     The subforms of keyplace might be evaluated again if none of the
     cases holds.

etypecase
     If no normal-clause matches, a non-correctable error of type
     type-error is signaled.  The offending datum is the test-key and
     the expected type is type equivalent to (or type1 type2 ...).

     Note that in contrast with ctypecase, the caller of etypecase may
     rely on the fact that etypecase does not return if a normal-clause
     does not match.

   In all three cases, is permissible for more than one clause to
specify a matching type, particularly if one is a subtype of another;
the earliest applicable clause is chosen.

Examples::
..........

     ;;; (Note that the parts of this example which use TYPE-OF
     ;;;  are implementation-dependent.)
      (defun what-is-it (x)
        (format t "~&~S is ~A.~
                x (typecase x
                    (float "a float")
                    (null "a symbol, boolean false, or the empty list")
                    (list "a list")
                    (t (format nil "a(n) ~(~A~)" (type-of x))))))
     =>  WHAT-IS-IT
      (map 'nil #'what-is-it '(nil (a b) 7.0 7 box))
      |>  NIL is a symbol, boolean false, or the empty list.
      |>  (A B) is a list.
      |>  7.0 is a float.
      |>  7 is a(n) integer.
      |>  BOX is a(n) symbol.
     =>  NIL
      (setq x 1/3)
     =>  1/3
      (ctypecase x
          (integer (* x 4))
          (symbol  (symbol-value x)))
      |>  Error: The value of X, 1/3, is neither an integer nor a symbol.
      |>  To continue, type :CONTINUE followed by an option number:
      |>   1: Specify a value to use instead.
      |>   2: Return to Lisp Toplevel.
      |>  Debug> |>>:CONTINUE 1<<|
      |>  Use value: |>>3.7<<|
      |>  Error: The value of X, 3.7, is neither an integer nor a symbol.
      |>  To continue, type :CONTINUE followed by an option number:
      |>   1: Specify a value to use instead.
      |>   2: Return to Lisp Toplevel.
      |>  Debug> |>>:CONTINUE 1<<|
      |>  Use value: |>>12<<|
     =>  48
      x =>  12

Affected By::
.............

ctypecase and etypecase, since they might signal an error, are
potentially affected by existing handlers and *debug-io*.

Exceptional Situations::
........................

ctypecase and etypecase signal an error of type type-error if no
normal-clause matches.

   The compiler may choose to issue a warning of type style-warning if a
clause will never be selected because it is completely shadowed by
earlier clauses.

See Also::
..........

*note case:: , *note cond:: , *note setf:: , *note Generalized
Reference::

Notes::
.......

     (typecase test-key
       {(type {form}*)}*)
     ==
     (let ((#1=#:g0001 test-key))
       (cond {((typep #1# 'type) {form}*)}*))

   The specific error message used by etypecase and ctypecase can vary
between implementations.  In situations where control of the specific
wording of the error message is important, it is better to use typecase
with an otherwise-clause that explicitly signals an error with an
appropriate message.


File: gcl.info,  Node: multiple-value-bind,  Next: multiple-value-call,  Prev: typecase,  Up: Data and Control Flow Dictionary

5.3.48 multiple-value-bind [Macro]
----------------------------------

'multiple-value-bind' ({var}*) values-form {declaration}* {form}*
=> {result}*

Arguments and Values::
......................

var--a symbol naming a variable; not evaluated.

   values-form--a form; evaluated.

   declaration--a declare expression; not evaluated.

   forms--an implicit progn.

   results--the values returned by the forms.

Description::
.............

Creates new variable bindings for the vars and executes a series of
forms that use these bindings.

   The variable bindings created are lexical unless special declarations
are specified.

   Values-form is evaluated, and each of the vars is bound to the
respective value returned by that form.  If there are more vars than
values returned, extra values of nil are given to the remaining vars.
If there are more values than vars, the excess values are discarded.
The vars are bound to the values over the execution of the forms, which
make up an implicit progn.  The consequences are unspecified if a type
declaration is specified for a var, but the value to which that var is
bound is not consistent with the type declaration.

   The scopes of the name binding and declarations do not include the
values-form.

Examples::
..........

      (multiple-value-bind (f r)
          (floor 130 11)
        (list f r)) =>  (11 9)

See Also::
..........

*note let:: , *note multiple-value-call::

Notes::
.......

      (multiple-value-bind ({var}*) values-form {form}*)
      == (multiple-value-call #'(lambda (&optional {var}* &rest #1=#:ignore)
                                  (declare (ignore #1#))
                                  {form}*)
                              values-form)


File: gcl.info,  Node: multiple-value-call,  Next: multiple-value-list,  Prev: multiple-value-bind,  Up: Data and Control Flow Dictionary

5.3.49 multiple-value-call [Special Operator]
---------------------------------------------

'multiple-value-call' function-form form* => {result}*

Arguments and Values::
......................

function-form--a form; evaluated to produce function.

   function--a function designator resulting from the evaluation of
function-form.

   form--a form.

   results--the values returned by the function.

Description::
.............

Applies function to a list of the objects collected from groups of
multiple values_2.

   multiple-value-call first evaluates the function-form to obtain
function, and then evaluates each form.  All the values of each form are
gathered together (not just one value from each) and given as arguments
to the function.

Examples::
..........

      (multiple-value-call #'list 1 '/ (values 2 3) '/ (values) '/ (floor 2.5))
     =>  (1 / 2 3 / / 2 0.5)
      (+ (floor 5 3) (floor 19 4)) == (+ 1 4)
     =>  5
      (multiple-value-call #'+ (floor 5 3) (floor 19 4)) == (+ 1 2 4 3)
     =>  10

See Also::
..........

*note multiple-value-list:: , *note multiple-value-bind::


File: gcl.info,  Node: multiple-value-list,  Next: multiple-value-prog1,  Prev: multiple-value-call,  Up: Data and Control Flow Dictionary

5.3.50 multiple-value-list [Macro]
----------------------------------

'multiple-value-list' form => list

Arguments and Values::
......................

form--a form; evaluated as described below.

   list--a list of the values returned by form.

Description::
.............

multiple-value-list evaluates form and creates a list of the multiple
values_2 it returns.

Examples::
..........

      (multiple-value-list (floor -3 4)) =>  (-1 1)

See Also::
..........

*note values-list:: , *note multiple-value-call::

Notes::
.......

multiple-value-list and values-list are inverses of each other.

      (multiple-value-list form) == (multiple-value-call #'list form)


File: gcl.info,  Node: multiple-value-prog1,  Next: multiple-value-setq,  Prev: multiple-value-list,  Up: Data and Control Flow Dictionary

5.3.51 multiple-value-prog1 [Special Operator]
----------------------------------------------

'multiple-value-prog' 1 => first-form {form}*

   first-form-results

Arguments and Values::
......................

first-form--a form; evaluated as described below.

   form--a form; evaluated as described below.

   first-form-results--the values resulting from the evaluation of
first-form.

Description::
.............

multiple-value-prog1 evaluates first-form and saves all the values
produced by that form.  It then evaluates each form from left to right,
discarding their values.

Examples::
..........

      (setq temp '(1 2 3)) =>  (1 2 3)
      (multiple-value-prog1
         (values-list temp)
         (setq temp nil)
         (values-list temp)) =>  1, 2, 3

See Also::
..........

*note prog1::


File: gcl.info,  Node: multiple-value-setq,  Next: values,  Prev: multiple-value-prog1,  Up: Data and Control Flow Dictionary

5.3.52 multiple-value-setq [Macro]
----------------------------------

'multiple-value-setq' vars form => result

Arguments and Values::
......................

vars--a list of symbols that are either variable names or names of
symbol macros.

   form--a form.

   result--The primary value returned by the form.

Description::
.............

multiple-value-setq assigns values to vars.

   The form is evaluated, and each var is assigned to the corresponding
value returned by that form.  If there are more vars than values
returned, nil is assigned to the extra vars.  If there are more values
than vars, the extra values are discarded.

   If any var is the name of a symbol macro, then it is assigned as if
by setf.  Specifically,

      (multiple-value-setq (symbol_1 ... symbol_n) value-producing-form)

   is defined to always behave in the same way as

      (values (setf (values symbol_1 ... symbol_n) value-producing-form))

   in order that the rules for order of evaluation and side-effects be
consistent with those used by setf.

   See *note VALUES Forms as Places::.

Examples::
..........

      (multiple-value-setq (quotient remainder) (truncate 3.2 2)) =>  1
      quotient =>  1
      remainder =>  1.2
      (multiple-value-setq (a b c) (values 1 2)) =>  1
      a =>  1
      b =>  2
      c =>  NIL
      (multiple-value-setq (a b) (values 4 5 6)) =>  4
      a =>  4
      b =>  5

See Also::
..........

*note setq:: , *note symbol-macrolet::


File: gcl.info,  Node: values,  Next: values-list,  Prev: multiple-value-setq,  Up: Data and Control Flow Dictionary

5.3.53 values [Accessor]
------------------------

'values' &rest object => {object}*

   (setf (' values' &rest place) new-values)

Arguments and Values::
......................

object--an object.

   place--a place.

   new-value--an object.

Description::
.............

values returns the objects as multiple values_2.

   setf of values is used to store the multiple values_2 new-values into
the places.  See *note VALUES Forms as Places::.

Examples::
..........

      (values) =>  <no values>
      (values 1) =>  1
      (values 1 2) =>  1, 2
      (values 1 2 3) =>  1, 2, 3
      (values (values 1 2 3) 4 5) =>  1, 4, 5
      (defun polar (x y)
        (values (sqrt (+ (* x x) (* y y))) (atan y x))) =>  POLAR
      (multiple-value-bind (r theta) (polar 3.0 4.0)
        (vector r theta))
     =>  #(5.0 0.927295)

   Sometimes it is desirable to indicate explicitly that a function
returns exactly one value.  For example, the function

      (defun foo (x y)
        (floor (+ x y) y)) =>  FOO

   returns two values because floor returns two values.  It may be that
the second value makes no sense, or that for efficiency reasons it is
desired not to compute the second value.  values is the standard idiom
for indicating that only one value is to be returned:

      (defun foo (x y)
        (values (floor (+ x y) y))) =>  FOO

   This works because values returns exactly one value for each of args;
as for any function call, if any of args produces more than one value,
all but the first are discarded.

See Also::
..........

*note values-list:: , *note multiple-value-bind:: , *note
multiple-values-limit:: , *note Evaluation::

Notes::
.......

Since values is a function, not a macro or special form, it receives as
arguments only the primary values of its argument forms.


File: gcl.info,  Node: values-list,  Next: multiple-values-limit,  Prev: values,  Up: Data and Control Flow Dictionary

5.3.54 values-list [Function]
-----------------------------

'values-list' list => {element}*

Arguments and Values::
......................

list--a list.

   elements--the elements of the list.

Description::
.............

Returns the elements of the list as multiple values_2.

Examples::
..........

      (values-list nil) =>  <no values>
      (values-list '(1)) =>  1
      (values-list '(1 2)) =>  1, 2
      (values-list '(1 2 3)) =>  1, 2, 3

Exceptional Situations::
........................

Should signal type-error if its argument is not a proper list.

See Also::
..........

*note multiple-value-bind:: , *note multiple-value-list:: , *note
multiple-values-limit:: , *note values::

Notes::
.......

      (values-list list) == (apply #'values list)

   (equal x (multiple-value-list (values-list x))) returns true for all
lists x.


File: gcl.info,  Node: multiple-values-limit,  Next: nth-value,  Prev: values-list,  Up: Data and Control Flow Dictionary

5.3.55 multiple-values-limit [Constant Variable]
------------------------------------------------

Constant Value::
................

An integer not smaller than 20, the exact magnitude of which is
implementation-dependent.

Description::
.............

The upper exclusive bound on the number of values that may be returned
from a function,

   bound or assigned by multiple-value-bind or multiple-value-setq, or
passed as a first argument to nth-value.  (If these individual limits
might differ, the minimum value is used.)

See Also::
..........

*note lambda-parameters-limit:: , *note call-arguments-limit::

Notes::
.......

Implementors are encouraged to make this limit as large as possible.


File: gcl.info,  Node: nth-value,  Next: prog,  Prev: multiple-values-limit,  Up: Data and Control Flow Dictionary

5.3.56 nth-value [Macro]
------------------------

'nth-value' n form => object

Arguments and Values::
......................

n--a non-negative integer; evaluated.

   form--a form; evaluated as described below.

   object--an object.

Description::
.............

Evaluates n and then form, returning as its only value the nth value
yielded by form, or nil if n is greater than or equal to the number of
values returned by form.  (The first returned value is numbered 0.)

Examples::
..........

      (nth-value 0 (values 'a 'b)) =>  A
      (nth-value 1 (values 'a 'b)) =>  B
      (nth-value 2 (values 'a 'b)) =>  NIL
      (let* ((x 83927472397238947423879243432432432)
             (y 32423489732)
             (a (nth-value 1 (floor x y)))
             (b (mod x y)))
        (values a b (= a b)))
     =>  3332987528, 3332987528, true

See Also::
..........

*note multiple-value-list:: , *note nth::

Notes::
.......

Operationally, the following relationship is true, although nth-value
might be more efficient in some implementations because, for example,
some consing might be avoided.

      (nth-value n form) == (nth n (multiple-value-list form))


File: gcl.info,  Node: prog,  Next: prog1,  Prev: nth-value,  Up: Data and Control Flow Dictionary

5.3.57 prog, prog* [Macro]
--------------------------

'prog' ({var | (var [init-form])}*) {declaration}* {tag | statement}*
=> {result}*

   'prog*' ({var | (var [init-form])}*) {declaration}* {tag |
statement}*
=> {result}*

Arguments and Values::
......................

var--variable name.

   init-form--a form.

   declaration--a declare expression; not evaluated.

   tag--a go tag; not evaluated.

   statement--a compound form; evaluated as described below.

   results--nil if a normal return occurs, or else, if an explicit
return occurs, the values that were transferred.

Description::
.............

Three distinct operations are performed by prog and prog*: they bind
local variables, they permit use of the return statement, and they
permit use of the go statement.  A typical prog looks like this:

      (prog (var1 var2 (var3 init-form-3) var4 (var5 init-form-5))
            {declaration}*
            statement1
       tag1
            statement2
            statement3
            statement4
       tag2
            statement5
            ...
            )

   For prog, init-forms are evaluated first, in the order in which they
are supplied.  The vars are then bound to the corresponding values in
parallel.  If no init-form is supplied for a given var, that var is
bound to nil.

   The body of prog is executed as if it were a tagbody form; the go
statement can be used to transfer control to a tag.  Tags label
statements.

   prog implicitly establishes a block named nil around the entire prog
form, so that return can be used at any time to exit from the prog form.

   The difference between prog* and prog is that in prog* the binding
and initialization of the vars is done sequentially, so that the
init-form for each one can use the values of previous ones.

Examples::
..........

     (prog* ((y z) (x (car y)))
            (return x))

   returns the car of the value of z.

      (setq a 1) =>  1
      (prog ((a 2) (b a)) (return (if (= a b) '= '/=))) =>  /=
      (prog* ((a 2) (b a)) (return (if (= a b) '= '/=))) =>  =
      (prog () 'no-return-value) =>  NIL

      (defun king-of-confusion (w)
        "Take a cons of two lists and make a list of conses.
         Think of this function as being like a zipper."
        (prog (x y z)          ;Initialize x, y, z to NIL
             (setq y (car w) z (cdr w))
         loop
             (cond ((null y) (return x))
                   ((null z) (go err)))
         rejoin
             (setq x (cons (cons (car y) (car z)) x))
             (setq y (cdr y) z (cdr z))
             (go loop)
         err
             (cerror "Will self-pair extraneous items"
                     "Mismatch - gleep!  ~S" y)
             (setq z y)
             (go rejoin))) =>  KING-OF-CONFUSION

   This can be accomplished more perspicuously as follows:

      (defun prince-of-clarity (w)
        "Take a cons of two lists and make a list of conses.
         Think of this function as being like a zipper."
        (do ((y (car w) (cdr y))
             (z (cdr w) (cdr z))
             (x '() (cons (cons (car y) (car z)) x)))
            ((null y) x)
          (when (null z)
            (cerror "Will self-pair extraneous items"
                   "Mismatch - gleep!  ~S" y)
            (setq z y)))) =>  PRINCE-OF-CLARITY

See Also::
..........

*note block:: , *note let:: , *note tagbody:: , *note go:: , *note
return:: , *note Evaluation::

Notes::
.......

prog can be explained in terms of block, let, and tagbody as follows:

      (prog variable-list declaration . body)
         == (block nil (let variable-list declaration (tagbody . body)))


File: gcl.info,  Node: prog1,  Next: progn,  Prev: prog,  Up: Data and Control Flow Dictionary

5.3.58 prog1, prog2 [Macro]
---------------------------

'prog' 1 => first-form {form}* result-1 'prog' 2 => first-form
second-form {form}* result-2

Arguments and Values::
......................

first-form--a form; evaluated as described below.

   second-form--a form; evaluated as described below.

   forms--an implicit progn; evaluated as described below.

   result-1--the primary value resulting from the evaluation of
first-form.

   result-2--the primary value resulting from the evaluation of
second-form.

Description::
.............

prog1 evaluates first-form and then forms, yielding as its only value
the primary value yielded by first-form.

   prog2 evaluates first-form, then second-form, and then forms,
yielding as its only value the primary value yielded by first-form.

Examples::
..........

      (setq temp 1) =>  1
      (prog1 temp (print temp) (incf temp) (print temp))
      |>  1
      |>  2
     =>  1
      (prog1 temp (setq temp nil)) =>  2
      temp =>  NIL
      (prog1 (values 1 2 3) 4) =>  1
      (setq temp (list 'a 'b 'c))
      (prog1 (car temp) (setf (car temp) 'alpha)) =>  A
      temp =>  (ALPHA B C)
      (flet ((swap-symbol-values (x y)
               (setf (symbol-value x)
                     (prog1 (symbol-value y)
                            (setf (symbol-value y) (symbol-value x))))))
        (let ((*foo* 1) (*bar* 2))
          (declare (special *foo* *bar*))
          (swap-symbol-values '*foo* '*bar*)
          (values *foo* *bar*)))
     =>  2, 1
      (setq temp 1) =>  1
      (prog2 (incf temp) (incf temp) (incf temp)) =>  3
      temp =>  4
      (prog2 1 (values 2 3 4) 5) =>  2

See Also::
..........

*note multiple-value-prog1:: , *note progn::

Notes::
.......

prog1 and prog2 are typically used to evaluate one or more forms with
side effects and return a value that must be computed before some or all
of the side effects happen.

      (prog1 {form}*) == (values (multiple-value-prog1 {form}*))
      (prog2 form1 {form}*) == (let () form1 (prog1 {form}*))


File: gcl.info,  Node: progn,  Next: define-modify-macro,  Prev: prog1,  Up: Data and Control Flow Dictionary

5.3.59 progn [Special Operator]
-------------------------------

'progn' {form}* => {result}*

Arguments and Values::
......................

forms--an implicit progn.

   results--the values of the forms.

Description::
.............

progn evaluates forms, in the order in which they are given.

   The values of each form but the last are discarded.

   If progn appears as a top level form, then all forms within that
progn are considered by the compiler to be top level forms.

Examples::
..........

      (progn) =>  NIL
      (progn 1 2 3) =>  3
      (progn (values 1 2 3)) =>  1, 2, 3
      (setq a 1) =>  1
      (if a
           (progn (setq a nil) 'here)
           (progn (setq a t) 'there)) =>  HERE
      a =>  NIL

See Also::
..........

*note prog1:: , prog2, *note Evaluation::

Notes::
.......

Many places in Common Lisp involve syntax that uses implicit progns.
That is, part of their syntax allows many forms to be written that are
to be evaluated sequentially, discarding the results of all forms but
the last and returning the results of the last form.  Such places
include, but are not limited to, the following: the body of a lambda
expression; the bodies of various control and conditional forms (e.g.,
case, catch, progn, and when).


File: gcl.info,  Node: define-modify-macro,  Next: defsetf,  Prev: progn,  Up: Data and Control Flow Dictionary

5.3.60 define-modify-macro [Macro]
----------------------------------

'define-modify-macro' name lambda-list function [documentation] => name

Arguments and Values::
......................

name--a symbol.

   lambda-list--a define-modify-macro lambda list

   function--a symbol.

   documentation--a string; not evaluated.

Description::
.............

define-modify-macro defines a macro named name to read and write a
place.

   The arguments to the new macro are a place, followed by the arguments
that are supplied in lambda-list.

   Macros defined with define-modify-macro correctly pass the
environment parameter to

   get-setf-expansion.

   When the macro is invoked, function is applied to the old contents of
the place and the lambda-list arguments to obtain the new value, and the
place is updated to contain the result.

   Except for the issue of avoiding multiple evaluation (see below), the
expansion of a define-modify-macro is equivalent to the following:

      (defmacro name (reference . lambda-list)
        documentation
        `(setf ,reference
               (function ,reference ,arg1 ,arg2 ...)))

   where arg1, arg2, ..., are the parameters appearing in lambda-list;
appropriate provision is made for a rest parameter.

   The subforms of the macro calls defined by define-modify-macro are
evaluated as specified in *note Evaluation of Subforms to Places::.

   Documentation is attached as a documentation string to name (as kind
function) and to the macro function.

   If a define-modify-macro form appears as a top level form, the
compiler must store the macro definition at compile time, so that
occurrences of the macro later on in the file can be expanded correctly.

Examples::
..........

      (define-modify-macro appendf (&rest args)
         append "Append onto list") =>  APPENDF
      (setq x '(a b c) y x) =>  (A B C)
      (appendf x '(d e f) '(1 2 3)) =>  (A B C D E F 1 2 3)
      x =>  (A B C D E F 1 2 3)
      y =>  (A B C)
      (define-modify-macro new-incf (&optional (delta 1)) +)
      (define-modify-macro unionf (other-set &rest keywords) union)

Side Effects::
..............

A macro definition is assigned to name.

See Also::
..........

*note defsetf:: ,

   *note define-setf-expander:: ,

   *note documentation:: , *note Syntactic Interaction of Documentation
Strings and Declarations::


File: gcl.info,  Node: defsetf,  Next: define-setf-expander,  Prev: define-modify-macro,  Up: Data and Control Flow Dictionary

5.3.61 defsetf [Macro]
----------------------

The "short form":

   'defsetf' access-fn update-fn [documentation]
=> access-fn

   The "long form":

   'defsetf' access-fn lambda-list ({store-variable}*) [[{declaration}*
| documentation]] {form}*
=> access-fn

Arguments and Values::
......................

access-fn--a symbol which names a function or a macro.

   update-fn--a symbol naming a function or macro.

   lambda-list--a defsetf lambda list.

   store-variable--a symbol (a variable name).

   declaration--a declare expression; not evaluated.

   documentation--a string; not evaluated.

   form--a form.

Description::
.............

defsetf defines how to setf a place of the form (access-fn ...) for
relatively simple cases.  (See define-setf-expander for more general
access to this facility.)

   It must be the case that the function or macro named by access-fn
evaluates all of its arguments.

   defsetf may take one of two forms, called the "short form" and the
"long form," which are distinguished by the type of the second argument.

   When the short form is used, update-fn must name a function (or
macro) that takes one more argument than access-fn takes.  When setf is
given a place that is a call on access-fn, it expands into a call on
update-fn that is given all the arguments to access-fn and also, as its
last argument, the new value (which must be returned by update-fn as its
value).

   The long form defsetf resembles defmacro.  The lambda-list describes
the arguments of access-fn.  The store-variables describe the value

   or values

   to be stored into the place.  The body must compute the expansion of
a setf of a call on access-fn.

   The expansion function is defined in the same lexical environment in
which the defsetf form appears.

   During the evaluation of the forms, the variables in the lambda-list
and the store-variables are bound to names of temporary variables,
generated as if by gensym or gentemp, that will be bound by the
expansion of setf to the values of those subforms.  This binding permits
the forms to be written without regard for order-of-evaluation issues.
defsetf arranges for the temporary variables to be optimized out of the
final result in cases where that is possible.

   The body code in defsetf is implicitly enclosed in a block whose name
is access-fn

   defsetf ensures that subforms of the place are evaluated exactly
once.

   Documentation is attached to access-fn as a documentation string of
kind setf.

   If a defsetf form appears as a top level form, the compiler must make
the setf expander available so that it may be used to expand calls to
setf later on in the file.  Users must ensure that the forms, if any,
can be evaluated at compile time if the access-fn is used in a place
later in the same file.  The compiler must make these setf expanders
available to compile-time calls to get-setf-expansion when its
environment argument is a value received as the environment parameter of
a macro.

Examples::
..........

The effect of

      (defsetf symbol-value set)

   is built into the Common Lisp system.  This causes the form (setf
(symbol-value foo) fu) to expand into (set foo fu).

   Note that

      (defsetf car rplaca)

   would be incorrect because rplaca does not return its last argument.

      (defun middleguy (x) (nth (truncate (1- (list-length x)) 2) x)) =>  MIDDLEGUY
      (defun set-middleguy (x v)
         (unless (null x)
           (rplaca (nthcdr (truncate (1- (list-length x)) 2) x) v))
         v) =>  SET-MIDDLEGUY
      (defsetf middleguy set-middleguy) =>  MIDDLEGUY
      (setq a (list 'a 'b 'c 'd)
            b (list 'x)
            c (list 1 2 3 (list 4 5 6) 7 8 9)) =>  (1 2 3 (4 5 6) 7 8 9)
      (setf (middleguy a) 3) =>  3
      (setf (middleguy b) 7) =>  7
      (setf (middleguy (middleguy c)) 'middleguy-symbol) =>  MIDDLEGUY-SYMBOL
      a =>  (A 3 C D)
      b =>  (7)
      c =>  (1 2 3 (4 MIDDLEGUY-SYMBOL 6) 7 8 9)

   An example of the use of the long form of defsetf:

      (defsetf subseq (sequence start &optional end) (new-sequence)
        `(progn (replace ,sequence ,new-sequence
                         :start1 ,start :end1 ,end)
                ,new-sequence)) =>  SUBSEQ

      (defvar *xy* (make-array '(10 10)))
      (defun xy (&key ((x x) 0) ((y y) 0)) (aref *xy* x y)) =>  XY
      (defun set-xy (new-value &key ((x x) 0) ((y y) 0))
        (setf (aref *xy* x y) new-value)) =>  SET-XY
      (defsetf xy (&key ((x x) 0) ((y y) 0)) (store)
        `(set-xy ,store 'x ,x 'y ,y)) =>  XY
      (get-setf-expansion '(xy a b))
     =>  (#:t0 #:t1),
        (a b),
        (#:store),
        ((lambda (&key ((x #:x)) ((y #:y)))
           (set-xy #:store 'x #:x 'y #:y))
         #:t0 #:t1),
        (xy #:t0 #:t1)
      (xy 'x 1) =>  NIL
      (setf (xy 'x 1) 1) =>  1
      (xy 'x 1) =>  1
      (let ((a 'x) (b 'y))
        (setf (xy a 1 b 2) 3)
        (setf (xy b 5 a 9) 14))
     =>  14
      (xy 'y 0 'x 1) =>  1
      (xy 'x 1 'y 2) =>  3

See Also::
..........

*note documentation:: , *note setf:: ,

   *note define-setf-expander:: , *note get-setf-expansion:: ,

   *note Generalized Reference::, *note Syntactic Interaction of
Documentation Strings and Declarations::

Notes::
.......

forms must include provision for returning the correct value (the value

   or values

   of store-variable).  This is handled by forms rather than by defsetf
because in many cases this value can be returned at no extra cost, by
calling a function that simultaneously stores into the place and returns
the correct value.

   A setf of a call on access-fn also evaluates all of access-fn's
arguments; it cannot treat any of them specially.  This means that
defsetf cannot be used to describe how to store into a generalized
reference to a byte, such as (ldb field reference).

   define-setf-expander

   is used to handle situations that do not fit the restrictions imposed
by defsetf and gives the user additional control.


File: gcl.info,  Node: define-setf-expander,  Next: get-setf-expansion,  Prev: defsetf,  Up: Data and Control Flow Dictionary

5.3.62 define-setf-expander [Macro]
-----------------------------------

'define-setf-expander' access-fn lambda-list [[{declaration}* |
documentation]] {form}*
=> access-fn

Arguments and Values::
......................

access-fn--a symbol that names a function or macro.

   lambda-list - macro lambda list.

   declaration--a declare expression; not evaluated.

   documentation--a string; not evaluated.

   forms--an implicit progn.

Description::
.............

define-setf-expander specifies the means by which setf updates a place
that is referenced by access-fn.

   When setf is given a place that is specified in terms of access-fn
and a new value for the place, it is expanded into a form that performs
the appropriate update.

   The lambda-list supports destructuring.  See *note Macro Lambda
Lists::.

   Documentation is attached to access-fn as a documentation string of
kind setf.

   Forms constitute the body of the

   setf expander

   definition and must compute the setf expansion for a call on setf
that references the place by means of the given access-fn.

   The setf expander function is defined in the same lexical environment
in which the define-setf-expander form appears.

   While forms are being executed, the variables in lambda-list are
bound to parts of the place form.

   The body forms (but not the lambda-list)

   in a define-setf-expander form are implicitly enclosed in a block
whose name is access-fn.

   The evaluation of forms must result in the five values described in
*note Setf Expansions::.

   If a define-setf-expander form appears as a top level form, the
compiler must make the setf expander available so that it may be used to
expand calls to setf later on in the file.  Programmers must ensure that
the forms can be evaluated at compile time if the access-fn is used in a
place later in the same file.  The compiler must make these setf
expanders available to compile-time calls to get-setf-expansion when its
environment argument is a value received as the environment parameter of
a macro.

Examples::
..........

      (defun lastguy (x) (car (last x))) =>  LASTGUY
      (define-setf-expander lastguy (x &environment env)
        "Set the last element in a list to the given value."
        (multiple-value-bind (dummies vals newval setter getter)
            (get-setf-expansion x env)
          (let ((store (gensym)))
            (values dummies
                    vals
                    `(,store)
                    `(progn (rplaca (last ,getter) ,store) ,store)
                    `(lastguy ,getter))))) =>  LASTGUY
      (setq a (list 'a 'b 'c 'd)
            b (list 'x)
            c (list 1 2 3 (list 4 5 6))) =>  (1 2 3 (4 5 6))
      (setf (lastguy a) 3) =>  3
      (setf (lastguy b) 7) =>  7
      (setf (lastguy (lastguy c)) 'lastguy-symbol) =>  LASTGUY-SYMBOL
      a =>  (A B C 3)
      b =>  (7)
      c =>  (1 2 3 (4 5 LASTGUY-SYMBOL))

     ;;; Setf expander for the form (LDB bytespec int).
     ;;; Recall that the int form must itself be suitable for SETF.
      (define-setf-expander ldb (bytespec int &environment env)
        (multiple-value-bind (temps vals stores
                               store-form access-form)
            (get-setf-expansion int env);Get setf expansion for int.
          (let ((btemp (gensym))     ;Temp var for byte specifier.
                (store (gensym))     ;Temp var for byte to store.
                (stemp (first stores))) ;Temp var for int to store.
            (if (cdr stores) (error "Can't expand this."))
     ;;; Return the setf expansion for LDB as five values.
            (values (cons btemp temps)       ;Temporary variables.
                    (cons bytespec vals)     ;Value forms.
                    (list store)             ;Store variables.
                    `(let ((,stemp (dpb ,store ,btemp ,access-form)))
                       ,store-form
                       ,store)               ;Storing form.
                    `(ldb ,btemp ,access-form) ;Accessing form.
                   ))))

See Also::
..........

*note setf:: , *note defsetf:: , *note documentation:: , *note
get-setf-expansion:: , *note Syntactic Interaction of Documentation
Strings and Declarations::

Notes::
.......

define-setf-expander differs from the long form of defsetf in that while
the body is being executed the variables in lambda-list are bound to
parts of the place form, not to temporary variables that will be bound
to the values of such parts.  In addition, define-setf-expander does not
have defsetf's restriction that access-fn must be a function or a
function-like macro; an arbitrary defmacro destructuring pattern is
permitted in lambda-list.


File: gcl.info,  Node: get-setf-expansion,  Next: setf,  Prev: define-setf-expander,  Up: Data and Control Flow Dictionary

5.3.63 get-setf-expansion [Function]
------------------------------------

'get-setf-expansion' place &optional environment
=> vars, vals, store-vars, writer-form, reader-form

Arguments and Values::
......................

place--a place.

   environment--an environment object.

   vars, vals, store-vars, writer-form, reader-form--a setf expansion.

Description::
.............

Determines five values constituting the setf expansion for place in
environment; see *note Setf Expansions::.

   If environment is not supplied or nil, the environment is the null
lexical environment.

Examples::
..........

      (get-setf-expansion 'x)
     =>  NIL, NIL, (#:G0001), (SETQ X #:G0001), X

     ;;; This macro is like POP

      (defmacro xpop (place &environment env)
        (multiple-value-bind (dummies vals new setter getter)
                             (get-setf-expansion place env)
           `(let* (,@(mapcar #'list dummies vals) (,(car new) ,getter))
              (if (cdr new) (error "Can't expand this."))
              (prog1 (car ,(car new))
                     (setq ,(car new) (cdr ,(car new)))
                     ,setter))))

      (defsetf frob (x) (value)
          `(setf (car ,x) ,value)) =>  FROB
     ;;; The following is an error; an error might be signaled at macro expansion time
      (flet ((frob (x) (cdr x)))  ;Invalid
        (xpop (frob z)))


See Also::
..........

*note defsetf:: , *note define-setf-expander:: , *note setf::

Notes::
.......

Any compound form is a valid place, since any compound form whose
operator f has no setf expander are expanded into a call to (setf f).


File: gcl.info,  Node: setf,  Next: shiftf,  Prev: get-setf-expansion,  Up: Data and Control Flow Dictionary

5.3.64 setf, psetf [Macro]
--------------------------

'setf' {!pair}* => {result}*

   'psetf' {!pair}* => nil

   pair ::=place newvalue

Arguments and Values::
......................

place--a place.

   newvalue--a form.

   results--the multiple values_2 returned by the storing form for the
last place, or nil if there are no pairs.

Description::
.............

setf changes the value of place to be newvalue.

   (setf place newvalue) expands into an update form that stores the
result of evaluating newvalue into the location referred to by place.
Some place forms involve uses of accessors that take optional arguments.
Whether those optional arguments are permitted by setf, or what their
use is, is up to the setf expander function and is not under the control
of setf.  The documentation for any function that accepts &optional,
&rest, or &key arguments and that claims to be usable with setf must
specify how those arguments are treated.

   If more than one pair is supplied, the pairs are processed
sequentially; that is,

      (setf place-1 newvalue-1
            place-2 newvalue-2
            ...
            place-N newvalue-N)

   is precisely equivalent to

      (progn (setf place-1 newvalue-1)
             (setf place-2 newvalue-2)
             ...
             (setf place-N newvalue-N))

   For psetf, if more than one pair is supplied then the assignments of
new values to places are done in parallel.  More precisely, all subforms
(in both the place and newvalue forms) that are to be evaluated are
evaluated from left to right; after all evaluations have been performed,
all of the assignments are performed in an unpredictable order.

   For detailed treatment of the expansion of setf and psetf, see *note
Kinds of Places::.

Examples::
..........

      (setq x (cons 'a 'b) y (list 1 2 3)) =>  (1 2 3)
      (setf (car x) 'x (cadr y) (car x) (cdr x) y) =>  (1 X 3)
      x =>  (X 1 X 3)
      y =>  (1 X 3)
      (setq x (cons 'a 'b) y (list 1 2 3)) =>  (1 2 3)
      (psetf (car x) 'x (cadr y) (car x) (cdr x) y) =>  NIL
      x =>  (X 1 A 3)
      y =>  (1 A 3)

Affected By::
.............

define-setf-expander, defsetf, *macroexpand-hook*

See Also::
..........

*note define-setf-expander:: , *note defsetf:: , macroexpand-1, *note
rotatef:: , *note shiftf:: , *note Generalized Reference::


File: gcl.info,  Node: shiftf,  Next: rotatef,  Prev: setf,  Up: Data and Control Flow Dictionary

5.3.65 shiftf [Macro]
---------------------

'shiftf' {place}^+ newvalue => old-value-1

Arguments and Values::
......................

place--a place.

   newvalue--a form; evaluated.

   old-value-1--an object (the old value of the first place).

Description::
.............

shiftf modifies the values of each place by storing newvalue into the
last place, and shifting the values of the second through the last place
into the remaining places.

   If newvalue produces more values than there are store variables, the
extra values are ignored.  If newvalue produces fewer values than there
are store variables, the missing values are set to nil.

   In the form (shiftf place1 place2 ... placen newvalue), the values in
place1 through placen are read and saved, and newvalue is evaluated, for
a total of n+1 values in all.  Values 2 through n+1 are then stored into
place1 through placen, respectively.  It is as if all the places form a
shift register; the newvalue is shifted in from the right, all values
shift over to the left one place, and the value shifted out of place1 is
returned.

   For information about the evaluation of subforms of places, see *note
Evaluation of Subforms to Places::.

Examples::
..........

      (setq x (list 1 2 3) y 'trash) =>  TRASH
      (shiftf y x (cdr x) '(hi there)) =>  TRASH
      x =>  (2 3)
      y =>  (1 HI THERE)

      (setq x (list 'a 'b 'c)) =>  (A B C)
      (shiftf (cadr x) 'z) =>  B
      x =>  (A Z C)
      (shiftf (cadr x) (cddr x) 'q) =>  Z
      x =>  (A (C) . Q)
      (setq n 0) =>  0
      (setq x (list 'a 'b 'c 'd)) =>  (A B C D)
      (shiftf (nth (setq n (+ n 1)) x) 'z) =>  B
      x =>  (A Z C D)

Affected By::
.............

define-setf-expander, defsetf, *macroexpand-hook*

See Also::
..........

*note setf:: , *note rotatef:: , *note Generalized Reference::

Notes::
.......

The effect of (shiftf place1 place2 ... placen newvalue) is roughly
equivalent to

      (let ((var1 place1)
            (var2 place2)
            ...
            (varn placen)
            (var0 newvalue))
        (setf place1 var2)
        (setf place2 var3)
        ...
        (setf placen var0)
        var1)

   except that the latter would evaluate any subforms of each place
twice, whereas shiftf evaluates them once.  For example,

      (setq n 0) =>  0
      (setq x (list 'a 'b 'c 'd)) =>  (A B C D)
      (prog1 (nth (setq n (+ n 1)) x)
             (setf (nth (setq n (+ n 1)) x) 'z)) =>  B
      x =>  (A B Z D)


File: gcl.info,  Node: rotatef,  Next: control-error,  Prev: shiftf,  Up: Data and Control Flow Dictionary

5.3.66 rotatef [Macro]
----------------------

'rotatef' {place}* => nil

Arguments and Values::
......................

place--a place.

Description::
.............

rotatef modifies the values of each place by rotating values from one
place into another.

   If a place produces more values than there are store variables, the
extra values are ignored.  If a place produces fewer values than there
are store variables, the missing values are set to nil.

   In the form (rotatef place1 place2 ... placen), the values in place1
through placen are read and written.  Values 2 through n and value 1 are
then stored into place1 through placen.  It is as if all the places form
an end-around shift register that is rotated one place to the left, with
the value of place1 being shifted around the end to placen.

   For information about the evaluation of subforms of places, see *note
Evaluation of Subforms to Places::.

Examples::
..........

      (let ((n 0)
             (x (list 'a 'b 'c 'd 'e 'f 'g)))
         (rotatef (nth (incf n) x)
                  (nth (incf n) x)
                  (nth (incf n) x))
         x) =>  (A C D B E F G)

See Also::
..........

*note define-setf-expander:: , *note defsetf:: , *note setf:: , *note
shiftf:: , *macroexpand-hook*, *note Generalized Reference::

Notes::
.......

The effect of (rotatef place1 place2 ... placen) is roughly equivalent
to

      (psetf place1 place2
             place2 place3
             ...
             placen place1)

   except that the latter would evaluate any subforms of each place
twice, whereas rotatef evaluates them once.


File: gcl.info,  Node: control-error,  Next: program-error,  Prev: rotatef,  Up: Data and Control Flow Dictionary

5.3.67 control-error [Condition Type]
-------------------------------------

Class Precedence List::
.......................

control-error, error, serious-condition, condition, t

Description::
.............

The type control-error consists of error conditions that result from
invalid dynamic transfers of control in a program.  The errors that
result from giving throw a tag that is not active or from giving go or
return-from a tag that is no longer dynamically available are of type
control-error.


File: gcl.info,  Node: program-error,  Next: undefined-function,  Prev: control-error,  Up: Data and Control Flow Dictionary

5.3.68 program-error [Condition Type]
-------------------------------------

Class Precedence List::
.......................

program-error, error, serious-condition, condition, t

Description::
.............

The type program-error consists of error conditions related to incorrect
program syntax.  The errors that result from naming a go tag or a block
tag that is not lexically apparent are of type program-error.


File: gcl.info,  Node: undefined-function,  Prev: program-error,  Up: Data and Control Flow Dictionary

5.3.69 undefined-function [Condition Type]
------------------------------------------

Class Precedence List::
.......................

undefined-function, cell-error, error, serious-condition, condition, t

Description::
.............

The type undefined-function consists of error conditions that represent
attempts to read the definition of an undefined function.

   The name of the cell (see cell-error) is the function name which was
funbound.

See Also::
..........

*note cell-error-name::


File: gcl.info,  Node: Iteration,  Next: Objects,  Prev: Data and Control Flow,  Up: Top

6 Iteration
***********

* Menu:

* The LOOP Facility::
* Iteration Dictionary::


File: gcl.info,  Node: The LOOP Facility,  Next: Iteration Dictionary,  Prev: Iteration,  Up: Iteration

6.1 The LOOP Facility
=====================

* Menu:

* Overview of the Loop Facility::
* Variable Initialization and Stepping Clauses::
* Value Accumulation Clauses::
* Termination Test Clauses::
* Unconditional Execution Clauses::
* Conditional Execution Clauses::
* Miscellaneous Clauses::
* Examples of Miscellaneous Loop Features::
* Notes about Loop::


File: gcl.info,  Node: Overview of the Loop Facility,  Next: Variable Initialization and Stepping Clauses,  Prev: The LOOP Facility,  Up: The LOOP Facility

6.1.1 Overview of the Loop Facility
-----------------------------------

The loop macro performs iteration.

* Menu:

* Simple vs Extended Loop::
* Simple Loop::
* Extended Loop::
* Loop Keywords::
* Parsing Loop Clauses::
* Expanding Loop Forms::
* Summary of Loop Clauses::
* Summary of Variable Initialization and Stepping Clauses::
* Summary of Value Accumulation Clauses::
* Summary of Termination Test Clauses::
* Summary of Unconditional Execution Clauses::
* Summary of Conditional Execution Clauses::
* Summary of Miscellaneous Clauses::
* Order of Execution::
* Destructuring::
* Restrictions on Side-Effects::


File: gcl.info,  Node: Simple vs Extended Loop,  Next: Simple Loop,  Prev: Overview of the Loop Facility,  Up: Overview of the Loop Facility

6.1.1.1 Simple vs Extended Loop
...............................

loop forms are partitioned into two categories: simple loop forms and
extended loop forms.


File: gcl.info,  Node: Simple Loop,  Next: Extended Loop,  Prev: Simple vs Extended Loop,  Up: Overview of the Loop Facility

6.1.1.2 Simple Loop
...................

A simple loop form is one that has a body containing only compound
forms.  Each form is evaluated in turn from left to right.  When the
last form has been evaluated, then the first form is evaluated again,
and so on, in a never-ending cycle.  A simple loop form establishes an
implicit block named nil.  The execution of a simple loop can be
terminated by explicitly transfering control to the implicit block
(using return or return-from) or to some exit point outside of the block
(e.g., using throw, go, or return-from).


File: gcl.info,  Node: Extended Loop,  Next: Loop Keywords,  Prev: Simple Loop,  Up: Overview of the Loop Facility

6.1.1.3 Extended Loop
.....................

An extended loop form is one that has a body containing atomic
expressions.  When the loop macro processes such a form, it invokes a
facility that is commonly called "the Loop Facility."

   The Loop Facility provides standardized access to mechanisms commonly
used in iterations through Loop schemas, which are introduced by loop
keywords.

   The body of an extended loop form is divided into loop clauses, each
which is in turn made up of loop keywords and forms.


File: gcl.info,  Node: Loop Keywords,  Next: Parsing Loop Clauses,  Prev: Extended Loop,  Up: Overview of the Loop Facility

6.1.1.4 Loop Keywords
.....................

Loop keywords are not true keywords_1; they are special symbols,
recognized by name rather than object identity, that are meaningful only
to the loop facility.  A loop keyword is a symbol but is recognized by
its name (not its identity), regardless of the packages in which it is
accessible.

   In general, loop keywords are not external symbols of the COMMON-LISP
package, except in the coincidental situation that a symbol with the
same name as a loop keyword was needed for some other purpose in Common
Lisp.  For example, there is a symbol in the COMMON-LISP package whose
name is "UNLESS" but not one whose name is "UNTIL".

   If no loop keywords are supplied in a loop form, the Loop Facility
executes the loop body repeatedly; see *note Simple Loop::.


File: gcl.info,  Node: Parsing Loop Clauses,  Next: Expanding Loop Forms,  Prev: Loop Keywords,  Up: Overview of the Loop Facility

6.1.1.5 Parsing Loop Clauses
............................

The syntactic parts of an extended loop form are called clauses; the
rules for parsing are determined by that clause's keyword.  The
following example shows a loop form with six clauses:

      (loop for i from 1 to (compute-top-value)       ; first clause
            while (not (unacceptable i))              ; second clause
            collect (square i)                        ; third clause
            do (format t "Working on ~D now" i)       ; fourth clause
            when (evenp i)                            ; fifth clause
              do (format t "~D is a non-odd number" i)
            finally (format t "About to exit!"))      ; sixth clause

   Each loop keyword introduces either a compound loop clause or a
simple loop clause that can consist of a loop keyword followed by a
single form.  The number of forms in a clause is determined by the loop
keyword that begins the clause and by the auxiliary keywords in the
clause.  The keywords do,

   doing,

   initially, and finally are the only loop keywords that can take any
number of forms and group them as an implicit progn.

   Loop clauses can contain auxiliary keywords, which are sometimes
called prepositions.  For example, the first clause in the code above
includes the prepositions from and to, which mark the value from which
stepping begins and the value at which stepping ends.

   For detailed information about loop syntax, see the macro loop.


File: gcl.info,  Node: Expanding Loop Forms,  Next: Summary of Loop Clauses,  Prev: Parsing Loop Clauses,  Up: Overview of the Loop Facility

6.1.1.6 Expanding Loop Forms
............................

A loop macro form expands into a form containing one or more binding
forms (that establish bindings of loop variables) and a block and a
tagbody (that express a looping control structure).  The variables
established in loop are bound as if by let or lambda.

   Implementations can interleave the setting of initial values with the
bindings.  However, the assignment of the initial values is always
calculated in the order specified by the user.  A variable is thus
sometimes bound to a meaningless value of the correct type, and then
later in the prologue it is set to the true initial value by using setq.

   One implication of this interleaving is that it is
implementation-dependent whether the lexical environment in which the
initial value forms (variously called the form1, form2, form3, step-fun,
vector, hash-table, and package) in any for-as-subclause, except
for-as-equals-then, are evaluated includes only the loop variables
preceding that form or includes more or all of the loop variables; the
form1 and form2 in a for-as-equals-then form includes the lexical
environment of all the loop variables.

   After the form is expanded, it consists of three basic parts in the
tagbody: the loop prologue, the loop body, and the loop epilogue.

Loop prologue
     The loop prologue contains forms that are executed before iteration
     begins, such as any automatic variable initializations prescribed
     by the variable clauses, along with any initially clauses in the
     order they appear in the source.

Loop body
     The loop body contains those forms that are executed during
     iteration, including application-specific calculations, termination
     tests, and variable stepping_1.

Loop epilogue
     The loop epilogue contains forms that are executed after iteration
     terminates, such as finally clauses, if any, along with any
     implicit return value from an accumulation clause or an
     termination-test clause.

   Some clauses from the source form contribute code only to the loop
prologue; these clauses must come before other clauses that are in the
main body of the loop form.  Others contribute code only to the loop
epilogue.  All other clauses contribute to the final translated form in
the same order given in the original source form of the loop.

   Expansion of the loop macro produces an implicit block named nil

   unless named is supplied.

   Thus, return-from (and sometimes return) can be used to return values
from loop or to exit loop.


File: gcl.info,  Node: Summary of Loop Clauses,  Next: Summary of Variable Initialization and Stepping Clauses,  Prev: Expanding Loop Forms,  Up: Overview of the Loop Facility

6.1.1.7 Summary of Loop Clauses
...............................

Loop clauses fall into one of the following categories:


File: gcl.info,  Node: Summary of Variable Initialization and Stepping Clauses,  Next: Summary of Value Accumulation Clauses,  Prev: Summary of Loop Clauses,  Up: Overview of the Loop Facility

6.1.1.8 Summary of Variable Initialization and Stepping Clauses
...............................................................

The for and as constructs provide iteration control clauses that
establish a variable to be initialized.  for and as clauses can be
combined with the loop keyword and to get parallel initialization and
stepping_1.  Otherwise, the initialization and stepping_1 are
sequential.

   The with construct is similar to a single let clause.  with clauses
can be combined using the loop keyword and to get parallel
initialization.

   For more information, see *note Variable Initialization and Stepping
Clauses::.


File: gcl.info,  Node: Summary of Value Accumulation Clauses,  Next: Summary of Termination Test Clauses,  Prev: Summary of Variable Initialization and Stepping Clauses,  Up: Overview of the Loop Facility

6.1.1.9 Summary of Value Accumulation Clauses
.............................................

The collect (or collecting) construct takes one form in its clause and
adds the value of that form to the end of a list of values.  By default,
the list of values is returned when the loop finishes.

   The append (or appending) construct takes one form in its clause and
appends the value of that form to the end of a list of values.  By
default, the list of values is returned when the loop finishes.

   The nconc (or nconcing) construct is similar to the append construct,
but its list values are concatenated as if by the function nconc.  By
default, the list of values is returned when the loop finishes.

   The sum (or summing) construct takes one form in its clause that must
evaluate to a number and accumulates the sum of all these numbers.  By
default, the cumulative sum is returned when the loop finishes.

   The count (or counting) construct takes one form in its clause and
counts the number of times that the form evaluates to true.  By default,
the count is returned when the loop finishes.

   The minimize (or minimizing) construct takes one form in its clause
and determines the minimum value obtained by evaluating that form.  By
default, the minimum value is returned when the loop finishes.

   The maximize (or maximizing) construct takes one form in its clause
and determines the maximum value obtained by evaluating that form.  By
default, the maximum value is returned when the loop finishes.

   For more information, see *note Value Accumulation Clauses::.


File: gcl.info,  Node: Summary of Termination Test Clauses,  Next: Summary of Unconditional Execution Clauses,  Prev: Summary of Value Accumulation Clauses,  Up: Overview of the Loop Facility

6.1.1.10 Summary of Termination Test Clauses
............................................

The for and as constructs provide a termination test that is determined
by the iteration control clause.

   The repeat construct causes termination after a specified number of
iterations.  (It uses an internal variable to keep track of the number
of iterations.)

   The while construct takes one form, a test, and terminates the
iteration if the test evaluates to false.  A while clause is equivalent
to the expression (if (not test) (loop-finish)).

   The until construct is the inverse of while; it terminates the
iteration if the test evaluates to any non-nil value.  An until clause
is equivalent to the expression (if test (loop-finish)).

   The always construct takes one form and terminates the loop if the
form ever evaluates to false; in this case, the loop form returns nil.
Otherwise, it provides a default return value of t.

   The never construct takes one form and terminates the loop if the
form ever evaluates to true; in this case, the loop form returns nil.
Otherwise, it provides a default return value of t.

   The thereis construct takes one form and terminates the loop if the
form ever evaluates to a non-nil object; in this case, the loop form
returns that object.

   Otherwise, it provides a default return value of nil.

   If multiple termination test clauses are specified, the loop form
terminates if any are satisfied.

   For more information, see *note Termination Test Clauses::.


File: gcl.info,  Node: Summary of Unconditional Execution Clauses,  Next: Summary of Conditional Execution Clauses,  Prev: Summary of Termination Test Clauses,  Up: Overview of the Loop Facility

6.1.1.11 Summary of Unconditional Execution Clauses
...................................................

The do (or doing) construct evaluates all forms in its clause.

   The return construct takes one

   form.  Any values returned by the form are immediately returned by
the loop form.  It is equivalent to the clause do (return-from
block-name value), where block-name is the name specified in a named
clause, or nil if there is no named clause.

   For more information, see *note Unconditional Execution Clauses::.


File: gcl.info,  Node: Summary of Conditional Execution Clauses,  Next: Summary of Miscellaneous Clauses,  Prev: Summary of Unconditional Execution Clauses,  Up: Overview of the Loop Facility

6.1.1.12 Summary of Conditional Execution Clauses
.................................................

The if and when constructs take one form as a test and a clause that is
executed when the test yields true.  The clause can be a value
accumulation, unconditional, or another conditional clause; it can also
be any combination of such clauses connected by the loop and keyword.

   The loop unless construct is similar to the loop when construct
except that it complements the test result.

   The loop else construct provides an optional component of if, when,
and unless clauses that is executed when an if or when test yields false
or when an unless test yields true.  The component is one of the clauses
described under if.

   The loop end construct provides an optional component to mark the end
of a conditional clause.

   For more information, see *note Conditional Execution Clauses::.


File: gcl.info,  Node: Summary of Miscellaneous Clauses,  Next: Order of Execution,  Prev: Summary of Conditional Execution Clauses,  Up: Overview of the Loop Facility

6.1.1.13 Summary of Miscellaneous Clauses
.........................................

The loop named construct gives a name for the block of the loop.

   The loop initially construct causes its forms to be evaluated in the
loop prologue, which precedes all loop code except for initial settings
supplied by the constructs with, for, or as.

   The loop finally construct causes its forms to be evaluated in the
loop epilogue after normal iteration terminates.

   For more information, see *note Miscellaneous Clauses::.


File: gcl.info,  Node: Order of Execution,  Next: Destructuring,  Prev: Summary of Miscellaneous Clauses,  Up: Overview of the Loop Facility

6.1.1.14 Order of Execution
...........................

With the exceptions listed below, clauses are executed in the loop body
in the order in which they appear in the source.  Execution is repeated
until a clause terminates the loop or until a return, go, or throw form
is encountered which transfers control to a point outside of the loop.
The following actions are exceptions to the linear order of execution:

*
     All variables are initialized first, regardless of where the
     establishing clauses appear in the source.  The order of
     initialization follows the order of these clauses.

*
     The code for any initially clauses is collected into one progn in
     the order in which the clauses appear in the source.  The collected
     code is executed once in the loop prologue after any implicit
     variable initializations.

*
     The code for any finally clauses is collected into one progn in the
     order in which the clauses appear in the source.  The collected
     code is executed once in the loop epilogue before any implicit
     values from the accumulation clauses are returned.  Explicit
     returns anywhere in the source, however, will exit the loop without
     executing the epilogue code.

*
     A with clause introduces a variable binding and an optional initial
     value.  The initial values are calculated in the order in which the
     with clauses occur.

*
     Iteration control clauses implicitly perform the following actions:

     -
          initialize variables;

     -
          step variables, generally between each execution of the loop
          body;

     -
          perform termination tests, generally just before the execution
          of the loop body.


File: gcl.info,  Node: Destructuring,  Next: Restrictions on Side-Effects,  Prev: Order of Execution,  Up: Overview of the Loop Facility

6.1.1.15 Destructuring
......................

The d-type-spec argument is used for destructuring.  If the d-type-spec
argument consists solely of the type fixnum, float, t, or nil, the
of-type keyword is optional.  The of-type construct is optional in these
cases to provide backwards compatibility; thus, the following two
expressions are the same:

     ;;; This expression uses the old syntax for type specifiers.
      (loop for i fixnum upfrom 3 ...)

     ;;; This expression uses the new syntax for type specifiers.
      (loop for i of-type fixnum upfrom 3 ...)

     ;; Declare X and Y to be of type VECTOR and FIXNUM respectively.
      (loop for (x y) of-type (vector fixnum)
            in l do ...)

   A type specifier for a destructuring pattern is a tree of type
specifiers with the same shape as the tree of variable names, with the
following exceptions:

*
     When aligning the trees, an atom in the tree of type specifiers
     that matches a cons in the variable tree declares the same type for
     each variable in the subtree rooted at the cons.

*
     A cons in the tree of type specifiers that matches an atom in the
     tree of variable names is a compound type specifer.

   Destructuring allows binding of a set of variables to a corresponding
set of values anywhere that a value can normally be bound to a single
variable.  During loop expansion, each variable in the variable list is
matched with the values in the values list.  If there are more variables
in the variable list than there are values in the values list, the
remaining variables are given a value of nil.  If there are more values
than variables listed, the extra values are discarded.

   To assign values from a list to the variables a, b, and c, the for
clause could be used to bind the variable numlist to the car of the
supplied form, and then another for clause could be used to bind the
variables a, b, and c sequentially.

     ;; Collect values by using FOR constructs.
      (loop for numlist in '((1 2 4.0) (5 6 8.3) (8 9 10.4))
            for a of-type integer = (first numlist)
            and b of-type integer = (second numlist)
            and c of-type float = (third numlist)
            collect (list c b a))
     =>  ((4.0 2 1) (8.3 6 5) (10.4 9 8))

   Destructuring makes this process easier by allowing the variables to
be bound in each loop iteration.  Types can be declared by using a list
of type-spec arguments.  If all the types are the same, a shorthand
destructuring syntax can be used, as the second example illustrates.

     ;; Destructuring simplifies the process.
      (loop for (a b c) of-type (integer integer float) in
            '((1 2 4.0) (5 6 8.3) (8 9 10.4))
            collect (list c b a))
     =>  ((4.0 2 1) (8.3 6 5) (10.4 9 8))

     ;; If all the types are the same, this way is even simpler.
      (loop for (a b c) of-type float in
            '((1.0 2.0 4.0) (5.0 6.0 8.3) (8.0 9.0 10.4))
            collect (list c b a))
     =>  ((4.0 2.0 1.0) (8.3 6.0 5.0) (10.4 9.0 8.0))

   If destructuring is used to declare or initialize a number of groups
of variables into types, the loop keyword and can be used to simplify
the process further.

     ;; Initialize and declare variables in parallel by using the AND construct.\kern-7pt
      (loop with (a b) of-type float = '(1.0 2.0)
            and (c d) of-type integer = '(3 4)
            and (e f)
            return (list a b c d e f))
     =>  (1.0 2.0 3 4 NIL NIL)

   If nil is used in a destructuring list, no variable is provided for
its place.

      (loop for (a nil b) = '(1 2 3)
            do (return (list a b)))
     =>  (1 3)

   Note that dotted lists can specify destructuring.

      (loop for (x . y) = '(1 . 2)
            do (return y))
     =>  2
      (loop for ((a . b) (c . d)) of-type ((float . float) (integer . integer)) in
            '(((1.2 . 2.4) (3 . 4)) ((3.4 . 4.6) (5 . 6)))
            collect (list a b c d))
     =>  ((1.2 2.4 3 4) (3.4 4.6 5 6))

   An error of type program-error is signaled (at macro expansion time)
if the same variable is bound twice in any variable-binding clause of a
single loop expression.  Such variables include local variables,
iteration control variables, and variables found by destructuring.


File: gcl.info,  Node: Restrictions on Side-Effects,  Prev: Destructuring,  Up: Overview of the Loop Facility

6.1.1.16 Restrictions on Side-Effects
.....................................

See *note Traversal Rules and Side Effects::.


File: gcl.info,  Node: Variable Initialization and Stepping Clauses,  Next: Value Accumulation Clauses,  Prev: Overview of the Loop Facility,  Up: The LOOP Facility

6.1.2 Variable Initialization and Stepping Clauses
--------------------------------------------------

* Menu:

* Iteration Control::
* The for-as-arithmetic subclause::
* Examples of for-as-arithmetic subclause::
* The for-as-in-list subclause::
* Examples of for-as-in-list subclause::
* The for-as-on-list subclause::
* Examples of for-as-on-list subclause::
* The for-as-equals-then subclause::
* Examples of for-as-equals-then subclause::
* The for-as-across subclause::
* Examples of for-as-across subclause::
* The for-as-hash subclause::
* The for-as-package subclause::
* Examples of for-as-package subclause::
* Local Variable Initializations::
* Examples of WITH clause::


File: gcl.info,  Node: Iteration Control,  Next: The for-as-arithmetic subclause,  Prev: Variable Initialization and Stepping Clauses,  Up: Variable Initialization and Stepping Clauses

6.1.2.1 Iteration Control
.........................

Iteration control clauses allow direction of loop iteration.  The loop
keywords for and as designate iteration control clauses.  Iteration
control clauses differ with respect to the specification of termination
tests and to the initialization and stepping_1 of loop variables.
Iteration clauses by themselves do not cause the Loop Facility to return
values, but they can be used in conjunction with value-accumulation
clauses to return values.

   All variables are initialized in the loop prologue.  A variable
binding has lexical scope unless it is proclaimed special; thus, by
default, the variable can be accessed only by forms that lie textually
within the loop.  Stepping assignments are made in the loop body before
any other forms are evaluated in the body.

   The variable argument in iteration control clauses can be a
destructuring list.  A destructuring list is a tree whose non-nil atoms
are variable names.  See *note Destructuring::.

   The iteration control clauses for, as, and repeat must precede any
other loop clauses, except initially, with, and named, since they
establish variable bindings.  When iteration control clauses are used in
a loop, the corresponding termination tests in the loop body are
evaluated before any other loop body code is executed.

   If multiple iteration clauses are used to control iteration, variable
initialization and stepping_1 occur sequentially by default.  The and
construct can be used to connect two or more iteration clauses when
sequential binding and stepping_1 are not necessary.  The iteration
behavior of clauses joined by and is analogous to the behavior of the
macro do with respect to do*.

   The for and as clauses iterate by using one or more local loop
variables that are initialized to some value and that can be modified or
stepped_1 after each iteration.  For these clauses, iteration terminates
when a local variable reaches some supplied value or when some other
loop clause terminates iteration.  At each iteration, variables can be
stepped_1 by an increment or a decrement or can be assigned a new value
by the evaluation of a form).  Destructuring can be used to assign
values to variables during iteration.

   The for and as keywords are synonyms; they can be used
interchangeably.  There are seven syntactic formats for these
constructs.  In each syntactic format, the type of var can be supplied
by the optional type-spec argument.  If var is a destructuring list, the
type supplied by the type-spec argument must appropriately match the
elements of the list.  By convention, for introduces new iterations and
as introduces iterations that depend on a previous iteration
specification.


File: gcl.info,  Node: The for-as-arithmetic subclause,  Next: Examples of for-as-arithmetic subclause,  Prev: Iteration Control,  Up: Variable Initialization and Stepping Clauses

6.1.2.2 The for-as-arithmetic subclause
.......................................

In the for-as-arithmetic subclause, the for or as construct iterates
from the value supplied by form1 to the value supplied by form2 in
increments or decrements denoted by form3.  Each expression is evaluated
only once and must evaluate to a number.  The variable var is bound to
the value of form1 in the first iteration and is stepped_1 by the value
of form3 in each succeeding iteration, or by 1 if form3 is not provided.
The following loop keywords serve as valid prepositions within this
syntax.  At least one of the prepositions must be used; and at most one
from each line may be used in a single subclause.

from | downfrom | upfrom
to | downto | upto | below | above
by

   The prepositional phrases in each subclause may appear in any order.
For example, either "from x by y" or "by y from x" is permitted.
However, because left-to-right order of evaluation is preserved, the
effects will be different in the case of side effects.

   Consider:

     (let ((x 1)) (loop for i from x by (incf x) to 10 collect i))
     =>  (1 3 5 7 9)
     (let ((x 1)) (loop for i by (incf x) from x to 10 collect i))
     =>  (2 4 6 8 10)

   The descriptions of the prepositions follow:

from
     The loop keyword from specifies the value from which stepping_1
     begins, as supplied by form1.  Stepping_1 is incremental by
     default.  If decremental stepping_1 is desired, the preposition
     downto or above must be used with form2.  For incremental
     stepping_1, the default from value is 0.

downfrom, upfrom
     The loop keyword downfrom indicates that the variable var is
     decreased in decrements supplied by form3; the loop keyword upfrom
     indicates that var is increased in increments supplied by form3.

to
     The loop keyword to marks the end value for stepping_1 supplied in
     form2.  Stepping_1 is incremental by default.  If decremental
     stepping_1 is desired, the preposition downfrom must be used with
     form1, or else the preposition downto or above should be used
     instead of to with form2.

downto, upto
     The loop keyword downto specifies decremental stepping; the loop
     keyword upto specifies incremental stepping.  In both cases, the
     amount of change on each step is specified by form3, and the loop
     terminates when the variable var passes the value of form2.  Since
     there is no default for form1 in decremental stepping_1, a form1
     value must be supplied (using from or downfrom) when downto is
     supplied.

below, above
     The loop keywords below and above are analogous to upto and downto
     respectively.  These keywords stop iteration just before the value
     of the variable var reaches the value supplied by form2; the end
     value of form2 is not included.  Since there is no default for
     form1 in decremental stepping_1, a form1 value must be supplied
     (using from or downfrom) when above is supplied.

by
     The loop keyword by marks the increment or decrement supplied by
     form3.  The value of form3 can be any positive number.  The default
     value is 1.

   In an iteration control clause, the for or as construct causes
termination when the supplied limit is reached.  That is, iteration
continues until the value var is stepped to the exclusive or inclusive
limit supplied by form2.  The range is exclusive if form3 increases or
decreases var to the value of form2 without reaching that value; the
loop keywords below and above provide exclusive limits.  An inclusive
limit allows var to attain the value of form2; to, downto, and upto
provide inclusive limits.


File: gcl.info,  Node: Examples of for-as-arithmetic subclause,  Next: The for-as-in-list subclause,  Prev: The for-as-arithmetic subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.3 Examples of for-as-arithmetic subclause
...............................................

     ;; Print some numbers.
      (loop for i from 1 to 3
            do (print i))
      |>  1
      |>  2
      |>  3
     =>  NIL

     ;; Print every third number.
      (loop for i from 10 downto 1 by 3
            do (print i))
      |>  10
      |>  7
      |>  4
      |>  1
     =>  NIL

     ;; Step incrementally from the default starting value.
      (loop for i below 3
            do (print i))
      |>  0
      |>  1
      |>  2
     =>  NIL


File: gcl.info,  Node: The for-as-in-list subclause,  Next: Examples of for-as-in-list subclause,  Prev: Examples of for-as-arithmetic subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.4 The for-as-in-list subclause
....................................

In the for-as-in-list subclause, the for or as construct iterates over
the contents of a list.  It checks for the end of the list as if by
using endp.  The variable var is bound to the successive elements of the
list in form1 before each iteration.  At the end of each iteration, the
function step-fun is applied to the list; the default value for step-fun
is cdr.  The loop keywords in and by serve as valid prepositions in this
syntax.  The for or as construct causes termination when the end of the
list is reached.


File: gcl.info,  Node: Examples of for-as-in-list subclause,  Next: The for-as-on-list subclause,  Prev: The for-as-in-list subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.5 Examples of for-as-in-list subclause
............................................

     ;; Print every item in a list.
      (loop for item in '(1 2 3) do (print item))
      |>  1
      |>  2
      |>  3
     =>  NIL

     ;; Print every other item in a list.
      (loop for item in '(1 2 3 4 5) by #'cddr
            do (print item))
      |>  1
      |>  3
      |>  5
     =>  NIL

     ;; Destructure a list, and sum the x values using fixnum arithmetic.
      (loop for (item . x) of-type (t . fixnum) in '((A . 1) (B . 2) (C . 3))
            unless (eq item 'B) sum x)
     =>  4


File: gcl.info,  Node: The for-as-on-list subclause,  Next: Examples of for-as-on-list subclause,  Prev: Examples of for-as-in-list subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.6 The for-as-on-list subclause
....................................

In the for-as-on-list subclause, the for or as construct iterates over a
list.  It checks for the end of the list as if by using atom.

   The variable var is bound to the successive tails of the list in
form1.  At the end of each iteration, the function step-fun is applied
to the list; the default value for step-fun is cdr.  The loop keywords
on and by serve as valid prepositions in this syntax.  The for or as
construct causes termination when the end of the list is reached.


File: gcl.info,  Node: Examples of for-as-on-list subclause,  Next: The for-as-equals-then subclause,  Prev: The for-as-on-list subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.7 Examples of for-as-on-list subclause
............................................

     ;; Collect successive tails of a list.
      (loop for sublist on '(a b c d)
            collect sublist)
     =>  ((A B C D) (B C D) (C D) (D))

     ;; Print a list by using destructuring with the loop keyword ON.
      (loop for (item) on '(1 2 3)
            do (print item))
      |>  1
      |>  2
      |>  3
     =>  NIL



File: gcl.info,  Node: The for-as-equals-then subclause,  Next: Examples of for-as-equals-then subclause,  Prev: Examples of for-as-on-list subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.8 The for-as-equals-then subclause
........................................

In the for-as-equals-then subclause the for or as construct initializes
the variable var by setting it to the result of evaluating form1 on the
first iteration, then setting it to the result of evaluating form2 on
the second and subsequent iterations.  If form2 is omitted, the
construct uses form1 on the second and subsequent iterations.  The loop
keywords = and then serve as valid prepositions in this syntax.  This
construct does not provide any termination tests.


File: gcl.info,  Node: Examples of for-as-equals-then subclause,  Next: The for-as-across subclause,  Prev: The for-as-equals-then subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.9 Examples of for-as-equals-then subclause
................................................

     ;; Collect some numbers.
      (loop for item = 1 then (+ item 10)
            for iteration from 1 to 5
            collect item)
     =>  (1 11 21 31 41)


File: gcl.info,  Node: The for-as-across subclause,  Next: Examples of for-as-across subclause,  Prev: Examples of for-as-equals-then subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.10 The for-as-across subclause
....................................

In the for-as-across subclause the for or as construct binds the
variable var to the value of each element in the array vector.  The loop
keyword across marks the array vector; across is used as a preposition
in this syntax.  Iteration stops when there are no more elements in the
supplied array that can be referenced.  Some implementations might
recognize a the special form in the vector form to produce more
efficient code.


File: gcl.info,  Node: Examples of for-as-across subclause,  Next: The for-as-hash subclause,  Prev: The for-as-across subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.11 Examples of for-as-across subclause
............................................

      (loop for char across (the simple-string (find-message channel))
            do (write-char char stream))


File: gcl.info,  Node: The for-as-hash subclause,  Next: The for-as-package subclause,  Prev: Examples of for-as-across subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.12 The for-as-hash subclause
..................................

In the for-as-hash subclause the for or as construct iterates over the
elements, keys, and values of a hash-table.  In this syntax, a compound
preposition is used to designate access to a hash table.  The variable
var takes on the value of each hash key or hash value in the supplied
hash-table.  The following loop keywords serve as valid prepositions
within this syntax:

being
     The keyword being introduces either the Loop schema hash-key or
     hash-value.

each, the
     The loop keyword each follows the loop keyword being when hash-key
     or hash-value is used.  The loop keyword the is used with hash-keys
     and hash-values only for ease of reading.  This agreement isn't
     required.

hash-key, hash-keys
     These loop keywords access each key entry of the hash table.  If
     the name hash-value is supplied in a using construct with one of
     these Loop schemas, the iteration can optionally access the keyed
     value.  The order in which the keys are accessed is undefined;
     empty slots in the hash table are ignored.

hash-value, hash-values
     These loop keywords access each value entry of a hash table.  If
     the name hash-key is supplied in a using construct with one of
     these Loop schemas, the iteration can optionally access the key
     that corresponds to the value.  The order in which the keys are
     accessed is undefined; empty slots in the hash table are ignored.

using
     The loop keyword using introduces the optional key or the keyed
     value to be accessed.  It allows access to the hash key if
     iteration is over the hash values, and the hash value if iteration
     is over the hash keys.

in, of
     These loop prepositions introduce hash-table.

   In effect

   being {each | the} {hash-value | hash-values | hash-key | hash-keys}
{in | of}

   is a compound preposition.

   Iteration stops when there are no more hash keys or hash values to be
referenced in the supplied hash-table.


File: gcl.info,  Node: The for-as-package subclause,  Next: Examples of for-as-package subclause,  Prev: The for-as-hash subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.13 The for-as-package subclause
.....................................

In the for-as-package subclause the for or as construct iterates over
the symbols in a package.  In this syntax, a compound preposition is
used to designate access to a package.  The variable var takes on the
value of each symbol in the supplied package.  The following loop
keywords serve as valid prepositions within this syntax:

being
     The keyword being introduces either the Loop schema symbol,
     present-symbol, or external-symbol.

each, the
     The loop keyword each follows the loop keyword being when symbol,
     present-symbol, or external-symbol is used.  The loop keyword the
     is used with symbols, present-symbols, and external-symbols only
     for ease of reading.  This agreement isn't required.

present-symbol, present-symbols
     These Loop schemas iterate over the symbols

     that are present in a package.

     The package to be iterated over is supplied in the same way that
     package arguments to find-package are supplied.  If the package for
     the iteration is not supplied, the current package is used.  If a
     package that does not exist is supplied, an error of type
     package-error is signaled.

symbol, symbols
     These Loop schemas iterate over symbols that are accessible in a
     given package.  The package to be iterated over is supplied in the
     same way that package arguments to find-package are supplied.  If
     the package for the iteration is not supplied, the current package
     is used.  If a package that does not exist is supplied, an error of
     type package-error is signaled.

external-symbol, external-symbols
     These Loop schemas iterate over the external symbols of a package.
     The package to be iterated over is supplied in the same way that
     package arguments to find-package are supplied.  If the package for
     the iteration is not supplied, the current package is used.  If a
     package that does not exist is supplied, an error of type
     package-error is signaled.

in, of
     These loop prepositions introduce package.

   In effect

   being {each | the} {symbol | symbols | present-symbol |
present-symbols | external-symbol | external-symbols} {in | of}

   is a compound preposition.

   Iteration stops when there are no more symbols to be referenced in
the supplied package.


File: gcl.info,  Node: Examples of for-as-package subclause,  Next: Local Variable Initializations,  Prev: The for-as-package subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.14 Examples of for-as-package subclause
.............................................

      (let ((*package* (make-package "TEST-PACKAGE-1")))
        ;; For effect, intern some symbols
        (read-from-string "(THIS IS A TEST)")
        (export (intern "THIS"))
        (loop for x being each present-symbol of *package*
               do (print x)))
      |>  A
      |>  TEST
      |>  THIS
      |>  IS
     =>  NIL


File: gcl.info,  Node: Local Variable Initializations,  Next: Examples of WITH clause,  Prev: Examples of for-as-package subclause,  Up: Variable Initialization and Stepping Clauses

6.1.2.15 Local Variable Initializations
.......................................

When a loop form is executed, the local variables are bound and are
initialized to some value.  These local variables exist until loop
iteration terminates, at which point they cease to exist.  Implicit
variables are also established by iteration control clauses and the into
preposition of accumulation clauses.

   The with construct initializes variables that are local to a loop.
The variables are initialized one time only.  If the optional type-spec
argument is supplied for the variable var, but there is no related
expression to be evaluated, var is initialized to an appropriate default
value for its type.  For example, for the types t, number, and float,
the default values are nil, 0, and 0.0 respectively.  The consequences
are undefined if a type-spec argument is supplied for var if the related
expression returns a value that is not of the supplied type.  By
default, the with construct initializes variables sequentially; that is,
one variable is assigned a value before the next expression is
evaluated.  However, by using the loop keyword and to join several with
clauses, initializations can be forced to occur in parallel; that is,
all of the supplied forms are evaluated, and the results are bound to
the respective variables simultaneously.

   Sequential binding is used when it is desireable for the
initialization of some variables to depend on the values of previously
bound variables.  For example, suppose the variables a, b, and c are to
be bound in sequence:

      (loop with a = 1
            with b = (+ a 2)
            with c = (+ b 3)
            return (list a b c))
     =>  (1 3 6)

   The execution of the above loop is equivalent to the execution of the
following code:

      (block nil
        (let* ((a 1)
               (b (+ a 2))
               (c (+ b 3)))
          (tagbody
              (next-loop (return (list a b c))
                         (go next-loop)
                         end-loop))))

   If the values of previously bound variables are not needed for the
initialization of other local variables, an and clause can be used to
specify that the bindings are to occur in parallel:

      (loop with a = 1
            and b = 2
            and c = 3
            return (list a b c))
     =>  (1 2 3)

   The execution of the above loop is equivalent to the execution of the
following code:

      (block nil
        (let ((a 1)
              (b 2)
              (c 3))
          (tagbody
              (next-loop (return (list a b c))
                         (go next-loop)
                         end-loop))))


File: gcl.info,  Node: Examples of WITH clause,  Prev: Local Variable Initializations,  Up: Variable Initialization and Stepping Clauses

6.1.2.16 Examples of WITH clause
................................

     ;; These bindings occur in sequence.
      (loop with a = 1
            with b = (+ a 2)
            with c = (+ b 3)
            return (list a b c))
     =>  (1 3 6)

     ;; These bindings occur in parallel.
      (setq a 5 b 10)
     =>  10
      (loop with a = 1
            and b = (+ a 2)
            and c = (+ b 3)
            return (list a b c))
     =>  (1 7 13)

     ;; This example shows a shorthand way to declare local variables
     ;; that are of different types.
      (loop with (a b c) of-type (float integer float)
            return (format nil "~A ~A ~A" a b c))
     =>  "0.0 0 0.0"

     ;; This example shows a shorthand way to declare local variables
     ;; that are the same type.
      (loop with (a b c) of-type float
            return (format nil "~A ~A ~A" a b c))
     =>  "0.0 0.0 0.0"


File: gcl.info,  Node: Value Accumulation Clauses,  Next: Termination Test Clauses,  Prev: Variable Initialization and Stepping Clauses,  Up: The LOOP Facility

6.1.3 Value Accumulation Clauses
--------------------------------

The constructs collect, collecting, append, appending, nconc, nconcing,
count, counting, maximize, maximizing, minimize, minimizing, sum, and
summing, allow values to be accumulated in a loop.

   The constructs collect, collecting, append, appending, nconc, and
nconcing, designate clauses that accumulate values in lists and return
them.  The constructs count, counting, maximize, maximizing, minimize,
minimizing, sum, and summing designate clauses that accumulate and
return numerical values.

   During each iteration, the constructs collect and collecting collect
the value of the supplied form into a list.  When iteration terminates,
the list is returned.  The argument var is set to the list of collected
values; if var is supplied, the loop does not return the final list
automatically.  If var is not supplied, it is equivalent to supplying an
internal name for var and returning its value in a finally clause.  The
var argument is bound as if by the construct with.  No mechanism is
provided for declaring the type of var; it must be of type list.

   The constructs append, appending, nconc, and nconcing are similar to
collect except that the values of the supplied form must be lists.

*
     The append keyword causes its list values to be concatenated into a
     single list, as if they were arguments to the function append.

*
     The nconc keyword causes its list values to be concatenated into a
     single list, as if they were arguments to the function nconc.

   The argument var is set to the list of concatenated values; if var is
supplied, loop does not return the final list automatically.  The var
argument is bound as if by the construct with.  A type cannot be
supplied for var; it must be of type list.  The construct nconc
destructively modifies its argument lists.

   The count construct counts the number of times that the supplied form
returns true.  The argument var accumulates the number of occurrences;
if var is supplied, loop does not return the final count automatically.
The var argument is bound as if by the construct with to a zero of the
appropriate type.  Subsequent values (including any necessary coercions)
are computed as if by the function 1+.  If into var is used, a type can
be supplied for var with the type-spec argument; the consequences are
unspecified if a nonnumeric type is supplied.  If there is no into
variable, the optional type-spec argument applies to the internal
variable that is keeping the count.  The default type is
implementation-dependent; but it must be a supertype of type fixnum.

   The maximize and minimize constructs compare the value of the
supplied form obtained during the first iteration with values obtained
in successive iterations.  The maximum (for maximize) or minimum (for
minimize) value encountered is determined (as if by the function max for
maximize and as if by the function min for minimize) and returned.  If
the maximize or minimize clause is never executed, the accumulated value
is unspecified.  The argument var accumulates the maximum or minimum
value; if var is supplied, loop does not return the maximum or minimum
automatically.  The var argument is bound as if by the construct with.
If into var is used, a type can be supplied for var with the type-spec
argument; the consequences are unspecified if a nonnumeric type is
supplied.  If there is no into variable, the optional type-spec argument
applies to the internal variable that is keeping the maximum or minimum
value.  The default type is implementation-dependent; but it must be a
supertype of type real.

   The sum construct forms a cumulative sum of the successive primary
values of the supplied form at each iteration.  The argument var is used
to accumulate the sum; if var is supplied, loop does not return the
final sum automatically.  The var argument is bound as if by the
construct with to a zero of the appropriate type.  Subsequent values
(including any necessary coercions) are computed as if by the function
+.  If into var is used, a type can be supplied for var with the
type-spec argument; the consequences are unspecified if a nonnumeric
type is supplied.  If there is no into variable, the optional type-spec
argument applies to the internal variable that is keeping the sum.  The
default type is implementation-dependent; but it must be a supertype of
type number.

   If into is used, the construct does not provide a default return
value; however, the variable is available for use in any finally clause.

   Certain kinds of accumulation clauses can be combined in a loop if
their destination is the same (the result of loop or an into var)
because they are considered to accumulate conceptually compatible
quantities.  In particular, any elements of following sets of
accumulation clauses can be mixed with other elements of the same set
for the same destination in a loop form:

*
     collect, append, nconc

*
     sum, count

*
     maximize, minimize

     ;; Collect every name and the kids in one list by using
     ;; COLLECT and APPEND.
      (loop for name in '(fred sue alice joe june)
            for kids in '((bob ken) () () (kris sunshine) ())
            collect name
            append kids)
     =>  (FRED BOB KEN SUE ALICE JOE KRIS SUNSHINE JUNE)

   Any two clauses that do not accumulate the same type of object can
coexist in a loop only if each clause accumulates its values into a
different variable.

* Menu:

* Examples of COLLECT clause::
* Examples of APPEND and NCONC clauses::
* Examples of COUNT clause::
* Examples of MAXIMIZE and MINIMIZE clauses::
* Examples of SUM clause::


File: gcl.info,  Node: Examples of COLLECT clause,  Next: Examples of APPEND and NCONC clauses,  Prev: Value Accumulation Clauses,  Up: Value Accumulation Clauses

6.1.3.1 Examples of COLLECT clause
..................................

     ;; Collect all the symbols in a list.
      (loop for i in '(bird 3 4 turtle (1 . 4) horse cat)
            when (symbolp i) collect i)
     =>  (BIRD TURTLE HORSE CAT)

     ;; Collect and return odd numbers.
      (loop for i from 1 to 10
            if (oddp i) collect i)
     =>  (1 3 5 7 9)

     ;; Collect items into local variable, but don't return them.
      (loop for i in '(a b c d) by #'cddr
            collect i into my-list
            finally (print my-list))
      |>  (A C)
     =>  NIL


File: gcl.info,  Node: Examples of APPEND and NCONC clauses,  Next: Examples of COUNT clause,  Prev: Examples of COLLECT clause,  Up: Value Accumulation Clauses

6.1.3.2 Examples of APPEND and NCONC clauses
............................................

     ;; Use APPEND to concatenate some sublists.
       (loop for x in '((a) (b) ((c)))
             append x)
     =>  (A B (C))

     ;; NCONC some sublists together.  Note that only lists made by the
     ;; call to LIST are modified.
       (loop for i upfrom 0
             as x in '(a b (c))
             nconc (if (evenp i) (list x) nil))
     =>  (A (C))


File: gcl.info,  Node: Examples of COUNT clause,  Next: Examples of MAXIMIZE and MINIMIZE clauses,  Prev: Examples of APPEND and NCONC clauses,  Up: Value Accumulation Clauses

6.1.3.3 Examples of COUNT clause
................................

      (loop for i in '(a b nil c nil d e)
            count i)
     =>  5


File: gcl.info,  Node: Examples of MAXIMIZE and MINIMIZE clauses,  Next: Examples of SUM clause,  Prev: Examples of COUNT clause,  Up: Value Accumulation Clauses

6.1.3.4 Examples of MAXIMIZE and MINIMIZE clauses
.................................................

      (loop for i in '(2 1 5 3 4)
            maximize i)
     =>  5
      (loop for i in '(2 1 5 3 4)
            minimize i)
     =>  1

     ;; In this example, FIXNUM applies to the internal variable that holds
     ;; the maximum value.
      (setq series '(1.2 4.3 5.7))
     =>  (1.2 4.3 5.7)
      (loop for v in series
            maximize (round v) of-type fixnum)
     =>  6

     ;; In this example, FIXNUM applies to the variable RESULT.
      (loop for v of-type float in series
            minimize (round v) into result of-type fixnum
            finally (return result))
     =>  1


File: gcl.info,  Node: Examples of SUM clause,  Prev: Examples of MAXIMIZE and MINIMIZE clauses,  Up: Value Accumulation Clauses

6.1.3.5 Examples of SUM clause
..............................

      (loop for i of-type fixnum in '(1 2 3 4 5)
            sum i)
     =>  15
      (setq series '(1.2 4.3 5.7))
     =>  (1.2 4.3 5.7)
      (loop for v in series
            sum (* 2.0 v))
     =>  22.4


File: gcl.info,  Node: Termination Test Clauses,  Next: Unconditional Execution Clauses,  Prev: Value Accumulation Clauses,  Up: The LOOP Facility

6.1.4 Termination Test Clauses
------------------------------

The repeat construct causes iteration to terminate after a specified
number of times.  The loop body executes n times, where n is the value
of the expression form.  The form argument is evaluated one time in the
loop prologue.  If the expression evaluates to 0 or to a negative
number, the loop body is not evaluated.

   The constructs always, never, thereis, while, until, and the macro
loop-finish allow conditional termination of iteration within a loop.

   The constructs always, never, and thereis provide specific values to
be returned when a loop terminates.  Using always, never, or thereis in
a loop with value accumulation clauses that are not into causes an error
of type program-error to be signaled (at macro expansion time).  Since
always, never, and thereis use

   the return-from special operator

   to terminate iteration, any finally clause that is supplied is not
evaluated when exit occurs due to any of these constructs.  In all other
respects these constructs behave like the while and until constructs.

   The always construct takes one form and terminates the loop if the
form ever evaluates to nil; in this case, it returns nil.  Otherwise, it
provides a default return value of t.  If the value of the supplied form
is never nil, some other construct can terminate the iteration.

   The never construct terminates iteration the first time that the
value of the supplied form is non-nil; the loop returns nil.  If the
value of the supplied form is always nil, some other construct can
terminate the iteration.  Unless some other clause contributes a return
value, the default value returned is t.

   The thereis construct terminates iteration the first time that the
value of the supplied form is non-nil; the loop returns the value of the
supplied form.  If the value of the supplied form is always nil, some
other construct can terminate the iteration.  Unless some other clause
contributes a return value, the default value returned is nil.

   There are two differences between the thereis and until constructs:

*
     The until construct does not return a value or nil based on the
     value of the supplied form.

*
     The until construct executes any finally clause.  Since thereis
     uses

     the return-from special operator

     to terminate iteration, any finally clause that is supplied is not
     evaluated when exit occurs due to thereis.

   The while construct allows iteration to continue until the supplied
form evaluates to false.  The supplied form is reevaluated at the
location of the while clause.

   The until construct is equivalent to while (not form)\dots.  If the
value of the supplied form is non-nil, iteration terminates.

   Termination-test control constructs can be used anywhere within the
loop body.  The termination tests are used in the order in which they
appear.  If an until or while clause causes termination, any clauses
that precede it in the source are still evaluated.  If the until and
while constructs cause termination, control is passed to the loop
epilogue, where any finally clauses will be executed.

   There are two differences between the never and until constructs:

*
     The until construct does not return t or nil based on the value of
     the supplied form.

*
     The until construct does not bypass any finally clauses.  Since
     never uses

     the return-from special operator

     to terminate iteration, any finally clause that is supplied is not
     evaluated when exit occurs due to never.

   In most cases it is not necessary to use loop-finish because other
loop control clauses terminate the loop.  The macro loop-finish is used
to provide a normal exit from a nested conditional inside a loop.  Since
loop-finish transfers control to the loop epilogue, using loop-finish
within a finally expression can cause infinite looping.

* Menu:

* Examples of REPEAT clause::
* Examples of ALWAYS::
* Examples of WHILE and UNTIL clauses::


File: gcl.info,  Node: Examples of REPEAT clause,  Next: Examples of ALWAYS,  Prev: Termination Test Clauses,  Up: Termination Test Clauses

6.1.4.1 Examples of REPEAT clause
.................................

      (loop repeat 3
            do (format t "~&What I say three times is true.~
      |>  What I say three times is true.
      |>  What I say three times is true.
      |>  What I say three times is true.
     =>  NIL
      (loop repeat -15
        do (format t "What you see is what you expect~
     =>  NIL


File: gcl.info,  Node: Examples of ALWAYS,  Next: Examples of WHILE and UNTIL clauses,  Prev: Examples of REPEAT clause,  Up: Termination Test Clauses

6.1.4.2 Examples of ALWAYS, NEVER, and THEREIS clauses
......................................................

     ;; Make sure I is always less than 11 (two ways).
     ;; The FOR construct terminates these loops.
      (loop for i from 0 to 10
            always (< i 11))
     =>  T
      (loop for i from 0 to 10
            never (> i 11))
     =>  T

     ;; If I exceeds 10 return I; otherwise, return NIL.
     ;; The THEREIS construct terminates this loop.
      (loop for i from 0
            thereis (when (> i 10) i) )
     =>  11

     ;;; The FINALLY clause is not evaluated in these examples.
      (loop for i from 0 to 10
            always (< i 9)
            finally (print "you won't see this"))
     =>  NIL
      (loop never t
            finally (print "you won't see this"))
     =>  NIL
      (loop thereis "Here is my value"
            finally (print "you won't see this"))
     =>  "Here is my value"

     ;; The FOR construct terminates this loop, so the FINALLY clause
     ;; is evaluated.
      (loop for i from 1 to 10
            thereis (> i 11)
            finally (prin1 'got-here))
      |>  GOT-HERE
     =>  NIL

     ;; If this code could be used to find a counterexample to Fermat's
     ;; last theorem, it would still not return the value of the
     ;; counterexample because all of the THEREIS clauses in this example
     ;; only return T.  But if Fermat is right, that won't matter
     ;; because this won't terminate.

      (loop for z upfrom 2
            thereis
              (loop for n upfrom 3 below (log z 2)
                    thereis
                      (loop for x below z
                            thereis
                              (loop for y below z
                                    thereis (= (+ (expt x n) (expt y n))
                                               (expt z n))))))


File: gcl.info,  Node: Examples of WHILE and UNTIL clauses,  Prev: Examples of ALWAYS,  Up: Termination Test Clauses

6.1.4.3 Examples of WHILE and UNTIL clauses
...........................................

      (loop while (hungry-p) do (eat))

     ;; UNTIL NOT is equivalent to WHILE.
      (loop until (not (hungry-p)) do (eat))

     ;; Collect the length and the items of STACK.
      (let ((stack '(a b c d e f)))
        (loop for item = (length stack) then (pop stack)
              collect item
              while stack))
     =>  (6 A B C D E F)

     ;; Use WHILE to terminate a loop that otherwise wouldn't terminate.
     ;; Note that WHILE occurs after the WHEN.
      (loop for i fixnum from 3
            when (oddp i) collect i
            while (< i 5))
     =>  (3 5)


File: gcl.info,  Node: Unconditional Execution Clauses,  Next: Conditional Execution Clauses,  Prev: Termination Test Clauses,  Up: The LOOP Facility

6.1.5 Unconditional Execution Clauses
-------------------------------------

The do and doing constructs evaluate the supplied forms wherever they
occur in the expanded form of loop.  The form argument can be any
compound form.  Each form is evaluated in every iteration.  Because
every loop clause must begin with a loop keyword, the keyword do is used
when no control action other than execution is required.

   The return construct takes one form.  Any values returned by the form
are immediately returned by the loop form.  It is equivalent to the
clause do (return-from block-name value), where block-name is the name
specified in a named clause, or nil if there is no named clause.

* Menu:

* Examples of unconditional execution::


File: gcl.info,  Node: Examples of unconditional execution,  Prev: Unconditional Execution Clauses,  Up: Unconditional Execution Clauses

6.1.5.1 Examples of unconditional execution
...........................................

     ;; Print numbers and their squares.
     ;; The DO construct applies to multiple forms.
      (loop for i from 1 to 3
            do (print i)
               (print (* i i)))
      |>  1
      |>  1
      |>  2
      |>  4
      |>  3
      |>  9
     =>  NIL



File: gcl.info,  Node: Conditional Execution Clauses,  Next: Miscellaneous Clauses,  Prev: Unconditional Execution Clauses,  Up: The LOOP Facility

6.1.6 Conditional Execution Clauses
-----------------------------------

The if, when, and unless constructs establish conditional control in a
loop.  If the test passes, the succeeding loop clause is executed.  If
the test does not pass, the succeeding clause is skipped, and program
control moves to the clause that follows the loop keyword else.  If the
test does not pass and no else clause is supplied, control is
transferred to the clause or construct following the entire conditional
clause.

   If conditional clauses are nested, each else is paired with the
closest preceding conditional clause that has no associated else or end.

   In the if and when clauses, which are synonymous, the test passes if
the value of form is true.

   In the unless clause, the test passes if the value of form is false.

   Clauses that follow the test expression can be grouped by using the
loop keyword and to produce a conditional block consisting of a compound
clause.

   The loop keyword it can be used to refer to the result of the test
expression in a clause.  Use the loop keyword it in place of the form in
a return clause or an accumulation clause that is inside a conditional
execution clause.  If multiple clauses are connected with and, the it
construct must be in the first clause in the block.

   The optional loop keyword end marks the end of the clause.  If this
keyword is not supplied, the next loop keyword marks the end.  The
construct end can be used to distinguish the scoping of compound
clauses.

* Menu:

* Examples of WHEN clause::


File: gcl.info,  Node: Examples of WHEN clause,  Prev: Conditional Execution Clauses,  Up: Conditional Execution Clauses

6.1.6.1 Examples of WHEN clause
...............................

     ;; Signal an exceptional condition.
      (loop for item in '(1 2 3 a 4 5)
            when (not (numberp item))
             return (cerror "enter new value" "non-numeric value: ~s" item))
     Error: non-numeric value: A

     ;; The previous example is equivalent to the following one.
      (loop for item in '(1 2 3 a 4 5)
            when (not (numberp item))
             do (return
                 (cerror "Enter new value" "non-numeric value: ~s" item)))
     Error: non-numeric value: A

     ;; This example parses a simple printed string representation from
     ;; BUFFER (which is itself a string) and returns the index of the
     ;; closing double-quote character.
      (let ((buffer "\"a\" \"b\""))
        (loop initially (unless (char= (char buffer 0) #\")
                          (loop-finish))
              for i of-type fixnum from 1 below (length (the string buffer))
              when (char= (char buffer i) #\")
               return i))
     =>  2

     ;; The collected value is returned.
      (loop for i from 1 to 10
            when (> i 5)
              collect i
            finally (prin1 'got-here))
      |>  GOT-HERE
     =>  (6 7 8 9 10)

     ;; Return both the count of collected numbers and the numbers.
      (loop for i from 1 to 10
            when (> i 5)
              collect i into number-list
              and count i into number-count
            finally (return (values number-count number-list)))
     =>  5, (6 7 8 9 10)


File: gcl.info,  Node: Miscellaneous Clauses,  Next: Examples of Miscellaneous Loop Features,  Prev: Conditional Execution Clauses,  Up: The LOOP Facility

6.1.7 Miscellaneous Clauses
---------------------------

* Menu:

* Control Transfer Clauses::
* Examples of NAMED clause::
* Initial and Final Execution::


File: gcl.info,  Node: Control Transfer Clauses,  Next: Examples of NAMED clause,  Prev: Miscellaneous Clauses,  Up: Miscellaneous Clauses

6.1.7.1 Control Transfer Clauses
................................

The named construct establishes a name for an implicit block surrounding
the

   entire

   loop so that the return-from special operator can be used to return
values from or to exit loop.  Only one name per loop form can be
assigned.  If used, the named construct must be the first clause in the
loop expression.

   The return construct takes one form.  Any values returned by the form
are immediately returned by the loop form.

   This construct is similar to the return-from special operator and the
return macro.  The return construct

   does not execute any finally clause that

   the loop form

   is given.


File: gcl.info,  Node: Examples of NAMED clause,  Next: Initial and Final Execution,  Prev: Control Transfer Clauses,  Up: Miscellaneous Clauses

6.1.7.2 Examples of NAMED clause
................................

     ;; Just name and return.
      (loop named max
            for i from 1 to 10
            do (print i)
            do (return-from max 'done))
      |>  1
     =>  DONE


File: gcl.info,  Node: Initial and Final Execution,  Prev: Examples of NAMED clause,  Up: Miscellaneous Clauses

6.1.7.3 Initial and Final Execution
...................................

The initially and finally constructs evaluate forms that occur before
and after the loop body.

   The initially construct causes the supplied compound-forms to be
evaluated in the loop prologue, which precedes all loop code except for
initial settings supplied by constructs with, for, or as.  The code for
any initially clauses is executed in the order in which the clauses
appeared in the loop.

   The finally construct causes the supplied compound-forms to be
evaluated in the loop epilogue after normal iteration terminates.  The
code for any finally clauses is executed in the order in which the
clauses appeared in the loop.  The collected code is executed once in
the loop epilogue before any implicit values are returned from the
accumulation clauses.  An explicit transfer of control (e.g., by return,
go, or throw) from the loop body, however, will exit the loop without
executing the epilogue code.

   Clauses such as return, always, never, and thereis can bypass the
finally clause.

   return (or return-from, if the named option was supplied)

   can be used after finally to return values from a loop.

   Such an explicit return

   inside the finally clause takes precedence over returning the
accumulation from clauses supplied by such keywords as collect, nconc,
append, sum, count, maximize, and minimize; the accumulation values for
these preempted clauses are not returned by loop if return or
return-from is used.


File: gcl.info,  Node: Examples of Miscellaneous Loop Features,  Next: Notes about Loop,  Prev: Miscellaneous Clauses,  Up: The LOOP Facility

6.1.8 Examples of Miscellaneous Loop Features
---------------------------------------------

      (let ((i 0))                     ; no loop keywords are used
         (loop (incf i) (if (= i 3) (return i)))) =>  3
      (let ((i 0)(j 0))
         (tagbody
           (loop (incf j 3) (incf i) (if (= i 3) (go exit)))
           exit)
         j) =>  9

   In the following example, the variable x is stepped before y is
stepped; thus, the value of y reflects the updated value of x:

      (loop for x from 1 to 10
            for y = nil then x
            collect (list x y))
     =>  ((1 NIL) (2 2) (3 3) (4 4) (5 5) (6 6) (7 7) (8 8) (9 9) (10 10))

   In this example, x and y are stepped in parallel:

      (loop for x from 1 to 10
            and y = nil then x
            collect (list x y))
     =>  ((1 NIL) (2 1) (3 2) (4 3) (5 4) (6 5) (7 6) (8 7) (9 8) (10 9))

* Menu:

* Examples of clause grouping::


File: gcl.info,  Node: Examples of clause grouping,  Prev: Examples of Miscellaneous Loop Features,  Up: Examples of Miscellaneous Loop Features

6.1.8.1 Examples of clause grouping
...................................

     ;; Group conditional clauses.
      (loop for i in '(1 324 2345 323 2 4 235 252)
            when (oddp i)
              do (print i)
              and collect i into odd-numbers
              and do (terpri)
            else                              ; I is even.
              collect i into even-numbers
            finally
              (return (values odd-numbers even-numbers)))
      |>  1
      |>
      |>  2345
      |>
      |>  323
      |>
      |>  235
     =>  (1 2345 323 235), (324 2 4 252)

     ;; Collect numbers larger than 3.
      (loop for i in '(1 2 3 4 5 6)
            when (and (> i 3) i)
            collect it)                      ; IT refers to (and (> i 3) i).
     =>  (4 5 6)

     ;; Find a number in a list.
      (loop for i in '(1 2 3 4 5 6)
            when (and (> i 3) i)
            return it)
     =>  4

     ;; The above example is similar to the following one.
      (loop for i in '(1 2 3 4 5 6)
            thereis (and (> i 3) i))
     =>  4

     ;; Nest conditional clauses.
      (let ((list '(0 3.0 apple 4 5 9.8 orange banana)))
        (loop for i in list
              when (numberp i)
                when (floatp i)
                  collect i into float-numbers
                else                                  ; Not (floatp i)
                  collect i into other-numbers
              else                                    ; Not (numberp i)
                when (symbolp i)
                  collect i into symbol-list
                else                                  ; Not (symbolp i)
                  do (error "found a funny value in list ~S, value ~S~
              finally (return (values float-numbers other-numbers symbol-list))))
     =>  (3.0 9.8), (0 4 5), (APPLE ORANGE BANANA)

     ;; Without the END preposition, the last AND would apply to the
     ;; inner IF rather than the outer one.
      (loop for x from 0 to 3
            do (print x)
            if (zerop (mod x 2))
              do (princ " a")
               and if (zerop (floor x 2))
                     do (princ " b")
                     end
               and do (princ " c"))
      |>  0  a b c
      |>  1
      |>  2  a c
      |>  3
     =>  NIL


File: gcl.info,  Node: Notes about Loop,  Prev: Examples of Miscellaneous Loop Features,  Up: The LOOP Facility

6.1.9 Notes about Loop
----------------------

Types can be supplied for loop variables.  It is not necessary to supply
a type for any variable, but supplying the type can ensure that the
variable has a correctly typed initial value, and it can also enable
compiler optimizations (depending on the implementation).

   The clause repeat n ...  is roughly equivalent to a clause such as

      (loop for internal-variable downfrom (- n 1) to 0 ...)

   but in some implementations, the repeat construct might be more
efficient.

   Within the executable parts of the loop clauses and around the entire
loop form, variables can be bound by using let.

   Use caution when using a variable named IT (in any package) in
connection with loop, since it is a loop keyword that can be used in
place of a form in certain contexts.

   There is

   no

   standardized mechanism for users to add extensions to loop.


File: gcl.info,  Node: Iteration Dictionary,  Prev: The LOOP Facility,  Up: Iteration

6.2 Iteration Dictionary
========================

* Menu:

* do::
* dotimes::
* dolist::
* loop::
* loop-finish::


File: gcl.info,  Node: do,  Next: dotimes,  Prev: Iteration Dictionary,  Up: Iteration Dictionary

6.2.1 do, do* [Macro]
---------------------

'do' ({var | (var [init-form [step-form]])}*) (end-test-form
{result-form}*) {declaration}* {tag | statement}*
=> {result}*

   'do*' ({var | (var [init-form [step-form]])}*) (end-test-form
{result-form}*) {declaration}* {tag | statement}*
=> {result}*

Arguments and Values::
......................

var--a symbol.

   init-form--a form.

   step-form--a form.

   end-test-form--a form.

   result-forms--an implicit progn.

   declaration--a declare expression; not evaluated.

   tag--a go tag; not evaluated.

   statement--a compound form; evaluated as described below.

   results--if a return or return-from form is executed, the values
passed from that form; otherwise, the values returned by the
result-forms.

Description::
.............

do iterates over a group of statements while a test condition holds.  do
accepts an arbitrary number of iteration vars which are bound within the
iteration and stepped in parallel.  An initial value may be supplied for
each iteration variable by use of an init-form.  Step-forms may be used
to specify how the vars should be updated on succeeding iterations
through the loop.  Step-forms may be used both to generate successive
values or to accumulate results.  If the end-test-form condition is met
prior to an execution of the body, the iteration terminates.  Tags label
statements.

   do* is exactly like do except that the bindings and steppings of the
vars are performed sequentially rather than in parallel.

   Before the first iteration, all the init-forms are evaluated, and
each var is bound to the value of its respective init-form, if supplied.
This is a binding, not an assignment; when the loop terminates, the old
values of those variables will be restored.  For do, all of the
init-forms are evaluated before any var is bound.  The init-forms can
refer to the bindings of the vars visible before beginning execution of
do.  For do*, the first init-form is evaluated, then the first var is
bound to that value, then the second init-form is evaluated, then the
second var is bound, and so on; in general, the kth init-form can refer
to the new binding of the jth var if j < k, and otherwise to the old
binding of the jth var.

   At the beginning of each iteration, after processing the variables,
the end-test-form is evaluated.  If the result is false, execution
proceeds with the body of the do (or do*) form.  If the result is true,
the result-forms are evaluated in order as an implicit progn, and then
do or do* returns.

   At the beginning of each iteration other than the first, vars are
updated as follows.  All the step-forms, if supplied, are evaluated,
from left to right, and the resulting values are assigned to the
respective vars.  Any var that has no associated step-form is not
assigned to.  For do, all the step-forms are evaluated before any var is
updated; the assignment of values to vars is done in parallel, as if by
psetq.  Because all of the step-forms are evaluated before any of the
vars are altered, a step-form when evaluated always has access to the
old values of all the vars, even if other step-forms precede it.  For
do*, the first step-form is evaluated, then the value is assigned to the
first var, then the second step-form is evaluated, then the value is
assigned to the second var, and so on; the assignment of values to
variables is done sequentially, as if by setq.  For either do or do*,
after the vars have been updated, the end-test-form is evaluated as
described above, and the iteration continues.

   The remainder of the do (or do*) form constitutes an implicit
tagbody.  Tags may appear within the body of a do loop for use by go
statements appearing in the body (but such go statements may not appear
in the variable specifiers, the end-test-form, or the result-forms).
When the end of a do body is reached, the next iteration cycle
(beginning with the evaluation of step-forms) occurs.

   An implicit block named nil surrounds the entire do (or do*) form.  A
return statement may be used at any point to exit the loop immediately.

   Init-form is an initial value for the var with which it is
associated.  If init-form is omitted, the initial value of var is nil.
If a declaration is supplied for a var, init-form must be consistent
with the declaration.

   Declarations can appear at the beginning of a do (or do*) body.  They
apply to code in the do (or do*) body, to the bindings of the do (or
do*) vars, to the step-forms, to the end-test-form, and to the
result-forms.

Examples::
..........

      (do ((temp-one 1 (1+ temp-one))
            (temp-two 0 (1- temp-two)))
           ((> (- temp-one temp-two) 5) temp-one)) =>  4

      (do ((temp-one 1 (1+ temp-one))
            (temp-two 0 (1+ temp-one)))
           ((= 3 temp-two) temp-one)) =>  3

      (do* ((temp-one 1 (1+ temp-one))
             (temp-two 0 (1+ temp-one)))
            ((= 3 temp-two) temp-one)) =>  2

      (do ((j 0 (+ j 1)))
          (nil)                       ;Do forever.
        (format t "~
        (let ((item (read)))
          (if (null item) (return)   ;Process items until NIL seen.
              (format t "~&Output ~D: ~S" j item))))
      |>  Input 0: |>>banana<<|
      |>  Output 0: BANANA
      |>  Input 1: |>>(57 boxes)<<|
      |>  Output 1: (57 BOXES)
      |>  Input 2: |>>NIL<<|
     =>  NIL

      (setq a-vector (vector 1 nil 3 nil))
      (do ((i 0 (+ i 1))     ;Sets every null element of a-vector to zero.
           (n (array-dimension a-vector 0)))
          ((= i n))
        (when (null (aref a-vector i))
          (setf (aref a-vector i) 0))) =>  NIL
     a-vector =>  #(1 0 3 0)

      (do ((x e (cdr x))
           (oldx x x))
          ((null x))
        body)

   is an example of parallel assignment to index variables.  On the
first iteration, the value of oldx is whatever value x had before the do
was entered.  On succeeding iterations, oldx contains the value that x
had on the previous iteration.

      (do ((x foo (cdr x))
           (y bar (cdr y))
           (z '() (cons (f (car x) (car y)) z)))
          ((or (null x) (null y))
           (nreverse z)))

   does the same thing as (mapcar #'f foo bar).  The step computation
for z is an example of the fact that variables are stepped in parallel.
Also, the body of the loop is empty.

      (defun list-reverse (list)
             (do ((x list (cdr x))
                  (y '() (cons (car x) y)))
                 ((endp x) y)))

   As an example of nested iterations, consider a data structure that is
a list of conses.  The car of each cons is a list of symbols, and the
cdr of each cons is a list of equal length containing corresponding
values.  Such a data structure is similar to an association list, but is
divided into "frames"; the overall structure resembles a rib-cage.  A
lookup function on such a data structure might be:

      (defun ribcage-lookup (sym ribcage)
             (do ((r ribcage (cdr r)))
                 ((null r) nil)
               (do ((s (caar r) (cdr s))
                    (v (cdar r) (cdr v)))
                   ((null s))
                 (when (eq (car s) sym)
                   (return-from ribcage-lookup (car v)))))) =>  RIBCAGE-LOOKUP

See Also::
..........

other iteration functions ( *note dolist:: , *note dotimes:: , and *note
loop:: ) and more primitive functionality ( *note tagbody:: , *note go::
, *note block:: , *note return:: ,

   *note let:: , and *note setq:: )

Notes::
.......

If end-test-form is nil, the test will never succeed.  This provides an
idiom for "do forever": the body of the do or do* is executed
repeatedly.  The infinite loop can be terminated by the use of return,
return-from, go to an outer level, or throw.

   A do form may be explained in terms of the more primitive forms
block, return, let, loop, tagbody, and psetq as follows:

      (block nil
        (let ((var1 init1)
              (var2 init2)
              ...
              (varn initn))
          declarations
          (loop (when end-test (return (progn . result)))
                (tagbody . tagbody)
                (psetq var1 step1
                       var2 step2
                       ...
                       varn stepn))))

   do* is similar, except that let* and setq replace the let and psetq,
respectively.


File: gcl.info,  Node: dotimes,  Next: dolist,  Prev: do,  Up: Iteration Dictionary

6.2.2 dotimes [Macro]
---------------------

'dotimes' (var count-form [result-form]) {declaration}* {tag |
statement}*
=> {result}*

Arguments and Values::
......................

var--a symbol.

   count-form--a form.

   result-form--a form.

   declaration--a declare expression; not evaluated.

   tag--a go tag; not evaluated.

   statement--a compound form; evaluated as described below.

   results--if a return or return-from form is executed, the values
passed from that form; otherwise, the values returned by the result-form
or nil if there is no result-form.

Description::
.............

dotimes iterates over a series of integers.

   dotimes evaluates count-form, which should produce an integer.  If
count-form is zero or negative, the body is not executed.  dotimes then
executes the body once for each integer from 0 up to but not including
the value of count-form, in the order in which the tags and statements
occur, with var bound to each integer.  Then result-form is evaluated.
At the time result-form is processed, var is bound to the number of
times the body was executed.  Tags label statements.

   An implicit block named nil surrounds dotimes.  return may be used to
terminate the loop immediately without performing any further
iterations, returning zero or more values.

   The body of the loop is an implicit tagbody; it may contain tags to
serve as the targets of go statements.  Declarations may appear before
the body of the loop.

   The scope of the binding of var does not include the count-form, but
the result-form is included.

   It is implementation-dependent whether dotimes establishes a new
binding of var on each iteration or whether it establishes a binding for
var once at the beginning and then assigns it on any subsequent
iterations.

Examples::
..........

      (dotimes (temp-one 10 temp-one)) =>  10
      (setq temp-two 0) =>  0
      (dotimes (temp-one 10 t) (incf temp-two)) =>  T
      temp-two =>  10

   Here is an example of the use of dotimes in processing strings:

     ;;; True if the specified subsequence of the string is a
     ;;; palindrome (reads the same forwards and backwards).
      (defun palindromep (string &optional
                                (start 0)
                                (end (length string)))
        (dotimes (k (floor (- end start) 2) t)
         (unless (char-equal (char string (+ start k))
                             (char string (- end k 1)))
           (return nil))))
      (palindromep "Able was I ere I saw Elba") =>  T
      (palindromep "A man, a plan, a canal--Panama!") =>  NIL
      (remove-if-not #'alpha-char-p          ;Remove punctuation.
                    "A man, a plan, a canal--Panama!")
     =>  "AmanaplanacanalPanama"
      (palindromep
       (remove-if-not #'alpha-char-p
                     "A man, a plan, a canal--Panama!")) =>  T
      (palindromep
       (remove-if-not
        #'alpha-char-p
        "Unremarkable was I ere I saw Elba Kramer, nu?")) =>  T
      (palindromep
       (remove-if-not
        #'alpha-char-p
        "A man, a plan, a cat, a ham, a yak,
                       a yam, a hat, a canal--Panama!")) =>  T

See Also::
..........

*note do:: , *note dolist:: , *note tagbody::

Notes::
.......

go may be used within the body of dotimes to transfer control to a
statement labeled by a tag.


File: gcl.info,  Node: dolist,  Next: loop,  Prev: dotimes,  Up: Iteration Dictionary

6.2.3 dolist [Macro]
--------------------

'dolist' (var list-form [result-form]) {declaration}* {tag | statement}*
=> {result}*

Arguments and Values::
......................

var--a symbol.

   list-form--a form.

   result-form--a form.

   declaration--a declare expression; not evaluated.

   tag--a go tag; not evaluated.

   statement--a compound form; evaluated as described below.

   results--if a return or return-from form is executed, the values
passed from that form; otherwise, the values returned by the result-form
or nil if there is no result-form.

Description::
.............

dolist iterates over the elements of a list.  The body of dolist is like
a tagbody.  It consists of a series of tags and statements.

   dolist evaluates list-form, which should produce a list.  It then
executes the body once for each element in the list, in the order in
which the tags and statements occur, with var bound to the element.
Then result-form is evaluated.  tags label statements.

   At the time result-form is processed, var is bound to nil.

   An implicit block named nil surrounds dolist.  return may be used to
terminate the loop immediately without performing any further
iterations, returning zero or more values.

   The scope of the binding of var does not include the list-form, but
the result-form is included.

   It is implementation-dependent whether dolist establishes a new
binding of var on each iteration or whether it establishes a binding for
var once at the beginning and then assigns it on any subsequent
iterations.

Examples::
..........

      (setq temp-two '()) =>  NIL
      (dolist (temp-one '(1 2 3 4) temp-two) (push temp-one temp-two)) =>  (4 3 2 1)

      (setq temp-two 0) =>  0
      (dolist (temp-one '(1 2 3 4)) (incf temp-two)) =>  NIL
      temp-two =>  4

      (dolist (x '(a b c d)) (prin1 x) (princ " "))
      |>  A B C D
     =>  NIL

See Also::
..........

*note do:: , *note dotimes:: , *note tagbody:: ,

   *note Traversal Rules and Side Effects::

Notes::
.......

go may be used within the body of dolist to transfer control to a
statement labeled by a tag.


File: gcl.info,  Node: loop,  Next: loop-finish,  Prev: dolist,  Up: Iteration Dictionary

6.2.4 loop [Macro]
------------------

The "simple" loop form:

   'loop' {compound-form}* => {result}*

   The "extended" loop form:

   'loop' [!name-clause] {!variable-clause}* {!main-clause}* =>
{result}*

   name-clause ::=named name

   variable-clause ::=!with-clause | !initial-final | !for-as-clause

   with-clause ::=with var1 [type-spec] [= form1] {and var2 [type-spec] [= form2]}*

   main-clause ::=!unconditional | !accumulation | !conditional | !termination-test | !initial-final

   initial-final ::=initially {compound-form}^+ | finally {compound-form}^+

   unconditional ::={do | doing} {compound-form}^+ | return {form | it}

   accumulation ::=!list-accumulation | !numeric-accumulation

   list-accumulation ::={collect | collecting | append | appending | nconc | nconcing} {form | it} 
                      [into simple-var]

   numeric-accumulation ::={count | counting | sum | summing | }                          maximize | maximizing | minimize | minimizing {form | it} 
                         [into simple-var] [type-spec]

   conditional ::={if | when | unless} form !selectable-clause {and !selectable-clause}* 
                [else !selectable-clause {and !selectable-clause}*] 
                [end]

   selectable-clause ::=!unconditional | !accumulation | !conditional

   termination-test ::=while form | until form | repeat form | always form | never form | thereis form

   for-as-clause ::={for | as} !for-as-subclause {and !for-as-subclause}*

   for-as-subclause ::=!for-as-arithmetic | !for-as-in-list | !for-as-on-list | !for-as-equals-then |
                     !for-as-across | !for-as-hash | !for-as-package

   for-as-arithmetic ::=var [type-spec] !for-as-arithmetic-subclause

   for-as-arithmetic-subclause ::=!arithmetic-up | !arithmetic-downto | !arithmetic-downfrom

   arithmetic-up ::=[[{from | upfrom} form1 | {to | upto | below} form2 | by form3]]^+

   arithmetic-downto ::=[[{from form1}^1 | {{downto | above} form2}^1 | by form3]]

   arithmetic-downfrom ::=[[{downfrom form1}^1 | {to | downto | above} form2 | by form3]]

   for-as-in-list ::=var [type-spec] in form1 [by step-fun]

   for-as-on-list ::=var [type-spec] on form1 [by step-fun]

   for-as-equals-then ::=var [type-spec] = form1 [then form2]

   for-as-across ::=var [type-spec] across vector

   for-as-hash ::=var [type-spec] being {each | the} 
                {{hash-key | hash-keys} {in | of} hash-table 
                [using (hash-value other-var)] | 
                {hash-value | hash-values} {in | of} hash-table 
                [using (hash-key other-var)]}

   for-as-package ::=var [type-spec] being {each | the} 
                   {symbol | symbols |
                   present-symbol | present-symbols |
                   external-symbol | external-symbols} 
                   [{in | of} package]

   type-spec ::=!simple-type-spec | !destructured-type-spec

   simple-type-spec ::=fixnum | float | t | nil

   destructured-type-spec ::=of-type d-type-spec

   d-type-spec ::=type-specifier | (d-type-spec . d-type-spec)

   var ::=!d-var-spec

   var1 ::=!d-var-spec

   var2 ::=!d-var-spec

   other-var ::=!d-var-spec

   d-var-spec ::=simple-var | nil | (!d-var-spec . !d-var-spec)

Arguments and Values::
......................

compound-form--a compound form.

   name--a symbol.

   simple-var--a symbol (a variable name).

   form, form1, form2, form3--a form.

   step-fun--a form that evaluates to a function of one argument.

   vector--a form that evaluates to a vector.

   hash-table--a form that evaluates to a hash table.

   package--a form that evaluates to a package designator.

   type-specifier--a type specifier.  This might be either an atomic
type specifier or a compound type specifier, which introduces some
additional complications to proper parsing in the face of destructuring;
for further information, see *note Destructuring::.

   result--an object.

Description::
.............

For details, see *note The LOOP Facility::.

Examples::
..........

     ;; An example of the simple form of LOOP.
      (defun sqrt-advisor ()
        (loop (format t "~&Number: ")
              (let ((n (parse-integer (read-line) :junk-allowed t)))
                (when (not n) (return))
                (format t "~&The square root of ~D is ~D.~%" n (sqrt n)))))
     =>  SQRT-ADVISOR
      (sqrt-advisor)
      |>  Number: |>>5 [<-~]<<|
      |>  The square root of 5 is 2.236068.
      |>  Number: |>>4 [<-~]<<|
      |>  The square root of 4 is 2.
      |>  Number: |>>done [<-~]<<|
     =>  NIL

     ;; An example of the extended form of LOOP.
      (defun square-advisor ()
        (loop as n = (progn (format t "~&Number: ")
                            (parse-integer (read-line) :junk-allowed t))
              while n
              do (format t "~&The square of ~D is ~D.~
     =>  SQUARE-ADVISOR
      (square-advisor)
      |>  Number: |>>4 [<-~]<<|
      |>  The square of 4 is 16.
      |>  Number: |>>23 [<-~]<<|
      |>  The square of 23 is 529.
      |>  Number: |>>done [<-~]<<|
     =>  NIL

     ;; Another example of the extended form of LOOP.
      (loop for n from 1 to 10
            when (oddp n)
              collect n)
     =>  (1 3 5 7 9)

See Also::
..........

*note do:: , *note dolist:: , *note dotimes:: , *note return:: , *note
go:: , *note throw:: , *note Destructuring::

Notes::
.......

Except that loop-finish cannot be used within a simple loop form, a
simple loop form is related to an extended loop form in the following
way:

      (loop {compound-form}*) == (loop do {compound-form}*)


File: gcl.info,  Node: loop-finish,  Prev: loop,  Up: Iteration Dictionary

6.2.5 loop-finish [Local Macro]
-------------------------------

Syntax::
........

'loop-finish' <no arguments> => #<NoValue>

Description::
.............

The loop-finish macro can be used lexically within an extended loop form
to terminate that form "normally."  That is, it transfers control to the
loop epilogue of the lexically innermost extended loop form.  This
permits execution of any finally clause (for effect) and the return of
any accumulated result.

Examples::
..........

     ;; Terminate the loop, but return the accumulated count.
      (loop for i in '(1 2 3 stop-here 4 5 6)
            when (symbolp i) do (loop-finish)
            count i)
     =>  3

     ;; The preceding loop is equivalent to:
      (loop for i in '(1 2 3 stop-here 4 5 6)
            until (symbolp i)
            count i)
     =>  3

     ;; While LOOP-FINISH can be used can be used in a variety of
     ;; situations it is really most needed in a situation where a need
     ;; to exit is detected at other than the loop's `top level'
     ;; (where UNTIL or WHEN often work just as well), or where some
     ;; computation must occur between the point where a need to exit is
     ;; detected and the point where the exit actually occurs.  For example:
      (defun tokenize-sentence (string)
        (macrolet ((add-word (wvar svar)
                     `(when ,wvar
                        (push (coerce (nreverse ,wvar) 'string) ,svar)
                        (setq ,wvar nil))))
          (loop with word = '() and sentence = '() and endpos = nil
                for i below (length string)
                do (let ((char (aref string i)))
                     (case char
                       (#\Space (add-word word sentence))
                       (#\. (setq endpos (1+ i)) (loop-finish))
                       (otherwise (push char word))))
                finally (add-word word sentence)
                        (return (values (nreverse sentence) endpos)))))
     =>  TOKENIZE-SENTENCE

      (tokenize-sentence "this is a sentence. this is another sentence.")
     =>  ("this" "is" "a" "sentence"), 19

      (tokenize-sentence "this is a sentence")
     =>  ("this" "is" "a" "sentence"), NIL


Side Effects::
..............

Transfers control.

Exceptional Situations::
........................

Whether or not loop-finish is fbound in the global environment is
implementation-dependent; however, the restrictions on redefinition and
shadowing of loop-finish are the same as for symbols in the COMMON-LISP
package which are fbound in the global environment.  The consequences of
attempting to use loop-finish outside of loop are undefined.

See Also::
..........

*note loop:: , *note The LOOP Facility::

Notes::
.......


File: gcl.info,  Node: Objects,  Next: Structures,  Prev: Iteration,  Up: Top

7 Objects
*********

* Menu:

* Object Creation and Initialization::
* Changing the Class of an Instance::
* Reinitializing an Instance::
* Meta-Objects::
* Slots::
* Generic Functions and Methods::
* Objects Dictionary::


File: gcl.info,  Node: Object Creation and Initialization,  Next: Changing the Class of an Instance,  Prev: Objects,  Up: Objects

7.1 Object Creation and Initialization
======================================

The generic function make-instance creates and returns a new instance of
a class.  The first argument is a class or the name of a class, and the
remaining arguments form an initialization argument list .

   The initialization of a new instance consists of several distinct
steps, including the following: combining the explicitly supplied
initialization arguments with default values for the unsupplied
initialization arguments, checking the validity of the initialization
arguments, allocating storage for the instance, filling slots with
values, and executing user-supplied methods that perform additional
initialization.  Each step of make-instance is implemented by a generic
function to provide a mechanism for customizing that step.  In addition,
make-instance is itself a generic function and thus also can be
customized.

   The object system specifies system-supplied primary methods for each
step and thus specifies a well-defined standard behavior for the entire
initialization process.  The standard behavior provides four simple
mechanisms for controlling initialization:

*
     Declaring a symbol to be an initialization argument for a slot.  An
     initialization argument is declared by using the :initarg slot
     option to defclass.  This provides a mechanism for supplying a
     value for a slot in a call to make-instance.

*
     Supplying a default value form for an initialization argument.
     Default value forms for initialization arguments are defined by
     using the :default-initargs class option to defclass.  If an
     initialization argument is not explicitly provided as an argument
     to make-instance, the default value form is evaluated in the
     lexical environment of the defclass form that defined it, and the
     resulting value is used as the value of the initialization
     argument.

*
     Supplying a default initial value form for a slot.  A default
     initial value form for a slot is defined by using the :initform
     slot option to defclass.  If no initialization argument associated
     with that slot is given as an argument to make-instance or is
     defaulted by :default-initargs, this default initial value form is
     evaluated in the lexical environment of the defclass form that
     defined it, and the resulting value is stored in the slot.  The
     :initform form for a local slot may be used when creating an
     instance, when updating an instance to conform to a redefined
     class, or when updating an instance to conform to the definition of
     a different class.  The :initform form for a shared slot may be
     used when defining or re-defining the class.

*
     Defining methods for initialize-instance and shared-initialize.
     The slot-filling behavior described above is implemented by a
     system-supplied primary method for initialize-instance which
     invokes shared-initialize.  The generic function shared-initialize
     implements the parts of initialization shared by these four
     situations: when making an instance, when re-initializing an
     instance, when updating an instance to conform to a redefined
     class, and when updating an instance to conform to the definition
     of a different class.  The system-supplied primary method for
     shared-initialize directly implements the slot-filling behavior
     described above, and initialize-instance simply invokes
     shared-initialize.

* Menu:

* Initialization Arguments::
* Declaring the Validity of Initialization Arguments::
* Defaulting of Initialization Arguments::
* Rules for Initialization Arguments::
* Shared-Initialize::
* Initialize-Instance::
* Definitions of Make-Instance and Initialize-Instance::


File: gcl.info,  Node: Initialization Arguments,  Next: Declaring the Validity of Initialization Arguments,  Prev: Object Creation and Initialization,  Up: Object Creation and Initialization

7.1.1 Initialization Arguments
------------------------------

An initialization argument controls object creation and initialization.
It is often convenient to use keyword symbols to name initialization
arguments, but the name of an initialization argument can be any symbol,
including nil.  An initialization argument can be used in two ways: to
fill a slot with a value or to provide an argument for an initialization
method.  A single initialization argument can be used for both purposes.

   An initialization argument list is a property list of initialization
argument names and values.  Its structure is identical to a property
list and also to the portion of an argument list processed for &key
parameters.  As in those lists, if an initialization argument name
appears more than once in an initialization argument list, the leftmost
occurrence supplies the value and the remaining occurrences are ignored.
The arguments to make-instance (after the first argument) form an
initialization argument list.

   An initialization argument can be associated with a slot.  If the
initialization argument has a value in the initialization argument list,
the value is stored into the slot of the newly created object,
overriding any :initform form associated with the slot.  A single
initialization argument can initialize more than one slot.  An
initialization argument that initializes a shared slot stores its value
into the shared slot, replacing any previous value.

   An initialization argument can be associated with a method.  When an
object is created and a particular initialization argument is supplied,
the generic functions initialize-instance, shared-initialize, and
allocate-instance are called with that initialization argument's name
and value as a keyword argument pair.  If a value for the initialization
argument is not supplied in the initialization argument list, the
method's lambda list supplies a default value.

   Initialization arguments are used in four situations: when making an
instance, when re-initializing an instance, when updating an instance to
conform to a redefined class, and when updating an instance to conform
to the definition of a different class.

   Because initialization arguments are used to control the creation and
initialization of an instance of some particular class, we say that an
initialization argument is "an initialization argument for" that class.


File: gcl.info,  Node: Declaring the Validity of Initialization Arguments,  Next: Defaulting of Initialization Arguments,  Prev: Initialization Arguments,  Up: Object Creation and Initialization

7.1.2 Declaring the Validity of Initialization Arguments
--------------------------------------------------------

Initialization arguments are checked for validity in each of the four
situations that use them.  An initialization argument may be valid in
one situation and not another.  For example, the system-supplied primary
method for make-instance defined for the class standard-class checks the
validity of its initialization arguments and signals an error if an
initialization argument is supplied that is not declared as valid in
that situation.

   There are two means for declaring initialization arguments valid.

*
     Initialization arguments that fill slots are declared as valid by
     the :initarg slot option to defclass.  The :initarg slot option is
     inherited from superclasses.  Thus the set of valid initialization
     arguments that fill slots for a class is the union of the
     initialization arguments that fill slots declared as valid by that
     class and its superclasses.  Initialization arguments that fill
     slots are valid in all four contexts.

*
     Initialization arguments that supply arguments to methods are
     declared as valid by defining those methods.  The keyword name of
     each keyword parameter specified in the method's lambda list
     becomes an initialization argument for all classes for which the
     method is applicable.

     The presence of &allow-other-keys in the lambda list of an
     applicable method disables validity checking of initialization
     arguments.

     Thus method inheritance controls the set of valid initialization
     arguments that supply arguments to methods.  The generic functions
     for which method definitions serve to declare initialization
     arguments valid are as follows:

     -
          Making an instance of a class: allocate-instance,
          initialize-instance, and shared-initialize.  Initialization
          arguments declared as valid by these methods are valid when
          making an instance of a class.

     -
          Re-initializing an instance: reinitialize-instance and
          shared-initialize.  Initialization arguments declared as valid
          by these methods are valid when re-initializing an instance.

     -
          Updating an instance to conform to a redefined class:
          update-instance-for-redefined-class and shared-initialize.
          Initialization arguments declared as valid by these methods
          are valid when updating an instance to conform to a redefined
          class.

     -
          Updating an instance to conform to the definition of a
          different class: update-instance-for-different-class and
          shared-initialize.  Initialization arguments declared as valid
          by these methods are valid when updating an instance to
          conform to the definition of a different class.

   The set of valid initialization arguments for a class is the set of
valid initialization arguments that either fill slots or supply
arguments to methods, along with the predefined initialization argument
:allow-other-keys.  The default value for :allow-other-keys is nil.

   Validity checking of initialization arguments is disabled if the
value of the initialization argument :allow-other-keys is true.


File: gcl.info,  Node: Defaulting of Initialization Arguments,  Next: Rules for Initialization Arguments,  Prev: Declaring the Validity of Initialization Arguments,  Up: Object Creation and Initialization

7.1.3 Defaulting of Initialization Arguments
--------------------------------------------

A default value form can be supplied for an initialization argument by
using the :default-initargs class option.  If an initialization argument
is declared valid by some particular class, its default value form might
be specified by a different class.  In this case :default-initargs is
used to supply a default value for an inherited initialization argument.

   The :default-initargs option is used only to provide default values
for initialization arguments; it does not declare a symbol as a valid
initialization argument name.  Furthermore, the :default-initargs option
is used only to provide default values for initialization arguments when
making an instance.

   The argument to the :default-initargs class option is a list of
alternating initialization argument names and forms.  Each form is the
default value form for the corresponding initialization argument.  The
default value form of an initialization argument is used and evaluated
only if that initialization argument does not appear in the arguments to
make-instance and is not defaulted by a more specific class.  The
default value form is evaluated in the lexical environment of the
defclass form that supplied it; the resulting value is used as the
initialization argument's value.

   The initialization arguments supplied to make-instance are combined
with defaulted initialization arguments to produce a defaulted
initialization argument list.  A defaulted initialization argument list
is a list of alternating initialization argument names and values in
which unsupplied initialization arguments are defaulted and in which the
explicitly supplied initialization arguments appear earlier in the list
than the defaulted initialization arguments.  Defaulted initialization
arguments are ordered according to the order in the class precedence
list of the classes that supplied the default values.

   There is a distinction between the purposes of the :default-initargs
and the :initform options with respect to the initialization of slots.
The :default-initargs class option provides a mechanism for the user to
give a default value form for an initialization argument without knowing
whether the initialization argument initializes a slot or is passed to a
method.  If that initialization argument is not explicitly supplied in a
call to make-instance, the default value form is used, just as if it had
been supplied in the call.  In contrast, the :initform slot option
provides a mechanism for the user to give a default initial value form
for a slot.  An :initform form is used to initialize a slot only if no
initialization argument associated with that slot is given as an
argument to make-instance or is defaulted by :default-initargs.

   The order of evaluation of default value forms for initialization
arguments and the order of evaluation of :initform forms are undefined.
If the order of evaluation is important, initialize-instance or
shared-initialize methods should be used instead.


File: gcl.info,  Node: Rules for Initialization Arguments,  Next: Shared-Initialize,  Prev: Defaulting of Initialization Arguments,  Up: Object Creation and Initialization

7.1.4 Rules for Initialization Arguments
----------------------------------------

The :initarg slot option may be specified more than once for a given
slot.

   The following rules specify when initialization arguments may be
multiply defined:

*
     A given initialization argument can be used to initialize more than
     one slot if the same initialization argument name appears in more
     than one :initarg slot option.

*
     A given initialization argument name can appear in the lambda list
     of more than one initialization method.

*
     A given initialization argument name can appear both in an :initarg
     slot option and in the lambda list of an initialization method.

   [Reviewer Note by The next three paragraphs could be replaced by "If
two or more initialization arguments that initialize the same slot
appear in the defaulted initialization argument list, the leftmost of
these supplies the value, even if they have different names."  And the
rest would follow from the rules above.]

   If two or more initialization arguments that initialize the same slot
are given in the arguments to make-instance, the leftmost of these
initialization arguments in the initialization argument list supplies
the value, even if the initialization arguments have different names.

   If two or more different initialization arguments that initialize the
same slot have default values and none is given explicitly in the
arguments to make-instance, the initialization argument that appears in
a :default-initargs class option in the most specific of the classes
supplies the value.  If a single :default-initargs class option
specifies two or more initialization arguments that initialize the same
slot and none is given explicitly in the arguments to make-instance, the
leftmost in the :default-initargs class option supplies the value, and
the values of the remaining default value forms are ignored.

   Initialization arguments given explicitly in the arguments to
make-instance appear to the left of defaulted initialization arguments.
Suppose that the classes C_1 and C_2 supply the values of defaulted
initialization arguments for different slots, and suppose that C_1 is
more specific than C_2; then the defaulted initialization argument whose
value is supplied by C_1 is to the left of the defaulted initialization
argument whose value is supplied by C_2 in the defaulted initialization
argument list.  If a single :default-initargs class option supplies the
values of initialization arguments for two different slots, the
initialization argument whose value is specified farther to the left in
the :default-initargs class option appears farther to the left in the
defaulted initialization argument list.

   [Reviewer Note by Barmar: End of claim made three paragraphs back.]

   If a slot has both an :initform form and an :initarg slot option, and
the initialization argument is defaulted using :default-initargs or is
supplied to make-instance, the captured :initform form is neither used
nor evaluated.

   The following is an example of the above rules:

      (defclass q () ((x :initarg a)))
      (defclass r (q) ((x :initarg b))
        (:default-initargs a 1 b 2))

                                 Defaulted                                     
      Form                         Initialization Argument List Contents of Slot X 
      _____________________________________________________________________________
      (make-instance 'r)           (a 1 b 2)                    1                  
      (make-instance 'r 'a 3)      (a 3 b 2)                    3                  
      (make-instance 'r 'b 4)      (b 4 a 1)                    4                  
      (make-instance 'r 'a 1 'a 2) (a 1 a 2 b 2)                1                  



File: gcl.info,  Node: Shared-Initialize,  Next: Initialize-Instance,  Prev: Rules for Initialization Arguments,  Up: Object Creation and Initialization

7.1.5 Shared-Initialize
-----------------------

The generic function shared-initialize is used to fill the slots of an
instance using initialization arguments and :initform forms when an
instance is created, when an instance is re-initialized, when an
instance is updated to conform to a redefined class, and when an
instance is updated to conform to a different class.  It uses standard
method combination.  It takes the following arguments: the instance to
be initialized, a specification of a set of names of slots accessible in
that instance, and any number of initialization arguments.  The
arguments after the first two must form an initialization argument list.

   The second argument to shared-initialize may be one of the following:

*
     It can be a (possibly empty) list of slot names, which specifies
     the set of those slot names.

*
     It can be the symbol t, which specifies the set of all of the
     slots.

   There is a system-supplied primary method for shared-initialize whose
first parameter specializer is the class standard-object.  This method
behaves as follows on each slot, whether shared or local:

*
     If an initialization argument in the initialization argument list
     specifies a value for that slot, that value is stored into the
     slot, even if a value has already been stored in the slot before
     the method is run.  The affected slots are independent of which
     slots are indicated by the second argument to shared-initialize.

*
     Any slots indicated by the second argument that are still unbound
     at this point are initialized according to their :initform forms.
     For any such slot that has an :initform form, that form is
     evaluated in the lexical environment of its defining defclass form
     and the result is stored into the slot.  For example, if a before
     method stores a value in the slot, the :initform form will not be
     used to supply a value for the slot.  If the second argument
     specifies a name that does not correspond to any slots accessible
     in the instance, the results are unspecified.

*
     The rules mentioned in *note Rules for Initialization Arguments::
     are obeyed.

   The generic function shared-initialize is called by the
system-supplied primary methods for reinitialize-instance,
update-instance-for-different-class,
update-instance-for-redefined-class, and initialize-instance.  Thus,
methods can be written for shared-initialize to specify actions that
should be taken in all of these contexts.


File: gcl.info,  Node: Initialize-Instance,  Next: Definitions of Make-Instance and Initialize-Instance,  Prev: Shared-Initialize,  Up: Object Creation and Initialization

7.1.6 Initialize-Instance
-------------------------

The generic function initialize-instance is called by make-instance to
initialize a newly created instance.  It uses standard method
combination.  Methods for initialize-instance can be defined in order to
perform any initialization that cannot be achieved simply by supplying
initial values for slots.

   During initialization, initialize-instance is invoked after the
following actions have been taken:

*
     The defaulted initialization argument list has been computed by
     combining the supplied initialization argument list with any
     default initialization arguments for the class.

*
     The validity of the defaulted initialization argument list has been
     checked.  If any of the initialization arguments has not been
     declared as valid, an error is signaled.

*
     A new instance whose slots are unbound has been created.

   The generic function initialize-instance is called with the new
instance and the defaulted initialization arguments.  There is a
system-supplied primary method for initialize-instance whose parameter
specializer is the class standard-object.  This method calls the generic
function shared-initialize to fill in the slots according to the
initialization arguments and the :initform forms for the slots; the
generic function shared-initialize is called with the following
arguments: the instance, t, and the defaulted initialization arguments.

   Note that initialize-instance provides the defaulted initialization
argument list in its call to shared-initialize, so the first step
performed by the system-supplied primary method for shared-initialize
takes into account both the initialization arguments provided in the
call to make-instance and the defaulted initialization argument list.

   Methods for initialize-instance can be defined to specify actions to
be taken when an instance is initialized.  If only after methods for
initialize-instance are defined, they will be run after the
system-supplied primary method for initialization and therefore will not
interfere with the default behavior of initialize-instance.

   The object system provides two functions that are useful in the
bodies of initialize-instance methods.  The function slot-boundp returns
a generic boolean value that indicates whether a specified slot has a
value; this provides a mechanism for writing after methods for
initialize-instance that initialize slots only if they have not already
been initialized.  The function slot-makunbound causes the slot to have
no value.


File: gcl.info,  Node: Definitions of Make-Instance and Initialize-Instance,  Prev: Initialize-Instance,  Up: Object Creation and Initialization

7.1.7 Definitions of Make-Instance and Initialize-Instance
----------------------------------------------------------

The generic function make-instance behaves as if it were defined as
follows, except that certain optimizations are permitted:

      (defmethod make-instance ((class standard-class) &rest initargs)
        ...
        (let ((instance (apply #'allocate-instance class initargs)))
          (apply #'initialize-instance instance initargs)
          instance))

      (defmethod make-instance ((class-name symbol) &rest initargs)
        (apply #'make-instance (find-class class-name) initargs))

   The elided code in the definition of make-instance augments the
initargs with any defaulted initialization arguments and checks the
resulting initialization arguments to determine whether an
initialization argument was supplied that neither filled a slot nor
supplied an argument to an applicable method.

   The generic function initialize-instance behaves as if it were
defined as follows, except that certain optimizations are permitted:

      (defmethod initialize-instance ((instance standard-object) &rest initargs)
        (apply #'shared-initialize instance t initargs)))

   These procedures can be customized.

   Customizing at the Programmer Interface level includes using the
:initform, :initarg, and :default-initargs options to defclass, as well
as defining methods for make-instance, allocate-instance, and
initialize-instance.  It is also possible to define methods for
shared-initialize, which would be invoked by the generic functions
reinitialize-instance, update-instance-for-redefined-class,
update-instance-for-different-class, and initialize-instance.  The
meta-object level supports additional customization.

   Implementations are permitted to make certain optimizations to
initialize-instance and shared-initialize.  The description of
shared-initialize in Chapter~7 mentions the possible optimizations.


File: gcl.info,  Node: Changing the Class of an Instance,  Next: Reinitializing an Instance,  Prev: Object Creation and Initialization,  Up: Objects

7.2 Changing the Class of an Instance
=====================================

The function change-class can be used to change the class of an instance
from its current class, C_{from}, to a different class, C_{to}; it
changes the structure of the instance to conform to the definition of
the class C_{to}.

   Note that changing the class of an instance may cause slots to be
added or deleted.  Changing the class of an instance does not change its
identity as defined by the eq function.

   When change-class is invoked on an instance, a two-step updating
process takes place.  The first step modifies the structure of the
instance by adding new local slots and discarding local slots that are
not specified in the new version of the instance.  The second step
initializes the newly added local slots and performs any other
user-defined actions.  These two steps are further described in the two
following sections.

* Menu:

* Modifying the Structure of the Instance::
* Initializing Newly Added Local Slots (Changing the Class of an Instance)::
* Customizing the Change of Class of an Instance::


File: gcl.info,  Node: Modifying the Structure of the Instance,  Next: Initializing Newly Added Local Slots (Changing the Class of an Instance),  Prev: Changing the Class of an Instance,  Up: Changing the Class of an Instance

7.2.1 Modifying the Structure of the Instance
---------------------------------------------

In order to make the instance conform to the class C_{to}, local slots
specified by the class C_{to} that are not specified by the class
C_{from} are added, and local slots not specified by the class C_{to}
that are specified by the class C_{from} are discarded.

   The values of local slots specified by both the class C_{to} and the
class C_{from} are retained.  If such a local slot was unbound, it
remains unbound.

   The values of slots specified as shared in the class C_{from} and as
local in the class C_{to} are retained.

   This first step of the update does not affect the values of any
shared slots.


File: gcl.info,  Node: Initializing Newly Added Local Slots (Changing the Class of an Instance),  Next: Customizing the Change of Class of an Instance,  Prev: Modifying the Structure of the Instance,  Up: Changing the Class of an Instance

7.2.2 Initializing Newly Added Local Slots
------------------------------------------

The second step of the update initializes the newly added slots and
performs any other user-defined actions.  This step is implemented by
the generic function update-instance-for-different-class.  The generic
function update-instance-for-different-class is invoked by change-class
after the first step of the update has been completed.

   The generic function update-instance-for-different-class is invoked
on arguments computed by change-class.  The first argument passed is a
copy of the instance being updated and is an instance of the class
C_{from}; this copy has dynamic extent within the generic function
change-class.  The second argument is the instance as updated so far by
change-class and is an instance of the class C_{to}.  The remaining
arguments are an initialization argument list.

   There is a system-supplied primary method for
update-instance-for-different-class that has two parameter specializers,
each of which is the class standard-object.  First this method checks
the validity of initialization arguments and signals an error if an
initialization argument is supplied that is not declared as valid.  (For
more information, see *note Declaring the Validity of Initialization
Arguments::.)  Then it calls the generic function shared-initialize with
the following arguments: the new instance, a list of names of the newly
added slots, and the initialization arguments it received.


File: gcl.info,  Node: Customizing the Change of Class of an Instance,  Prev: Initializing Newly Added Local Slots (Changing the Class of an Instance),  Up: Changing the Class of an Instance

7.2.3 Customizing the Change of Class of an Instance
----------------------------------------------------

Methods for update-instance-for-different-class may be defined to
specify actions to be taken when an instance is updated.  If only after
methods for update-instance-for-different-class are defined, they will
be run after the system-supplied primary method for initialization and
will not interfere with the default behavior of
update-instance-for-different-class.

   Methods for shared-initialize may be defined to customize class
redefinition.  For more information, see *note Shared-Initialize::.


File: gcl.info,  Node: Reinitializing an Instance,  Next: Meta-Objects,  Prev: Changing the Class of an Instance,  Up: Objects

7.3 Reinitializing an Instance
==============================

The generic function reinitialize-instance may be used to change the
values of slots according to initialization arguments.

   The process of reinitialization changes the values of some slots and
performs any user-defined actions.  It does not modify the structure of
an instance to add or delete slots, and it does not use any :initform
forms to initialize slots.

   The generic function reinitialize-instance may be called directly.
It takes one required argument, the instance.  It also takes any number
of initialization arguments to be used by methods for
reinitialize-instance or for shared-initialize.  The arguments after the
required instance must form an initialization argument list.

   There is a system-supplied primary method for reinitialize-instance
whose parameter specializer is the class standard-object.  First this
method checks the validity of initialization arguments and signals an
error if an initialization argument is supplied that is not declared as
valid.  (For more information, see *note Declaring the Validity of
Initialization Arguments::.)  Then it calls the generic function
shared-initialize with the following arguments: the instance, nil, and
the initialization arguments it received.

* Menu:

* Customizing Reinitialization::


File: gcl.info,  Node: Customizing Reinitialization,  Prev: Reinitializing an Instance,  Up: Reinitializing an Instance

7.3.1 Customizing Reinitialization
----------------------------------

Methods for reinitialize-instance may be defined to specify actions to
be taken when an instance is updated.  If only after methods for
reinitialize-instance are defined, they will be run after the
system-supplied primary method for initialization and therefore will not
interfere with the default behavior of reinitialize-instance.

   Methods for shared-initialize may be defined to customize class
redefinition.  For more information, see *note Shared-Initialize::.


File: gcl.info,  Node: Meta-Objects,  Next: Slots,  Prev: Reinitializing an Instance,  Up: Objects

7.4 Meta-Objects
================

The implementation of the object system manipulates classes, methods,
and generic functions.  The object system contains a set of generic
functions defined by methods on classes; the behavior of those generic
functions defines the behavior of the object system.  The instances of
the classes on which those methods are defined are called meta-objects.

* Menu:

* Standard Meta-objects::


File: gcl.info,  Node: Standard Meta-objects,  Prev: Meta-Objects,  Up: Meta-Objects

7.4.1 Standard Meta-objects
---------------------------

The object system supplies a set of meta-objects, called standard
meta-objects.  These include the class standard-object and instances of
the classes standard-method, standard-generic-function, and
method-combination.

     [Editorial Note by KMP: This is said redundantly in the definition
     of STANDARD-METHOD.]
*
     The class standard-method is the default class of methods defined
     by the defmethod and defgeneric forms.

*
     The class standard-generic-function is the default class of generic
     functions defined by the forms defmethod, defgeneric,

     and defclass.

*
     The class named standard-object is an instance of the class
     standard-class and is a superclass of every class that is an
     instance of standard-class except itself and structure-class.

*
     Every method combination object is an instance of a subclass of
     class method-combination.


File: gcl.info,  Node: Slots,  Next: Generic Functions and Methods,  Prev: Meta-Objects,  Up: Objects

7.5 Slots
=========

* Menu:

* Introduction to Slots::
* Accessing Slots::
* Inheritance of Slots and Slot Options::

