~ubuntu-branches/ubuntu/intrepid/mit-scheme/intrepid-updates

« back to all changes in this revision

Viewing changes to doc/ref-manual/special-forms.texi

  • Committer: Bazaar Package Importer
  • Author(s): Chris Hanson
  • Date: 2005-01-18 00:33:57 UTC
  • mfrom: (2.1.1 warty)
  • Revision ID: james.westby@ubuntu.com-20050118003357-pv3i8iqlm5m80tl5
Tags: 7.7.90-5
* Add "libx11-dev" to build-depends.  (closes: Bug#290845)
* Fix debian/control and debian/menu to eliminate some lintian errors
  and warnings.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 $
 
3
 
 
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.
 
8
 
 
9
@node Special Forms, Equivalence Predicates, Overview, Top
 
10
@chapter Special Forms
 
11
 
 
12
@cindex special form
 
13
A special form is an expression that follows special evaluation rules.
 
14
This chapter describes the basic Scheme special forms.
 
15
 
 
16
@menu
 
17
* Lambda Expressions::          
 
18
* Lexical Binding::             
 
19
* Dynamic Binding::             
 
20
* Definitions::                 
 
21
* Assignments::                 
 
22
* Quoting::                     
 
23
* Conditionals::                
 
24
* Sequencing::                  
 
25
* Iteration::                   
 
26
* Structure Definitions::       
 
27
* Macros::                      
 
28
* SRFI syntax::                 
 
29
@end menu
 
30
 
 
31
@node Lambda Expressions, Lexical Binding, Special Forms, Special Forms
 
32
@section Lambda Expressions
 
33
 
 
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}.
 
53
 
 
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
 
62
call.
 
63
 
 
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
 
68
@dfn{lambda list}.
 
69
 
 
70
The process of matching up formal parameters with arguments is somewhat
 
71
involved.  There are three types of parameters, and the matching treats
 
72
each in sequence:
 
73
 
 
74
@need 1000
 
75
@table @asis
 
76
@item Required
 
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
 
85
 
 
86
@item Optional
 
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
 
98
 
 
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.
 
103
 
 
104
@item Rest
 
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)
 
111
 
 
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.
 
115
@end table
 
116
 
 
117
@findex #!optional
 
118
@findex #!rest
 
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}.
 
124
 
 
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
 
129
instead.
 
130
 
 
131
@table @code
 
132
@item (a b c)
 
133
@code{a}, @code{b}, and @code{c} are all required.  The procedure must
 
134
be passed exactly three arguments.
 
135
 
 
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.
 
139
 
 
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.
 
143
 
 
144
@item a
 
145
@itemx (#!rest a)
 
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}.
 
149
 
 
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
 
153
arguments.
 
154
@end table
 
155
 
 
156
Some examples of @code{lambda} expressions:
 
157
 
 
158
@example
 
159
@group
 
160
(lambda (x) (+ x x))            @result{}  #[compound-procedure 53]
 
161
 
 
162
((lambda (x) (+ x x)) 4)                @result{}  8
 
163
 
 
164
(define reverse-subtract
 
165
  (lambda (x y)
 
166
    (- y x)))
 
167
(reverse-subtract 7 10)                 @result{}  3
 
168
 
 
169
(define foo
 
170
  (let ((x 4))
 
171
    (lambda (y) (+ x y))))
 
172
(foo 6)                                 @result{}  10
 
173
@end group
 
174
@end example
 
175
@end deffn
 
176
 
 
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''.
 
187
 
 
188
@example
 
189
@group
 
190
(named-lambda (f x) (+ x x))    @result{}  #[compound-procedure 53 f]
 
191
((named-lambda (f x) (+ x x)) 4)        @result{}  8
 
192
@end group
 
193
@end example
 
194
@end deffn
 
195
 
 
196
@node Lexical Binding, Dynamic Binding, Lambda Expressions, Special Forms
 
197
@section Lexical Binding
 
198
 
 
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
 
210
definitions).
 
211
 
 
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
 
220
its region.
 
221
 
 
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.
 
224
 
 
225
@cindex lambda, implicit in let
 
226
Note that the following are equivalent:
 
227
 
 
228
@example
 
229
@group
 
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{})
 
232
@end group
 
233
@end example
 
234
 
 
235
Some examples:
 
236
 
 
237
@example
 
238
@group
 
239
(let ((x 2) (y 3))
 
240
  (* x y))                              @result{}  6
 
241
@end group
 
242
 
 
243
@group
 
244
(let ((x 2) (y 3))
 
245
  (let ((foo (lambda (z) (+ x y z)))
 
246
        (x 7))
 
247
    (foo 4)))                           @result{}  9
 
248
@end group
 
249
@end example
 
250
 
 
251
@xref{Iteration}, for information on ``named @code{let}''.
 
252
@end deffn
 
253
 
 
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.
 
262
 
 
263
Note that the following are equivalent:
 
264
 
 
265
@example
 
266
@group
 
267
(let* ((@var{variable1} @var{init1})
 
268
       (@var{variable2} @var{init2})
 
269
       @dots{}
 
270
       (@var{variableN} @var{initN}))
 
271
   @var{expression}
 
272
   @var{expression} @dots{})
 
273
@end group
 
274
 
 
275
@group
 
276
(let ((@var{variable1} @var{init1}))
 
277
  (let ((@var{variable2} @var{init2}))
 
278
    @dots{}
 
279
      (let ((@var{variableN} @var{initN}))
 
280
        @var{expression}
 
281
        @var{expression} @dots{})
 
282
    @dots{}))
 
283
@end group
 
284
@end example
 
285
 
 
286
An example:
 
287
 
 
288
@example
 
289
@group
 
290
(let ((x 2) (y 3))
 
291
  (let* ((x 7)
 
292
         (z (+ x y)))
 
293
    (* z x)))                           @result{}  70
 
294
@end group
 
295
@end example
 
296
@end deffn
 
297
 
 
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.
 
309
 
 
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.
 
312
 
 
313
@example
 
314
@group
 
315
(letrec ((even?
 
316
          (lambda (n)
 
317
            (if (zero? n)
 
318
                #t
 
319
                (odd? (- n 1)))))
 
320
         (odd?
 
321
          (lambda (n)
 
322
            (if (zero? n)
 
323
                #f
 
324
                (even? (- n 1))))))
 
325
  (even? 88))                           @result{}  #t
 
326
@end group
 
327
@end example
 
328
 
 
329
@findex lambda
 
330
@findex delay
 
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.
 
338
@end deffn
 
339
 
 
340
@node Dynamic Binding, Definitions, Lexical Binding, Special Forms
 
341
@section Dynamic Binding
 
342
 
 
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.
 
354
 
 
355
@findex let
 
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}.
 
361
 
 
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.
 
365
 
 
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
 
371
 
 
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:
 
374
 
 
375
@example
 
376
@group
 
