-
Notifications
You must be signed in to change notification settings - Fork 9
/
contrl.tex
8224 lines (7255 loc) · 401 KB
/
contrl.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%Part{Contrl, Root = "CLM.MSS"}
%Chapter of Common Lisp Manual. Copyright 1984, 1988, 1989 Guy L. Steele Jr.
\clearpage\def\pagestatus{ULTIMATE}
\ifx \rulang\Undef
\chapter{Control Structure}
\label{CONTRL}
Common Lisp provides a variety of special structures for organizing
programs. Some have to do with flow of control (control structures),
while others control access to variables (environment structures).
Some of these features are implemented as special operators;
others are implemented as macros, which typically expand into
complex program fragments expressed in terms of special operators
or other macros.
Function application is the primary method for construction of Lisp
programs. Operations are written as the application of a function
to its arguments. Usually, Lisp programs are written as a large collection
of small functions, each of which implements a simple operation.
These functions operate by calling one another, and so larger
operations are defined in terms of smaller ones.
Lisp functions may call upon themselves recursively,
either directly or indirectly.
Locally defined functions (\cdf{flet}, \cdf{labels}) and macros (\cdf{macrolet})
are quite versatile.
The new symbol macro facility allows even more syntactic flexibility.
While the Lisp language
is more applicative in style than statement-oriented, it
nevertheless provides many operations that produce side effects and
consequently requires constructs for controlling the sequencing of
side effects. The construct
\cdf{progn}, which is roughly equivalent to an Algol \textbf{begin}-\textbf{end}
block with all its semicolons, executes a number of forms sequentially,
discarding the values of all but the last.
Many Lisp control constructs
include sequencing implicitly, in which case they are said to
provide an ``implicit \cdf{progn}.''
\indexterm{implicit \cdf{progn}}
Other sequencing constructs include \cdf{prog1} and \cdf{prog2}.
For looping, Common Lisp provides the general iteration facility
\cdf{do} as well as a variety
of special-purpose iteration facilities for iterating or mapping
over various data structures.
Common Lisp provides the simple one-way conditionals \cdf{when} and \cdf{unless},
the simple two-way conditional \cdf{if}, and the more general multi-way
conditionals such as \cdf{cond} and \cdf{case}. The choice of which form
to use in any particular situation is a matter of taste and
style.
Constructs for performing non-local exits with various scoping
disciplines are provided: \cdf{block}, \cdf{return},
\cdf{return-from},
\cdf{catch}, and \cdf{throw}.
The multiple-value constructs provide an efficient way for a function
to return more than one value; see \cdf{values}.
\section{Constants and Variables}
\label{FUNCTION-NAME-SECTION}
Because some Lisp data objects are used to represent programs,
one cannot always notate a constant data object in a program simply
by writing the notation for the object unadorned; it would be ambiguous
whether a constant object or a program fragment was intended.
The \cdf{quote} special operator resolves this ambiguity.
There are two kinds of variables in Common Lisp, in effect: ordinary
variables and function names. There are some similarities between
the two kinds, and in a few cases there are similar functions for
dealing with them, for example \cdf{boundp} and \cdf{fboundp}.
However, for the most part the two kinds of variables are
used for very different purposes: one to name defined functions,
macros, and special operators, and the other to name data objects.
\begin{newer}
X3J13 voted in March 1989 \issue{FUNCTION-NAME} to introduce the concept
of a \emph{function-name}, which may be either a symbol or a two-element list whose
first element is the symbol \cdf{setf} and whose second element is a symbol.
The primary purpose of this is to allow \cdf{setf} expander functions to be
CLOS generic functions with user-defined methods.
Many places in Common Lisp that used to require a symbol for a function
name are changed to allow 2-lists as well; for example, \cdf{defun}
is changed so that one may write \cd{(defun (setf~foo) ...)},
and the \cdf{function} special operator is changed to accept any function-name.
See also \cdf{fdefinition}.
By convention, any function named \cd{(setf \emph{f\/})} should return its first
argument as its only value, in order to preserve the specification that
\cdf{setf} returns its \emph{newvalue}. See \cdf{setf}.
Implementations are free to extend the syntax of function-names to
include lists beginning with additional symbols other than \cdf{setf}
or \cdf{lambda}.
\end{newer}
\subsection{Reference}
The value of an ordinary variable
may be obtained simply by writing the name of the variable
as a form to be executed. Whether this is treated as the name
of a special variable or a lexical variable is determined
by the presence or absence of an applicable \cdf{special} declaration;
see chapter~\ref{DECLAR}.
The following functions and special operators allow reference to the
values of constants and variables in other ways.
\begin{defspec}
quote object
\cd{(quote \emph{x})} simply returns \emph{x}.
The \emph{object} is not evaluated and may be any Lisp object whatsoever.
This construct allows any Lisp object to be written as a constant
value in a program.
For example:
\begin{lisp}
(setq a 43) \\
(list a (cons a 3)) \EV\ (43 (43 . 3)) \\
(list (quote a) (quote (cons a 3)) \EV\ (a (cons a 3))
\end{lisp}
Since \cdf{quote} forms are so frequently useful
but somewhat cumbersome to type, a standard abbreviation is defined for them:
any form \emph{f} preceded by a single quote (\cd{~'~}) character
is assumed to have \cd{(quote~~)} wrapped around it to
make \cd{(quote \emph{f})}.
For example:
\begin{lisp}
(setq x '(the magic quote hack))
\end{lisp}
is normally interpreted by \cdf{read} to mean
\begin{lisp}
(setq x (quote (the magic quote hack)))
\end{lisp}
See section~\ref{MACRO-CHARACTERS-SECTION}.
It is an error to destructively modify any object that appears as a constant
in executable code, whether within a \cdf{quote} special operator or as
a self-evaluating form.
See section~\ref{COMPILER-SECTION} for a discussion of how quoted constants
are treated by the compiler.
\begin{newer}
X3J13 voted in March 1989 \issue{QUOTE-SEMANTICS} to clarify that
\cdf{eval} and \cdf{compile} are not permitted either to copy or
to coalesce (``collapse'') constants (see \cdf{eq})
appearing in the code they process; the resulting
program behavior must refer to objects that are \cdf{eql} to the
corresponding objects in the source code.
Moreover, the constraints introduced by the votes on
issues \issue{CONSTANT-COMPILABLE-TYPES}
and \issue{CONSTANT-CIRCULAR-COMPILATION}
on what kinds of objects may appear
as constants apply only to \cdf{compile-file} (see section~\ref{COMPILER-SECTION}).
\end{newer}
\end{defspec}
\begin{defspec}
function fn
The value of \cdf{function} is always the functional interpretation
of \emph{fn}; \emph{fn} is interpreted as if it had appeared
in the functional position of a function invocation.
In particular,
if \emph{fn} is a symbol, the functional definition associated with
that symbol is returned; see \cdf{symbol-function}.
If \emph{fn} is a lambda-expression, then a
``lexical closure'' is returned, that is, a function that when invoked
will execute the body of the lambda-expression in such a way as to
observe the rules of lexical scoping properly.
\begin{newer}
X3J13 voted in June 1988 \issue{FUNCTION-TYPE}
to specify that the result of a \cdf{function} special operator is always
of type \cdf{function}. This implies that a form \cd{(function~\emph{fn\/})}
may be interpreted as \cd{(the (function~\emph{fn\/}))}.
It is an error to use the \cdf{function} special operator on a
symbol that does not denote a function in the lexical or global environment in
which the special operator appears. Specifically, it is an error to use the
\cdf{function} special operator on a symbol that denotes a macro or special operator.
Some implementations may choose not to signal this error for
performance reasons, but implementations are forbidden
to extend the semantics of \cdf{function} in this respect; that is, an
implementation is not allowed to
define the failure to signal an error to be a ``useful'' behavior.
\end{newer}
\cdf{function}
accepts any function-name (a symbol or a list
whose \emph{car} is \cdf{setf}---see section~\ref{FUNCTION-NAME-SECTION})
as well as lambda-expressions.
Thus one may write \cd{(function (setf cadr))} to refer to the \cdf{setf}
expansion function for \cdf{cadr}.
\indexterm{closure}
For example:
\begin{lisp}
(defun adder (x) (function (lambda (y) (+ x y))))
\end{lisp}
The result of \cd{(adder 3)} is a function that will add \cd{3} to its
argument:
\begin{lisp}
(setq add3 (adder 3)) \\
(funcall add3 5) \EV\ 8
\end{lisp}
This works because \cdf{function} creates a closure of
the inner lambda-expression that is able to refer to the value \cd{3}
of the variable \cd{x} even after control has returned from the
function \cdf{adder}.
More generally, a lexical closure in effect retains the ability to
refer to lexically visible \emph{bindings}, not just values.
Consider this code:
\begin{lisp}
(defun two-funs (x) \\
~~(list (function (lambda () x)) \\
~~~~~~~~(function (lambda (y) (setq x y))))) \\
(setq funs (two-funs 6)) \\
(funcall (car funs)) \EV\ 6 \\
(funcall (cadr funs) 43) \EV\ 43 \\
(funcall (car funs)) \EV\ 43
\end{lisp}
The function \cdf{two-funs} returns a list of two functions, each of which
refers to the \emph{binding} of the variable \cdf{x} created on entry to
the function \cdf{two-funs} when it was called with argument \cd{6}.
This binding has the value \cd{6} initially, but \cdf{setq} can alter
a binding. The lexical closure created for the first lambda-expression
does not ``snapshot'' the value \cd{6} for \cdf{x} when the closure is created.
The second function can be used to alter the binding (to \cd{43}, in the
example), and this altered
value then becomes accessible to the first function.
In situations where a closure of a lambda-expression over the same set
of bindings may be produced more than once, the various resulting closures
may or may not be \cdf{eq}, at the discretion of the implementation.
For example:
\begin{lisp}
(let ((x 5) (funs '())) \\*
~~(dotimes (j 10) \\*
~~~~(push \#'(lambda (z) \\*
~~~~~~~~~~~~~~(if (null z) (setq x 0) (+ x z))) \\*
~~~~~~~~~~funs)) \\*
~~funs)
\end{lisp}
The result of the above expression is a list of ten closures.
Each logically requires only the binding of \cdf{x}.
It is the same binding in each case,
so the ten closures may or may not be the same identical (\cdf{eq}) object.
On the other hand, the result of the expression
\begin{lisp}
(let ((funs '())) \\*
~~(dotimes (j 10) \\*
~~~~(let ((x 5)) \\*
~~~~~~(push (function (lambda (z) \\*
~~~~~~~~~~~~~~~~~~~~~~~~(if (null z) (setq x 0) (+ x z)))) \\*
~~~~~~~~~~~~funs))) \\*
~~funs)
\end{lisp}
is also a list of ten closures.
However, in this case no two of the closures may be \cdf{eq}, because each
closure is over a distinct binding of \cdf{x}, and these bindings can
be behaviorally distinguished because of the use of \cdf{setq}.
The question of distinguishable behavior is important; the result of
the simpler expression
\begin{lisp}
(let ((funs '())) \\*
~~(dotimes (j 10) \\*
~~~~(let ((x 5)) \\*
~~~~~~(push (function (lambda (z) (+ x z))) \\*
~~~~~~~~~~~~funs))) \\*
~~funs)
\end{lisp}
is a list of ten closures that \emph{may} be pairwise \cdf{eq}. Although
one might think that a different binding of \cdf{x} is involved for
each closure (which is indeed the case), the bindings cannot be distinguished
because their values are identical and immutable, there being no occurrence
of \cdf{setq} on \cdf{x}. A compiler would therefore be justified in
transforming the expression to
\begin{lisp}
(let ((funs '())) \\*
~~(dotimes (j 10) \\*
~~~~(push (function (lambda (z) (+ 5 z))) \\*
~~~~~~~~~~funs)) \\*
~~funs)
\end{lisp}
where clearly the closures may be the same after all.
The general rule, then, is that the implementation is free to
have two distinct evaluations of the same \cdf{function} form
produce identical (\cdf{eq}) closures if it can prove that the
two conceptually distinct resulting closures must in fact be
behaviorally identical with respect to invocation.
This is merely a permitted optimization; a perfectly valid
implementation might simply cause every distinct evaluation of a \cdf{function}
form to produce a new closure object not \cdf{eq} to any other.
Frequently a compiler can deduce that a closure in fact does not
need to close over any variable bindings. For example,
in the code fragment
\begin{lisp}
(mapcar (function (lambda (x) (+ x 2))) y)
\end{lisp}
the function \cd{(lambda (x) (+ x 2))} contains no references to any outside
entity. In this important special case, the same ``closure'' may be used
as the value for all evaluations of the \cdf{function} special operator.
Indeed, this value need not be a closure object at all; it may
be a simple compiled function containing no environment information.
This example is simply a special case of the foregoing discussion and
is included as a hint to implementors familiar with previous methods
of implementing Lisp. The distinction between closures and other
kinds of functions is somewhat pointless, actually, as Common Lisp defines
no particular representation for closures and no way to distinguish
between closures and non-closure functions. All that matters is that
the rules of lexical scoping be obeyed.
Since \cdf{function} forms are so frequently useful
but somewhat cumbersome to type, a standard abbreviation is defined for them:
any form \emph{f} preceded by \cd{\#'} (\cd{\#} followed by an apostrophe)
is assumed to have \cd{(function )} wrapped around it to make
\cd{(function \emph{f})}. For example,
\begin{lisp}
(remove-if \#'numberp '(1 a b 3))
\end{lisp}
is normally interpreted by \cdf{read} to mean
\begin{lisp}
(remove-if (function numberp) '(1 a b 3))
\end{lisp}
See section~\ref{SHARP-SIGN-MACRO-CHARACTER-SECTION}.
\end{defspec}
\begin{defun}[Function]
symbol-value symbol
\cdf{symbol-value} returns the current value of the dynamic (special) variable
named by \emph{symbol}.
An error occurs if the symbol has no value; see \cdf{boundp}
and \cdf{makunbound}.
Note that constant symbols are really variables that cannot be changed,
and so \cdf{symbol-value} may be used to get the value of
a named constant. In particular, \cdf{symbol-value} of a keyword
will return that keyword.
\cdf{symbol-value} cannot access the value of a lexical variable.
This function is particularly useful for implementing interpreters
for languages embedded in Lisp.
The corresponding assignment primitive is \cdf{set};
alternatively, \cdf{symbol-value} may be used with \cdf{setf}.
\end{defun}
\begin{defun}[Function]
symbol-function symbol
\cdf{symbol-function} returns the current global function definition
named by \emph{symbol}. An error is signalled if the symbol has no function
definition; see \cdf{fboundp}. Note that the definition may be a
function or may be an object representing a special operator or macro.
In the latter case, however, it is an error
to attempt to invoke the object as a function.
If it is desired to process macros, special operators, and functions
equally well, as when writing an interpreter,
it is best first to test the symbol with \cdf{macro-function}
and \cdf{special-operator-p}
and then to invoke the functional value only if these
two tests both yield false.
This function is particularly useful for implementing interpreters
for languages embedded in Lisp.
\cdf{symbol-function} cannot access the value of a lexical function name
produced by \cdf{flet} or \cdf{labels}; it can access only
the global function value.
The global function definition of a symbol may be altered
by using \cdf{setf} with \cdf{symbol-function}.
Performing this operation causes the symbol to have \emph{only} the
specified definition as its global function definition; any previous
definition, whether as a macro or as a function, is lost.
It is an error to attempt to redefine the name of a special
form (see table~\ref{SPECIAL-FORM-TABLE}).
\begin{newer}
X3J13 voted in June 1988 \issue{FUNCTION-TYPE} to clarify the behavior
of \cdf{symbol-function} in the light of the redefinition of the type \cdf{function}.
\begin{itemize}
\item It is permissible to call \cdf{symbol-function}
on any symbol for which \cdf{fboundp} returns true.
Note that \cdf{fboundp} must return true for a symbol naming a macro or
a special operator.
\item If \cdf{fboundp} returns true for a symbol
but the symbol denotes a macro or special operator,
then the value returned by \cdf{symbol-function} is not well-defined
but \cdf{symbol-function} will not signal an error.
\item When \cdf{symbol-function} is used with \cdf{setf}
the new value must be of type \cdf{function}.
It is an error to set the \cdf{symbol-function} of a symbol to a
symbol, a list, or the value returned by \cdf{symbol-function} on
the name of a macro or a special operator.
\end{itemize}
\end{newer}
\end{defun}
\begin{defun}[Function]
fdefinition function-name
X3J13 voted in March 1989 \issue{FUNCTION-NAME} to add the function
\cdf{fdefinition} to the language.
It is exactly like \cdf{symbol-function}
except that its argument may be any function-name (a symbol or a list
whose \emph{car} is \cdf{setf}---see section~\ref{FUNCTION-NAME-SECTION});
it returns the current global function
definition named by the argument \emph{function-name}.
One may use \cdf{fdefinition} with \cdf{setf}
to change the current global function definition associated with
a function-name.
\end{defun}
\begin{defun}[Function]
boundp symbol
\cdf{boundp} is true if the dynamic (special) variable named by \emph{symbol}
has a value; otherwise, it returns {\false}.
See also \cdf{set} and \cdf{makunbound}.
\end{defun}
\begin{defun}[Function]
fboundp symbol
\cdf{fboundp} is true if the symbol has a global function definition.
Note that \cdf{fboundp} is true when the symbol names a special operator or
macro. \cdf{macro-function} and \cdf{special-operator-p} may be used to test
for these cases.
Despite the tightening of the definition of the type \cdf{function},
\cdf{fboundp} must return true when the argument names a special operator or
macro.
See also \cdf{symbol-function} and \cdf{fmakunbound}.
\cdf{fboundp}
accepts any function-name (a symbol or a list
whose \emph{car} is \cdf{setf}---see section~\ref{FUNCTION-NAME-SECTION}).
Thus one may write \cd{(fboundp '(setf cadr))} to determine whether a \cdf{setf}
expansion function has been globally defined for \cdf{cadr}.
\end{defun}
\begin{defun}[Function]
special-operator-p symbol
The function \cdf{special-operator-p} takes a symbol. If the symbol
globally names a special operator,
then a non-{\false} value is returned; otherwise {\false} is returned.
A returned non-{\nil} value is typically a function
of implementation-dependent nature that can be used to
interpret (evaluate) the special operator.
It is possible for \emph{both} \cdf{special-operator-p} and \cdf{macro-function}
to be true of a symbol. This is possible because an implementation is
permitted to implement any macro also as a special operator for speed.
On the other hand, the macro definition must be available
for use by programs that understand only the standard special operators
listed in table~\ref{SPECIAL-FORM-TABLE}.
\end{defun}
\subsection{Assignment}
The following facilities allow the value of a variable (more specifically,
the value associated with the current binding of the variable) to be altered.
Such alteration is different from establishing a new binding.
Constructs for establishing new bindings of variables are described
in section~\ref{VAR-BINDING-SECTION}.
\begin{defspec}
setq {var form}*
The special operator \cd{(setq \emph{var1} \emph{form1} \emph{var2} \emph{form2} ...)} is the
``simple variable assignment statement'' of Lisp.
First \emph{form1} is evaluated
and the result is stored in the variable \emph{var1}, then \emph{form2}
is evaluated and the result stored in \emph{var2}, and so forth.
The variables are represented as symbols, of course, and are interpreted
as referring to static or dynamic instances according to the usual rules.
Therefore \cdf{setq} may be used for assignment of both lexical
and special variables.
\cdf{setq} returns the last value assigned, that is, the result of the
evaluation of its last argument.
As a boundary case, the form \cd{(setq)} is legal and returns {\false}.
There must be an even number of argument forms.
For example, in
\begin{lisp}
(setq x (+ 3 2 1) y (cons x nil))
\end{lisp}
\cdf{x} is set to \cd{6}, \cdf{y} is set to \cd{(6)}, and the \cdf{setq}
returns \cd{(6)}. Note that the first assignment is performed before
the second form is evaluated, allowing that form to
use the new value of \cdf{x}.
See also the description of \cdf{setf},
the Common Lisp ``general assignment statement'' that is capable of assigning
to variables, array elements, and other locations.
Some programmers choose to avoid
\cdf{setq} as a matter of style, always using \cdf{setf} for any kind of
structure modification. Others use \cdf{setq} with simple variable names and
\cdf{setf} with all other generalized variables.
If any \emph{var}
refers not to an ordinary variable but to a binding made by
\cdf{symbol-macrolet}, then that \emph{var} is handled as
if \cdf{setf} had been used instead of \cdf{setq}.
\end{defspec}
\begin{defmac}
psetq {var form}*
A \cdf{psetq} form is just like a \cdf{setq} form, except
that the assignments happen in parallel. First all of the forms
are evaluated, and then the variables are set to the resulting
values. The value of the \cdf{psetq} form is {\false}.
For example:
\begin{lisp}
(setq a 1) \\
(setq b 2) \\
(psetq a b b a) \\
a \EV\ 2 \\
b \EV\ 1
\end{lisp}
In this example, the values of \cdf{a} and \cdf{b} are exchanged by
using parallel assignment.
(If several variables are to be assigned in parallel in
the context of a loop, the \cdf{do} construct may be appropriate.)
See also the description of \cdf{psetf},
the Common Lisp ``general parallel assignment statement'' that
is capable of assigning
to variables, array elements, and other locations.
If any \emph{var}
refers not to an ordinary variable but to a binding made by
\cdf{symbol-macrolet}, then that \emph{var} is handled as
if \cdf{psetf} had been used instead of \cdf{psetq}.
\end{defmac}
\begin{defun}[Function]
set symbol value
\cdf{set} allows alteration of the value of a dynamic (special) variable.
\cdf{set} causes the dynamic variable named by \emph{symbol} to take on
\emph{value} as its value.
The \emph{value}
may be any Lisp datum whatsoever.
Only the value of the current dynamic binding is altered;
if there are no bindings in effect, the most global value is altered.
For example,
\begin{lisp}
(set (if (eq a b) 'c 'd) 'foo)
\end{lisp}
will either set \cdf{c} to \cdf{foo} or set \cdf{d} to \cdf{foo}, depending
on the outcome of the test \cd{(eq~a~b)}.
\cdf{set} returns \emph{value} as its result.
\cdf{set} cannot alter
the value of a local (lexically bound) variable.
The special operator \cdf{setq}
is usually used for altering the values of variables
(lexical or dynamic) in programs.
\cdf{set} is particularly useful for implementing interpreters for
languages embedded in Lisp.
See also \cdf{progv}, a construct that performs binding rather
than assignment of dynamic variables.
\end{defun}
\begin{defun}[Function]
makunbound symbol \\
fmakunbound symbol
\cdf{makunbound} causes the dynamic (special) variable named
by \emph{symbol} to become unbound (have no value). \cdf{fmakunbound}
does the analogous thing for the global function definition named
by \emph{symbol}.
For example:
\begin{lisp}
(setq a 1) \\
a \EV\ 1 \\
(makunbound 'a) \\
a \EV\ \textrm{causes an error} \\
\\
(defun foo (x) (+ x 1)) \\
(foo 4) \EV\ 5 \\
(fmakunbound 'foo) \\
(foo 4) \EV\ \textrm{causes an error}
\end{lisp}
Both functions return \emph{symbol} as the result value.
\cdf{fmakunbound}
accepts any function-name (a symbol or a list
whose \emph{car} is \cdf{setf}---see section~\ref{FUNCTION-NAME-SECTION}).
Thus one may write \cd{(fmakunbound '(setf cadr))} to remove any
global definition of a \cdf{setf} expansion function for \cdf{cadr}.
\end{defun}
\section{Generalized Variables}
\label{SETF-SECTION}
In Lisp, a variable can remember one piece of data,
that is, one Lisp object.
The main operations on a variable are to recover that object and
to alter the variable to remember a new object; these operations are
often called \emph{access} and \emph{update} operations. The concept of
variables named by symbols can be generalized to any storage location
that can remember one piece of data, no matter how that location is
named. Examples of such storage locations are the \emph{car} and \emph{cdr} of
a cons, elements of an array, and components of a structure.
For each kind of generalized variable, typically there are two functions
that implement the conceptual \emph{access} and \emph{update} operations.
For a variable, merely mentioning the name of the variable accesses it,
while the \cdf{setq} special operator can be used to update it.
The function \cdf{car} accesses the \emph{car} of a cons,
and the function \cdf{rplaca} updates it.
The function \cdf{symbol-value} accesses the dynamic value of a variable
named by a given symbol, and the function \cdf{set} updates it.
Rather than thinking about two distinct functions that respectively
access and update a storage location somehow deduced from their
arguments, we can instead simply think of a call to the access function
with given arguments as a \emph{name} for the storage location. Thus, just
as \cdf{x} may be considered a name for a storage location (a variable), so
\cd{(car x)} is a name for the \emph{car} of some cons (which is in turn
named by \cdf{x}). Now, rather than having to remember two functions for
each kind of generalized variable (having to remember, for example, that
\cdf{rplaca} corresponds to \cdf{car}), we adopt a uniform syntax for updating
storage locations named in this way, using the \cdf{setf} macro.
This is analogous to the way we use the \cdf{setq} special operator to convert
the name of a variable (which is also a form that accesses it) into a
form that updates it. The uniformity of this approach is illustrated in
the following table.
\begin{flushleft}
\begin{tabular*}{\textwidth}{@{}l@{\extracolsep{\fill}}ll@{}}
\textrm{Access Function}&\textrm{Update Function}&\textrm{Update Using \cdf{setf}} \\
\hlinesp
\cd{x}&\cd{(setq x datum)}&\cd{(setf x datum)} \\
\cd{(car x)}&\cd{(rplaca x datum)}&\cd{(setf (car x) datum)} \\
\cd{(symbol-value x)}&\cd{(set x datum)}&\cd{(setf (symbol-value x) datum)} \\
\hline
\end{tabular*}
\end{flushleft}
\cdf{setf} is actually a macro that examines an access form and
produces a call to the corresponding update function.
Given the existence of \cdf{setf} in Common Lisp, it is not necessary to have
\cdf{setq}, \cdf{rplaca}, and \cdf{set}; they are redundant. They
are retained in Common Lisp because of their historical importance in Lisp.
However, most other update functions (such as \cdf{putprop}, the update
function for \cdf{get}) have been eliminated from Common Lisp
in the expectation that \cdf{setf} will be uniformly used in their place.
\begin{defmac}
setf {place newvalue}*
\cd{(setf \emph{place} \emph{newvalue})} takes a form \emph{place} that when evaluated
\emph{accesses} a data object in some location and ``inverts''
it to produce a corresponding form to \emph{update} the location.
A call to the \cdf{setf} macro therefore
expands into an update form that stores the result of evaluating
the form \emph{newvalue} into the place referred to by the access form.
If more than one \emph{place}-\emph{newvalue} pair is specified,
the pairs are processed sequentially; that is,
\begin{lisp}
(setf \emph{place1} \emph{newvalue1} \\
~~~~~~\emph{place2} \emph{newvalue2}) \\
~~~~~~... \\
~~~~~~\emph{placen} \emph{newvaluen})
\end{lisp}
is precisely equivalent to
\begin{lisp}
(progn (setf \emph{place1} \emph{newvalue1}) \\
~~~~~~~(setf \emph{place2} \emph{newvalue2}) \\
~~~~~~~... \\
~~~~~~~(setf \emph{placen} \emph{newvaluen}))
\end{lisp}
For consistency, it is legal to write \cd{(setf)}, which simply returns {\nil}.
The form \emph{place} may be any one of the following:
\begin{itemize}
\item
The name of a variable (either lexical or dynamic).
\item
A function call form whose first element is the name of
any one of the following functions:
\begin{flushleft}
\begin{tabular}{@{}llll@{}}
\cdf{aref}&\cdf{car}&\cdf{svref}& \\
\cdf{nth}&\cdf{cdr}&\cdf{get}& \\
\cdf{elt}&\cdf{caar}&\cdf{getf}&\cdf{symbol-value} \\
\cdf{rest}&\cdf{cadr}&\cdf{gethash}&\cdf{symbol-function} \\
\cdf{first}&\cdf{cdar}&\cdf{documentation}&\cdf{symbol-plist} \\
\cdf{second}&\cdf{cddr}&\cdf{fill-pointer}&\cdf{macro-function} \\
\cdf{third}&\cdf{caaar}&\cdf{caaaar}&\cdf{cdaaar} \\
\cdf{fourth}&\cdf{caadr}&\cdf{caaadr}&\cdf{cdaadr} \\
\cdf{fifth}&\cdf{cadar}&\cdf{caadar}&\cdf{cdadar} \\
\cdf{sixth}&\cdf{caddr}&\cdf{caaddr}&\cdf{cdaddr} \\
\cdf{seventh}&\cdf{cdaar}&\cdf{cadaar}&\cdf{cddaar} \\
\cdf{eighth}&\cdf{cdadr}&\cdf{cadadr}&\cdf{cddadr} \\
\cdf{ninth}&\cdf{cddar}&\cdf{caddar}&\cdf{cdddar} \\
\cdf{tenth}&\cdf{cdddr}&\cdf{cadddr}&\cdf{cddddr} \\
\cdf{row-major-aref}&\cdf{compiler-macro-function}& &
\end{tabular}
\end{flushleft}
This
rule applies only when the function name refers to a global function
definition and not to a locally defined function or macro.
\item
A function call form whose first element is the name of
a selector function constructed by \cdf{defstruct}.
This
rule applies only when the function name refers to a global function
definition and not to a locally defined function or macro.
\item
A function call form whose first element is the name of
any one of the following functions, provided that the new value
is of the specified type so that it can be used to
replace the specified ``location'' (which is in each of these cases
not truly a generalized variable):
\begin{obsolete}
\begin{flushleft}
\leavevmode
\begin{tabular}{@{}ll@{}}
Function Name&Required Type \\
\hlinesp
\cdf{char}&\cdf{string-char} \\
\cdf{schar}&\cdf{string-char} \\
\cdf{bit}&\cdf{bit} \\
\cdf{sbit}&\cdf{bit} \\
\cdf{subseq}&\cdf{sequence} \\
\hline
\end{tabular}
\end{flushleft}
\end{obsolete}
\begin{newer}
X3J13 voted in March 1989 \issue{CHARACTER-PROPOSAL}
to eliminate the type \cdf{string-char} and to redefine
\cdf{string} to be the union of one or more specialized vector
types, the types of whose elements are subtypes of the type \cdf{character}.
In the preceding table, the type \cdf{string-char} should be replaced
by some such phrase as ``the element-type of the argument vector.''
\end{newer}
\begin{newer}
X3J13 voted in March 1989 \issue{FUNCTION-NAME} to clarify that this
rule applies only when the function name refers to a global function
definition and not to a locally defined function or macro.
\end{newer}
In the case of \cdf{subseq}, the replacement value must be a sequence
whose elements may be contained by the sequence argument to \cdf{subseq}.
(Note that this is not so stringent as to require that the
replacement value be a sequence of the same type as the sequence
of which the subsequence is specified.)
If the length of the replacement value does not equal the length of
the subsequence to be replaced, then the shorter length determines
the number of elements to be stored, as for the function \cdf{replace}.
\item
A function call form whose first element is the name of
any one of the following functions, provided that the specified argument
to that function is in turn a \emph{place} form;
in this case the new \emph{place} has stored back into it the
result of applying the specified ``update'' function
(which is in each of these cases not a true update function):
\begin{flushleft}
\begin{tabular}{@{}lll@{}}
Function Name&Argument That Is a \emph{place}&Update Function Used \\
\hlinesp
\cdf{ldb}&second&\cdf{dpb} \\
\cdf{mask-field}&second&\cdf{deposit-field} \\
\hline
\end{tabular}
\end{flushleft}
This
rule applies only when the function name refers to a global function
definition and not to a locally defined function or macro.
\item
A \cdf{the} type declaration form, in which case the declaration is
transferred to the \emph{newvalue} form, and the resulting \cdf{setf} form is
analyzed. For example,
\begin{lisp}
(setf (the integer (cadr x)) (+ y 3))
\end{lisp}
is processed as if it were
\begin{lisp}
(setf (cadr x) (the integer (+ y 3)))
\end{lisp}
\item
A call to \cdf{apply} where the first argument form is of the form
\cd{\#'\emph{name}}, that is, \cd{(function \emph{name})}, where \emph{name}
is the name of a function, calls to which are recognized as places by \cdf{setf}.
Suppose that the use of \cdf{setf} with \cdf{apply} looks like this:
\begin{lisp}
(setf (apply \#'\emph{name} \emph{x1} \emph{x2} ... \emph{xn} \emph{rest}) \emph{x0})
\end{lisp}
The \cdf{setf} method for the function \emph{name} must be such that
\begin{lisp}
(setf (\emph{name} \emph{z1} \emph{z2} ... \emph{zm}) \emph{z0})
\end{lisp}
expands into a store form
\begin{lisp}
(\emph{storefn} \emph{zi${}_1$} \emph{zi${}_2$} ... \emph{zi${}_k$} \emph{zm})
\end{lisp}
That is, it must expand into a function call such that all arguments but
the last may be any permutation or subset of the new value \emph{z0} and
the arguments of the access form, but the \emph{last} argument of the storing
call must be the same as the last argument of the access call.
See \cdf{define-setf-method} for more details on accessing
and storing forms.
Given this, the \cdf{setf}-of-\cdf{apply} form shown above expands into
\begin{lisp}
(apply \#'\emph{storefn} \emph{xi${}_1$} \emph{xi${}_2$} ... \emph{xi${}_k$} \emph{rest})
\end{lisp}
As an example, suppose that the variable \cdf{indexes} contains a list
of subscripts for a multidimensional array \emph{foo} whose rank is not
known until run time. One may access the indicated
element of the array by writing
\begin{lisp}
(apply \#'aref foo indexes)
\end{lisp}
and one may alter the value of the indicated element to that
of \cdf{newvalue} by writing
\begin{lisp}
(setf (apply \#'aref foo indexes) newvalue)
\end{lisp}
This
rule applies only when the function name \cdf{apply} refers to the global function
definition and not to a locally defined function or macro named \cdf{apply}.
\item
A macro call, in which case \cdf{setf} expands the macro call and
then analyzes the resulting form.
This
step uses \cdf{macroexpand-1}, not \cdf{macroexpand}. This allows the chance
to apply any of the rules preceding this one to any of the intermediate expansions.
\item
Any form for which a \cdf{defsetf}
or \cdf{define-setf-method} declaration has been made.
This
rule applies only when the function name in the form refers to a global function
definition and not to a locally defined function or macro.
\end{itemize}
\begin{newer}
X3J13 voted in March 1989 \issue{FUNCTION-NAME} to add one more rule to
the preceding list, coming after all those listed above:
\begin{itemize}
\item Any other list whose first element is a symbol (call it \emph{f\/}).
In this case, the call to \cdf{setf} expands into a call to the function
named by the
list \cd{(setf~\emph{f\/})} (see section~\ref{FUNCTION-NAME-SECTION}).
The first argument is the new value and the
remaining arguments are the values of the remaining elements of
\emph{place}. This expansion occurs regardless of whether either \emph{f\/} or
\cd{(setf \emph{f\/})} is defined as a function locally, globally, or not at
all. For example,
\begin{lisp}
(setf (\emph{f\/} \emph{arg1} \emph{arg2} ...) \emph{newvalue})
\end{lisp}
expands into a form with the same effect and value as
\begin{lisp}
(let ((\#:temp1 \emph{arg1})~~~~~;\textrm{Force correct order of evaluation} \\*
~~~~~~(\#:temp2 \emph{arg2}) \\*
~~~~~~... \\*
~~~~~~(\#:temp0 newvalue)) \\*
~~(funcall (function (setf \emph{f\/})) \\*
~~~~~~~~~~~\#:temp0 \\*
~~~~~~~~~~~\#:temp1 \\*
~~~~~~~~~~~\#:temp2 ...))
\end{lisp}
By convention, any function named \cd{(setf \emph{f\/})} should return its first
argument as its only value, in order to preserve the specification that
\cdf{setf} returns its \emph{newvalue}.
\end{itemize}
\end{newer}
\begin{new}
X3J13 voted in March 1989
\issue{SYMBOL-MACROLET-SEMANTICS} to add this case as well:
\begin{itemize}
\item A variable reference that refers to a symbol macro definition made by
\cdf{symbol-macrolet}, in which case \cdf{setf} expands the reference and
then analyzes the resulting form.
\end{itemize}
\end{new}
\cdf{setf} carefully arranges to preserve the usual left-to-right
order in which the various subforms are evaluated.
On the other hand,
the exact expansion for any particular form is not guaranteed and
may even be implementation-dependent; all that is guaranteed is that
the expansion of a \cdf{setf} form will be an update form that works
for that particular implementation, and that the left-to-right evaluation
of subforms is preserved.
The ultimate result of evaluating a \cdf{setf} form is the value
of \emph{newvalue}. Therefore \cd{(setf (car x) y)} does not expand
into precisely \cd{(rplaca x y)}, but into something more like
\begin{lisp}
(let ((G1 x) (G2 y)) (rplaca G1 G2) G2)
\end{lisp}
the precise expansion being implementation-dependent.
The user can define new \cdf{setf} expansions by using \cdf{defsetf}.
\begin{newer}
X3J13 voted in June 1989 \issue{SETF-MULTIPLE-STORE-VARIABLES}
to extend the specification of \cdf{setf} to allow a \emph{place}
whose \cdf{setf} method has more than one store variable (see \cdf{define-setf-method}).
In such a case as many values are accepted from the \emph{newvalue} form
as there are store variables; extra values are ignored
and missing values default to \cdf{nil},
as is usual in situations involving multiple values.
A proposal was submitted to X3J13 in September 1989
to add a \cdf{setf} method for \cdf{values} so that one could
in fact write, for example,
\begin{lisp}
(setf (values quotient remainder) \\
~~~~~~(truncate linewidth tabstop))
\end{lisp}
but unless this proposal is accepted users will have to
define a \cdf{setf} method for \cdf{values} themselves (not a difficult task).
\end{newer}
\end{defmac}
\begin{defmac}
psetf {place newvalue}*
\cdf{psetf} is like \cdf{setf} except that if more than one \emph{place}-\emph{newvalue}
pair is specified, then the assignments of new values to places are
done in parallel. More precisely, all subforms 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.
(The unpredictability matters only if more than one \emph{place} form
refers to the same place.)
\cdf{psetf} always returns {\false}.
\begin{newer}
X3J13 voted in June 1989 \issue{SETF-MULTIPLE-STORE-VARIABLES}
to extend the specification of \cdf{psetf} to allow a \emph{place}
whose \cdf{setf} method has more than one store variable (see \cdf{define-setf-method}).
In such a case as many values are accepted from the \emph{newvalue} form
as there are store variables; extra values are ignored
and missing values default to \cdf{nil},
as is usual in situations involving multiple values.
\end{newer}
\end{defmac}
\begin{defmac}
shiftf {place}+ newvalue
Each \emph{place} form may be any form acceptable
as a generalized variable to \cdf{setf}.
In the form \cd{(shiftf \emph{place1} \emph{place2} ... \emph{placen} \emph{newvalue})},
the values in \emph{place1} through \emph{placen} are accessed and saved,
and \emph{newvalue} is evaluated, for a total of $\emph{n}+1$ values in all.
Values 2 through $\emph{n}+1$ are then stored into \emph{place1} through \emph{placen},
and value 1 (the original value of \emph{place1}) is returned.