-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompat.html
1039 lines (740 loc) · 43.3 KB
/
compat.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><!-- DO NOT EDIT THIS FILE-->
<!-- Edit the .tex version instead-->
<html>
<head>
<title>Compatibility Features</title>
<link href="csug.css" rel="stylesheet" type="text/css">
</head>
<body>
<a name="g142"></a>
<a name="./compat:h0"></a>
<h1>Chapter 16. Compatibility Features<a name="CHPTCOMPAT"></a></h1>
<p>
This chapter describes several items that are included with current
versions of <i>Chez Scheme</i> primarily for compatibility with older
versions of the system.
<p>
Section <a href="./compat.html#g143">16.1</a> describes a hash-table interface
that has since been replaced by the R6RS hashtable interface.
Section <a href="./compat.html#g144">16.2</a>
describes <tt>extend-syntax</tt> macros.
These features are supported directly by current versions of <i>Chez Scheme</i>,
but support may be dropped in future versions.
New programs should use the standard mechanisms described in
in <i>The Scheme Programming Language, 4th Edition</i> [<a class=citation href="./bibliography.html#g157">11</a>]
instead.
<p>
Section <a href="./compat.html#g145">16.3</a> describes a mechanism for defining
record-like structures as vectors instead of new unique types.
New programs should use <tt>define-record</tt>, which is described
in Section <a href="./objects.html#g61">7.14</a>, instead.
<p>
Section <a href="./compat.html#g146">16.4</a>
describes a compatibility file distributed with
<i>Chez Scheme</i> that contains definitions for forms and procedures no
longer supported directly by <i>Chez Scheme</i>.
<p>
<h3><a name="g143"></a><a name="./compat:h1"></a>Section 16.1. Hash Tables<a name="SECTCOMPATHASHTABLES"></a></h3>
<p>
The hash table procedures here are obviated by the new hash table procedures
listed in Section <a href="./objects.html#g59">7.12</a>.
<p>
<a name="./compat:s0"></a><span class=formdef><b>procedure</b>: <tt>(make-hash-table)</tt></span>
<br><span class=formdef><b>procedure</b>: <tt>(make-hash-table <i>weak?</i>)</tt></span>
<br>
<b>returns: </b>a new hash table
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p>If <tt><i>weak?</i></tt> is provided and is non-false, the hash
table is a weak hash table, which means that it does not protect
keys from the garbage collector.
Keys reclaimed by the garbage collector are removed from the table,
and their associated values are dropped the next time the table
is modified, if not sooner.
<p>
<a name="./compat:s1"></a><span class=formdef><b>procedure</b>: <tt>(hash-table? <i>obj</i>)</tt></span>
<br>
<b>returns: </b><tt>#t</tt> if <tt><i>obj</i></tt> is a hash table, otherwise <tt>#f</tt>
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p><a name="./compat:s2"></a><span class=formdef><b>procedure</b>: <tt>(put-hash-table! <i>ht</i> <i>k</i> <i>v</i>)</tt></span>
<br>
<b>returns: </b>unspecified
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p><tt><i>ht</i></tt> must be a hash table.
<tt><i>k</i></tt> and <tt><i>v</i></tt> may be any Scheme values.
<p>
<tt>put-hash-table!</tt> associates the value
<tt><i>v</i></tt> with the key <tt><i>k</i></tt> in <tt><i>ht</i></tt>.
<p>
<a name="./compat:s3"></a><span class=formdef><b>procedure</b>: <tt>(get-hash-table <i>ht</i> <i>k</i> <i>d</i>)</tt></span>
<br>
<b>returns: </b>see below
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p><tt>get-hash-table</tt> returns the value
associated with <tt><i>k</i></tt> in <tt><i>ht</i></tt>.
If no value is associated with <tt><i>k</i></tt> in <tt><i>ht</i></tt>,
<tt>get-hash-table</tt> returns <tt><i>d</i></tt>.
<p>
Key comparisons are performed with <tt><i>eq?</i></tt>.
<p>
Because objects may be moved by the garbage collector, <tt>get-hash-table</tt>
may need to rehash some objects and therefore cause side effects in the
hash table.
Thus, it is not safe to perform concurrent accesses of the same hash table
from multiple threads using <tt>get-hash-table</tt>.
<p>
<a name="./compat:s4"></a><span class=formdef><b>procedure</b>: <tt>(remove-hash-table! <i>ht</i> <i>k</i>)</tt></span>
<br>
<b>returns: </b>unspecified
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p><tt>remove-hash-table!</tt> drops any association
for <tt><i>k</i></tt> from <tt><i>ht</i></tt>.
<p>
<a name="./compat:s5"></a><span class=formdef><b>procedure</b>: <tt>(hash-table-map <i>ht</i> <i>p</i>)</tt></span>
<br>
<b>returns: </b>see below
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p><tt>hash-table-map</tt> applies <tt><i>p</i></tt> to each key, value association
in <tt><i>ht</i></tt>, in no particular order, and returns a list of the resulting
values, again in no particular order.
<tt><i>p</i></tt> should accept two arguments, a key and a value.
<p>
<a name="./compat:s6"></a><span class=formdef><b>procedure</b>: <tt>(hash-table-for-each <i>ht</i> <i>p</i>)</tt></span>
<br>
<b>returns: </b>unspecified
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p><tt>hash-table-for-each</tt> applies <tt><i>p</i></tt> to each key, value
association in <tt><i>ht</i></tt>, in no particular order.
Unlike <tt>hash-table-map</tt>, it does not create a list of the values;
instead, it's value is unspecified.
<tt><i>p</i></tt> should accept two arguments, a key and a value.
<p>
<h3><a name="g144"></a><a name="./compat:h2"></a>Section 16.2. Extend-Syntax Macros<a name="SECTCOMPATEXTENDSYNTAX"></a></h3>
<p>
This section describes <tt>extend-syntax</tt>, a powerful yet easy to use
syntactic extension facility based on
<a name="./compat:s7"></a>pattern matching [<a class=citation href="./bibliography.html#g172">26</a>].
Syntactic transformations written using
<tt>extend-syntax</tt> are similar to those written using a
<tt>define-syntax</tt> with <tt>syntax-case</tt>, except that the
transformations produced by <tt>extend-syntax</tt> do not automatically
respect lexical scoping.
<p>
It is not typically possible to mix syntactic abstractions written using
<tt>syntax-case</tt> with those written using <tt>extend-syntax</tt>
seamlessly; it is generally preferable to use one or the other wherever
possible.
Support for <tt>extend-syntax</tt> within the <tt>syntax-case</tt> expander
is provided only as an aid to migrating to <tt>syntax-case</tt>.
<p>
<a name="./compat:s8"></a><span class=formdef><b>syntax</b>: <tt>(extend-syntax (<i>name</i> <i>key</i> ...) (<i>pat</i> <i>fender</i> <i>template</i>) ...)</tt></span>
<br>
<b>returns: </b>unspecified
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p>The identifier <tt><i>name</i></tt> is the name, or syntax keyword, for the
syntactic extension to be defined.
When the system expander processes any list expression whose car is
<tt><i>name</i></tt>, the syntactic transformation procedure generated by
<tt>extend-syntax</tt> is invoked on this expression.
The remaining identifiers <tt><i>key</i> ...</tt> are additional keywords to
be recognized within input expressions during expansion (such as
<tt>else</tt> in <tt>cond</tt> or <tt>case</tt>).
<p>
Each clause after the list of keys consists of a pattern <tt><i>pat</i></tt>, an
optional <a name="./compat:s9"></a><tt><i>fender</i></tt>,
and a <tt><i>template</i></tt>.
The optional <tt><i>fender</i></tt> is omitted more often than not.
The <tt><i>pat</i></tt> specifies the syntax the input expression must have
for the clause to be chosen.
Identifiers within the pattern that are not keywords
(<i>pattern variables</i>) are bound to corresponding pieces of the input expression.
If present, the <tt><i>fender</i></tt> is a Scheme expression that specifies
additional constraints on the input expression (accessed through the
pattern variables) that must be satisfied in order for the clause to
be chosen.
The <tt><i>template</i></tt> specifies what form the output takes, usually in
terms of the pattern variables.
<p>
During expansion, the transformation procedure <tt>extend-syntax</tt>
generates attempts to match the input expression against each
pattern in the order the clauses are given.
If the input expression matches the pattern, the pattern variables are
bound to the corresponding pieces of the input expression and the
fender for the clause, if any, is evaluated.
If the fender returns a true value, the given expansion is performed.
If input does not match the pattern or if the fender returns a false
value, the transformation procedure tries the next clause.
An exception is raised with condition type <tt>&assertion</tt> if no clause can be chosen.
<p>
Within the pattern,
<a name="./compat:s10"></a><a name="./compat:s11"></a><i>ellipsis</i>
(<tt>...</tt>) may be
used to specify zero or more occurrences
of the preceding pattern fragment, or prototype.
Similarly, ellipses may be used in the output to specify the construction
of zero or more expansion prototypes.
In this case, the expansion prototype must contain part of an input pattern
prototype.
The use of patterns, templates, ellipses within patterns and templates,
and fenders is illustrated in the following sequence of examples.
<p>
The first example, defining <a name="./compat:s12"></a><tt>rec</tt>, uses a single keyword, a single
clause with no fender, and no ellipses.
<p>
<p><tt>(extend-syntax (rec)<br>
[(rec id val)<br>
(let ([id #f])<br>
(set! id val)<br>
id)])</tt>
<p>The second example, defining <a name="./compat:s13"></a><tt>when</tt>, shows
the use of ellipses.
<p>
<p><tt>(extend-syntax (when)<br>
[(when test exp1 exp2 ...)<br>
(if test (begin exp1 exp2 ...) #f)])</tt>
<p>The next example shows the definition of
<a name="./compat:s14"></a><tt>let</tt>.
The definition of <tt>let</tt> shows the use of multiple ellipses, employing
one for the identifier/value pairs and one for the expressions in the body.
It also shows that the prototype need not be a single identifier, and that
pieces of the prototype may be separated from one another in the template.
<p>
<p><tt>(extend-syntax (let)<br>
[(let ([x e] ...) b1 b2 ...)<br>
((lambda (x ...) b1 b2 ...) e ...)])</tt>
<p>The next example shows <a name="./compat:s15"></a><tt>let*</tt>, whose syntax is the same as for
<tt>let</tt>, but which is defined recursively in terms of <tt>let</tt> with
two clauses (one for the base case, one for the recursion step) since
it must produce a nested structure.
<p>
<p><tt>(extend-syntax (let*)<br>
[(let* () b1 b2 ...)<br>
(let () b1 b2 ...)]<br>
[(let* ([x e] more ...) b1 b2 ...)<br>
(let ([x e]) (let* (more ...) b1 b2 ...))])</tt>
<p>The first pattern/template pair matches any <tt>let*</tt> expression with no
identifier/value pairs and maps it into the equivalent <tt>begin</tt> expression.
This is the base case.
The second pattern/template pair matches any <tt>let*</tt> expression with one
or more identifier/value pairs and transforms it into a <tt>let</tt> expression
binding the first pair whose body is a <tt>let*</tt> expression binding the
remaining pairs.
This is the recursion step, which will eventually lead us to the base case
because we remove one identifier/value pair at each step.
Notice that the second pattern uses the pattern variable <tt>more</tt> for the
second and later identifier/value pairs; this makes the pattern and template
less cluttered and makes it clear that only the first identifier/value pair
is dealt with explicitly.
<p>
The definition for <a name="./compat:s16"></a><tt>and</tt> requires three clauses.
The first clause is necessary to recognize <tt>(and)</tt>, and the second
two define all other <tt>and</tt> forms recursively.
<p>
<p><tt>(extend-syntax (and)<br>
[(and) #t]<br>
[(and x) x]<br>
[(and x y ...) (if x (and y ...) #f)])</tt>
<p>The definition for <a name="./compat:s17"></a><tt>cond</tt> requires four clauses.
As with <tt>let*</tt>, <tt>cond</tt> must be described recursively, partly because
it produces nested <tt>if</tt> expressions, and partly because one
ellipsis prototype would not be sufficient to describe all possible
<tt>cond</tt> clauses.
The definition of <tt>cond</tt> also requires that we specify <tt>else</tt> as a
keyword, in addition to <tt>cond</tt>.
Here is the definition:
<p>
<p><tt>(extend-syntax (cond else)<br>
[(cond) #f]<br>
[(cond (else e1 e2 ...))<br>
(begin e1 e2 ...)]<br>
[(cond (test) more ...)<br>
(or test (cond more ...))]<br>
[(cond (test e1 e2 ...) more ...)<br>
(if test<br>
(begin e1 e2 ...)<br>
(cond more ...))])</tt>
<p>Two of the clauses are base cases and two are recursion steps.
The first base case is an empty <tt>cond</tt>.
The value of <tt>cond</tt> in this case is unspecified, so the choice of
<tt>#f</tt> is somewhat arbitrary.
The second base case is a <tt>cond</tt> containing only an <tt>else</tt> clause;
this is transformed to the equivalent <tt>begin</tt> expression.
The two recursion steps differ in the number of expressions in the <tt>cond</tt>
clause.
The value of <tt>cond</tt> when the first true clause contains only the test
expression is the value of the test.
This is similar to what <tt>or</tt> does, so we expand the <tt>cond</tt> clause
into an <tt>or</tt> expression.
On the other hand, when there are expressions following the test expression,
the value of the last expression is returned, so we use <tt>if</tt> and
<tt>begin</tt>.
<p>
To be absolutely correct about the syntax of <tt>let</tt>, we actually
must require that the bound identifiers in the input are symbols.
If we typed something like <tt>(let ([3 x]) x)</tt> we would not get an
error from <tt>let</tt> because it does not check to verify that the
objects in the identifier positions are symbols.
Instead, <tt>lambda</tt> may complain, or perhaps the system evaluator
long after expansion is complete.
This is where <a name="./compat:s18"></a>fenders
are useful.
<p>
<p><tt>(extend-syntax (let)<br>
[(let ([x e] ...) b1 b2 ...)<br>
(andmap symbol? '(x ...))<br>
((lambda (x ...) b1 b2 ...) e ...)])</tt>
<p>The <a name="./compat:s19"></a><tt>andmap</tt> of <tt>symbol?</tt>
over <tt>'(x ...)</tt> assures that each
bound identifier is a symbol.
A fender is simply a Scheme expression.
Within that expression, any quoted object is first expanded by the same
rules as the template part of the clause.
In this case, <tt>'(x ...)</tt> is expanded to the list of identifiers from
the identifier/value pairs.
<p>
<tt>extend-syntax</tt> typically handles everything you need it for, but
some syntactic extension definitions require the ability to include the
result of evaluating an arbitrary Scheme expression.
This ability is provided by <tt>with</tt>.
<p>
<a name="./compat:s20"></a><span class=formdef><b>syntax</b>: <tt>(with ((<i>pat</i> <i>expr</i>) ...) <i>template</i>)</tt></span>
<br>
<b>returns: </b>processed <tt><i>template</i></tt>
<p>
<p><tt>with</tt> is valid only within an template inside of <tt>extend-syntax</tt>.
<tt>with</tt> patterns are the same as <tt>extend-syntax</tt> patterns, <tt>with</tt>
expressions are the same as <tt>extend-syntax</tt> fenders, and <tt>with</tt>
templates are the same as <tt>extend-syntax</tt> templates.
<p>
<tt>with</tt> can be used to introduce new pattern identifiers bound to
expressions produced by arbitrary Scheme expressions within
<tt>extend-syntax</tt> templates.
That is, <tt>with</tt> allows an escape from the declarative style of
<tt>extend-syntax</tt> into the procedural style of full Scheme.
<p>
One common use of <tt>with</tt> is the introduction of a temporary
identifier or list of temporary identifiers into a template.
<tt>with</tt> is also used to perform complex transformations that might
be clumsy or inefficient if performed within the <tt>extend-syntax</tt>
framework.
<p>
For example, <tt>or</tt> requires the use of a temporary identifier.
We could define <tt>or</tt> as follows.
<p>
<p><tt>(extend-syntax (or)<br>
[(or) #f]<br>
[(or x) x]<br>
[(or x y ...)<br>
(let ([temp x])<br>
(if temp temp (or y ...)))])</tt>
<p>This would work until we placed an <tt>or</tt> expression within the scope
of an occurrence of <tt>temp</tt>, in which case strange things could happen,
since <tt>extend-syntax</tt> does not respect lexical scoping.
(This is one of the reasons that <tt>define-syntax</tt> is preferable to
<tt>extend-syntax</tt>.)
<p>
<p><tt>(let ([temp #t])<br>
(or #f temp)) <img src="math/csug/0.gif" alt="<graphic>"> #f</tt>
<p>One solution is to use
<a name="./compat:s21"></a><tt>gensym</tt> and <tt>with</tt> to
create a temporary identifier, as follows.
<p>
<p><tt>(extend-syntax (or)<br>
[(or) #f]<br>
[(or x) x]<br>
[(or x y ...)<br>
(with ([temp (gensym)])<br>
(let ([temp x])<br>
(if temp temp (or y ...))))])</tt>
<p>Also, <tt>with</tt> can be used to combine elements of the input pattern
in ways not possible directly with <tt>extend-syntax</tt>, such as the
following <tt>folding-plus</tt> example.
<p>
<p><tt>(extend-syntax (folding-plus)<br>
[(folding-plus x y)<br>
(and (number? 'x) (number? 'y))<br>
(with ([val (+ 'x 'y)])<br>
val)]<br>
[(folding-plus x y) (+ x y)])</tt>
<p><tt>folding-plus</tt> collapses into the value of <tt>(+ x y)</tt> if both
<tt>x</tt> and <tt>y</tt> are numeric constants.
Otherwise, <tt>folding-plus</tt> is transformed into <tt>(+ x y)</tt> for
later evaluation.
The fender checks that the operands are numbers at expansion time, and
the <tt>with</tt> performs the evaluation.
As with fenders, expansion is performed only within a quoted expressions,
since <tt>quote</tt> sets the data apart from the remainder of the Scheme
expression.
<p>
The example below binds a list of pattern variables to a list of
temporary symbols, taking advantage of the fact that <tt>with</tt> allows
us to bind patterns to expressions.
This list of temporaries helps us to implement the <tt>sigma</tt> syntactic
extension.
<tt>sigma</tt> is similar to <tt>lambda</tt>, except it assigns the identifiers
in the identifier list instead of creating new bindings.
It may be used to perform a series of assignments in parallel.
<p>
<p><tt>(extend-syntax (sigma)<br>
[(sigma (x ...) e1 e2 ...)<br>
(with ([(t ...) (map (lambda (x) (gensym)) '(x ...))])<br>
(lambda (t ...)<br>
(set! x t) ...<br>
e1 e2 ...))])
<br>
<br>
(let ([x 'a] [y 'b])<br>
((sigma (x y) (list x y)) y x)) <img src="math/csug/0.gif" alt="<graphic>"> (b a)</tt>
<p>The final example below uses <tt>extend-syntax</tt> to implement
<tt>define-structure</tt>, following a similar example using
<tt>syntax-case</tt> in Section <a href="http://scheme.com/tspl4/./syntax.html#g137">8.4</a> of
<i>The Scheme Programming Language, 4th Edition</i>.
<p>
The definition of <tt>define-structure</tt> makes use of two pattern/template
clauses.
Two clauses are needed to handle the optionality of the second subexpression.
The first clause matches the form without the second subexpression and
merely converts it into the equivalent form with the second subexpression
present, but empty.
<p>
The definition also makes heavy use of <a name="./compat:s22"></a><tt>with</tt> to evaluate Scheme
expressions at expansion time.
The first four <tt>with</tt> clauses are used to manufacture the identifiers
that name the automatically defined procedures.
(The procedure <a name="./compat:s23"></a><tt>format</tt> is particularly useful here, but it could be
replaced with <tt>string-append!</tt>, using <tt>symbol->string</tt> as needed.)
The first two clauses yield single identifiers (for the constructor and
predicate), while the next two yield lists of identifiers (for the field
access and assignment procedures).
The fifth <tt>with</tt> clause (the final clause in the outer <tt>with</tt>)
is used to count the total length vector needed for each instance of
the structure, which must include room for the name and all of the fields.
The final <tt>with</tt> clause (the only clause in the inner <tt>with</tt>)
is used to create a list of vector indexes, one for each field (starting at
1, since the structure name occupies position 0).
<p>
<p><tt>(extend-syntax (define-structure)<br>
[(define-structure (name id1 ...))<br>
(define-structure (name id1 ...) ())]<br>
[(define-structure (name id1 ...) ([id2 val] ...))<br>
(with ([constructor<br>
(string->symbol (format "make-~a" 'name))]<br>
[predicate<br>
(string->symbol (format "~a?" 'name))]<br>
[(access ...)<br>
(map (lambda (x)<br>
(string->symbol<br>
(format "~a-~a" 'name x)))<br>
'(id1 ... id2 ...))]<br>
[(assign ...)<br>
(map (lambda (x)<br>
(string->symbol<br>
(format "set-~a-~a!" 'name x)))<br>
'(id1 ... id2 ...))]<br>
[count (length '(name id1 ... id2 ...))])<br>
(with ([(index ...)<br>
(let f ([i 1])<br>
(if (= i 'count)<br>
'()<br>
(cons i (f (+ i 1)))))])<br>
(begin<br>
(define constructor<br>
(lambda (id1 ...)<br>
(let* ([id2 val] ...)<br>
(vector 'name id1 ... id2 ...))))<br>
(define predicate<br>
(lambda (obj)<br>
(and (vector? obj)<br>
(= (vector-length obj) count)<br>
(eq? (vector-ref obj 0) 'name))))<br>
(define access<br>
(lambda (obj)<br>
(vector-ref obj index)))<br>
...<br>
(define assign<br>
(lambda (obj newval)<br>
(vector-set! obj index newval)))<br>
...)))])</tt>
<p>
<h3><a name="g145"></a><a name="./compat:h3"></a>Section 16.3. Structures<a name="SECTCOMPATSTRUCTURES"></a></h3>
<p>
<a name="./compat:s24"></a>This section describes a mechanism, similar
to the record-defining mechanisms of Section <a href="./objects.html#g61">7.14</a>,
that permits the creation of data structures
with fixed sets of named fields.
Unlike record types, structure types are not unique types, but are
instead implemented as vectors.
Specifically, a structure is implemented as a vector whose length is
one more than the number of fields and whose first element contains
the symbolic name of the structure.
<p>
The representation of structures as vectors
simplifies reading and printing of structures somewhat as well
as extension of the structure definition facility.
It does, however, have some drawbacks.
One is that structures may be treated as ordinary vectors by mistake in
situations where doing so is inappropriate.
When dealing with both structures and vectors in a program, care must
be taken to look for the more specific structure type before checking
for the more generic vector type, e.g., in a series of <tt>cond</tt>
clauses.
A similar drawback is that structure instances are easily "forged," either
intentionally or by accident.
It is also impossible to control how structures are printed and read.
<p>
Structures are created via <tt>define-structure</tt>.
Each structure definition defines a constructor
procedure, a type predicate, an access procedure for each of its fields,
and an assignment procedure for each of its fields.
<tt>define-structure</tt> allows the programmer to control which fields
are arguments to the generated constructor procedure and which fields
are explicitly initialized by the constructor procedure.
<p>
<tt>define-structure</tt> is simple
yet powerful enough for most applications, and it is easily
extended to handle many applications for which it is not sufficient.
The definition of <tt>define-structure</tt> given at the end of
this section can serve as a starting point for more complicated
variants.
<p>
<a name="./compat:s25"></a><span class=formdef><b>syntax</b>: <tt>(define-structure (<i>name</i> <i>id<sub>1</sub></i> ...) ((<i>id<sub>2</sub></i> <i>expr</i>) ...))</tt></span>
<br>
<b>returns: </b>unspecified
<br>
<b>libraries: </b><tt>(chezscheme)</tt>
<p>A <tt>define-structure</tt> form is a definition and may appear anywhere
and only where other definitions may appear.
<p>
<tt>define-structure</tt> defines a new data structure, <tt><i>name</i></tt>, and
creates a set of procedures for creating and manipulating instances of
the structure.
The identifiers <tt><i>id<sub>1</sub></i> ...</tt> and <tt><i>id<sub>2</sub></i> ...</tt>
name the fields of the data structure.
<p>
The following procedures are defined by <tt>define-structure</tt>:
<p>
<ul>
<li>a constructor procedure whose name is <tt>make-<i>name</i></tt>,
<p>
<li>a type predicate whose name is <tt><i>name</i>?</tt>,
<p>
<li>an access procedure whose name is <tt><i>name</i>-<i>field</i></tt>
for each field name <tt><i>id<sub>1</sub></i> ...</tt> and
<tt><i>id<sub>2</sub></i> ...</tt>, and
<p>
<li>an assignment procedure whose name is
<tt>set-<i>name</i>-<i>field</i>!</tt>
for each field name <tt><i>id<sub>1</sub></i> ...</tt> and <tt><i>id<sub>2</sub></i> ...</tt>.
</ul>
<p>
<p>
The fields named by the identifiers <tt><i>id<sub>1</sub></i> ...</tt> are
initialized by the arguments to the constructor procedure.
The fields named by the identifiers <tt><i>id<sub>2</sub></i> ...</tt> are initialized
explicitly to the values of the expressions <tt><i>expr</i> ...</tt>.
Each expression is evaluated within the scope of the identifiers
<tt><i>id<sub>1</sub></i> ...</tt> (bound to the corresponding field values) and any
of the identifiers <tt><i>id<sub>2</sub></i> ...</tt> (bound to the corresponding field
values) appearing before it (as if within a <tt>let*</tt>).
<p>
To clarify, the constructor behaves as if defined as
<p>
<p><tt>(define make-<i>name</i><br>
(lambda (<i>id<sub>1</sub></i> ...)<br>
(let* ([<i>id<sub>2</sub></i> <i>expr</i>] ...)<br>
<i>body</i>)))</tt>
<p>where <tt><i>body</i></tt> builds the structure from the values of the identifiers
<tt><i>id<sub>1</sub></i> ...</tt> and <tt><i>id<sub>2</sub></i> ...</tt>.
<p>
If no fields other than those initialized by the arguments to the
constructor procedure are needed, the second subexpression,
<tt>((<i>id<sub>2</sub></i> <i>expr</i>) ...)</tt>, may be omitted.
<p>
<a name="./compat:s26"></a><a name="./compat:s27"></a>The following simple example
demonstrates how pairs might be defined in Scheme if they did not
already exist.
Both fields are initialized by the arguments to the constructor
procedure.
<p>
<p><tt>(define-structure (pare car cdr))<br>
(define p (make-pare 'a 'b))
<br>
<br>
(pare? p) <img src="math/csug/0.gif" alt="<graphic>"> #t<br>
(pair? p) <img src="math/csug/0.gif" alt="<graphic>"> #f<br>
(pare? '(a . b)) <img src="math/csug/0.gif" alt="<graphic>"> #f
<br>
<br>
(pare-car p) <img src="math/csug/0.gif" alt="<graphic>"> a<br>
(pare-cdr p) <img src="math/csug/0.gif" alt="<graphic>"> b
<br>
<br>
(set-pare-cdr! p (make-pare 'b 'c))
<br>
<br>
(pare-car (pare-cdr p)) <img src="math/csug/0.gif" alt="<graphic>"> b<br>
(pare-cdr (pare-cdr p)) <img src="math/csug/0.gif" alt="<graphic>"> c</tt>
<p>The following example defines a handy string data structure, called a
<a name="./compat:s28"></a><i>stretch-string</i>, that grows as needed.
This example uses a field explicitly initialized to a value that
depends on the value of the constructor argument fields.
<p>
<p><tt>(define-structure (stretch-string length fill)<br>
([string (make-string length fill)]))
<br>
<br>
(define stretch-string-ref<br>
(lambda (s i)<br>
(let ([n (stretch-string-length s)])<br>
(when (>= i n) (stretch-stretch-string! s (+ i 1) n))<br>
(string-ref (stretch-string-string s) i))))
<br>
<br>
(define stretch-string-set!<br>
(lambda (s i c)<br>
(let ([n (stretch-string-length s)])<br>
(when (>= i n) (stretch-stretch-string! s (+ i 1) n))<br>
(string-set! (stretch-string-string s) i c))))
<br>
<br>
(define stretch-string-fill!<br>
(lambda (s c)<br>
(string-fill! (stretch-string-string s) c)<br>
(set-stretch-string-fill! s c)))
<br>
<br>
(define stretch-stretch-string!<br>
(lambda (s i n)<br>
(set-stretch-string-length! s i)<br>
(let ([str (stretch-string-string s)]<br>
[fill (stretch-string-fill s)])<br>
(let ([xtra (make-string (- i n) fill)])<br>
(set-stretch-string-string! s<br>
(string-append str xtra))))))</tt>
<p>As often happens, most of the procedures defined automatically are
used only to define more specialized procedures, in this case the procedures
<tt>stretch-string-ref</tt> and <tt>stretch-string-set!</tt>.
<tt>stretch-string-length</tt> and <tt>stretch-string-string</tt> are
the only automatically defined procedures that are likely to be
called directly in code that uses stretch strings.
<p>
<p><tt>(define ss (make-stretch-string 2 #\X))
<br>
<br>
(stretch-string-string ss) <img src="math/csug/0.gif" alt="<graphic>"> "XX"<br>
(stretch-string-ref ss 3) <img src="math/csug/0.gif" alt="<graphic>"> #\X<br>
(stretch-string-length ss) <img src="math/csug/0.gif" alt="<graphic>"> 4<br>
(stretch-string-string ss) <img src="math/csug/0.gif" alt="<graphic>"> "XXXX"
<br>
<br>
(stretch-string-fill! ss #\@)<br>
(stretch-string-string ss) <img src="math/csug/0.gif" alt="<graphic>"> "@@@@"<br>
(stretch-string-ref ss 5) <img src="math/csug/0.gif" alt="<graphic>"> #\@<br>
(stretch-string-string ss) <img src="math/csug/0.gif" alt="<graphic>"> "@@@@@@"
<br>
<br>
(stretch-string-set! ss 7 #\=)<br>
(stretch-string-length ss) <img src="math/csug/0.gif" alt="<graphic>"> 8<br>
(stretch-string-string ss) <img src="math/csug/0.gif" alt="<graphic>"> "@@@@@@@="</tt>
<p>Section <a href="http://scheme.com/tspl4/./syntax.html#g137">8.4</a> of <i>The Scheme Programming Language, 4th Edition</i> defines a simplified
variant of <tt>define-structure</tt> as an example of the use of
<a name="./compat:s29"></a><tt>syntax-case</tt>.
The definition given below implements the complete version.
<p>
<tt>define-structure</tt> expands into a series of definitions for names
generated from the structure name and field names.
The generated identifiers are created with
<a name="./compat:s30"></a><tt>datum->syntax</tt> to
make the identifiers visible where the <tt>define-structure</tt>
form appears.
Since a <tt>define-structure</tt> form expands into a <tt>begin</tt>
containing definitions, it is itself a definition and can be used
wherever definitions are valid.
<p>
<p><tt>(define-syntax define-structure<br>
(lambda (x)<br>
(define gen-id<br>
(lambda (template-id . args)<br>
(datum->syntax template-id<br>
(string->symbol<br>
(apply string-append<br>
(map (lambda (x)<br>
(if (string? x)<br>
x<br>
(symbol->string<br>
(syntax->datum x))))<br>
args))))))<br>
(syntax-case x ()<br>
((_ (name field1 ...))<br>
(andmap identifier? #'(name field1 ...))<br>
#'(define-structure (name field1 ...) ()))<br>
((_ (name field1 ...) ((field2 init) ...))<br>
(andmap identifier? #'(name field1 ... field2 ...))<br>
(with-syntax<br>
((constructor (gen-id #'name "make-" #'name))<br>
(predicate (gen-id #'name #'name "?"))<br>
((access ...)<br>
(map (lambda (x) (gen-id x #'name "-" x))<br>
#'(field1 ... field2 ...)))<br>
((assign ...)<br>
(map (lambda (x) (gen-id x "set-" #'name "-" x "!"))<br>
#'(field1 ... field2 ...)))<br>
(structure-length<br>
(+ (length #'(field1 ... field2 ...)) 1))<br>
((index ...)<br>
(let f ([i 1] [ids #'(field1 ... field2 ...)])<br>
(if (null? ids)<br>
'()<br>
(cons i (f (+ i 1) (cdr ids)))))))<br>
#'(begin<br>
(define constructor<br>
(lambda (field1 ...)<br>
(let* ([field2 init] ...)<br>
(vector 'name field1 ... field2 ...))))<br>
(define predicate<br>
(lambda (x)<br>
(and (vector? x)<br>
(#3%fx= (vector-length x) structure-length)<br>
(eq? (vector-ref x 0) 'name))))<br>
(define access (lambda (x) (vector-ref x index)))<br>
...<br>
(define assign<br>
(lambda (x update) (vector-set! x index update)))<br>