377
(define variable #t)
 
378
(define (access-variable) variable)
 
379
variable                                @result{}  #t
 
380
(let ((variable #f))
 
381
  (access-variable))                    @result{}  #t
 
382
variable                                @result{}  #t
 
383
@end group
 
384
@end example
 
385
 
 
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
 
389
existing variable:
 
390
 
 
391
@example
 
392
@group
 
393
variable                                @result{}  #t
 
394
(fluid-let ((variable #f))              @r{;reuses old binding}
 
395
  (access-variable))                    @result{}  #f
 
396
variable                                @result{}  #t
 
397
@end group
 
398
@end example
 
399
 
 
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.
 
408
 
 
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.
 
417
@end deffn
 
418
 
 
419
Here is a complicated example that shows the interaction between dynamic
 
420
binding and continuations:
 
421
 
 
422
@example
 
423
@group
 
424
(define (complicated-dynamic-binding)
 
425
  (let ((variable 1)
 
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)
 
432
         (set! variable 3)
 
433
         (call-with-current-continuation
 
434
          (lambda (k)
 
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
 
441
        (begin
 
442
          (set! variable 4)
 
443
          (inside-continuation #f)))))
 
444
@end group
 
445
@end example
 
446
 
 
447
@noindent
 
448
Evaluating @samp{(complicated-dynamic-binding)} writes the following on
 
449
the console:
 
450
 
 
451
@example
 
452
@group
 
453
1
 
454
2
 
455
1
 
456
3
 
457
4
 
458
@end group
 
459
@end example
 
460
 
 
461
@noindent
 
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.
 
474
 
 
475
@node Definitions, Assignments, Dynamic Binding, Special Forms
 
476
@section Definitions
 
477
@cindex definition
 
478
 
 
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)
 
486
@findex lambda
 
487
@findex let
 
488
@findex let*
 
489
@findex letrec
 
490
@findex fluid-let
 
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
 
498
definition}.
 
499
 
 
500
@cindex lambda, implicit in define
 
501
@cindex procedure define (defn)
 
502
@cindex define, procedure (defn)
 
503
@findex named-lambda
 
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:
 
508
 
 
509
@example
 
510
@group
 
511
(define (@var{name1} @var{name2} @dots{})
 
512
  @var{expression}
 
513
  @var{expression} @dots{})
 
514
@end group
 
515
 
 
516
@group
 
517
(define @var{name1}
 
518
  (named-lambda (@var{name1} @var{name2} @dots{})
 
519
    @var{expression}
 
520
    @var{expression} @dots{}))
 
521
@end group
 
522
@end example
 
523
@end deffn
 
524
 
 
525
@menu
 
526
* Top-Level Definitions::       
 
527
* Internal Definitions::        
 
528
@end menu
 
529
 
 
530
@node Top-Level Definitions, Internal Definitions, Definitions, Definitions
 
531
@subsection Top-Level Definitions
 
532
@cindex top-level definition
 
533
@cindex definition, top-level
 
534
 
 
535
@cindex variable binding, top-level definition
 
536
A top-level definition,
 
537
 
 
538
@example
 
539
(define @var{variable} @var{expression})
 
540
@end example
 
541
 
 
542
@noindent
 
543
has essentially the same effect as this assignment expression, if
 
544
@var{variable} is bound:
 
545
 
 
546
@example
 
547
(set! @var{variable} @var{expression})
 
548
@end example
 
549
 
 
550
@cindex unassigned variable, and definition
 
551
@findex set!
 
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.
 
557
 
 
558
@example
 
559
@group
 
560
(define add3
 
561
   (lambda (x) (+ x 3)))                @result{}  @r{unspecified}
 
562
(add3 3)                                @result{}  6
 
563
 
 
564
(define first car)                      @result{}  @r{unspecified}
 
565
(first '(1 2))                          @result{}  1
 
566
 
 
567
(define bar)                            @result{}  @r{unspecified}
 
568
bar                                     @error{} Unassigned variable
 
569
@end group
 
570
@end example
 
571
 
 
572
@node Internal Definitions,  , Top-Level Definitions, Definitions
 
573
@subsection Internal Definitions
 
574
 
 
575
@cindex internal definition
 
576
@cindex definition, internal
 
577
@cindex region of variable binding, internal definition
 
578
@cindex variable binding, internal definition
 
579
@findex lambda
 
580
@findex let
 
581
@findex let*
 
582
@findex letrec
 
583
@findex fluid-let
 
584
@findex define
 
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,
 
592
 
 
593
@example
 
594
@group
 
595
(let ((x 5))
 
596
  (define foo (lambda (y) (bar x y)))
 
597
  (define bar (lambda (a b) (+ (* a b) a)))
 
598
  (foo (+ x 3)))                        @result{}  45
 
599
@end group
 
600
@end example
 
601
 
 
602
@findex letrec
 
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
 
606
 
 
607
@cindex letrec, implicit in define
 
608
@example
 
609
@group
 
610
(let ((x 5))
 
611
  (letrec ((foo (lambda (y) (bar x y)))
 
612
           (bar (lambda (a b) (+ (* a b) a))))
 
613
    (foo (+ x 3))))
 
614
@end group
 
615
@end example
 
616
 
 
617
@need 1000
 
618
@node Assignments, Quoting, Definitions, Special Forms
 
619
@section Assignments
 
620
@cindex assignment
 
621
 
 
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.
 
630
 
 
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.
 
634
 
 
635
@example
 
636
@group
 
637
(define x 2)                            @result{}  @r{unspecified}
 
638
(+ x 1)                                 @result{}  3
 
639
(set! x 4)                              @result{}  @r{unspecified}
 
640
(+ x 1)                                 @result{}  5
 
641
@end group
 
642
@end example
 
643
 
 
644
@cindex access, used with set!
 
645
@findex access
 
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,
 
649
 
 
650
@example
 
651
@group
 
652
(define x (let ((y 0)) (the-environment)))
 
653
(define y 'a)
 
654
y                                       @result{}  a
 
655
(access y x)                            @result{}  0
 
656
(set! (access y x) 1)                   @result{}  @r{unspecified}
 
657
y                                       @result{}  a
 
658
(access y x)                            @result{}  1
 
659
@end group
 
660
@end example
 
661
@end deffn
 
662
 
 
663
@node Quoting, Conditionals, Assignments, Special Forms
 
664
@section Quoting
 
665
@cindex quoting
 
666
 
 
667
This section describes the expressions that are used to modify or
 
668
prevent the evaluation of objects.
 
669
 
 
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
 
678
Scheme code.
 
679
 
 
680
@example
 
681
@group
 
682
(quote a)                               @result{}  a
 
683
(quote #(a b c))                        @result{}  #(a b c)
 
684
(quote (+ 1 2))                         @result{}  (+ 1 2)
 
685
@end group
 
686
@end example
 
687
 
 
688
@cindex ' as external representation
 
689
@cindex apostrophe, as external representation
 
690
@cindex quote, as external representation
 
691
@findex '
 
692
@code{(quote @var{datum})} may be abbreviated as @code{'@var{datum}}.
 
693
The two notations are equivalent in all respects.
 
694
 
 
695
@example
 
696
@group
 
697
'a                                      @result{}  a
 
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)
 
702
@end group
 
703
@end example
 
704
 
 
705
Numeric constants, string constants, character constants, and boolean
 
706
constants evaluate to themselves, so they don't need to be quoted.
 
707
 
 
708
@example
 
709
@group
 
710
'"abc"                                  @result{}  "abc"
 
711
"abc"                                   @result{}  "abc"
 
712
'145932                                 @result{}  145932
 
713
145932                                  @result{}  145932
 
714
'#t                                     @result{}  #t
 
715
#t                                      @result{}  #t
 
716
'#\a                                    @result{}  #\a
 
717
#\a                                     @result{}  #\a
 
718
@end group
 
719
@end example
 
720
@end deffn
 
721
 
 
722
@deffn {special form} quasiquote template
 
723
@cindex external representation, and quasiquote
 
724
@cindex literal, and quasiquote
 
725
@cindex constant, and quasiquote
 
726
@findex equal?
 
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
 
739
expression sequence.
 
740
 
 
741
@example
 
742
@group
 
743
`(list ,(+ 1 2) 4)                       @result{}  (list 3 4)
 
744
 
 
745
(let ((name 'a)) `(list ,name ',name))   @result{}  (list a 'a)
 
746
 
 
747
`(a ,(+ 1 2) ,@@(map abs '(4 -5 6)) b)    @result{}  (a 3 4 5 6 b)
 
748
 
 
749
`((foo ,(- 10 3)) ,@@(cdr '(c)) . ,(car '(cons)))
 
750
                                         @result{}  ((foo 7) . cons)
 
751
 
 
752
`#(10 5 ,(sqrt 4) ,@@(map sqrt '(16 9)) 8)
 
753
                                         @result{}  #(10 5 2 4 3 8)
 
754
 
 
755
`,(+ 2 3)                                @result{}  5
 
756
@end group
 
757
@end example
 
758
 
 
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.
 
764
 
 
765
@example
 
766
@group
 
767
`(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f)
 
768
     @result{}  (a `(b ,(+ 1 2) ,(foo 4 d) e) f)
 
769
 
 
770
(let ((name1 'x)
 
771
      (name2 'y))
 
772
   `(a `(b ,,name1 ,',name2 d) e))
 
773
     @result{}  (a `(b ,x ,'y d) e)
 
774
@end group
 
775
@end example
 
776
 
 
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
 
782
@findex unquote
 
783
@findex unquote-splicing
 
784
@findex `
 
785
@findex ,
 
786
@findex ,@@
 
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})}.
 
792
 
 
793
@example
 
794
@group
 
795
(quasiquote (list (unquote (+ 1 2)) 4))
 
796
     @result{}  (list 3 4)
 
797
 
 
798
'(quasiquote (list (unquote (+ 1 2)) 4))
 
799
     @result{}  `(list ,(+ 1 2) 4)
 
800
     @emph{i.e.,} (quasiquote (list (unquote (+ 1 2)) 4))
 
801
@end group
 
802
@end example
 
803
 
 
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.
 
807
@end deffn
 
808
 
 
809
@node Conditionals, Sequencing, Quoting, Special Forms
 
810
@section Conditionals
 
811
 
 
812
@cindex expression, conditional (defn)
 
813
@cindex conditional expression (defn)
 
814
@cindex true, in conditional expression (defn)
 
815
@cindex false, in conditional expression (defn)
 
816
@findex #f
 
817
@findex #t
 
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}).
 
823
 
 
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.
 
828
 
 
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.
 
837
 
 
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}.
 
841
 
 
842
@example
 
843
@group
 
844
(if (> 3 2) 'yes 'no)                   @result{}  yes
 
845
(if (> 2 3) 'yes 'no)                   @result{}  no
 
846
(if (> 3 2)
 
847
    (- 3 2)
 
848
    (+ 3 2))                            @result{}  1
 
849
@end group
 
850
@end example
 
851
@end deffn
 
852
 
 
853
@deffn {special form} cond clause clause @dots{}
 
854
@cindex cond clause
 
855
@cindex clause, of cond expression
 
856
Each @var{clause} has this form:
 
857
 
 
858
@example
 
859
(@var{predicate} @var{expression} @dots{})
 
860
@end example
 
861
 
 
862
@noindent
 
863
@cindex else clause, of cond expression (defn)
 
864
@findex else
 
865
where @var{predicate} is any expression.  The last @var{clause} may be
 
866
an @dfn{@code{else} clause}, which has the form:
 
867
 
 
868
@example
 
869
(else @var{expression} @var{expression} @dots{})
 
870
@end example
 
871
 
 
872
A @code{cond} expression does the following:
 
873
 
 
874
@enumerate
 
875
@item
 
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
 
878
value.
 
879
 
 
880
@item
 
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.
 
885
 
 
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}
 
888
as the result.
 
889
 
 
890
@item
 
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
 
895
one.
 
896
@end enumerate
 
897
 
 
898
@example
 
899
@group
 
900
(cond ((> 3 2) 'greater)
 
901
      ((< 3 2) 'less))                  @result{}  greater
 
902
 
 
903
(cond ((> 3 3) 'greater)
 
904
      ((< 3 3) 'less)
 
905
      (else 'equal))                    @result{}  equal
 
906
@end group
 
907
@end example
 
908
 
 
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.
 
914
 
 
915
@cindex => in cond clause
 
916
@findex =>
 
917
Scheme supports an alternative @var{clause} syntax:
 
918
 
 
919
@example
 
920
(@var{predicate} => @var{recipient})
 
921
@end example
 
922
 
 
923
@noindent
 
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}.
 
928
 
 
929
@example
 
930
@group
 
931
(cond ((assv 'b '((a 1) (b 2))) => cadr)
 
932
      (else #f))                        @result{}  2
 
933
@end group
 
934
@end example
 
935
@end deffn
 
936
 
 
937
@deffn {special form} case key clause clause @dots{}
 
938
@cindex case clause
 
939
@cindex clause, of case expression
 
940
@var{Key} may be any expression.  Each @var{clause} has this
 
941
form:
 
942
 
 
943
@example
 
944
((@var{object} @dots{}) @var{expression} @var{expression} @dots{})
 
945
@end example
 
946
 
 
947
@cindex else clause, of case expression (defn)
 
948
@findex else
 
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},
 
951
which has the form:
 
952
 
 
953
@example
 
954
(else @var{expression} @var{expression} @dots{})
 
955
@end example
 
956
 
 
957
A @code{case} expression does the following:
 
958
 
 
959
@enumerate
 
960
@item
 
961
Evaluates @var{key} and compares the result with each
 
962
@var{object}.
 
963
 
 
964
@item
 
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.
 
971
@findex eqv?
 
972
 
 
973
@item
 
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}
 
980
clause.
 
981
@end enumerate
 
982
 
 
983
For example,
 
984
 
 
985
@example
 
986
@group
 
987
(case (* 2 3)
 
988
   ((2 3 5 7) 'prime)
 
989
   ((1 4 6 8 9) 'composite))            @result{}  composite
 
990
 
 
991
(case (car '(c d))
 
992
   ((a) 'a)
 
993
   ((b) 'b))                            @result{}  @r{unspecified}
 
994
 
 
995
(case (car '(c d))
 
996
   ((a e i o u) 'vowel)
 
997
   ((w y) 'semivowel)
 
998
   (else 'consonant))                   @result{}  consonant
 
999
@end group
 
1000
@end example
 
1001
@end deffn
 
1002
 
 
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.
 
1010
 
 
1011
@example
 
1012
@group
 
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)
 
1016
(and)                                   @result{}  #t
 
1017
@end group
 
1018
@end example
 
1019
@end deffn
 
1020
 
 
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.
 
1028
 
 
1029
@example
 
1030
@group
 
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)
 
1035
@end group
 
1036
@end example
 
1037
@end deffn
 
1038
 
 
1039
@node Sequencing, Iteration, Conditionals, Special Forms
 
1040
@section Sequencing
 
1041
@cindex sequencing expressions
 
1042
 
 
1043
The @code{begin} special form is used to evaluate expressions in a
 
1044
particular order.
 
1045
 
 
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.
 
1050
 
 
1051
@example
 
1052
@group
 
1053
(define x 0)
 
1054
(begin (set! x 5)
 
1055
       (+ x 1))                 @result{}  6
 
1056
 
 
1057
(begin (display "4 plus 1 equals ")
 
1058
       (display (+ 4 1)))
 
1059
                                @print{}  4 plus 1 equals 5
 
1060
                                @result{}  @r{unspecified}
 
1061
@end group
 
1062
@end example
 
1063
 
 
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:
 
1068
 
 
1069
@example
 
1070
@group
 
1071
case
 
1072
cond
 
1073
define          @r{;``procedure @code{define}'' only}
 
1074
do
 
1075
fluid-let
 
1076
lambda
 
1077
let
 
1078
let*
 
1079
letrec
 
1080
named-lambda
 
1081
@end group
 
1082
@end example
 
1083
@findex case
 
1084
@findex cond
 
1085
@findex define
 
1086
@findex do
 
1087
@findex fluid-let
 
1088
@findex lambda
 
1089
@findex let
 
1090
@findex let*
 
1091
@findex letrec
 
1092
@findex named-lambda
 
1093
 
 
1094
@findex sequence
 
1095
The obsolete special form @code{sequence} is identical to @code{begin}.
 
1096
It should not be used in new code.
 
1097
@end deffn
 
1098
 
 
1099
@node Iteration, Structure Definitions, Sequencing, Special Forms
 
1100
@section Iteration
 
1101
 
 
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.
 
1111
 
 
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.
 
1117
 
 
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
 
1123
@var{name}.
 
1124
 
 
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.
 
1128
 
 
1129
Note: the following expressions are equivalent:
 
1130
 
 
1131
@example
 
1132
@group
 
1133
(let @var{name} ((@var{variable} @var{init}) @dots{})
 
1134
  @var{expression}
 
1135
  @var{expression} @dots{})
 
1136
 
 
1137
((letrec ((@var{name}
 
1138
           (named-lambda (@var{name} @var{variable} @dots{})
 
1139
             @var{expression}
 
1140
             @var{expression} @dots{})))
 
1141
   @var{name})
 
1142
 @var{init} @dots{})
 
1143
@end group
 
1144
@end example
 
1145
 
 
1146
Here is an example:
 
1147
 
 
1148
@example
 
1149
@group
 
1150
(let loop
 
1151
     ((numbers '(3 -2 1 6 -5))
 
1152
      (nonneg '())
 
1153
      (neg '()))
 
1154
  (cond ((null? numbers)
 
1155
         (list nonneg neg))
 
1156
        ((>= (car numbers) 0)
 
1157
         (loop (cdr numbers)
 
1158
               (cons (car numbers) nonneg)
 
1159
               neg))
 
1160
        (else
 
1161
         (loop (cdr numbers)
 
1162
               nonneg
 
1163
               (cons (car numbers) neg)))))
 
1164
 
 
1165
     @result{}  ((6 1 3) (-5 -2))
 
1166
@end group
 
1167
@end example
 
1168
@end deffn
 
1169
 
 
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.
 
1175
 
 
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.
 
1181
 
 
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.
 
1188
 
 
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.
 
1195
 
 
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}
 
1201
variables.
 
1202
 
 
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})}.
 
1206
 
 
1207
@example
 
1208
@group
 
1209
(do ((vec (make-vector 5))
 
1210
      (i 0 (+ i 1)))
 
1211
    ((= i 5) vec)
 
1212
   (vector-set! vec i i))               @result{}  #(0 1 2 3 4)
 
1213
@end group
 
1214
 
 
1215
@group
 
1216
(let ((x '(1 3 5 7 9)))
 
1217
   (do ((x x (cdr x))
 
1218
        (sum 0 (+ sum (car x))))
 
1219
       ((null? x) sum)))                @result{}  25
 
1220
@end group
 
1221
@end example
 
1222
@end deffn
 
1223
 
 
1224
@node Structure Definitions, Macros, Iteration, Special Forms
 
1225
@section Structure Definitions
 
1226
 
 
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.
 
1232
 
 
1233
@deffn {special form} define-structure (name structure-option @dots{}) slot-description @dots{}
 
1234
Each @var{slot-description} takes one of the following forms:
 
1235
 
 
1236
@example
 
1237
@group
 
1238
@var{slot-name}
 
1239
(@var{slot-name} @var{default-init} [@var{slot-option} @var{value}]*)
 
1240
@end group
 
1241
@end example
 
1242
 
 
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).
 
1251
 
 
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:
 
1260
 
 
1261
@example
 
1262
(define-structure foo a b c)
 
1263
@end example
 
1264
 
 
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!}.
 
1269
 
 
1270
In general, if no options are specified, @code{define-structure} defines
 
1271
the following (using the simple call above as an example):
 
1272
 
 
1273
@table @asis
 
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?}.
 
1278
 
 
1279
@item constructor
 
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.
 
1285
 
 
1286
@item predicate
 
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.
 
1291
 
 
1292
@item accessors
 
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.
 
1299
 
 
1300
@item modifiers
 
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.
 
1308
@end table
 
1309
 
 
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:
 
1313
 
 
1314
@example
 
1315
@group
 
1316
(define-structure foo a b c)
 
1317
(define-structure (foo) (a) b (c))
 
1318
@end group
 
1319
@end example
 
1320
 
 
1321
@noindent
 
1322
as are
 
1323
 
 
1324
@example
 
1325
@group
 
1326
(define-structure (foo keyword-constructor) a b c)
 
1327
(define-structure (foo (keyword-constructor)) a b c)
 
1328
@end group
 
1329
@end example
 
1330
 
 
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
 
1333
@code{#t}.
 
1334
@end deffn
 
1335
 
 
1336
Possible @var{slot-options} are:
 
1337
 
 
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.
 
1341
@end deffn
 
1342
 
 
1343
@deffn {slot option} type type-descriptor
 
1344
This is accepted but not presently used.
 
1345
@end deffn
 
1346
 
 
1347
Possible @var{structure-options} are:
 
1348
 
 
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.
 
1355
@end deffn
 
1356
 
 
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.
 
1366
@end deffn
 
1367
 
 
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!
 
1375
@end deffn
 
1376
 
 
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.
 
1386
 
 
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
 
1402
supplied.
 
1403
 
 
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.
 
1408
 
 
1409
@example
 
1410
@group
 
1411
(define-structure (foo
 
1412
                   (constructor make-foo (#!optional a b)))
 
1413
  (a 6 read-only #t)
 
1414
  (b 9))
 
1415
@end group
 
1416
@end example
 
1417
@end deffn
 
1418
 
 
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.
 
1428
 
 
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.
 
1434
 
 
1435
@example
 
1436
@group
 
1437
(define-structure (foo (keyword-constructor make-bar)) a b)
 
1438
(foo-a (make-bar 'b 20 'a 19))         @result{} 19
 
1439
@end group
 
1440
@end example
 
1441
@end deffn
 
1442
 
 
1443
@deffn {structure option} type-descriptor name
 
1444
This option cannot be used with the @code{type} or @code{named} options.
 
1445
 
 
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.
 
1450
 
 
1451
@example
 
1452
@group
 
1453
(define-structure foo a b)
 
1454
foo             @result{} #[record-type 18]
 
1455
 
 
1456
(define-structure (bar (type-descriptor <bar>)) a b)
 
1457
bar             @error{} Unbound variable: bar
 
1458
<bar>         @result{} #[record-type 19]
 
1459
@end group
 
1460
@end example
 
1461
@end deffn
 
1462
 
 
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
 
1470
the prefix.
 
1471
 
 
1472
@example
 
1473
@code{(define-structure (foo (conc-name moby/)) a b)}
 
1474
@end example
 
1475
 
 
1476
@noindent
 
1477
defines accessors @code{moby/a} and @code{moby/b}, and modifiers
 
1478
@code{set-moby/a!} and @code{set-moby/b!}.
 
1479
 
 
1480
@example
 
1481
@code{(define-structure (foo (conc-name #f)) a b)}
 
1482
@end example
 
1483
 
 
1484
@noindent
 
1485
defines accessors @code{a} and @code{b}, and modifiers @code{set-a!} and
 
1486
@code{set-b!}.
 
1487
@end deffn
 
1488
 
 
1489
@deffn {structure option} type representation-type
 
1490
This option cannot be used with the @code{type-descriptor} option.
 
1491
 
 
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.
 
1498
 
 
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.
 
1503
 
 
1504
@example
 
1505
@group
 
1506
(define-structure (foo (type list)) a b) 
 
1507
(make-foo 1 2)                          @result{} (1 2)
 
1508
@end group
 
1509
@end example
 
1510
@end deffn
 
1511
 
 
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.
 
1517
 
 
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.
 
1533
 
 
1534
 
 
1535
@example
 
1536
@group
 
1537
(define-structure (foo (type vector) named) a b c)
 
1538
(vector-ref (make-foo 1 2 3) 0) @result{} #[structure-type 52]
 
1539
@end group
 
1540
@end example
 
1541
 
 
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.
 
1551
 
 
1552
@example
 
1553
@group
 
1554
(define-structure (foo (type vector) (named 'foo)) a b c)
 
1555
(vector-ref (make-foo 1 2 3) 0) @result{} foo
 
1556
@end group
 
1557
@end example
 
1558
@end deffn
 
1559
 
 
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.
 
1571
 
 
1572
@example
 
1573
@group
 
1574
(define-structure (foo safe-accessors) a b c)
 
1575
@end group
 
1576
@end example
 
1577
@end deffn
 
1578
 
 
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.
 
1585
 
 
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
 
1589
regular slots.
 
1590
 
 
1591
@example
 
1592
@group
 
1593
(define-structure (foo (type vector) (initial-offset 3))
 
1594
  a b c)
 
1595
(make-foo 1 2 3)                @result{} #(() () () 1 2 3)
 
1596
@end group
 
1597
@end example
 
1598
@end deffn
 
1599
 
 
1600
The essential differences between MIT/GNU Scheme's @code{define-structure}
 
1601
and Common Lisp's @code{defstruct} are:
 
1602
 
 
1603
@itemize @bullet
 
1604
@item
 
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}.
 
1609
 
 
1610
@item
 
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.
 
1614
 
 
1615
@item
 
1616
By default, no @code{copier} procedure is defined.
 
1617
 
 
1618
@item
 
1619
The side-effect procedure corresponding to the accessor @code{foo} is
 
1620
given the name @code{set-foo!}.
 
1621
 
 
1622
@item
 
1623
Keywords are ordinary symbols -- use @code{foo} instead of @code{:foo}.
 
1624
 
 
1625
@item
 
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
 
1628
instead.
 
1629
 
 
1630
@item
 
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.
 
1634
 
 
1635
@item
 
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.
 
1640
 
 
1641
@item
 
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.
 
1647
 
 
1648
@item
 
1649
The @code{type} option is restricted to the values @code{vector} and
 
1650
@code{list}.
 
1651
 
 
1652
@item
 
1653
The @code{include} option is not implemented.
 
1654
@end itemize
 
1655
 
 
1656
@node Macros, SRFI syntax, Structure Definitions, Special Forms
 
1657
@section Macros
 
1658
 
 
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
 
1663
Clinger.)
 
1664
 
 
1665
@cindex macro
 
1666
Scheme programs can define and use new derived expression types, called
 
1667
@dfn{macros}.  Program-defined expression types have the syntax
 
1668
 
 
1669
@example
 
1670
(@var{keyword} @var{datum} @dots{})
 
1671
@end example
 
1672
 
 
1673
@noindent
 
1674
@cindex syntactic keyword
 
1675
@cindex 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.
 
1681
 
 
1682
@cindex macro use
 
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.
 
1687
 
 
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
 
1693
by the transformer.
 
1694
 
 
1695
The macro definition facility consists of these parts:
 
1696
 
 
1697
@itemize @bullet
 
1698
@item
 
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.
 
1702
 
 
1703
@item
 
1704
A standard high-level pattern language for specifying macro
 
1705
transformers, introduced by the @code{syntax-rules} special form.
 
1706
 
 
1707
@item
 
1708
Two non-standard low-level languages for specifying macro transformers,
 
1709
@dfn{syntactic closures} and @dfn{explicit renaming}.
 
1710
@end itemize
 
1711
 
 
1712
@cindex hygienic
 
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:
 
1718
 
 
1719
@itemize @bullet
 
1720
@item
 
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.
 
1724
 
 
1725
@item
 
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
 
1729
use of the macro.
 
1730
@end itemize
 
1731
 
 
1732
@menu
 
1733
* Syntactic Binding Constructs::  
 
1734
* Pattern Language::            
 
1735
* Syntactic Closures::          
 
1736
* Explicit Renaming::           
 
1737
@end menu
 
1738
 
 
1739
@node Syntactic Binding Constructs, Pattern Language, Macros, Macros
 
1740
@subsection Binding Constructs for Syntactic Keywords
 
1741
 
 
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
 
1746
values.
 
1747
 
 
1748
Any argument named @var{transformer-spec} must be a macro-transformer
 
1749
expression, which is one of the following:
 
1750
 
 
1751
@itemize @bullet
 
1752
@item
 
1753
A macro transformer defined by the pattern language and denoted by the
 
1754
syntactic keyword @code{syntax-rules}.
 
1755
 
 
1756
@item
 
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}.
 
1760
 
 
1761
@item
 
1762
A syntactic keyword bound in the enclosing environment.  This is used
 
1763
to bind another name to an existing macro transformer.
 
1764
@end itemize
 
1765
 
 
1766
@deffn {special form} let-syntax bindings expression expression @dots{}
 
1767
@var{Bindings} should have the form
 
1768
 
 
1769
@example
 
1770
((@var{keyword} @var{transformer-spec}) @dots{})
 
1771
@end example
 
1772
 
 
1773
@noindent
 
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.
 
1778
 
 
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.
 
1784
 
 
1785
@example
 
1786
@group
 
1787
(let-syntax ((when (syntax-rules ()
 
1788
                     ((when test stmt1 stmt2 ...)
 
1789
                      (if test
 
1790
                          (begin stmt1
 
1791
                                 stmt2 ...))))))
 
1792
  (let ((if #t))
 
1793
    (when if (set! if 'now))
 
1794
    if))                           @result{}  now
 
1795
 
 
1796
(let ((x 'outer))
 
1797
  (let-syntax ((m (syntax-rules () ((m) x))))
 
1798
    (let ((x 'inner))
 
1799
      (m))))                       @result{}  outer
 
1800
@end group
 
1801
@end example
 
1802
@end deffn
 
1803
 
 
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}.
 
1806
 
 
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.
 
1814
 
 
1815
@example
 
1816
@group
 
1817
(letrec-syntax
 
1818
  ((my-or (syntax-rules ()
 
1819
            ((my-or) #f)
 
1820
            ((my-or e) e)
 
1821
            ((my-or e1 e2 ...)
 
1822
             (let ((temp e1))
 
1823
               (if temp
 
1824
                   temp
 
1825
                   (my-or e2 ...)))))))
 
1826
  (let ((x #f)
 
1827
        (y 7)
 
1828
        (temp 8)
 
1829
        (let odd?)
 
1830
        (if even?))
 
1831
    (my-or x
 
1832
           (let temp)
 
1833
           (if y)
 
1834
           y)))        @result{}  7
 
1835
@end group
 
1836
@end example
 
1837
@end deffn
 
1838
 
 
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}.
 
1841
 
 
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
 
1847
region.  Thus
 
1848
 
 
1849
@example
 
1850
@group
 
1851
(let*-syntax
 
1852
   ((a (syntax-rules @dots{}))
 
1853
    (b (syntax-rules @dots{})))
 
1854
  @dots{})
 
1855
@end group
 
1856
@end example
 
1857
 
 
1858
@noindent
 
1859
is equivalent to
 
1860
 
 
1861
@example
 
1862
@group
 
1863
(let-syntax ((a (syntax-rules @dots{})))
 
1864
  (let-syntax ((b (syntax-rules @dots{})))
 
1865
    @dots{}))
 
1866
@end group
 
1867
@end example
 
1868
@end deffn
 
1869
 
 
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.
 
1874
 
 
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.
 
1878
 
 
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}.
 
1882
 
 
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.
 
1888
 
 
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:
 
1896
 
 
1897
@example
 
1898
(define define 3)
 
1899
 
 
1900
(begin (define begin list))
 
1901
 
 
1902
(let-syntax
 
1903
  ((foo (syntax-rules ()
 
1904
          ((foo (proc args ...) body ...)
 
1905
           (define proc
 
1906
             (lambda (args ...)
 
1907
               body ...))))))
 
1908
  (let ((x 3))
 
1909
    (foo (plus x y) (+ x y))
 
1910
    (define foo x)
 
1911
    (plus foo x)))
 
1912
@end example
 
1913
@end deffn
 
1914
 
 
1915
@node Pattern Language, Syntactic Closures, Syntactic Binding Constructs, Macros
 
1916
@subsection Pattern Language
 
1917
 
 
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:
 
1923
 
 
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
 
1927
 
 
1928
@example
 
1929
(@var{pattern} @var{template})
 
1930
@end example
 
1931
 
 
1932
The @var{pattern} in a @var{syntax-rule} is a list @var{pattern} that
 
1933
begins with the keyword for the macro.
 
1934
 
 
1935
A @var{pattern} is either an identifier, a constant, or one of the
 
1936
following
 
1937
 
 
1938
@example
 
1939
(@var{pattern} @dots{})
 
1940
(@var{pattern} @var{pattern} @dots{} . @var{pattern})
 
1941
(@var{pattern} @dots{} @var{pattern} @var{ellipsis})
 
1942
@end example
 
1943
 
 
1944
@noindent
 
1945
and a template is either an identifier, a constant, or one of the
 
1946
following
 
1947
 
 
1948
@example
 
1949
(@var{element} @dots{})
 
1950
(@var{element} @var{element} @dots{} . @var{template})
 
1951
@end example
 
1952
 
 
1953
@vindex ...
 
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).
 
1957
 
 
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
 
1964
the template.
 
1965
 
 
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}.
 
1972
 
 
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
 
1975
literal identifier.
 
1976
 
 
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.
 
1983
 
 
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.
 
1988
 
 
1989
More formally, an input form @var{F} matches a pattern @var{P} if and
 
1990
only if:
 
1991
 
 
1992
@itemize @bullet
 
1993
@item
 
1994
@var{P} is a non-literal identifier; or
 
1995
 
 
1996
@item
 
1997
@var{P} is a literal identifier and @var{F} is an identifier with the
 
1998
same binding; or
 
1999
 
 
2000
@item
 
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},
 
2003
respectively; or
 
2004
 
 
2005
@item
 
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
 
2010
 
 
2011
@item
 
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
 
2017
 
 
2018
@item
 
2019
@var{P} is a datum and @var{F} is equal to @var{P} in the sense of the
 
2020
@code{equal?} procedure.
 
2021
@end itemize
 
2022
 
 
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.
 
2025
 
 
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.
 
2034
 
 
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.
 
2042
 
 
2043
@example
 
2044
@group
 
2045
(let ((=> #f))
 
2046
  (cond (#t => 'ok)))           @result{} ok
 
2047
@end group
 
2048
@end example
 
2049
 
 
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
 
2054
 
 
2055
@example
 
2056
@group
 
2057
(let ((=> #f))
 
2058
  (if #t (begin => 'ok)))
 
2059
@end group
 
2060
@end example
 
2061
 
 
2062
instead of
 
2063
 
 
2064
@example
 
2065
@group
 
2066
(let ((=> #f))
 
2067
  (let ((temp #t))
 
2068
    (if temp 
 
2069
        ('ok temp))))
 
2070
@end group
 
2071
@end example
 
2072
 
 
2073
which would result in an invalid procedure call.
 
2074
@end deffn
 
2075
 
 
2076
@node Syntactic Closures, Explicit Renaming, Pattern Language, Macros
 
2077
@subsection Syntactic Closures
 
2078
 
 
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.
 
2087
 
 
2088
@menu
 
2089
* Syntax Terminology::          
 
2090
* SC Transformer Definition::   
 
2091
* SC Identifiers::              
 
2092
@end menu
 
2093
 
 
2094
@node Syntax Terminology, SC Transformer Definition, Syntactic Closures, Syntactic Closures
 
2095
@subsubsection Syntax Terminology
 
2096
 
 
2097
This section defines the concepts and data types used by the syntactic
 
2098
closures facility.
 
2099
 
 
2100
@itemize @bullet
 
2101
@item
 
2102
@cindex form
 
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
 
2107
forms:
 
2108
 
 
2109
@example
 
2110
@group
 
2111
17
 
2112
#t
 
2113
car
 
2114
(+ x 4)
 
2115
(lambda (x) x)
 
2116
(define pi 3.14159)
 
2117
if
 
2118
define
 
2119
@end group
 
2120
@end example
 
2121
 
 
2122
@item
 
2123
@cindex alias
 
2124
@cindex identifier
 
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.
 
2132
 
 
2133
@item
 
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.
 
2142
 
 
2143
@item
 
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
 
2149
later.
 
2150
 
 
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.
 
2155
 
 
2156
A syntactic closure appearing in a quoted structure is replaced by its
 
2157
form.
 
2158
@end itemize
 
2159
 
 
2160
@node SC Transformer Definition, SC Identifiers, Syntax Terminology, Syntactic Closures
 
2161
@subsubsection Transformer Definition
 
2162
 
 
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.
 
2166
 
 
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}).
 
2174
 
 
2175
@cindex macro transformer
 
2176
@cindex input form
 
2177
@cindex usage environment
 
2178
@cindex output form
 
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
 
2188
occurred.
 
2189
 
 
2190
For example, here is a definition of a @code{push} macro using
 
2191
@code{syntax-rules}:
 
2192
 
 
2193
@example
 
2194
@group
 
2195
(define-syntax push
 
2196
  (syntax-rules ()
 
2197
    ((push item list)
 
2198
     (set! list (cons item list)))))
 
2199
@end group
 
2200
@end example
 
2201
 
 
2202
@noindent
 
2203
Here is an equivalent definition using @code{sc-macro-transformer}:
 
2204
 
 
2205
@example
 
2206
@group
 
2207
(define-syntax push
 
2208
  (sc-macro-transformer
 
2209
   (lambda (exp env)
 
2210
     (let ((item (make-syntactic-closure env '() (cadr exp)))
 
2211
           (list (make-syntactic-closure env '() (caddr exp))))
 
2212
       `(set! ,list (cons ,item ,list))))))
 
2213
@end group
 
2214
@end example
 
2215
 
 
2216
@noindent
 
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}.
 
2220
 
 
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:
 
2226
 
 
2227
@example
 
2228
@group
 
2229
(define-syntax loop
 
2230
  (sc-macro-transformer
 
2231
   (lambda (exp env)
 
2232
     (let ((body (cdr exp)))
 
2233
       `(call-with-current-continuation
 
2234
         (lambda (exit)
 
2235
           (let f ()
 
2236
             ,@@(map (lambda (exp)
 
2237
                      (make-syntactic-closure env '(exit)
 
2238
                        exp))
 
2239
                    body)
 
2240
             (f))))))))
 
2241
@end group
 
2242
@end example
 
2243
@end deffn
 
2244
 
 
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.
 
2255
 
 
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:
 
2259
 
 
2260
@example
 
2261
@group
 
2262
(define-syntax push
 
2263
  (rsc-macro-transformer
 
2264
   (lambda (exp env)
 
2265
     `(,(make-syntactic-closure env '() 'SET!)
 
2266
       ,(caddr exp)
 
2267
       (,(make-syntactic-closure env '() 'CONS)
 
2268
        ,(cadr exp)
 
2269
        ,(caddr exp))))))
 
2270
@end group
 
2271
@end example
 
2272
 
 
2273
@noindent
 
2274
In this style only the introduced keywords are closed, while everything
 
2275
else remains open.
 
2276
 
 
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.)
 
2281
 
 
2282
@example
 
2283
@group
 
2284
(define-syntax push
 
2285
  (sc-macro-transformer
 
2286
   (lambda (exp usage-env)
 
2287
     (capture-syntactic-environment
 
2288
      (lambda (env)
 
2289
        (make-syntactic-closure usage-env '()
 
2290
          `(,(make-syntactic-closure env '() 'SET!)
 
2291
            ,(caddr exp)
 
2292
            (,(make-syntactic-closure env '() 'CONS)
 
2293
             ,(cadr exp)
 
2294
             ,(caddr exp)))))))))
 
2295
@end group
 
2296
@end example
 
2297
@end deffn
 
2298
 
 
2299
To assign meanings to the identifiers in a form, use
 
2300
@code{make-syntactic-closure} to close the form in a syntactic
 
2301
environment.
 
2302
 
 
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}.
 
2311
 
 
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
 
2316
free.
 
2317
 
 
2318
@example
 
2319
@group
 
2320
(define-syntax let1
 
2321
  (sc-macro-transformer
 
2322
   (lambda (exp env)
 
2323
     (let ((id (cadr exp))
 
2324
           (init (caddr exp))
 
2325
           (exp (cadddr exp)))
 
2326
       `((lambda (,id)
 
2327
           ,(make-syntactic-closure env (list id) exp))
 
2328
         ,(make-syntactic-closure env '() init))))))
 
2329
@end group
 
2330
@end example
 
2331
 
 
2332
@noindent
 
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.
 
2339
@end deffn
 
2340
 
 
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:
 
2344
 
 
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
 
2349
 
 
2350
@example
 
2351
(make-syntactic-closure @var{environment} '() @var{form})
 
2352
@end example
 
2353
@end deffn
 
2354
 
 
2355
To obtain a syntactic environment other than the usage environment,
 
2356
use @code{capture-syntactic-environment}.
 
2357
 
 
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.
 
2363
 
 
2364
An example will make this clear.  Suppose we wanted to define a simple
 
2365
@code{loop-until} keyword equivalent to
 
2366
 
 
2367
@example
 
2368
@group
 
2369
(define-syntax loop-until
 
2370
  (syntax-rules ()
 
2371
    ((loop-until id init test return step)
 
2372
     (letrec ((loop
 
2373
               (lambda (id)
 
2374
                 (if test return (loop step)))))
 
2375
       (loop init)))))
 
2376
@end group
 
2377
@end example
 
2378
 
 
2379
@noindent
 
2380
The following attempt at defining @code{loop-until} has a subtle
 
2381
bug:
 
2382
 
 
2383
@example
 
2384
@group
 
2385
(define-syntax loop-until
 
2386
  (sc-macro-transformer
 
2387
   (lambda (exp env)
 
2388
     (let ((id (cadr exp))
 
2389
           (init (caddr exp))
 
2390
           (test (cadddr exp))
 
2391
           (return (cadddr (cdr exp)))
 
2392
           (step (cadddr (cddr exp)))
 
2393
           (close
 
2394
            (lambda (exp free)
 
2395
              (make-syntactic-closure env free exp))))
 
2396
       `(letrec ((loop
 
2397
                  (lambda (,id)
 
2398
                    (if ,(close test (list id))
 
2399
                        ,(close return (list id))
 
2400
                        (loop ,(close step (list id)))))))
 
2401
          (loop ,(close init '())))))))
 
2402
@end group
 
2403
@end example
 
2404
 
 
2405
@noindent
 
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.
 
2415
 
 
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
 
2421
as follows:
 
2422
 
 
2423
@example
 
2424
@group
 
2425
(define-syntax loop-until
 
2426
  (sc-macro-transformer
 
2427
   (lambda (exp env)
 
2428
     (let ((id (cadr exp))
 
2429
           (init (caddr exp))
 
2430
           (test (cadddr exp))
 
2431
           (return (cadddr (cdr exp)))
 
2432
           (step (cadddr (cddr exp)))
 
2433
           (close
 
2434
            (lambda (exp free)
 
2435
              (make-syntactic-closure env free exp))))
 
2436
       `(letrec ((loop
 
2437
                  ,(capture-syntactic-environment
 
2438
                    (lambda (env)
 
2439
                      `(lambda (,id)
 
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 '())))))))
 
2446
@end group
 
2447
@end example
 
2448
 
 
2449
@noindent
 
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
 
2453
@code{lambda}.
 
2454
 
 
2455
A common use of @code{capture-syntactic-environment} is to get the
 
2456
transformer environment of a macro transformer:
 
2457
 
 
2458
@example
 
2459
@group
 
2460
(sc-macro-transformer
 
2461
 (lambda (exp env)
 
2462
   (capture-syntactic-environment
 
2463
    (lambda (transformer-env)
 
2464
      @dots{}))))
 
2465
@end group
 
2466
@end example
 
2467
@end deffn
 
2468
 
 
2469
@node SC Identifiers,  , SC Transformer Definition, Syntactic Closures
 
2470
@subsubsection Identifiers
 
2471
 
 
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}
 
2475
facility.
 
2476
 
 
2477
@cindex alias
 
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:
 
2481
 
 
2482
@example
 
2483
@group
 
2484
(make-syntactic-closure env '() 'a) @result{} @r{an alias}
 
2485
@end group
 
2486
@end example
 
2487
 
 
2488
@noindent
 
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.
 
2495
 
 
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.
 
2505
 
 
2506
@deffn procedure identifier? object
 
2507
Returns @code{#t} if @var{object} is an identifier, otherwise returns
 
2508
@code{#f}.  Examples:
 
2509
 
 
2510
@example
 
2511
@group
 
2512
(identifier? 'a)        @result{} #t
 
2513
(identifier? (make-syntactic-closure env '() 'a))
 
2514
                        @result{} #t
 
2515
 
 
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
 
2522
@end group
 
2523
@end example
 
2524
@end deffn
 
2525
 
 
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
 
2537
environment.
 
2538
 
 
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}.
 
2545
Examples:
 
2546
 
 
2547
@example
 
2548
@group
 
2549
(let-syntax
 
2550
    ((foo
 
2551
      (sc-macro-transformer
 
2552
       (lambda (form env)
 
2553
         (capture-syntactic-environment
 
2554
          (lambda (transformer-env)
 
2555
            (identifier=? transformer-env 'x env 'x)))))))
 
2556
  (list (foo)
 
2557
        (let ((x 3))
 
2558
          (foo))))
 
2559
                        @result{} (#t #f)
 
2560
@end group
 
2561
 
 
2562
@group
 
2563
(let-syntax ((bar foo))
 
2564
  (let-syntax
 
2565
      ((foo
 
2566
        (sc-macro-transformer
 
2567
         (lambda (form env)
 
2568
           (capture-syntactic-environment
 
2569
            (lambda (transformer-env)
 
2570
              (identifier=? transformer-env 'foo
 
2571
                            env (cadr form))))))))
 
2572
    (list (foo foo)
 
2573
          (foo bar))))
 
2574
                        @result{} (#f #t)
 
2575
@end group
 
2576
@end example
 
2577
@end deffn
 
2578
 
 
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. 
 
2582
 
 
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.
 
2588
 
 
2589
This is implemented by syntactically closing @var{identifier} in a
 
2590
special empty environment.
 
2591
@end deffn
 
2592
 
 
2593
@node Explicit Renaming,  , Syntactic Closures, Macros
 
2594
@subsection Explicit Renaming
 
2595
 
 
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:
 
2602
 
 
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}).
 
2610
 
 
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.
 
2617
 
 
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
 
2624
written as
 
2625
 
 
2626
@example
 
2627
@group
 
2628
(lambda (exp rename compare)
 
2629
  (let ((vars (map car (cadr exp)))
 
2630
        (inits (map cadr (cadr exp)))
 
2631
        (body (cddr exp)))
 
2632
    `((lambda ,vars ,@@body)
 
2633
      ,@@inits)))
 
2634
@end group
 
2635
@end example
 
2636
 
 
2637
@noindent
 
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:
 
2642
 
 
2643
@example
 
2644
@group
 
2645
(lambda (exp rename compare)
 
2646
  (let ((vars (map car (cadr exp)))
 
2647
        (inits (map cadr (cadr exp)))
 
2648
        (body (cddr exp)))
 
2649
    `((,(rename 'lambda) ,vars ,@@body)
 
2650
      ,@@inits)))
 
2651
@end group
 
2652
@end example
 
2653
 
 
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.
 
2662
 
 
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.
 
2667
 
 
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
 
2675
 
 
2676
@example
 
2677
@group
 
2678
(lambda (exp rename compare)
 
2679
  (let ((clauses (cdr exp)))
 
2680
    (if (null? clauses)
 
2681
        `(,(rename 'quote) unspecified)
 
2682
        (let* ((first (car clauses))
 
2683
               (rest (cdr clauses))
 
2684
               (test (car first)))
 
2685
          (cond ((and (identifier? test)
 
2686
                      (compare test (rename 'else)))
 
2687
                 `(,(rename 'begin) ,@@(cdr first)))
 
2688
                (else `(,(rename 'if)
 
2689
                        ,test
 
2690
                         (,(rename 'begin) ,@@(cdr first))
 
2691
                         (cond ,@@rest))))))))))
 
2692
@end group
 
2693
@end example
 
2694
 
 
2695
@noindent
 
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.
 
2704
 
 
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}
 
2709
is not renamed.
 
2710
 
 
2711
@example
 
2712
@group
 
2713
(define-syntax loop
 
2714
  (er-macro-transformer
 
2715
   (lambda (x r c)
 
2716
     (let ((body (cdr x)))
 
2717
       `(,(r 'call-with-current-continuation)
 
2718
         (,(r 'lambda) (exit)
 
2719
          (,(r 'let) ,(r 'f) () ,@@body (,(r 'f)))))))))
 
2720
@end group
 
2721
@end example
 
2722
 
 
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
 
2726
 
 
2727
@example
 
2728
@group
 
2729
(define-syntax while
 
2730
  (syntax-rules ()
 
2731
    ((while test body ...)
 
2732
     (loop (if (not test) (exit #f))
 
2733
           body ...))))
 
2734
@end group
 
2735
@end example
 
2736
 
 
2737
@noindent
 
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:
 
2743
 
 
2744
@example
 
2745
@group
 
2746
(define-syntax while
 
2747
  (er-macro-transformer
 
2748
   (lambda (x r c)
 
2749
     (let ((test (cadr x))
 
2750
           (body (cddr x)))
 
2751
       `(,(r 'loop)
 
2752
         (,(r 'if) (,(r 'not) ,test) (exit #f))
 
2753
         ,@@body)))))
 
2754
@end group
 
2755
@end example
 
2756
@end deffn
 
2757
 
 
2758
@node SRFI syntax,  , Macros, Special Forms
 
2759
@section SRFI syntax
 
2760
 
 
2761
@cindex 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.
 
2770
 
 
2771
@menu
 
2772
* cond-expand (SRFI 0)::        
 
2773
* receive (SRFI 8)::            
 
2774
* define-record-type (SRFI 9)::  
 
2775
@end menu
 
2776
 
 
2777
@node cond-expand (SRFI 0), receive (SRFI 8), SRFI syntax, SRFI syntax
 
2778
@subsection cond-expand (SRFI 0)
 
2779
 
 
2780
@cindex 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.
 
2786
 
 
2787
@deffn {special form} cond-expand clause clause dots{}
 
2788
Each @var{clause} has the form
 
2789
 
 
2790
@example
 
2791
(@var{feature-requirement} @var{expression} @dots{})
 
2792
@end example
 
2793
 
 
2794
where @var{feature-requirement} can have one of the following forms:
 
2795
 
 
2796
@example
 
2797
@group
 
2798
@var{feature-identifier}
 
2799
(and @var{feature-requirement} @dots{})
 
2800
(or @var{feature-requirement} @dots{})
 
2801
(not @var{feature-requirement})
 
2802
else
 
2803
@end group
 
2804
@end example
 
2805
 
 
2806
(Note that at most one @code{else} clause may be present, and it must
 
2807
always be the last clause.)
 
2808
 
 
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).
 
2816
 
 
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
 
2823
interpretation.
 
2824
 
 
2825
@example
 
2826
@group
 
2827
(cond-expand
 
2828
  ((and srfi-1 srfi-10)
 
2829
   (write 1))
 
2830
  ((or srfi-1 srfi-10)
 
2831
   (write 2))
 
2832
  (else))
 
2833
 
 
2834
(cond-expand
 
2835
  (command-line
 
2836
   (define (program-name) (car (argv)))))
 
2837
@end group
 
2838
@end example
 
2839
 
 
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
 
2843
present.
 
2844
 
 
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.
 
2848
@end deffn
 
2849
 
 
2850
@node receive (SRFI 8), define-record-type (SRFI 9), cond-expand (SRFI 0), SRFI syntax
 
2851
@subsection receive (SRFI 8)
 
2852
 
 
2853
@cindex 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:
 
2859
 
 
2860
@example
 
2861
@group
 
2862
(call-with-values
 
2863
  (lambda ()
 
2864
    (partition (precedes pivot) others))
 
2865
  (lambda (fore aft)
 
2866
    (append (qsort fore) (cons pivot (qsort aft)))))
 
2867
@end group
 
2868
@end example
 
2869
 
 
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
 
2875
a sorted list.
 
2876
 
 
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.
 
2885
 
 
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:
 
2892
 
 
2893
@example
 
2894
@group
 
2895
(receive (fore aft) (partition (precedes pivot) others)
 
2896
  (append (qsort fore) (cons pivot (qsort aft))))
 
2897
@end group
 
2898
@end example
 
2899
 
 
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
 
2904
follow the code.
 
2905
 
 
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):
 
2911
 
 
2912
@table @samp
 
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.)
 
2919
 
 
2920
@item @var{ident}
 
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
 
2925
@var{ident}.
 
2926
 
 
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.)
 
2935
@end table
 
2936
 
 
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.
 
2940
@end deffn
 
2941
 
 
2942
@node define-record-type (SRFI 9),  , receive (SRFI 8), SRFI syntax
 
2943
@subsection define-record-type (SRFI 9)
 
2944
 
 
2945
@cindex 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:
 
2953
 
 
2954
@itemize @bullet
 
2955
@item
 
2956
It can be defined using a simple macro in Scheme implementations that
 
2957
provide a procedural interface for creating record types.
 
2958
 
 
2959
@item
 
2960
It does not restrict users to a particular naming convention.
 
2961
 
 
2962
@item
 
2963
Tools like @command{grep} and the GNU Emacs tag facility will see the
 
2964
defining occurance of each identifier.
 
2965
@end itemize
 
2966
 
 
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
 
2970
two forms:
 
2971
 
 
2972
@example
 
2973
@group
 
2974
(@var{field-tag} @var{accessor-name})
 
2975
(@var{field-tag} @var{accessor-name} @var{modifier-name})
 
2976
@end group
 
2977
@end example
 
2978
 
 
2979
@noindent
 
2980
where @var{field-tag}, @var{accessor-name}, and @var{modifier-name} are
 
2981
each identifiers.
 
2982
 
 
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).
 
2989
 
 
2990
An instance of @code{define-record-type} is equivalent to the following
 
2991
definitions:
 
2992
 
 
2993
@itemize @bullet
 
2994
@item
 
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.
 
2998
 
 
2999
@item
 
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
 
3005
are unspecified.
 
3006
 
 
3007
@item
 
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
 
3010
else.
 
3011
 
 
3012
@item
 
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.
 
3017
 
 
3018
@item
 
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
 
3023
appropriate type.
 
3024
@end itemize
 
3025
 
 
3026
Assigning the value of any of these identifiers has no effect on the
 
3027
behavior of any of their original values.
 
3028
@end deffn
 
3029
 
 
3030
The following
 
3031
 
 
3032
@example
 
3033
@group
 
3034
(define-record-type :pare
 
3035
  (kons x y)
 
3036
  pare?
 
3037
  (x kar set-kar!)
 
3038
  (y kdr))
 
3039
@end group
 
3040
@end example
 
3041
 
 
3042
@noindent
 
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}.
 
3046
 
 
3047
@example
 
3048
@group
 
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)))
 
3054
  (set-kar! k 3)
 
3055
  (kar k))                @result{} 3
 
3056
@end group
 
3057
@end example