1
@c This file is part of the MIT/GNU Scheme Reference Manual.
2
@c $Id: special-forms.texi,v 1.2 2003/04/25 20:40:22 cph Exp $
4
@c Copyright 1991,1992,1993,1994,1995 Massachusetts Institute of Technology
5
@c Copyright 1996,1997,1999,2000,2001 Massachusetts Institute of Technology
6
@c Copyright 2002,2003 Massachusetts Institute of Technology
7
@c See file scheme.texinfo for copying conditions.
9
@node Special Forms, Equivalence Predicates, Overview, Top
10
@chapter Special Forms
13
A special form is an expression that follows special evaluation rules.
14
This chapter describes the basic Scheme special forms.
17
* Lambda Expressions::
26
* Structure Definitions::
31
@node Lambda Expressions, Lexical Binding, Special Forms, Special Forms
32
@section Lambda Expressions
34
@deffn {special form} lambda formals expression expression @dots{}
35
@cindex lambda expression (defn)
36
@cindex procedure, construction
37
@cindex procedure, closing environment (defn)
38
@cindex procedure, invocation environment (defn)
39
@cindex construction, of procedure
40
@cindex closing environment, of procedure (defn)
41
@cindex invocation environment, of procedure (defn)
42
@cindex environment, of procedure
43
@cindex environment, procedure closing (defn)
44
@cindex environment, procedure invocation (defn)
45
A @code{lambda} expression evaluates to a procedure. The environment in
46
effect when the @code{lambda} expression is evaluated is remembered as
47
part of the procedure; it is called the @dfn{closing environment}. When
48
the procedure is later called with some arguments, the closing
49
environment is extended by binding the variables in the formal parameter
50
list to fresh locations, and the locations are filled with the arguments
51
according to rules about to be given. The new environment created by
52
this process is referred to as the @dfn{invocation environment}.
54
@cindex region of variable binding, lambda
55
@cindex variable binding, lambda
56
Once the invocation environment has been constructed, the
57
@var{expression}s in the body of the @code{lambda} expression are
58
evaluated sequentially in it. This means that the region of the
59
variables bound by the @code{lambda} expression is all of the
60
@var{expression}s in the body. The result of evaluating the last
61
@var{expression} in the body is returned as the result of the procedure
64
@cindex lambda list (defn)
65
@cindex parameter list, of lambda (defn)
66
@cindex formal parameter list, of lambda (defn)
67
@var{Formals}, the formal parameter list, is often referred to as a
70
The process of matching up formal parameters with arguments is somewhat
71
involved. There are three types of parameters, and the matching treats
77
All of the @dfn{required} parameters are matched against the arguments
78
first. If there are fewer arguments than required parameters, an error
79
of type @code{condition-type:wrong-number-of-arguments} is signalled;
80
this error is also signalled if there are more arguments than required
81
parameters and there are no further parameters.
82
@cindex required parameter (defn)
83
@cindex parameter, required (defn)
84
@findex condition-type:wrong-number-of-arguments
87
Once the required parameters have all been matched, the @dfn{optional}
88
parameters are matched against the remaining arguments. If there are
89
fewer arguments than optional parameters, the unmatched parameters are
90
bound to special objects called @dfn{default objects}. If there are
91
more arguments than optional parameters, and there are no further
92
parameters, an error of type
93
@code{condition-type:wrong-number-of-arguments} is signalled.
94
@cindex optional parameter (defn)
95
@cindex parameter, optional (defn)
96
@cindex default object (defn)
97
@findex condition-type:wrong-number-of-arguments
99
@findex default-object?
100
The predicate @code{default-object?}, which is true only of default
101
objects, can be used to determine which optional parameters were
102
supplied, and which were defaulted.
105
Finally, if there is a @dfn{rest} parameter (there can only be one), any
106
remaining arguments are made into a list, and the list is bound to the
107
rest parameter. (If there are no remaining arguments, the rest
108
parameter is bound to the empty list.)
109
@cindex rest parameter (defn)
110
@cindex parameter, rest (defn)
112
In Scheme, unlike some other Lisp implementations, the list to which a
113
rest parameter is bound is always freshly allocated. It has infinite
114
extent and may be modified without affecting the procedure's caller.
119
Specially recognized keywords divide the @var{formals} parameters into
120
these three classes. The keywords used here are @samp{#!optional},
121
@samp{.}, and @samp{#!rest}. Note that only @samp{.} is defined by
122
standard Scheme --- the other keywords are MIT/GNU Scheme extensions.
123
@samp{#!rest} has the same meaning as @samp{.} in @var{formals}.
125
The use of these keywords is best explained by means of examples. The
126
following are typical lambda lists, followed by descriptions of which
127
parameters are required, optional, and rest. We will use @samp{#!rest}
128
in these examples, but anywhere it appears @samp{.} could be used
133
@code{a}, @code{b}, and @code{c} are all required. The procedure must
134
be passed exactly three arguments.
136
@item (a b #!optional c)
137
@code{a} and @code{b} are required, @code{c} is optional. The procedure
138
may be passed either two or three arguments.
140
@item (#!optional a b c)
141
@code{a}, @code{b}, and @code{c} are all optional. The procedure may be
142
passed any number of arguments between zero and three, inclusive.
146
These two examples are equivalent. @code{a} is a rest parameter. The
147
procedure may be passed any number of arguments. Note: this is the only
148
case in which @samp{.} cannot be used in place of @samp{#!rest}.
150
@item (a b #!optional c d #!rest e)
151
@code{a} and @code{b} are required, @code{c} and @code{d} are optional,
152
and @code{e} is rest. The procedure may be passed two or more
156
Some examples of @code{lambda} expressions:
160
(lambda (x) (+ x x)) @result{} #[compound-procedure 53]
162
((lambda (x) (+ x x)) 4) @result{} 8
164
(define reverse-subtract
167
(reverse-subtract 7 10) @result{} 3
171
(lambda (y) (+ x y))))
177
@deffn {special form} named-lambda formals expression expression @dots{}
178
@cindex named lambda (defn)
179
The @code{named-lambda} special form is similar to @code{lambda}, except
180
that the first ``required parameter'' in @var{formals} is not a
181
parameter but the @dfn{name} of the resulting procedure; thus
182
@var{formals} must have at least one required parameter. This name has
183
no semantic meaning, but is included in the external representation of
184
the procedure, making it useful for debugging. In MIT/GNU Scheme,
185
@code{lambda} is implemented as @code{named-lambda}, with a special name
186
that means ``unnamed''.
190
(named-lambda (f x) (+ x x)) @result{} #[compound-procedure 53 f]
191
((named-lambda (f x) (+ x x)) 4) @result{} 8
196
@node Lexical Binding, Dynamic Binding, Lambda Expressions, Special Forms
197
@section Lexical Binding
199
@cindex lexical binding expression
200
@cindex binding expression, lexical
201
@cindex block structure
202
The three binding constructs @code{let}, @code{let*}, and @code{letrec},
203
give Scheme block structure. The syntax of the three constructs is
204
identical, but they differ in the regions they establish for their
205
variable bindings. In a @code{let} expression, the initial values are
206
computed before any of the variables become bound. In a @code{let*}
207
expression, the evaluations and bindings are sequentially interleaved.
208
And in a @code{letrec} expression, all the bindings are in effect while
209
the initial values are being computed (thus allowing mutually recursive
212
@deffn {special form} let ((@var{variable} @var{init}) @dots{}) expression expression @dots{}
213
@cindex region of variable binding, let
214
@cindex variable binding, let
215
The @var{init}s are evaluated in the current environment (in some
216
unspecified order), the @var{variable}s are bound to fresh locations
217
holding the results, the @var{expression}s are evaluated sequentially in
218
the extended environment, and the value of the last @var{expression} is
219
returned. Each binding of a @var{variable} has the @var{expression}s as
222
MIT/GNU Scheme allows any of the @var{init}s to be omitted, in which
223
case the corresponding @var{variable}s are unassigned.
225
@cindex lambda, implicit in let
226
Note that the following are equivalent:
230
(let ((@var{variable} @var{init}) @dots{}) @var{expression} @var{expression} @dots{})
231
((lambda (@var{variable} @dots{}) @var{expression} @var{expression} @dots{}) @var{init} @dots{})
245
(let ((foo (lambda (z) (+ x y z)))
247
(foo 4))) @result{} 9
251
@xref{Iteration}, for information on ``named @code{let}''.
254
@deffn {special form} let* ((@var{variable} @var{init}) @dots{}) expression expression @dots{}
255
@cindex region of variable binding, let*
256
@cindex variable binding, let*
257
@code{let*} is similar to @code{let}, but the bindings are performed
258
sequentially from left to right, and the region of a binding is that
259
part of the @code{let*} expression to the right of the binding. Thus
260
the second binding is done in an environment in which the first binding
261
is visible, and so on.
263
Note that the following are equivalent:
267
(let* ((@var{variable1} @var{init1})
268
(@var{variable2} @var{init2})
270
(@var{variableN} @var{initN}))
272
@var{expression} @dots{})
276
(let ((@var{variable1} @var{init1}))
277
(let ((@var{variable2} @var{init2}))
279
(let ((@var{variableN} @var{initN}))
281
@var{expression} @dots{})
293
(* z x))) @result{} 70
298
@deffn {special form} letrec ((@var{variable} @var{init}) @dots{}) expression expression @dots{}
299
@cindex region of variable binding, letrec
300
@cindex variable binding, letrec
301
The @var{variable}s are bound to fresh locations holding unassigned
302
values, the @var{init}s are evaluated in the extended environment (in
303
some unspecified order), each @var{variable} is assigned to the result
304
of the corresponding @var{init}, the @var{expression}s are evaluated
305
sequentially in the extended environment, and the value of the last
306
@var{expression} is returned. Each binding of a @var{variable} has the
307
entire @code{letrec} expression as its region, making it possible to
308
define mutually recursive procedures.
310
MIT/GNU Scheme allows any of the @var{init}s to be omitted, in which
311
case the corresponding @var{variable}s are unassigned.
325
(even? 88)) @result{} #t
331
One restriction on @code{letrec} is very important: it shall be possible
332
to evaluated each @var{init} without assigning or referring to the value
333
of any @var{variable}. If this restriction is violated, then it is an
334
error. The restriction is necessary because Scheme passes arguments by
335
value rather than by name. In the most common uses of @code{letrec},
336
all the @var{init}s are @code{lambda} or @code{delay} expressions and
337
the restriction is satisfied automatically.
340
@node Dynamic Binding, Definitions, Lexical Binding, Special Forms
341
@section Dynamic Binding
343
@deffn {special form} fluid-let ((@var{variable} @var{init}) @dots{}) expression expression @dots{}
344
@cindex binding expression, dynamic (or fluid)
345
@cindex fluid binding
346
@cindex dynamic binding
347
@cindex variable binding, fluid-let
348
The @var{init}s are evaluated in the current environment (in some
349
unspecified order), the current values of the @var{variable}s are saved,
350
the results are assigned to the @var{variable}s, the @var{expression}s
351
are evaluated sequentially in the current environment, the
352
@var{variable}s are restored to their original values, and the value of
353
the last @var{expression} is returned.
356
The syntax of this special form is similar to that of @code{let}, but
357
@code{fluid-let} temporarily rebinds existing variables. Unlike
358
@code{let}, @code{fluid-let} creates no new bindings; instead it
359
@emph{assigns} the value of each @var{init} to the binding (determined
360
by the rules of lexical scoping) of its corresponding @var{variable}.
362
@cindex unassigned variable, and dynamic bindings
363
MIT/GNU Scheme allows any of the @var{init}s to be omitted, in which
364
case the corresponding @var{variable}s are temporarily unassigned.
366
An error of type @code{condition-type:unbound-variable} is signalled if
367
any of the @var{variable}s are unbound. However, because
368
@code{fluid-let} operates by means of side effects, it is valid for any
369
@var{variable} to be unassigned when the form is entered.
370
@findex condition-type:unbound-variable
372
Here is an example showing the difference between @code{fluid-let} and
373
@code{let}. First see how @code{let} affects the binding of a variable:
378
(define (access-variable) variable)
379
variable @result{} #t
381
(access-variable)) @result{} #t
382
variable @result{} #t
386
@code{access-variable} returns @code{#t} in this case because it
387
is defined in an environment with @code{variable} bound to
388
@code{#t}. @code{fluid-let}, on the other hand, temporarily reuses an
393
variable @result{} #t
394
(fluid-let ((variable #f)) @r{;reuses old binding}
395
(access-variable)) @result{} #f
396
variable @result{} #t
400
@cindex extent, of dynamic binding (defn)
401
The @dfn{extent} of a dynamic binding is defined to be the time period
402
during which the variable contains the new value. Normally this time
403
period begins when the body is entered and ends when it is exited; on a
404
sequential machine it is normally a contiguous time period. However,
405
because Scheme has first-class continuations, it is possible to leave
406
the body and then reenter it, as many times as desired. In this
407
situation, the extent becomes non-contiguous.
409
@cindex dynamic binding, and continuations
410
@cindex continuation, and dynamic binding
411
When the body is exited by invoking a continuation, the new value is
412
saved, and the variable is set to the old value. Then, if the body is
413
reentered by invoking a continuation, the old value is saved, and the
414
variable is set to the new value. In addition, side effects to the
415
variable that occur both inside and outside of body are preserved, even
416
if continuations are used to jump in and out of body repeatedly.
419
Here is a complicated example that shows the interaction between dynamic
420
binding and continuations:
424
(define (complicated-dynamic-binding)
426
(inside-continuation))
427
(write-line variable)
428
(call-with-current-continuation
429
(lambda (outside-continuation)
430
(fluid-let ((variable 2))
431
(write-line variable)
433
(call-with-current-continuation
435
(set! inside-continuation k)
436
(outside-continuation #t)))
437
(write-line variable)
438
(set! inside-continuation #f))))
439
(write-line variable)
440
(if inside-continuation
443
(inside-continuation #f)))))
448
Evaluating @samp{(complicated-dynamic-binding)} writes the following on
462
Commentary: the first two values written are the initial binding of
463
@code{variable} and its new binding after the @code{fluid-let}'s body is
464
entered. Immediately after they are written, @code{variable} is set to
465
@samp{3}, and then @code{outside-continuation} is invoked, causing us to
466
exit the body. At this point, @samp{1} is written, demonstrating that
467
the original value of @code{variable} has been restored, because we have
468
left the body. Then we set @code{variable} to @samp{4} and reenter the
469
body by invoking @code{inside-continuation}. At this point, @samp{3} is
470
written, indicating that the side effect that previously occurred within
471
the body has been preserved. Finally, we exit body normally, and write
472
@samp{4}, demonstrating that the side effect that occurred outside of
473
the body was also preserved.
475
@node Definitions, Assignments, Dynamic Binding, Special Forms
479
@deffn {special form} define variable [expression]
480
@deffnx {special form} define @var{formals} expression expression @dots{}
481
@cindex variable, adding to environment
482
@cindex definition, top-level (defn)
483
@cindex definition, internal (defn)
484
@cindex top-level definition (defn)
485
@cindex internal definition (defn)
491
Definitions are valid in some but not all contexts where expressions are
492
allowed. Definitions may only occur at the top level of a program and
493
at the beginning of a lambda body (that is, the body of a @code{lambda},
494
@code{let}, @code{let*}, @code{letrec}, @code{fluid-let}, or ``procedure
495
@code{define}'' expression). A definition that occurs at the top level
496
of a program is called a @dfn{top-level definition}, and a definition
497
that occurs at the beginning of a body is called an @dfn{internal
500
@cindex lambda, implicit in define
501
@cindex procedure define (defn)
502
@cindex define, procedure (defn)
504
In the second form of @code{define} (called ``@dfn{procedure
505
@code{define}}''), the component @var{formals} is identical to the
506
component of the same name in a @code{named-lambda} expression. In
507
fact, these two expressions are equivalent:
511
(define (@var{name1} @var{name2} @dots{})
513
@var{expression} @dots{})
518
(named-lambda (@var{name1} @var{name2} @dots{})
520
@var{expression} @dots{}))
526
* Top-Level Definitions::
527
* Internal Definitions::
530
@node Top-Level Definitions, Internal Definitions, Definitions, Definitions
531
@subsection Top-Level Definitions
532
@cindex top-level definition
533
@cindex definition, top-level
535
@cindex variable binding, top-level definition
536
A top-level definition,
539
(define @var{variable} @var{expression})
543
has essentially the same effect as this assignment expression, if
544
@var{variable} is bound:
547
(set! @var{variable} @var{expression})
550
@cindex unassigned variable, and definition
552
If @var{variable} is not bound, however, @code{define} binds
553
@var{variable} to a new location in the current environment before
554
performing the assignment (it is an error to perform a @code{set!} on an
555
unbound variable). If you omit @var{expression}, the variable becomes
556
unassigned; an attempt to reference such a variable is an error.
561
(lambda (x) (+ x 3))) @result{} @r{unspecified}
564
(define first car) @result{} @r{unspecified}
565
(first '(1 2)) @result{} 1
567
(define bar) @result{} @r{unspecified}
568
bar @error{} Unassigned variable
572
@node Internal Definitions, , Top-Level Definitions, Definitions
573
@subsection Internal Definitions
575
@cindex internal definition
576
@cindex definition, internal
577
@cindex region of variable binding, internal definition
578
@cindex variable binding, internal definition
585
An @dfn{internal definition} is a definition that occurs at the
586
beginning of a @var{body} (that is, the body of a @code{lambda},
587
@code{let}, @code{let*}, @code{letrec}, @code{fluid-let}, or ``procedure
588
@code{define}'' expression), rather than at the top level of a program.
589
The variable defined by an internal definition is local to the
590
@var{body}. That is, @var{variable} is bound rather than assigned, and
591
the region of the binding is the entire @var{body}. For example,
596
(define foo (lambda (y) (bar x y)))
597
(define bar (lambda (a b) (+ (* a b) a)))
598
(foo (+ x 3))) @result{} 45
603
A @var{body} containing internal definitions can always be converted
604
into a completely equivalent @code{letrec} expression. For example, the
605
@code{let} expression in the above example is equivalent to
607
@cindex letrec, implicit in define
611
(letrec ((foo (lambda (y) (bar x y)))
612
(bar (lambda (a b) (+ (* a b) a))))
618
@node Assignments, Quoting, Definitions, Special Forms
622
@deffn {special form} set! variable [expression]
623
@cindex variable, assigning values to
624
@cindex unassigned variable, and assignment
625
If @var{expression} is specified, evaluates @var{expression} and stores
626
the resulting value in the location to which @var{variable} is bound.
627
If @var{expression} is omitted, @var{variable} is altered to be
628
unassigned; a subsequent reference to such a @var{variable} is an error.
629
In either case, the value of the @code{set!} expression is unspecified.
631
@var{Variable} must be bound either in some region enclosing the
632
@code{set!} expression, or at the top level. However, @var{variable} is
633
permitted to be unassigned when the @code{set!} form is entered.
637
(define x 2) @result{} @r{unspecified}
639
(set! x 4) @result{} @r{unspecified}
644
@cindex access, used with set!
646
@var{Variable} may be an @code{access} expression
647
(@pxref{Environments}). This allows you to assign variables in an
648
arbitrary environment. For example,
652
(define x (let ((y 0)) (the-environment)))
655
(access y x) @result{} 0
656
(set! (access y x) 1) @result{} @r{unspecified}
658
(access y x) @result{} 1
663
@node Quoting, Conditionals, Assignments, Special Forms
667
This section describes the expressions that are used to modify or
668
prevent the evaluation of objects.
670
@deffn {special form} quote datum
671
@cindex external representation, and quote
672
@cindex literal, and quote
673
@cindex constant, and quote
674
@code{(quote @var{datum})} evaluates to @var{datum}. @var{Datum} may be
675
any external representation of a Scheme object
676
(@pxref{External Representations}).
677
Use @code{quote} to include literal constants in
682
(quote a) @result{} a
683
(quote #(a b c)) @result{} #(a b c)
684
(quote (+ 1 2)) @result{} (+ 1 2)
688
@cindex ' as external representation
689
@cindex apostrophe, as external representation
690
@cindex quote, as external representation
692
@code{(quote @var{datum})} may be abbreviated as @code{'@var{datum}}.
693
The two notations are equivalent in all respects.
698
'#(a b c) @result{} #(a b c)
699
'(+ 1 2) @result{} (+ 1 2)
700
'(quote a) @result{} (quote a)
701
''a @result{} (quote a)
705
Numeric constants, string constants, character constants, and boolean
706
constants evaluate to themselves, so they don't need to be quoted.
710
'"abc" @result{} "abc"
711
"abc" @result{} "abc"
712
'145932 @result{} 145932
713
145932 @result{} 145932
722
@deffn {special form} quasiquote template
723
@cindex external representation, and quasiquote
724
@cindex literal, and quasiquote
725
@cindex constant, and quasiquote
727
``Backquote'' or ``quasiquote'' expressions are useful for constructing
728
a list or vector structure when most but not all of the desired
729
structure is known in advance. If no commas appear within the
730
@var{template}, the result of evaluating @code{`@var{template}} is
731
equivalent (in the sense of @code{equal?}) to the result of evaluating
732
@code{'@var{template}}. If a comma appears within the @var{template},
733
however, the expression following the comma is evaluated (``unquoted'')
734
and its result is inserted into the structure instead of the comma and
735
the expression. If a comma appears followed immediately by an at-sign
736
(@@), then the following expression shall evaluate to a list; the
737
opening and closing parentheses of the list are then ``stripped away''
738
and the elements of the list are inserted in place of the comma at-sign
743
`(list ,(+ 1 2) 4) @result{} (list 3 4)
745
(let ((name 'a)) `(list ,name ',name)) @result{} (list a 'a)
747
`(a ,(+ 1 2) ,@@(map abs '(4 -5 6)) b) @result{} (a 3 4 5 6 b)
749
`((foo ,(- 10 3)) ,@@(cdr '(c)) . ,(car '(cons)))
750
@result{} ((foo 7) . cons)
752
`#(10 5 ,(sqrt 4) ,@@(map sqrt '(16 9)) 8)
753
@result{} #(10 5 2 4 3 8)
755
`,(+ 2 3) @result{} 5
759
@cindex nesting, of quasiquote expressions
760
Quasiquote forms may be nested. Substitutions are made only for
761
unquoted components appearing at the same nesting level as the outermost
762
backquote. The nesting level increases by one inside each successive
763
quasiquotation, and decreases by one inside each unquotation.
767
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
768
@result{} (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
772
`(a `(b ,,name1 ,',name2 d) e))
773
@result{} (a `(b ,x ,'y d) e)
777
@cindex backquote, as external representation
778
@cindex ` as external representation
779
@cindex comma, as external representation
780
@cindex , as external representation
781
@cindex ,@@ as external representation
783
@findex unquote-splicing
787
The notations @code{`@var{template}} and (@code{quasiquote
788
@var{template}}) are identical in all respects.
789
@code{,@var{expression}} is identical to @code{(unquote
790
@var{expression})} and @code{,@@@var{expression}} is identical to
791
@code{(unquote-splicing @var{expression})}.
795
(quasiquote (list (unquote (+ 1 2)) 4))
798
'(quasiquote (list (unquote (+ 1 2)) 4))
799
@result{} `(list ,(+ 1 2) 4)
800
@emph{i.e.,} (quasiquote (list (unquote (+ 1 2)) 4))
804
Unpredictable behavior can result if any of the symbols
805
@code{quasiquote}, @code{unquote}, or @code{unquote-splicing} appear in
806
a @var{template} in ways otherwise than as described above.
809
@node Conditionals, Sequencing, Quoting, Special Forms
810
@section Conditionals
812
@cindex expression, conditional (defn)
813
@cindex conditional expression (defn)
814
@cindex true, in conditional expression (defn)
815
@cindex false, in conditional expression (defn)
818
The behavior of the @dfn{conditional expressions} is determined by
819
whether objects are true or false. The conditional expressions count
820
only @code{#f} as false. They count everything else, including
821
@code{#t}, pairs, symbols, numbers, strings, vectors, and procedures as
822
true (but @pxref{True and False}).
824
In the descriptions that follow, we say that an object has ``a true
825
value'' or ``is true'' when the conditional expressions treat it as
826
true, and we say that an object has ``a false value'' or ``is false''
827
when the conditional expressions treat it as false.
829
@deffn {special form} if predicate consequent [alternative]
830
@var{Predicate}, @var{consequent}, and @var{alternative} are
831
expressions. An @code{if} expression is evaluated as follows: first,
832
@var{predicate} is evaluated. If it yields a true value, then
833
@var{consequent} is evaluated and its value is returned. Otherwise
834
@var{alternative} is evaluated and its value is returned. If
835
@var{predicate} yields a false value and no @var{alternative} is
836
specified, then the result of the expression is unspecified.
838
An @code{if} expression evaluates either @var{consequent} or
839
@var{alternative}, never both. Programs should not depend on the value
840
of an @code{if} expression that has no @var{alternative}.
844
(if (> 3 2) 'yes 'no) @result{} yes
845
(if (> 2 3) 'yes 'no) @result{} no
853
@deffn {special form} cond clause clause @dots{}
855
@cindex clause, of cond expression
856
Each @var{clause} has this form:
859
(@var{predicate} @var{expression} @dots{})
863
@cindex else clause, of cond expression (defn)
865
where @var{predicate} is any expression. The last @var{clause} may be
866
an @dfn{@code{else} clause}, which has the form:
869
(else @var{expression} @var{expression} @dots{})
872
A @code{cond} expression does the following:
876
Evaluates the @var{predicate} expressions of successive @var{clause}s in
877
order, until one of the @var{predicate}s evaluates to a true
881
When a @var{predicate} evaluates to a true value, @code{cond} evaluates
882
the @var{expression}s in the associated @var{clause} in left to right
883
order, and returns the result of evaluating the last @var{expression} in
884
the @var{clause} as the result of the entire @code{cond} expression.
886
If the selected @var{clause} contains only the @var{predicate} and no
887
@var{expression}s, @code{cond} returns the value of the @var{predicate}
891
If all @var{predicate}s evaluate to false values, and there is no
892
@code{else} clause, the result of the conditional expression is
893
unspecified; if there is an @code{else} clause, @code{cond} evaluates
894
its @var{expression}s (left to right) and returns the value of the last
900
(cond ((> 3 2) 'greater)
901
((< 3 2) 'less)) @result{} greater
903
(cond ((> 3 3) 'greater)
905
(else 'equal)) @result{} equal
909
Normally, programs should not depend on the value of a @code{cond}
910
expression that has no @code{else} clause. However, some Scheme
911
programmers prefer to write @code{cond} expressions in which at least
912
one of the @var{predicate}s is always true. In this style, the final
913
@var{clause} is equivalent to an @code{else} clause.
915
@cindex => in cond clause
917
Scheme supports an alternative @var{clause} syntax:
920
(@var{predicate} => @var{recipient})
924
where @var{recipient} is an expression. If @var{predicate} evaluates to
925
a true value, then @var{recipient} is evaluated. Its value must be a
926
procedure of one argument; this procedure is then invoked on the value
927
of the @var{predicate}.
931
(cond ((assv 'b '((a 1) (b 2))) => cadr)
932
(else #f)) @result{} 2
937
@deffn {special form} case key clause clause @dots{}
939
@cindex clause, of case expression
940
@var{Key} may be any expression. Each @var{clause} has this
944
((@var{object} @dots{}) @var{expression} @var{expression} @dots{})
947
@cindex else clause, of case expression (defn)
949
No @var{object} is evaluated, and all the @var{object}s must be
950
distinct. The last @var{clause} may be an @dfn{@code{else} clause},
954
(else @var{expression} @var{expression} @dots{})
957
A @code{case} expression does the following:
961
Evaluates @var{key} and compares the result with each
965
If the result of evaluating @var{key} is equivalent (in the sense of
966
@code{eqv?}; @pxref{Equivalence Predicates}) to an @var{object},
967
@code{case} evaluates the @var{expression}s in the corresponding
968
@var{clause} from left to right and returns the result of evaluating the
969
last @var{expression} in the @var{clause} as the result of the
970
@code{case} expression.
974
If the result of evaluating @var{key} is different from every
975
@var{object}, and if there's an @code{else} clause, @code{case}
976
evaluates its @var{expression}s and returns the result of the last one
977
as the result of the @code{case} expression. If there's no @code{else}
978
clause, @code{case} returns an unspecified result. Programs should not
979
depend on the value of a @code{case} expression that has no @code{else}
989
((1 4 6 8 9) 'composite)) @result{} composite
993
((b) 'b)) @result{} @r{unspecified}
998
(else 'consonant)) @result{} consonant
1003
@deffn {special form} and expression @dots{}
1004
The @var{expression}s are evaluated from left to right, and the value of
1005
the first @var{expression} that evaluates to a false value is returned.
1006
Any remaining @var{expression}s are not evaluated. If all the
1007
@var{expression}s evaluate to true values, the value of the last
1008
@var{expression} is returned. If there are no @var{expression}s then
1009
@code{#t} is returned.
1013
(and (= 2 2) (> 2 1)) @result{} #t
1014
(and (= 2 2) (< 2 1)) @result{} #f
1015
(and 1 2 'c '(f g)) @result{} (f g)
1021
@deffn {special form} or expression @dots{}
1022
The @var{expression}s are evaluated from left to right, and the value of
1023
the first @var{expression} that evaluates to a true value is returned.
1024
Any remaining @var{expression}s are not evaluated. If all
1025
@var{expression}s evaluate to false values, the value of the last
1026
@var{expression} is returned. If there are no @var{expression}s then
1027
@code{#f} is returned.
1031
(or (= 2 2) (> 2 1)) @result{} #t
1032
(or (= 2 2) (< 2 1)) @result{} #t
1033
(or #f #f #f) @result{} #f
1034
(or (memq 'b '(a b c)) (/ 3 0)) @result{} (b c)
1039
@node Sequencing, Iteration, Conditionals, Special Forms
1041
@cindex sequencing expressions
1043
The @code{begin} special form is used to evaluate expressions in a
1046
@deffn {special form} begin expression expression @dots{}
1047
The @var{expression}s are evaluated sequentially from left to right, and
1048
the value of the last @var{expression} is returned. This expression
1049
type is used to sequence side effects such as input and output.
1055
(+ x 1)) @result{} 6
1057
(begin (display "4 plus 1 equals ")
1059
@print{} 4 plus 1 equals 5
1060
@result{} @r{unspecified}
1064
@cindex implicit begin
1065
Often the use of @code{begin} is unnecessary, because many special forms
1066
already support sequences of expressions (that is, they have an implicit
1067
@code{begin}). Some of these special forms are:
1073
define @r{;``procedure @code{define}'' only}
1092
@findex named-lambda
1095
The obsolete special form @code{sequence} is identical to @code{begin}.
1096
It should not be used in new code.
1099
@node Iteration, Structure Definitions, Sequencing, Special Forms
1102
@cindex expression, iteration (defn)
1103
@cindex iteration expression (defn)
1104
@cindex looping (see iteration expressions)
1105
@cindex tail recursion, vs. iteration expression
1106
The @dfn{iteration expressions} are: ``named @code{let}'' and @code{do}.
1107
They are also binding expressions, but are more commonly referred to as
1108
iteration expressions. Because Scheme is properly tail-recursive, you
1109
don't need to use these special forms to express iteration; you can
1110
simply use appropriately written ``recursive'' procedure calls.
1112
@deffn {special form} let name ((@var{variable} @var{init}) @dots{}) expression expression @dots{}
1113
@cindex named let (defn)
1114
MIT/GNU Scheme permits a variant on the syntax of @code{let} called
1115
``named @code{let}'' which provides a more general looping construct
1116
than @code{do}, and may also be used to express recursions.
1118
Named @code{let} has the same syntax and semantics as ordinary
1119
@code{let} except that @var{name} is bound within the @var{expression}s
1120
to a procedure whose formal arguments are the @var{variable}s and whose
1121
body is the @var{expression}s. Thus the execution of the
1122
@var{expression}s may be repeated by invoking the procedure named by
1125
@cindex unassigned variable, and named let
1126
MIT/GNU Scheme allows any of the @var{init}s to be omitted, in which
1127
case the corresponding @var{variable}s are unassigned.
1129
Note: the following expressions are equivalent:
1133
(let @var{name} ((@var{variable} @var{init}) @dots{})
1135
@var{expression} @dots{})
1137
((letrec ((@var{name}
1138
(named-lambda (@var{name} @var{variable} @dots{})
1140
@var{expression} @dots{})))
1151
((numbers '(3 -2 1 6 -5))
1154
(cond ((null? numbers)
1156
((>= (car numbers) 0)
1158
(cons (car numbers) nonneg)
1163
(cons (car numbers) neg)))))
1165
@result{} ((6 1 3) (-5 -2))
1170
@deffn {special form} do ((@var{variable} @var{init} @var{step}) @dots{}) (@var{test} @var{expression} @dots{}) command @dots{}
1171
@code{do} is an iteration construct. It specifies a set of variables to
1172
be bound, how they are to be initialized at the start, and how they are
1173
to be updated on each iteration. When a termination condition is met,
1174
the loop exits with a specified result value.
1176
@code{do} expressions are evaluated as follows: The @var{init}
1177
expressions are evaluated (in some unspecified order), the
1178
@var{variable}s are bound to fresh locations, the results of the
1179
@var{init} expressions are stored in the bindings of the
1180
@var{variable}s, and then the iteration phase begins.
1182
Each iteration begins by evaluating @var{test}; if the result is false,
1183
then the @var{command} expressions are evaluated in order for effect,
1184
the @var{step} expressions are evaluated in some unspecified order, the
1185
@var{variable}s are bound to fresh locations, the results of the
1186
@var{step}s are stored in the bindings of the @var{variable}s, and the
1187
next iteration begins.
1189
If @var{test} evaluates to a true value, then the @var{expression}s are
1190
evaluated from left to right and the value of the last @var{expression}
1191
is returned as the value of the @code{do} expression. If no
1192
@var{expression}s are present, then the value of the @code{do}
1193
expression is unspecified in standard Scheme; in MIT/GNU Scheme, the
1194
value of @var{test} is returned.
1196
@cindex region of variable binding, do
1197
@cindex variable binding, do
1198
The region of the binding of a @var{variable} consists of the entire
1199
@code{do} expression except for the @var{init}s. It is an error for a
1200
@var{variable} to appear more than once in the list of @code{do}
1203
A @var{step} may be omitted, in which case the effect is the same as if
1204
@code{(@var{variable} @var{init} @var{variable})} had been written
1205
instead of @code{(@var{variable} @var{init})}.
1209
(do ((vec (make-vector 5))
1212
(vector-set! vec i i)) @result{} #(0 1 2 3 4)
1216
(let ((x '(1 3 5 7 9)))
1218
(sum 0 (+ sum (car x))))
1219
((null? x) sum))) @result{} 25
1224
@node Structure Definitions, Macros, Iteration, Special Forms
1225
@section Structure Definitions
1227
This section provides examples and describes the options and syntax of
1228
@code{define-structure}, an MIT/GNU Scheme macro that is very similar to
1229
@code{defstruct} in Common Lisp. The differences between them are
1230
summarized at the end of this section. For more information, see
1231
Steele's Common Lisp book.
1233
@deffn {special form} define-structure (name structure-option @dots{}) slot-description @dots{}
1234
Each @var{slot-description} takes one of the following forms:
1239
(@var{slot-name} @var{default-init} [@var{slot-option} @var{value}]*)
1243
@cindex keyword constructor
1244
@cindex BOA constructor
1245
The fields @var{name} and @var{slot-name} must both be symbols. The
1246
field @var{default-init} is an expression for the initial value of the
1247
slot. It is evaluated each time a new instance is constructed. If it
1248
is not specified, the initial content of the slot is undefined. Default
1249
values are only useful with a @sc{boa} constructor with argument list or
1250
a keyword constructor (see below).
1252
Evaluation of a @code{define-structure} expression defines a structure
1253
descriptor and a set of procedures to manipulate instances of the
1254
structure. These instances are represented as records by default
1255
(@pxref{Records}) but may alternately be lists or vectors. The
1256
accessors and modifiers are marked with compiler declarations so that
1257
calls to them are automatically transformed into appropriate references.
1258
Often, no options are required, so a simple call to
1259
@code{define-structure} looks like:
1262
(define-structure foo a b c)
1265
This defines a type descriptor @code{rtd:foo}, a constructor
1266
@code{make-foo}, a predicate @code{foo?}, accessors @code{foo-a},
1267
@code{foo-b}, and @code{foo-c}, and modifiers @code{set-foo-a!},
1268
@code{set-foo-b!}, and @code{set-foo-c!}.
1270
In general, if no options are specified, @code{define-structure} defines
1271
the following (using the simple call above as an example):
1274
@item type descriptor
1275
The name of the type descriptor is @code{"rtd:"} followed by the name of
1276
the structure, e.g.@: @samp{rtd:foo}. The type descriptor satisfies the
1277
predicate @code{record-type?}.
1280
The name of the constructor is @code{"make-"} followed by the name of
1281
the structure, e.g.@: @samp{make-foo}. The number of arguments accepted
1282
by the constructor is the same as the number of slots; the arguments are
1283
the initial values for the slots, and the order of the arguments matches
1284
the order of the slot definitions.
1287
The name of the predicate is the name of the structure followed by
1288
@code{"?"}, e.g.@: @samp{foo?}. The predicate is a procedure of one
1289
argument, which returns @code{#t} if its argument is a record of the
1290
type defined by this structure definition, and @code{#f} otherwise.
1293
For each slot, an accessor is defined. The name of the accessor is
1294
formed by appending the name of the structure, a hyphen, and the name of
1295
the slot, e.g.@: @samp{foo-a}. The accessor is a procedure of one
1296
argument, which must be a record of the type defined by this structure
1297
definition. The accessor extracts the contents of the corresponding
1298
slot in that record and returns it.
1301
For each slot, a modifier is defined. The name of the modifier is
1302
formed by appending @code{"set-"}, the name of the accessor, and
1303
@code{"!"}, e.g.@: @samp{set-foo-a!}. The modifier is a procedure of
1304
two arguments, the first of which must be a record of the type defined
1305
by this structure definition, and the second of which may be any object.
1306
The modifier modifies the contents of the corresponding slot in that
1307
record to be that object, and returns an unspecified value.
1310
When options are not supplied, @code{(@var{name})} may be abbreviated to
1311
@var{name}. This convention holds equally for @var{structure-options}
1312
and @var{slot-options}. Hence, these are equivalent:
1316
(define-structure foo a b c)
1317
(define-structure (foo) (a) b (c))
1326
(define-structure (foo keyword-constructor) a b c)
1327
(define-structure (foo (keyword-constructor)) a b c)
1331
When specified as option values, @code{false} and @code{nil} are
1332
equivalent to @code{#f}, and @code{true} and @code{t} are equivalent to
1336
Possible @var{slot-options} are:
1338
@deffn {slot option} read-only value
1339
When given a @var{value} other than @code{#f}, this specifies that no
1340
modifier should be created for the slot.
1343
@deffn {slot option} type type-descriptor
1344
This is accepted but not presently used.
1347
Possible @var{structure-options} are:
1349
@deffn {structure option} predicate [name]
1350
This option controls the definition of a predicate procedure for the
1351
structure. If @var{name} is not given, the predicate is defined with
1352
the default name (see above). If @var{name} is @code{#f}, the predicate
1353
is not defined at all. Otherwise, @var{name} must be a symbol, and
1354
the predicate is defined with that symbol as its name.
1357
@deffn {structure option} copier [name]
1358
This option controls the definition of a procedure to copy instances of
1359
the structure. This is a procedure of one argument, a structure
1360
instance, that makes a newly allocated copy of the structure and returns
1361
it. If @var{name} is not given, the copier is defined, and the name
1362
of the copier is @code{"copy-"} followed by the structure name (e.g.@:
1363
@samp{copy-foo}). If @var{name} is @code{#f}, the copier is not
1364
defined. Otherwise, @var{name} must be a symbol, and the copier is
1365
defined with that symbol as its name.
1368
@deffn {structure option} print-procedure expression
1369
Evaluating @var{expression} must yield a procedure of two arguments,
1370
which is used to print instances of the structure. The procedure is an
1371
@dfn{unparser method} (@pxref{Custom Output}). If the structure
1372
instances are records, this option has the same effect as calling
1373
@code{set-record-type-unparser-method!}.
1374
@findex set-record-type-unparser-method!
1377
@deffn {structure option} constructor [name [argument-list]]
1378
@cindex BOA constructor (defn)
1379
This option controls the definition of constructor procedures. These
1380
constructor procedures are called ``@sc{boa} constructors'', for ``By
1381
Order of Arguments'', because the arguments to the constructor specify
1382
the initial contents of the structure's slots by the order in which they
1383
are given. This is as opposed to ``keyword constructors'', which
1384
specify the initial contents using keywords, and in which the order of
1385
arguments is irrelevant.
1387
If @var{name} is not given, a constructor is defined with the default
1388
name and arguments (see above). If @var{name} is @code{#f}, no
1389
constructor is defined; @var{argument-list} may not be specified in this
1390
case. Otherwise, @var{name} must be a symbol, and a constructor is
1391
defined with that symbol as its name. If @var{name} is a symbol,
1392
@var{argument-list} is optionally allowed; if it is omitted, the
1393
constructor accepts one argument for each slot in the structure
1394
definition, in the same order in which the slots appear in the
1395
definition. Otherwise, @var{argument-list} must be a lambda list
1396
(@pxref{Lambda Expressions}), and each of the parameters of the lambda
1397
list must be the name of a slot in the structure. The arguments
1398
accepted by the constructor are defined by this lambda list. Any slot
1399
that is not specified by the lambda list is initialized to the
1400
@var{default-init} as specified above; likewise for any slot specified
1401
as an optional parameter when the corresponding argument is not
1404
If the @code{constructor} option is specified, the default constructor
1405
is not defined. Additionally, the @code{constructor} option may be
1406
specified multiple times to define multiple constructors with
1407
different names and argument lists.
1411
(define-structure (foo
1412
(constructor make-foo (#!optional a b)))
1419
@deffn {structure option} keyword-constructor [name]
1420
@cindex keyword constructor (defn)
1421
This option controls the definition of keyword constructor procedures.
1422
A @dfn{keyword constructor} is a procedure that accepts arguments that
1423
are alternating slot names and values. If @var{name} is omitted, a
1424
keyword constructor is defined, and the name of the constructor is
1425
@code{"make-"} followed by the name of the structure (e.g.@:
1426
@samp{make-foo}). Otherwise, @var{name} must be a symbol, and a keyword
1427
constructor is defined with this symbol as its name.
1429
If the @code{keyword-constructor} option is specified, the default
1430
constructor is not defined. Additionally, the
1431
@code{keyword-constructor} option may be specified multiple times to
1432
define multiple keyword constructors; this is usually not done since
1433
such constructors would all be equivalent.
1437
(define-structure (foo (keyword-constructor make-bar)) a b)
1438
(foo-a (make-bar 'b 20 'a 19)) @result{} 19
1443
@deffn {structure option} type-descriptor name
1444
This option cannot be used with the @code{type} or @code{named} options.
1446
By default, structures are implemented as records. The name of the
1447
structure is defined to hold the type descriptor of the record defined
1448
by the structure. The @code{type-descriptor} option specifies a
1449
different name to hold the type descriptor.
1453
(define-structure foo a b)
1454
foo @result{} #[record-type 18]
1456
(define-structure (bar (type-descriptor <bar>)) a b)
1457
bar @error{} Unbound variable: bar
1458
<bar> @result{} #[record-type 19]
1463
@deffn {structure option} conc-name [name]
1464
By default, the prefix for naming accessors and modifiers is the name of
1465
the structure followed by a hyphen. The @code{conc-name} option can be
1466
used to specify an alternative. If @var{name} is not given, the prefix
1467
is the name of the structure followed by a hyphen (the default). If
1468
@var{name} is @code{#f}, the slot names are used directly, without
1469
prefix. Otherwise, @var{name} must a symbol, and that symbol is used as
1473
@code{(define-structure (foo (conc-name moby/)) a b)}
1477
defines accessors @code{moby/a} and @code{moby/b}, and modifiers
1478
@code{set-moby/a!} and @code{set-moby/b!}.
1481
@code{(define-structure (foo (conc-name #f)) a b)}
1485
defines accessors @code{a} and @code{b}, and modifiers @code{set-a!} and
1489
@deffn {structure option} type representation-type
1490
This option cannot be used with the @code{type-descriptor} option.
1492
By default, structures are implemented as records. The @code{type}
1493
option overrides this default, allowing the programmer to specify that
1494
the structure be implemented using another data type. The option value
1495
@var{representation-type} specifies the alternate data type; it is
1496
allowed to be one of the symbols @code{vector} or @code{list}, and the
1497
data type used is the one corresponding to the symbol.
1499
If this option is given, and the @code{named} option is not specified,
1500
the representation will not be tagged, and neither a predicate nor a
1501
type descriptor will be defined; also, the @code{print-procedure}
1502
option may not be given.
1506
(define-structure (foo (type list)) a b)
1507
(make-foo 1 2) @result{} (1 2)
1512
@deffn {structure option} named [expression]
1513
This is valid only in conjunction with the @code{type} option and
1514
specifies that the structure instances be tagged to make them
1515
identifiable as instances of this structure type. This option cannot be
1516
used with the @code{type-descriptor} option.
1518
In the usual case, where @var{expression} is not given, the @code{named}
1519
option causes a type descriptor and predicate to be defined for the
1520
structure (recall that the @code{type} option without @code{named}
1521
suppresses their definition), and also defines a default unparser method
1522
for the structure instances (which can be overridden by the
1523
@code{print-procedure} option). If the default unparser method is not
1524
wanted then the @code{print-procedure} option should be specified as
1525
@code{#F}. This causes the structure to be printed in its native
1526
representation, as a list or vector, which includes the type descriptor.
1527
The type descriptor is a unique object, @emph{not} a record type, that
1528
describes the structure instances and is additionally stored in the
1529
structure instances to identify them: if the representation type is
1530
@code{vector}, the type descriptor is stored in the zero-th slot of the
1531
vector, and if the representation type is @code{list}, it is stored as
1532
the first element of the list.
1537
(define-structure (foo (type vector) named) a b c)
1538
(vector-ref (make-foo 1 2 3) 0) @result{} #[structure-type 52]
1542
If @var{expression} is specified, it is an expression that is evaluated
1543
to yield a tag object. The @var{expression} is evaluated once when the
1544
structure definition is evaluated (to specify the unparser method), and
1545
again whenever a predicate or constructor is called. Because of this,
1546
@var{expression} is normally a variable reference or a constant. The
1547
value yielded by @var{expression} may be any object at all. That object
1548
is stored in the structure instances in the same place that the type
1549
descriptor is normally stored, as described above. If @var{expression}
1550
is specified, no type descriptor is defined, only a predicate.
1554
(define-structure (foo (type vector) (named 'foo)) a b c)
1555
(vector-ref (make-foo 1 2 3) 0) @result{} foo
1560
@deffn {structure option} safe-accessors [boolean]
1561
This option allows the programmer to have some control over the safety
1562
of the slot accessors (and modifiers) generated by
1563
@code{define-structure}. If @code{safe-accessors} is not specified, or
1564
if @var{boolean} is @code{#f}, then the accessors are optimized for
1565
speed at the expense of safety; when compiled, the accessors will turn
1566
into very fast inline sequences, usually one to three machine
1567
instructions in length. However, if @code{safe-accessors} is specified
1568
and @var{boolean} is either omitted or @code{#t}, then the accessors are
1569
optimized for safety, will check the type and structure of their
1570
argument, and will be close-coded.
1574
(define-structure (foo safe-accessors) a b c)
1579
@deffn {structure option} initial-offset offset
1580
This is valid only in conjunction with the @code{type} option.
1581
@var{Offset} must be an exact non-negative integer and specifies the
1582
number of slots to leave open at the beginning of the structure instance
1583
before the specified slots are allocated. Specifying an @var{offset} of
1584
zero is equivalent to omitting the @code{initial-offset} option.
1586
If the @code{named} option is specified, the structure tag appears in
1587
the first slot, followed by the ``offset'' slots, and then the regular
1588
slots. Otherwise, the ``offset'' slots come first, followed by the
1593
(define-structure (foo (type vector) (initial-offset 3))
1595
(make-foo 1 2 3) @result{} #(() () () 1 2 3)
1600
The essential differences between MIT/GNU Scheme's @code{define-structure}
1601
and Common Lisp's @code{defstruct} are:
1605
The default constructor procedure takes positional arguments, in the
1606
same order as specified in the definition of the structure. A keyword
1607
constructor may be specified by giving the option
1608
@code{keyword-constructor}.
1611
@sc{boa} constructors are described using Scheme lambda lists. Since there
1612
is nothing corresponding to @code{&aux} in Scheme lambda lists, this
1613
functionality is not implemented.
1616
By default, no @code{copier} procedure is defined.
1619
The side-effect procedure corresponding to the accessor @code{foo} is
1620
given the name @code{set-foo!}.
1623
Keywords are ordinary symbols -- use @code{foo} instead of @code{:foo}.
1626
The option values @code{false}, @code{nil}, @code{true}, and @code{t}
1627
are treated as if the appropriate boolean constant had been specified
1631
The @code{print-function} option is named @code{print-procedure}. Its
1632
argument is a procedure of two arguments (the unparser state and the
1633
structure instance) rather than three as in Common Lisp.
1636
By default, named structures are tagged with a unique object of some
1637
kind. In Common Lisp, the structures are tagged with symbols. This
1638
depends on the Common Lisp package system to help generate unique tags;
1639
MIT/GNU Scheme has no such way to generate unique symbols.
1642
The @code{named} option may optionally take an argument, which is
1643
normally the name of a variable (any expression may be used, but it is
1644
evaluated whenever the tag name is needed). If used, structure
1645
instances will be tagged with that variable's value. The variable must
1646
be defined when @code{define-structure} is evaluated.
1649
The @code{type} option is restricted to the values @code{vector} and
1653
The @code{include} option is not implemented.
1656
@node Macros, SRFI syntax, Structure Definitions, Special Forms
1659
(This section is largely taken from the @cite{Revised^4 Report on the
1660
Algorithmic Language Scheme}. The section on Syntactic Closures is
1661
derived from a document written by Chris Hanson. The section on
1662
Explicit Renaming is derived from a document written by William
1666
Scheme programs can define and use new derived expression types, called
1667
@dfn{macros}. Program-defined expression types have the syntax
1670
(@var{keyword} @var{datum} @dots{})
1674
@cindex syntactic keyword
1676
@cindex macro keyword
1677
where @var{keyword} is an identifier that uniquely determines the
1678
expression type. This identifier is called the @dfn{syntactic keyword},
1679
or simply @dfn{keyword}, of the macro. The number of the @var{datum}s,
1680
and their syntax, depends on the expression type.
1683
@cindex macro transformer
1684
Each instance of a macro is called a @dfn{use} of the macro. The set of
1685
rules that specifies how a use of a macro is transcribed into a more
1686
primitive expression is called the @dfn{transformer} of the macro.
1688
@cindex anonymous syntactic keyword
1689
MIT/GNU Scheme also supports @dfn{anonymous syntactic keywords}. This means
1690
that it's not necessary to bind a macro transformer to a syntactic
1691
keyword before it is used. Instead, any macro-transformer expression
1692
can appear as the first element of a form, and the form will be expanded
1695
The macro definition facility consists of these parts:
1699
A set of expressions used to establish that certain identifiers are
1700
macro keywords, associate them with macro transformers, and control the
1701
scope within which a macro is defined.
1704
A standard high-level pattern language for specifying macro
1705
transformers, introduced by the @code{syntax-rules} special form.
1708
Two non-standard low-level languages for specifying macro transformers,
1709
@dfn{syntactic closures} and @dfn{explicit renaming}.
1713
@cindex referentially transparent
1714
The syntactic keyword of a macro may shadow variable bindings, and local
1715
variable bindings may shadow keyword bindings. All macros defined using
1716
the pattern language are ``hygienic'' and ``referentially transparent''
1717
and thus preserve Scheme's lexical scoping:
1721
If a macro transformer inserts a binding for an identifier (variable or
1722
keyword), the identifier will in effect be renamed throughout its scope
1723
to avoid conflicts with other identifiers.
1726
If a macro transformer inserts a free reference to an identifier, the
1727
reference refers to the binding that was visible where the transformer
1728
was specified, regardless of any local bindings that may surround the
1733
* Syntactic Binding Constructs::
1734
* Pattern Language::
1735
* Syntactic Closures::
1736
* Explicit Renaming::
1739
@node Syntactic Binding Constructs, Pattern Language, Macros, Macros
1740
@subsection Binding Constructs for Syntactic Keywords
1742
@code{let-syntax}, @code{letrec-syntax}, @code{let*-syntax} and
1743
@code{define-syntax} are analogous to @code{let}, @code{letrec},
1744
@code{let*} and @code{define}, but they bind syntactic keywords to macro
1745
transformers instead of binding variables to locations that contain
1748
Any argument named @var{transformer-spec} must be a macro-transformer
1749
expression, which is one of the following:
1753
A macro transformer defined by the pattern language and denoted by the
1754
syntactic keyword @code{syntax-rules}.
1757
A macro transformer defined by one of the low-level mechanisms and
1758
denoted by one of the syntactic keywords @code{sc-macro-transformer},
1759
@code{rsc-macro-transformer}, or @code{er-macro-transformer}.
1762
A syntactic keyword bound in the enclosing environment. This is used
1763
to bind another name to an existing macro transformer.
1766
@deffn {special form} let-syntax bindings expression expression @dots{}
1767
@var{Bindings} should have the form
1770
((@var{keyword} @var{transformer-spec}) @dots{})
1774
Each @var{keyword} is an identifier, each @var{transformer-spec} is a
1775
a macro-transformer expression, and the body is a sequence of
1776
one or more expressions. It is an error for a @var{keyword} to appear
1777
more than once in the list of keywords being bound.
1779
The @var{expression}s are expanded in the syntactic environment obtained
1780
by extending the syntactic environment of the @code{let-syntax}
1781
expression with macros whose keywords are the @var{keyword}s, bound to
1782
the specified transformers. Each binding of a @var{keyword} has the
1783
@var{expression}s as its region.
1787
(let-syntax ((when (syntax-rules ()
1788
((when test stmt1 stmt2 ...)
1793
(when if (set! if 'now))
1797
(let-syntax ((m (syntax-rules () ((m) x))))
1799
(m)))) @result{} outer
1804
@deffn {special form} letrec-syntax bindings expression expression @dots{}
1805
The syntax of @code{letrec-syntax} is the same as for @code{let-syntax}.
1807
The @var{expression}s are expanded in the syntactic environment obtained
1808
by extending the syntactic environment of the @code{letrec-syntax}
1809
expression with macros whose keywords are the @var{keyword}s, bound to
1810
the specified transformers. Each binding of a @var{keyword} has the
1811
@var{bindings} as well as the @var{expression}s within its region, so
1812
the transformers can transcribe expressions into uses of the macros
1813
introduced by the @code{letrec-syntax} expression.
1818
((my-or (syntax-rules ()
1825
(my-or e2 ...)))))))
1839
@deffn {special form} let*-syntax bindings expression expression @dots{}
1840
The syntax of @code{let*-syntax} is the same as for @code{let-syntax}.
1842
The @var{expression}s are expanded in the syntactic environment obtained
1843
by extending the syntactic environment of the @code{letrec-syntax}
1844
expression with macros whose keywords are the @var{keyword}s, bound to
1845
the specified transformers. Each binding of a @var{keyword} has the
1846
subsequent @var{bindings} as well as the @var{expression}s within its
1852
((a (syntax-rules @dots{}))
1853
(b (syntax-rules @dots{})))
1863
(let-syntax ((a (syntax-rules @dots{})))
1864
(let-syntax ((b (syntax-rules @dots{})))
1870
@deffn {special form} define-syntax keyword transformer-spec
1871
@var{Keyword} is an identifier, and @var{transformer-spec} is a macro
1872
transformer expression. The syntactic environment is extended by
1873
binding the @var{keyword} to the specified transformer.
1875
The region of the binding introduced by @code{define-syntax} is the
1876
entire block in which it appears. However, the @var{keyword} may only
1877
be used after it has been defined.
1879
MIT/GNU Scheme permits @code{define-syntax} to appear both at top level and
1880
within @code{lambda} bodies. The Revised^4 Report permits only
1881
top-level uses of @code{define-syntax}.
1883
When compiling a program, a top-level instance of @code{define-syntax}
1884
both defines the syntactic keyword and generates code that will redefine
1885
the keyword when the program is loaded. This means that the same syntax
1886
can be used for defining macros that will be used during compilation
1887
and for defining macros to be used at run time.
1889
Although macros may expand into definitions and syntax definitions in
1890
any context that permits them, it is an error for a definition or syntax
1891
definition to shadow a syntactic keyword whose meaning is needed to
1892
determine whether some form in the group of forms that contains the
1893
shadowing definition is in fact a definition, or, for internal definitions,
1894
is needed to determine the boundary between the group and the expressions
1895
that follow the group. For example, the following are errors:
1900
(begin (define begin list))
1903
((foo (syntax-rules ()
1904
((foo (proc args ...) body ...)
1909
(foo (plus x y) (+ x y))
1915
@node Pattern Language, Syntactic Closures, Syntactic Binding Constructs, Macros
1916
@subsection Pattern Language
1918
MIT/GNU Scheme supports a high-level pattern language for specifying macro
1919
transformers. This pattern language is defined by the Revised^4 Report
1920
and is portable to other conforming Scheme implementations. To use the
1921
pattern language, specify a @var{transformer-spec} as a
1922
@code{syntax-rules} form:
1924
@deffn {special form} syntax-rules literals syntax-rule @dots{}
1925
@var{Literals} is a list of identifiers and each @var{syntax-rule}
1926
should be of the form
1929
(@var{pattern} @var{template})
1932
The @var{pattern} in a @var{syntax-rule} is a list @var{pattern} that
1933
begins with the keyword for the macro.
1935
A @var{pattern} is either an identifier, a constant, or one of the
1939
(@var{pattern} @dots{})
1940
(@var{pattern} @var{pattern} @dots{} . @var{pattern})
1941
(@var{pattern} @dots{} @var{pattern} @var{ellipsis})
1945
and a template is either an identifier, a constant, or one of the
1949
(@var{element} @dots{})
1950
(@var{element} @var{element} @dots{} . @var{template})
1954
where an @var{element} is a @var{template} optionally followed by an
1955
@var{ellipsis} and an @var{ellipsis} is the identifier @samp{...} (which
1956
cannot be used as an identifier in either a template or a pattern).
1958
An instance of @code{syntax-rules} produces a new macro transformer by
1959
specifying a sequence of hygienic rewrite rules. A use of a macro whose
1960
keyword is associated with a transformer specified by
1961
@code{syntax-rules} is matched against the patterns contained in the
1962
@var{syntax-rule}s, beginning with the leftmost @var{syntax-rule}. When
1963
a match is found, the macro use is transcribed hygienically according to
1966
An identifier that appears in the pattern of a @var{syntax-rule} is a
1967
@dfn{pattern-variable}, unless it is the keyword that begins the
1968
pattern, is listed in @var{literals}, or is the identifier @samp{...}.
1969
Pattern variables match arbitrary input elements and are used to refer
1970
to elements of the input in the template. It is an error for the same
1971
pattern variable to appear more than once in a @var{pattern}.
1973
The keyword at the beginning of the pattern in a @var{syntax-rule} is
1974
not involved in the matching and is not considered a pattern variable or
1977
Identifiers that appear in @var{literals} are interpreted as literal
1978
identifiers to be matched against corresponding subforms of the input.
1979
A subform in the input matches a literal identifier if and only if it is
1980
an identifier and either both its occurrence in the macro expression and
1981
its occurrence in the macro definition have the same lexical binding, or
1982
the two identifiers are equal and both have no lexical binding.
1984
A subpattern followed by @samp{...} can match zero or more elements of
1985
the input. It is an error for @samp{...} to appear in @var{literals}.
1986
Within a pattern the identifier @samp{...} must follow the last element
1987
of a nonempty sequence of subpatterns.
1989
More formally, an input form @var{F} matches a pattern @var{P} if and
1994
@var{P} is a non-literal identifier; or
1997
@var{P} is a literal identifier and @var{F} is an identifier with the
2001
@var{P} is a list @code{(@var{P_1} @dots{} @var{P_n})} and @var{F} is a
2002
list of @var{n} forms that match @var{P_1} through @var{P_n},
2006
@var{P} is an improper list @code{(@var{P_1} @var{P_2} @dots{} @var{P_n}
2007
. @var{P_n+1})} and @var{F} is a list or improper list of @var{n} or
2008
more forms that match @var{P_1} through @var{P_n}, respectively, and
2009
whose @var{n}th ``cdr'' matches @var{P_n+1}; or
2012
@var{P} is of the form @code{(@var{P_1} @dots{} @var{P_n} @var{P_n+1}
2013
@var{ellipsis})} where @var{ellipsis} is the identifier @samp{...} and
2014
@var{F} is a proper list of at least @var{n} forms, the first @var{n} of
2015
which match @var{P_1} through @var{P_n}, respectively, and each
2016
remaining element of @var{F} matches @var{P_n+1}; or
2019
@var{P} is a datum and @var{F} is equal to @var{P} in the sense of the
2020
@code{equal?} procedure.
2023
It is an error to use a macro keyword, within the scope of its
2024
binding, in an expression that does not match any of the patterns.
2026
When a macro use is transcribed according to the template of the
2027
matching @var{syntax rule}, pattern variables that occur in the template
2028
are replaced by the subforms they match in the input. Pattern variables
2029
that occur in subpatterns followed by one or more instances of the
2030
identifier @samp{...} are allowed only in subtemplates that are followed
2031
by as many instances of @samp{...}. They are replaced in the output by
2032
all of the subforms they match in the input, distributed as indicated.
2033
It is an error if the output cannot be built up as specified.
2035
Identifiers that appear in the template but are not pattern variables or
2036
the identifier @samp{...} are inserted into the output as literal
2037
identifiers. If a literal identifier is inserted as a free identifier
2038
then it refers to the binding of that identifier within whose scope the
2039
instance of @code{syntax-rules} appears. If a literal identifier is
2040
inserted as a bound identifier then it is in effect renamed to prevent
2041
inadvertent captures of free identifiers.
2046
(cond (#t => 'ok))) @result{} ok
2050
The macro transformer for @code{cond} recognizes @code{=>}
2051
as a local variable, and hence an expression, and not as the
2052
top-level identifier @code{=>}, which the macro transformer treats
2053
as a syntactic keyword. Thus the example expands into
2058
(if #t (begin => 'ok)))
2073
which would result in an invalid procedure call.
2076
@node Syntactic Closures, Explicit Renaming, Pattern Language, Macros
2077
@subsection Syntactic Closures
2079
@cindex syntactic closures
2080
MIT/GNU Scheme's syntax-transformation engine is an implementation of
2081
@dfn{syntactic closures}, a mechanism invented by Alan Bawden and
2082
Jonathan Rees. The main feature of the syntactic-closures mechanism is
2083
its simplicity and its close relationship to the environment models
2084
commonly used with Scheme. Using the mechanism to write macro
2085
transformers is somewhat cumbersome and can be confusing for the newly
2086
initiated, but it is easily mastered.
2089
* Syntax Terminology::
2090
* SC Transformer Definition::
2094
@node Syntax Terminology, SC Transformer Definition, Syntactic Closures, Syntactic Closures
2095
@subsubsection Syntax Terminology
2097
This section defines the concepts and data types used by the syntactic
2103
@dfn{Forms} are the syntactic entities out of which programs are
2104
recursively constructed. A form is any expression, any definition, any
2105
syntactic keyword, or any syntactic closure. The variable name that
2106
appears in a @code{set!} special form is also a form. Examples of
2125
@cindex synthetic identifier
2126
An @dfn{alias} is an alternate name for a given symbol. It can appear
2127
anywhere in a form that the symbol could be used, and when quoted it is
2128
replaced by the symbol; however, it does not satisfy the predicate
2129
@code{symbol?}. Macro transformers rarely distinguish symbols from
2130
aliases, referring to both as @dfn{identifiers}. Another name for an
2131
alias is @dfn{synthetic identifier}; this document uses both names.
2134
@cindex syntactic environment
2135
A @dfn{syntactic environment} maps identifiers to their meanings. More
2136
precisely, it determines whether an identifier is a syntactic keyword
2137
or a variable. If it is a keyword, the meaning is an interpretation
2138
for the form in which that keyword appears. If it is a variable, the
2139
meaning identifies which binding of that variable is referenced. In
2140
short, syntactic environments contain all of the contextual information
2141
necessary for interpreting the meaning of a particular form.
2144
@cindex syntactic closure
2145
A @dfn{syntactic closure} consists of a form, a syntactic environment,
2146
and a list of identifiers. All identifiers in the form take their
2147
meaning from the syntactic environment, except those in the given list.
2148
The identifiers in the list are to have their meanings determined
2151
A syntactic closure may be used in any context in which its form could
2152
have been used. Since a syntactic closure is also a form, it may not
2153
be used in contexts where a form would be illegal. For example, a form
2154
may not appear as a clause in the @code{cond} special form.
2156
A syntactic closure appearing in a quoted structure is replaced by its
2160
@node SC Transformer Definition, SC Identifiers, Syntax Terminology, Syntactic Closures
2161
@subsubsection Transformer Definition
2163
This section describes the special forms for defining syntactic-closures
2164
macro transformers, and the associated procedures for manipulating
2165
syntactic closures and syntactic environments.
2167
@deffn {special form} sc-macro-transformer expression
2168
The @var{expression} is expanded in the syntactic environment of the
2169
@code{sc-macro-transformer} expression, and the expanded expression is
2170
evaluated in the transformer environment to yield a macro transformer as
2171
described below. This macro transformer is bound to a macro keyword by
2172
the special form in which the @code{transformer} expression appears (for
2173
example, @code{let-syntax}).
2175
@cindex macro transformer
2177
@cindex usage environment
2179
@cindex transformer environment
2180
In the syntactic closures facility, a @dfn{macro transformer} is a
2181
procedure that takes two arguments, a form and a syntactic environment,
2182
and returns a new form. The first argument, the @dfn{input form}, is
2183
the form in which the macro keyword occurred. The second argument, the
2184
@dfn{usage environment}, is the syntactic environment in which the input
2185
form occurred. The result of the transformer, the @dfn{output form}, is
2186
automatically closed in the @dfn{transformer environment}, which is the
2187
syntactic environment in which the @code{transformer} expression
2190
For example, here is a definition of a @code{push} macro using
2191
@code{syntax-rules}:
2198
(set! list (cons item list)))))
2203
Here is an equivalent definition using @code{sc-macro-transformer}:
2208
(sc-macro-transformer
2210
(let ((item (make-syntactic-closure env '() (cadr exp)))
2211
(list (make-syntactic-closure env '() (caddr exp))))
2212
`(set! ,list (cons ,item ,list))))))
2217
In this example, the identifiers @code{set!} and @code{cons} are closed
2218
in the transformer environment, and thus will not be affected by the
2219
meanings of those identifiers in the usage environment @code{env}.
2221
Some macros may be non-hygienic by design. For example, the following
2222
defines a @code{loop} macro that implicitly binds @code{exit} to an
2223
escape procedure. The binding of @code{exit} is intended to capture
2224
free references to @code{exit} in the body of the loop, so @code{exit}
2225
must be left free when the body is closed:
2230
(sc-macro-transformer
2232
(let ((body (cdr exp)))
2233
`(call-with-current-continuation
2236
,@@(map (lambda (exp)
2237
(make-syntactic-closure env '(exit)
2245
@deffn {special form} rsc-macro-transformer expression
2246
This form is an alternative way to define a syntactic-closures macro
2247
transformer. Its syntax and usage are identical to
2248
@code{sc-macro-transformer}, except that the roles of the usage
2249
environment and transformer environment are reversed. (Hence
2250
@acronym{RSC} stands for @dfn{Reversed Syntactic Closures}.) In other
2251
words, the procedure specified by @var{expression} still accepts two
2252
arguments, but its second argument will be the transformer environment
2253
rather than the usage environment, and the returned expression is closed
2254
in the usage environment rather than the transformer environment.
2256
The advantage of this arrangement is that it allows a simpler definition
2257
style in some situations. For example, here is the @code{push} macro
2258
from above, rewritten in this style:
2263
(rsc-macro-transformer
2265
`(,(make-syntactic-closure env '() 'SET!)
2267
(,(make-syntactic-closure env '() 'CONS)
2274
In this style only the introduced keywords are closed, while everything
2277
Note that @code{rsc-macro-transformer} and @code{sc-macro-transformer}
2278
are easily interchangeable. Here is how to emulate
2279
@code{rsc-macro-transformer} using @code{sc-macro-transformer}. (This
2280
technique can be used to effect the opposite emulation as well.)
2285
(sc-macro-transformer
2286
(lambda (exp usage-env)
2287
(capture-syntactic-environment
2289
(make-syntactic-closure usage-env '()
2290
`(,(make-syntactic-closure env '() 'SET!)
2292
(,(make-syntactic-closure env '() 'CONS)
2294
,(caddr exp)))))))))
2299
To assign meanings to the identifiers in a form, use
2300
@code{make-syntactic-closure} to close the form in a syntactic
2303
@deffn procedure make-syntactic-closure environment free-names form
2304
@var{Environment} must be a syntactic environment, @var{free-names}
2305
must be a list of identifiers, and @var{form} must be a form.
2306
@code{make-syntactic-closure} constructs and returns a syntactic
2307
closure of @var{form} in @var{environment}, which can be used anywhere
2308
that @var{form} could have been used. All the identifiers used in
2309
@var{form}, except those explicitly excepted by @var{free-names},
2310
obtain their meanings from @var{environment}.
2312
Here is an example where @var{free-names} is something other than the
2313
empty list. It is instructive to compare the use of @var{free-names}
2314
in this example with its use in the @code{loop} example above: the
2315
examples are similar except for the source of the identifier being left
2321
(sc-macro-transformer
2323
(let ((id (cadr exp))
2327
,(make-syntactic-closure env (list id) exp))
2328
,(make-syntactic-closure env '() init))))))
2333
@code{let1} is a simplified version of @code{let} that only binds a
2334
single identifier, and whose body consists of a single expression.
2335
When the body expression is syntactically closed in its original
2336
syntactic environment, the identifier that is to be bound by
2337
@code{let1} must be left free, so that it can be properly captured by
2338
the @code{lambda} in the output form.
2341
In most situations, the @var{free-names} argument to
2342
@code{make-syntactic-closure} is the empty list. In those cases, the
2343
more succinct @code{close-syntax} can be used:
2345
@deffn procedure close-syntax form environment
2346
@var{Environment} must be a syntactic environment and @var{form} must be
2347
a form. Returns a new syntactic closure of @var{form} in
2348
@var{environment}, with no free names. Entirely equivalent to
2351
(make-syntactic-closure @var{environment} '() @var{form})
2355
To obtain a syntactic environment other than the usage environment,
2356
use @code{capture-syntactic-environment}.
2358
@deffn procedure capture-syntactic-environment procedure
2359
@code{capture-syntactic-environment} returns a form that will, when
2360
transformed, call @var{procedure} on the current syntactic environment.
2361
@var{Procedure} should compute and return a new form to be transformed,
2362
in that same syntactic environment, in place of the form.
2364
An example will make this clear. Suppose we wanted to define a simple
2365
@code{loop-until} keyword equivalent to
2369
(define-syntax loop-until
2371
((loop-until id init test return step)
2374
(if test return (loop step)))))
2380
The following attempt at defining @code{loop-until} has a subtle
2385
(define-syntax loop-until
2386
(sc-macro-transformer
2388
(let ((id (cadr exp))
2391
(return (cadddr (cdr exp)))
2392
(step (cadddr (cddr exp)))
2395
(make-syntactic-closure env free exp))))
2398
(if ,(close test (list id))
2399
,(close return (list id))
2400
(loop ,(close step (list id)))))))
2401
(loop ,(close init '())))))))
2406
This definition appears to take all of the proper precautions to
2407
prevent unintended captures. It carefully closes the subexpressions in
2408
their original syntactic environment and it leaves the @code{id}
2409
identifier free in the @code{test}, @code{return}, and @code{step}
2410
expressions, so that it will be captured by the binding introduced by
2411
the @code{lambda} expression. Unfortunately it uses the identifiers
2412
@code{if} and @code{loop} @emph{within} that @code{lambda} expression,
2413
so if the user of @code{loop-until} just happens to use, say, @code{if}
2414
for the identifier, it will be inadvertently captured.
2416
The syntactic environment that @code{if} and @code{loop} want to be
2417
exposed to is the one just outside the @code{lambda} expression: before
2418
the user's identifier is added to the syntactic environment, but after
2419
the identifier @code{loop} has been added.
2420
@code{capture-syntactic-environment} captures exactly that environment
2425
(define-syntax loop-until
2426
(sc-macro-transformer
2428
(let ((id (cadr exp))
2431
(return (cadddr (cdr exp)))
2432
(step (cadddr (cddr exp)))
2435
(make-syntactic-closure env free exp))))
2437
,(capture-syntactic-environment
2440
(,(make-syntactic-closure env '() `if)
2441
,(close test (list id))
2442
,(close return (list id))
2443
(,(make-syntactic-closure env '() `loop)
2444
,(close step (list id)))))))))
2445
(loop ,(close init '())))))))
2450
In this case, having captured the desired syntactic environment, it is
2451
convenient to construct syntactic closures of the identifiers @code{if}
2452
and the @code{loop} and use them in the body of the
2455
A common use of @code{capture-syntactic-environment} is to get the
2456
transformer environment of a macro transformer:
2460
(sc-macro-transformer
2462
(capture-syntactic-environment
2463
(lambda (transformer-env)
2469
@node SC Identifiers, , SC Transformer Definition, Syntactic Closures
2470
@subsubsection Identifiers
2472
This section describes the procedures that create and manipulate
2473
identifiers. The identifier data type extends the syntactic closures
2474
facility to be compatible with the high-level @code{syntax-rules}
2478
As discussed earlier, an identifier is either a symbol or an
2479
@dfn{alias}. An alias is implemented as a syntactic closure whose
2480
@var{form} is an identifier:
2484
(make-syntactic-closure env '() 'a) @result{} @r{an alias}
2489
Aliases are implemented as syntactic closures because they behave just
2490
like syntactic closures most of the time. The difference is that an
2491
alias may be bound to a new value (for example by @code{lambda} or
2492
@code{let-syntax}); other syntactic closures may not be used this way.
2493
If an alias is bound, then within the scope of that binding it is looked
2494
up in the syntactic environment just like any other identifier.
2496
Aliases are used in the implementation of the high-level facility
2497
@code{syntax-rules}. A macro transformer created by @code{syntax-rules}
2498
uses a template to generate its output form, substituting subforms of
2499
the input form into the template. In a syntactic closures
2500
implementation, all of the symbols in the template are replaced by
2501
aliases closed in the transformer environment, while the output form
2502
itself is closed in the usage environment. This guarantees that the
2503
macro transformation is hygienic, without requiring the transformer to
2504
know the syntactic roles of the substituted input subforms.
2506
@deffn procedure identifier? object
2507
Returns @code{#t} if @var{object} is an identifier, otherwise returns
2508
@code{#f}. Examples:
2512
(identifier? 'a) @result{} #t
2513
(identifier? (make-syntactic-closure env '() 'a))
2516
(identifier? "a") @result{} #f
2517
(identifier? #\a) @result{} #f
2518
(identifier? 97) @result{} #f
2519
(identifier? #f) @result{} #f
2520
(identifier? '(a)) @result{} #f
2521
(identifier? '#(a)) @result{} #f
2526
The predicate @code{eq?} is used to determine if two identifers are
2527
``the same''. Thus @code{eq?} can be used to compare identifiers
2528
exactly as it would be used to compare symbols. Often, though, it is
2529
useful to know whether two identifiers ``mean the same thing''. For
2530
example, the @code{cond} macro uses the symbol @code{else} to identify
2531
the final clause in the conditional. A macro transformer for
2532
@code{cond} cannot just look for the symbol @code{else}, because the
2533
@code{cond} form might be the output of another macro transformer that
2534
replaced the symbol @code{else} with an alias. Instead the transformer
2535
must look for an identifier that ``means the same thing'' in the usage
2536
environment as the symbol @code{else} means in the transformer
2539
@deffn procedure identifier=? environment1 identifier1 environment2 identifier2
2540
@var{Environment1} and @var{environment2} must be syntactic
2541
environments, and @var{identifier1} and @var{identifier2} must be
2542
identifiers. @code{identifier=?} returns @code{#t} if the meaning of
2543
@var{identifier1} in @var{environment1} is the same as that of
2544
@var{identifier2} in @var{environment2}, otherwise it returns @code{#f}.
2551
(sc-macro-transformer
2553
(capture-syntactic-environment
2554
(lambda (transformer-env)
2555
(identifier=? transformer-env 'x env 'x)))))))
2563
(let-syntax ((bar foo))
2566
(sc-macro-transformer
2568
(capture-syntactic-environment
2569
(lambda (transformer-env)
2570
(identifier=? transformer-env 'foo
2571
env (cadr form))))))))
2579
Sometimes it is useful to be able to introduce a new identifier that is
2580
guaranteed to be different from any existing identifier, similarly to
2581
the way that @code{generate-uninterned-symbol} is used.
2583
@deffn procedure make-synthetic-identifier identifier
2584
Creates and returns and new synthetic identifier (alias) that is
2585
guaranteed to be different from all existing identifiers.
2586
@var{Identifier} is any existing identifier, which is used in deriving
2587
the name of the new identifier.
2589
This is implemented by syntactically closing @var{identifier} in a
2590
special empty environment.
2593
@node Explicit Renaming, , Syntactic Closures, Macros
2594
@subsection Explicit Renaming
2596
@cindex explicit renaming
2597
@dfn{Explicit renaming} is an alternative facility for defining macro
2598
transformers. In the MIT/GNU Scheme implementation, explicit-renaming
2599
transformers are implemented as an abstraction layer on top of syntactic
2600
closures. An explicit-renaming macro transformer is defined by an
2601
instance of the @code{er-macro-transformer} keyword:
2603
@deffn {special form} er-macro-transformer expression
2604
The @var{expression} is expanded in the syntactic environment of the
2605
@code{er-macro-transformer} expression, and the expanded expression is
2606
evaluated in the transformer environment to yield a macro transformer as
2607
described below. This macro transformer is bound to a macro keyword by
2608
the special form in which the @code{transformer} expression appears (for
2609
example, @code{let-syntax}).
2611
@cindex macro transformer
2612
@cindex input form, to macro
2613
In the explicit-renaming facility, a @dfn{macro transformer} is a
2614
procedure that takes three arguments, a form, a renaming procedure, and
2615
a comparison predicate, and returns a new form. The first argument, the
2616
@dfn{input form}, is the form in which the macro keyword occurred.
2618
@cindex renaming procedure
2619
The second argument to a transformation procedure is a @dfn{renaming
2620
procedure} that takes the representation of an identifier as its
2621
argument and returns the representation of a fresh identifier that
2622
occurs nowhere else in the program. For example, the transformation
2623
procedure for a simplified version of the @code{let} macro might be
2628
(lambda (exp rename compare)
2629
(let ((vars (map car (cadr exp)))
2630
(inits (map cadr (cadr exp)))
2632
`((lambda ,vars ,@@body)
2638
This would not be hygienic, however. A hygienic @code{let} macro must
2639
rename the identifier @code{lambda} to protect it from being captured by
2640
a local binding. The renaming effectively creates an fresh alias for
2641
@code{lambda}, one that cannot be captured by any subsequent binding:
2645
(lambda (exp rename compare)
2646
(let ((vars (map car (cadr exp)))
2647
(inits (map cadr (cadr exp)))
2649
`((,(rename 'lambda) ,vars ,@@body)
2654
The expression returned by the transformation procedure will be expanded
2655
in the syntactic environment obtained from the syntactic environment of
2656
the macro application by binding any fresh identifiers generated by the
2657
renaming procedure to the denotations of the original identifiers in the
2658
syntactic environment in which the macro was defined. This means that a
2659
renamed identifier will denote the same thing as the original identifier
2660
unless the transformation procedure that renamed the identifier placed
2661
an occurrence of it in a binding position.
2663
The renaming procedure acts as a mathematical function in the sense that
2664
the identifiers obtained from any two calls with the same argument will
2665
be the same in the sense of @code{eqv?}. It is an error if the renaming
2666
procedure is called after the transformation procedure has returned.
2668
@cindex comparison predicate
2669
The third argument to a transformation procedure is a @dfn{comparison
2670
predicate} that takes the representations of two identifiers as its
2671
arguments and returns true if and only if they denote the same thing in
2672
the syntactic environment that will be used to expand the transformed
2673
macro application. For example, the transformation procedure for a
2674
simplified version of the @code{cond} macro can be written as
2678
(lambda (exp rename compare)
2679
(let ((clauses (cdr exp)))
2681
`(,(rename 'quote) unspecified)
2682
(let* ((first (car clauses))
2683
(rest (cdr clauses))
2685
(cond ((and (identifier? test)
2686
(compare test (rename 'else)))
2687
`(,(rename 'begin) ,@@(cdr first)))
2688
(else `(,(rename 'if)
2690
(,(rename 'begin) ,@@(cdr first))
2691
(cond ,@@rest))))))))))
2696
In this example the identifier @code{else} is renamed before being passed
2697
to the comparison predicate, so the comparison will be true if and
2698
only if the test expression is an identifier that denotes the same
2699
thing in the syntactic environment of the expression being transformed
2700
as @code{else} denotes in the syntactic environment in which the @code{cond}
2701
macro was defined. If @code{else} were not renamed before being passed to
2702
the comparison predicate, then it would match a local variable that
2703
happened to be named @code{else}, and the macro would not be hygienic.
2705
Some macros are non-hygienic by design. For example, the following
2706
defines a @code{loop} macro that implicitly binds @code{exit} to an
2707
escape procedure. The binding of @code{exit} is intended to capture
2708
free references to @code{exit} in the body of the loop, so @code{exit}
2714
(er-macro-transformer
2716
(let ((body (cdr x)))
2717
`(,(r 'call-with-current-continuation)
2718
(,(r 'lambda) (exit)
2719
(,(r 'let) ,(r 'f) () ,@@body (,(r 'f)))))))))
2723
Suppose a @code{while} macro is implemented using @code{loop}, with the
2724
intent that @code{exit} may be used to escape from the @code{while}
2725
loop. The @code{while} macro cannot be written as
2729
(define-syntax while
2731
((while test body ...)
2732
(loop (if (not test) (exit #f))
2738
because the reference to @code{exit} that is inserted by the
2739
@code{while} macro is intended to be captured by the binding of
2740
@code{exit} that will be inserted by the @code{loop} macro. In other
2741
words, this @code{while} macro is not hygienic. Like @code{loop}, it
2742
must be written using the @code{er-macro-transformer} syntax:
2746
(define-syntax while
2747
(er-macro-transformer
2749
(let ((test (cadr x))
2752
(,(r 'if) (,(r 'not) ,test) (exit #f))
2758
@node SRFI syntax, , Macros, Special Forms
2759
@section SRFI syntax
2762
Several special forms have been introduced to support some of the
2763
@uref{http://srfi.schemers.org/,Scheme Requests for Implementation}
2764
(@acronym{SRFI}). Note that MIT/GNU Scheme has for some time supported
2765
@uref{http://srfi.schemers.org/srfi-23/srfi-23.html,@acronym{SRFI} 23}
2766
(error-reporting mechanism) and
2767
@uref{http://srfi.schemers.org/srfi-30/srfi-30.html,@acronym{SRFI} 30}
2768
(nested multi-line comments), since these @acronym{SRFI}s reflect
2769
existing practice rather than introducing new functionality.
2772
* cond-expand (SRFI 0)::
2773
* receive (SRFI 8)::
2774
* define-record-type (SRFI 9)::
2777
@node cond-expand (SRFI 0), receive (SRFI 8), SRFI syntax, SRFI syntax
2778
@subsection cond-expand (SRFI 0)
2781
@uref{http://srfi.schemers.org/srfi-0/srfi-0.html,@acronym{SRFI} 0}
2782
is a mechanism for portably determining the availability of
2783
@uref{http://srfi.schemers.org/,@acronym{SRFI}} @dfn{features}.
2784
The @code{cond-expand} special form conditionally expands according to
2785
the features available.
2787
@deffn {special form} cond-expand clause clause dots{}
2788
Each @var{clause} has the form
2791
(@var{feature-requirement} @var{expression} @dots{})
2794
where @var{feature-requirement} can have one of the following forms:
2798
@var{feature-identifier}
2799
(and @var{feature-requirement} @dots{})
2800
(or @var{feature-requirement} @dots{})
2801
(not @var{feature-requirement})
2806
(Note that at most one @code{else} clause may be present, and it must
2807
always be the last clause.)
2809
The @code{cond-expand} special form tests for the existence of features
2810
at macro-expansion time. It either expands into the body of one of its
2811
@var{clause}s or signals an error during syntactic processing.
2812
@code{cond-expand} expands into the body of the first @var{clause} whose
2813
@var{feature-requirement} is currently satisfied (an @code{else}
2814
@var{clause}, if present, is selected if none of the previous
2815
@var{clauses} is selected).
2817
A @var{feature-requirement} has an obvious interpretation as a logical
2818
formula, where the @var{feature-identifier} variables have meaning true
2819
if the feature corresponding to the @var{feature-identifier}, as
2820
specified in the @acronym{SRFI} registry, is in effect at the location
2821
of the @code{cond-expand} form, and false otherwise. A
2822
@var{feature-requirement} is satisfied if its formula is true under this
2828
((and srfi-1 srfi-10)
2830
((or srfi-1 srfi-10)
2836
(define (program-name) (car (argv)))))
2840
The second example assumes that @code{command-line} is an alias for some
2841
feature which gives access to command line arguments. Note that an
2842
error will be signaled at macro-expansion time if this feature is not
2845
Note that MIT/GNU Scheme allows @code{cond-expand} in any context where a
2846
special form is allowed. This is an extension of the semantics defined
2847
by @acronym{SRFI 0}, which only allows @code{cond-expand} at top level.
2850
@node receive (SRFI 8), define-record-type (SRFI 9), cond-expand (SRFI 0), SRFI syntax
2851
@subsection receive (SRFI 8)
2854
@uref{http://srfi.schemers.org/srfi-8/srfi-8.html,@acronym{SRFI} 8}
2855
defines a convenient syntax to bind an identifier to each of the values
2856
of a multiple-valued expression and then evaluate an expression in the
2857
scope of the bindings. As an instance of this pattern, consider the
2858
following excerpt from a @samp{quicksort} procedure:
2864
(partition (precedes pivot) others))
2866
(append (qsort fore) (cons pivot (qsort aft)))))
2870
Here @samp{partition} is a multiple-valued procedure that takes two
2871
arguments, a predicate and a list, and returns two lists, one comprising
2872
the list elements that satisfy the predicate, the other those that do
2873
not. The purpose of the expression shown is to partition the list
2874
@samp{others}, sort each of the sublists, and recombine the results into
2877
For our purposes, the important step is the binding of the identifiers
2878
@samp{fore} and @samp{aft} to the values returned by @samp{partition}.
2879
Expressing the construction and use of these bindings with the
2880
call-by-values primitive is cumbersome: One must explicitly embed the
2881
expression that provides the values for the bindings in a parameterless
2882
procedure, and one must explicitly embed the expression to be evaluated
2883
in the scope of those bindings in another procedure, writing as its
2884
parameters the identifiers that are to be bound to the values received.
2886
These embeddings are boilerplate, exposing the underlying binding
2887
mechanism but not revealing anything relevant to the particular program
2888
in which it occurs. So the use of a syntactic abstraction that exposes
2889
only the interesting parts -- the identifiers to be bound, the
2890
multiple-valued expression that supplies the values, and the body of the
2891
receiving procedure -- makes the code more concise and more readable:
2895
(receive (fore aft) (partition (precedes pivot) others)
2896
(append (qsort fore) (cons pivot (qsort aft))))
2900
The advantages are similar to those of a @samp{let} expression over a
2901
procedure call with a @samp{lambda} expression as its operator. In both
2902
cases, cleanly separating a ``header'' in which the bindings are
2903
established from a ``body'' in which they are used makes it easier to
2906
@deffn {special form} receive formals expression body
2907
@var{Formals} and @var{body} are defined as for @samp{lambda}
2908
(@pxref{Lambda Expressions}). Specifically, @var{formals} can have the
2909
following forms (the use of @samp{#!optional} and @samp{#!rest} is also
2910
allowed in @var{formals} but is omitted for brevity):
2913
@item (@var{ident1} @dots{} @var{identN})
2914
The environment in which the @samp{receive} expression is evaluated is
2915
extended by binding @var{ident1}, @dots{}, @var{identN} to fresh
2916
locations. The @var{expression} is evaluated, and its values are stored
2917
into those locations. (It is an error if @var{expression} does not have
2918
exactly @var{N} values.)
2921
The environment in which the @samp{receive} expression is evaluated is
2922
extended by binding @var{ident} to a fresh location. The
2923
@var{expression} is evaluated, its values are converted into a newly
2924
allocated list, and the list is stored in the location bound to
2927
@item (@var{ident1} @dots{} @var{identN} . @var{identN+1})
2928
The environment in which the @samp{receive} expression is evaluated is
2929
extended by binding @var{ident1}, @dots{}, @var{identN+1} to fresh
2930
locations. The @var{expression} is evaluated. Its first @var{N} values
2931
are stored into the locations bound to @var{ident1} @dots{} @var{identN}.
2932
Any remaining values are converted into a newly allocated list, which is
2933
stored into the location bound to @var{identN+1}. (It is an error if
2934
@var{expression} does not have at least @var{N} values.)
2937
In any case, the expressions in @var{body} are evaluated sequentially in
2938
the extended environment. The results of the last expression in the
2939
body are the values of the @samp{receive} expression.
2942
@node define-record-type (SRFI 9), , receive (SRFI 8), SRFI syntax
2943
@subsection define-record-type (SRFI 9)
2946
The @samp{define-record-type} syntax described in
2947
@uref{http://srfi.schemers.org/srfi-9/srfi-9.html,@acronym{SRFI} 9} is a
2948
slight simplification of one written for Scheme 48 by Jonathan Rees.
2949
Unlike many record-defining special forms, it does not create any new
2950
identifiers. Instead, the names of the record type, predicate,
2951
constructor, and so on are all listed explicitly in the source. This
2952
has the following advantages:
2956
It can be defined using a simple macro in Scheme implementations that
2957
provide a procedural interface for creating record types.
2960
It does not restrict users to a particular naming convention.
2963
Tools like @command{grep} and the GNU Emacs tag facility will see the
2964
defining occurance of each identifier.
2967
@deffn {special form} define-record-type type-name (constructor-name field-tag @dots{}) predicate-name field-spec @dots{}
2968
@var{Type-name}, @var{contructor-name}, @var{field-tag}, and
2969
@var{predicate-name} are identifiers. @var{Field-spec} has one of these
2974
(@var{field-tag} @var{accessor-name})
2975
(@var{field-tag} @var{accessor-name} @var{modifier-name})
2980
where @var{field-tag}, @var{accessor-name}, and @var{modifier-name} are
2983
@code{define-record-type} is generative: each use creates a new record
2984
type that is distinct from all existing types, including other record
2985
types and Scheme's predefined types. Record-type definitions may only
2986
occur at top-level (there are two possible semantics for ``internal''
2987
record-type definitions, generative and nongenerative, and no consensus
2988
as to which is better).
2990
An instance of @code{define-record-type} is equivalent to the following
2995
@var{Type-name} is bound to a representation of the record type itself.
2996
Operations on record types, such as defining print methods, reflection,
2997
etc.@: are left to other SRFIs.
3000
@var{constructor-name} is bound to a procedure that takes as many
3001
arguments as there are @var{field-tag}s in the (@var{constructor-name}
3002
@dots{}) subform and returns a new @var{type-name} record. Fields whose
3003
tags are listed with @var{constructor-name} have the corresponding
3004
argument as their initial value. The initial values of all other fields
3008
@var{predicate-name} is a predicate that returns @code{#t} when given a
3009
value returned by @var{constructor-name} and @code{#f} for everything
3013
Each @var{accessor-name} is a procedure that takes a record of type
3014
@var{type-name} and returns the current value of the corresponding
3015
field. It is an error to pass an accessor a value which is not a record
3016
of the appropriate type.
3019
Each @var{modifier-name} is a procedure that takes a record of type
3020
@var{type-name} and a value which becomes the new value of the
3021
corresponding field; an unspecified value is returned. It is an error
3022
to pass a modifier a first argument which is not a record of the
3026
Assigning the value of any of these identifiers has no effect on the
3027
behavior of any of their original values.
3034
(define-record-type :pare
3043
defines @samp{kons} to be a constructor, @samp{kar} and @samp{kdr} to be
3044
accessors, @samp{set-kar!} to be a modifier, and @samp{pare?} to be a
3045
predicate for objects of type @samp{:pare}.
3049
(pare? (kons 1 2)) @result{} #t
3050
(pare? (cons 1 2)) @result{} #f
3051
(kar (kons 1 2)) @result{} 1
3052
(kdr (kons 1 2)) @result{} 2
3053
(let ((k (kons 1 2)))
3055
(kar k)) @result{} 3