forked from ovenpasta/thunderchez
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatch.html
673 lines (429 loc) · 32 KB
/
match.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
<!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>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Using Match</title>
<link href="match_files/base.css" rel="stylesheet" type="text/css">
<script>(function n(){!function(){function e(e,t,n){t=t||{};var i=e.ownerDocument||e,a=i.createEvent?i.createEvent("CustomEvent"):i.createEventObject();a.initCustomEvent&&a.initCustomEvent(t.type,!!t.bubbles,!!t.cancelable,t.detail);for(var r in t)a[r]=t[r];return setTimeout(function(){try{e.dispatchEvent?e.dispatchEvent(a):e.fireEvent("on"+t.type,i.createEventObject())}catch(r){var o=e["listen"+t.type];if(o)for(var s=0;s<o.length;++s)try{o[s].call(e,a)}catch(r){}}n()},0),this}function t(e,t,n){function i(e,t){try{var n=e.ownerDocument;if(n.createEventObject){var i=n.createEventObject();e.fireEvent("on"+t,i)}else i=n.createEvent("HTMLEvents"),i.initEvent(t,!0,!0),e.dispatchEvent(i)}catch(a){}}var a=!0,r=e.className&&-1!=e.className.indexOf("fancified");if(window.jQuery){var o=window.jQuery(e);try{if(o.selectBoxIt)o.selectBoxIt("selectOption",o.val());else if(o.data("chosen")||o.chosen)o.trigger("chosen:updated").trigger("liszt:updated");else if(o.data("chooserElement"))o.trigger("change");else if(o.fancySelect)o.get("fancySelect").select("value",o.val());else if(o.selectBox)o.selectBox("value",o.val());else if(o.selectric)o.selectric("refresh");else if(o.coreUISelect){var s=o.data("coreUISelect");s.isSelectShow=!0,s.changeDropdownData(),s.isSelectShow=!1}else if(o.data("myJSPulldownObject")){var l=o.data("myJSPulldownObject");l.setToValue(o.val())}else if(o.fancyfields)o.setVal(o.val());else if(o.data("select2"));else if(o.data("selectize"))a=!1,o.data("selectize").setValue(o.val());else if(o.hasClass("fancified"))o.trigger("update");else if(o.selectmenu){var c=o.val();try{o.selectmenu("value",o[0].options[0].value)}catch(d){}o.selectmenu("value",c)}o.trigger("change")}catch(d){}}a&&(r&&i(e,"update"),i(e,"change"),i(e,"blur")),n()}function n(t,n,i,a){var r=t.value;e(t,{type:"keydown",keyCode:n,which:n,charCode:n,bubbles:!0},function(){e(t,{type:"keypress",keyCode:n,which:n,charCode:n,bubbles:!0},function(){setTimeout(function(){var o=t.value;r==o&&(t.value=i),e(t,{type:"input",keyCode:n,which:n,charCode:n,bubbles:!0},function(){e(t,{type:"keyup",keyCode:n,which:n,charCode:n,bubbles:!0},function(){a()})})},1)})})}function i(e,t,a,r){if(!t||""==t)return void r();var o=t.charCodeAt(0);a+=t.charAt(0),n(e,o,a,function(){i(e,t.substring(1),a,r)})}function a(t,n,a){e(t,{type:"focus"},function(){e(t,{type:"click"},function(){i(t,n,"",function(){e(t,{type:"change"},function(){e(t,{type:"blur"},function(){e(document,{type:"abineFilled"},function(){a()})})})})})})}function r(n,i,a,r){var o=(i||"").toLowerCase(),s=function(){e(document,{type:"abineFilled"},function(){r()})},l=!1,c=!1,d=n.getElementsByTagName("option");if(d&&d.length>0){for(var u=-1,m=0;m<d.length;m++){var h=(d[m].text||"").toLowerCase();if(d[m].getAttribute("value")==i||h==o){d[m].selected||(l=!0),c=!0,d[m].selected=!0;break}-1==u&&-1!=h.indexOf(o)&&(u=m)}c||-1==u||a||d[u].selected||(l=!0,d[u].selected=!0)}n.setAttribute("abineFillResponse",c),l?t(n,i,s):s()}function o(){var e=document.getElementsByClassName("abineFillTarget");if(e.length>0)return e[0];for(var t=0;t<frames.length;t++)try{var e=frames[t].document.getElementsByClassName("abineFillTarget");if(e.length>0)return e[0]}catch(n){}return null}function s(){var n=document.createElement("div");n.id="abineFillElement","undefined"!=typeof paypal&&n.setAttribute("data-paypal","1"),"undefined"!=typeof MasterPass&&n.setAttribute("data-masterpass","1"),document.documentElement.appendChild(n),n.addEventListener("fill",function(){var t=o();if(t){var i=n.getAttribute("value");a(t,i,function(){})}else e(document,{type:"abineFilled"},function(){})},!1),n.addEventListener("fillSelect",function(){var t=o();if(t){var i=n.getAttribute("value"),a=!!n.getAttribute("skipPartial");r(t,i,a,function(){})}else e(document,{type:"abineFilled"},function(){})}),n.addEventListener("triggerChange",function(){var i=o();if(i){var a=n.getAttribute("value");i.nodeName.match(/select/i)?t(i,a,function(){}):e(i,{type:"change"},function(){e(i,{type:"blur"},function(){})})}})}s()}()})()</script></head>
<body data-link64watched="1">
<h1>Using Match</h1>
<h2>R. Kent Dybvig</h2>
<h3>January 17, 2010</h3>
<p>
</p><table cellpadding="0" cellspacing="0">
</table>
<p>
This document describes a pattern matcher, unimaginatively called
<tt>match</tt>, the source code for which is available at:
</p><p>
<a class="ref" href="http://www.cs.indiana.edu/chezscheme/match/match.ss">http://www.cs.indiana.edu/chezscheme/match/match.ss</a>
</p><p>
A <tt>match</tt> expression looks a lot like a <tt>case</tt> expression,
except that the keys are replaced with a pattern to be matched against
the input.
A <tt>match</tt> expression has the general form below.
</p><p>
</p><p><tt>(match <i>input-expr</i> <i>clause</i>)</tt>
</p><p>Each clause consists of an input pattern, an optional guard, and a
set of expressions.
</p><p>
</p><p><tt>[<i>input-pattern</i> <i>expr1</i> <i>expr2</i> ...]</tt>
</p><p>or
</p><p>
</p><p><tt>[<i>input-pattern</i> (guard <i>guard-expr</i> ...) <i>expr1</i> <i>expr2</i> ...]</tt>
</p><p>As with <tt>case</tt>, the input expression is evaluated to produce
the input value, and the first clause the input value matches,
if any, is selected.
The output expressions of the selected clause are evaluated in sequence,
and the value of the last expression is returned.
</p><p>
An input value matches a clause if it fits the clause's pattern and
passes the clause's guards, if any.
Patterns may contain symbolic constants, which must match exactly, and
pattern variables, which match any input.
Pattern variables are prefixed by commas; symbolic constants are not.
</p><p>
</p><p><tt>(match '(a 17 37)<br>
[(a ,x) 1]<br>
[(b ,x ,y) 2]<br>
[(a ,x ,y) 3]) <img src="match_files/0.gif" alt="<graphic>"> 3</tt>
</p><p>The first clause fails to match because there are three items in the
input list, and the pattern has only two.
The second clause fails because <tt>b</tt> does not match <tt>a</tt>.
</p><p>
In the output expression, the values of the pattern variables are
bound to the corresponding pieces of input.
</p><p>
</p><p><tt>(match '(a 17 37)<br>
[(a ,x) (- x)]<br>
[(b ,x ,y) (+ x y)]<br>
[(a ,x ,y) (* x y)]) <img src="match_files/0.gif" alt="<graphic>"> 629</tt>
</p><p>When followed by an ellipsis (<tt>...</tt>), a pattern variable
represents a sequence of input values.
</p><p>
</p><p><tt>(match '(a 17 37) [(a ,x* ...) x*]) <img src="match_files/0.gif" alt="<graphic>"> (17 37)</tt>
</p><p>By convention, we place a <tt>*</tt> suffix on each pattern variable
that matches a sequence of input expressions.
This is just a convention, however, and not part of the syntax of
<tt>match</tt>.
</p><p>
Ellipses can follow a structured pattern containing one or more
pattern variables.
</p><p>
</p><p><tt>(match '(say (a time) (stitch saves) (in nine))<br>
[(say (,x* ,y*) ...) (append x* y*)]) <img src="match_files/0.gif" alt="<graphic>"> (a stitch in time saves nine)</tt>
</p><p>Ellipses can be nested, producing sequences of sequences of values.
</p><p>
</p><p><tt>(match '((a b c d) (e f g) (h i) (j))<br>
[((,x* ,y** ...) ...)<br>
(list x* y**)]) <img src="match_files/0.gif" alt="<graphic>"> ((a e h j) ((b c d) (f g) (i) ()))</tt>
</p><p>Recursion is frequently required while processing an input expression
with <tt>match</tt>.
Here is a simple definition of <tt>length</tt> using <tt>match</tt>.
</p><p>
</p><p><tt>(define length<br>
(lambda (ls)<br>
(match ls<br>
[() 0]<br>
[(,x . ,x*) (add1 (length x*))])))</tt>
</p><p>Using ellipses may make this more clear.
</p><p>
</p><p><tt>(define length<br>
(lambda (ls)<br>
(match ls<br>
[() 0]<br>
[(,x ,x* ...) (add1 (length x*))])))</tt>
</p><p>Here is a more realistic example of recursion.
It also illustrates the use of guards and the use of
<tt>error</tt> to signal match errors.
</p><p>
</p><p><tt>(define simple-eval<br>
(lambda (x)<br>
(match x<br>
[,i (guard (integer? i)) i]<br>
[(+ ,x* ...) (apply + (map simple-eval x*))]<br>
[(* ,x* ...) (apply * (map simple-eval x*))]<br>
[(- ,x ,y) (- (simple-eval x) (simple-eval y))]<br>
[(/ ,x ,y) (/ (simple-eval x) (simple-eval y))]<br>
[,x (error 'simple-eval "invalid expression ~s" x)])))</tt>
</p><p>Try out <tt>simple-eval</tt> using Chez Scheme's <tt>new-cafe</tt>
with <tt>simple-eval</tt> as the evaluation procedure:
</p><p>
</p><p><tt>> (new-cafe simple-eval)<br>
>> (+ 1 2 3) <br>
6<br>
>> (+ (- 0 1) (+ 2 3))<br>
4<br>
>> (- 1 2 3)
<br>
<br>
Error in simple-eval: invalid expression (- 1 2 3).<br>
Type (debug) to enter the debugger.<br>
>> </tt>
</p><p>Unlike <tt>case</tt> and <tt>cond</tt>, <tt>match</tt> does not have
an explicit <tt>else</tt> clause.
In fact, if a clause of the form
</p><p>
</p><p><tt> [else <i>expr</i>]</tt>
</p><p>is used, it matches (only) the symbol <tt>else</tt>.
To achieve the effect of a catch-all clause, <tt>simple-eval</tt>
uses the pattern <tt>,x</tt> which matches any input.
</p><p>
An even simpler version of the above uses <tt>match</tt>'s
"catamorphism" feature to perform the recursion
automatically.
</p><p>
</p><p><tt>(define simple-eval<br>
(lambda (x)<br>
(match x<br>
[,i (guard (integer? i)) i]<br>
[(+ ,[x*] ...) (apply + x*)]<br>
[(* ,[x*] ...) (apply * x*)]<br>
[(- ,[x] ,[y]) (- x y)]<br>
[(/ ,[x] ,[y]) (/ x y)]<br>
[,x (error 'simple-eval "invalid expression ~s" x)])))</tt>
</p><p>In the second version of <tt>simple-eval</tt>, the explicit
recursive calls are gone.
Instead, the pattern variables have been written as
<tt>,[<i>var</i>]</tt>; this tells <tt>match</tt> to recur on the
matching subpart of the input before evaluating the
output expressions of the clause.
Parentheses may be used in place of brackets, i.e.,
<tt>,(<i>var</i>)</tt>; we use brackets for readability.
</p><p>
Here is another definition of <tt>length</tt>, this time using the
catamorphism feature.
</p><p>
</p><p><tt>(define length<br>
(lambda (x)<br>
(match x<br>
[() 0]<br>
[(,x . ,[y]) (+ y 1)])))</tt>
</p><p>Since we usually use <tt>match</tt> to write translators from one
language to another, we usually need to build an output expression,
rather than return an output value.
For example, the following converts <tt>let</tt> expressions into
equivalent <tt>lambda</tt> applications.
</p><p>
</p><p><tt>(define translate<br>
(lambda (x)<br>
(match x<br>
[(let ((,var* ,expr*) ...) ,body ,body* ...)<br>
`((lambda ,var* ,body ,@body*) ,@expr*)]<br>
[,x (error 'translate "invalid expression: ~s" x)])))
<br>
<br>
(translate '(let ((x 3) (y 4)) (+ x y))) <img src="match_files/0.gif" alt="<graphic>"> ((lambda (x y) (+ x y)) 3 4)</tt>
</p><p>This procedure uses Scheme's <tt>quasiquote</tt> (backquote),
<tt>unquote</tt> (comma), and <tt>unquote-splicing</tt> (comma-at)
to piece together the output form.
These are not described here, but are described in
<a class="ref" href="http://www.scheme.com/tspl4/objects.html#SECTQUOTING"><i>The
Scheme Programming Language</i></a>.
</p><p>
One useful feature of <tt>quasiquote</tt> not described in these documents
is a <tt>match</tt> extension that allows ellipses to be used in place
of <tt>unquote-splicing</tt>, which often leads to more readable code.
</p><p>
</p><p><tt>(define translate<br>
(lambda (x)<br>
(match x<br>
[(let ((,var* ,expr*) ...) ,body ,body* ...)<br>
`((lambda ,var* ,body ,body* ...) ,expr* ...)]<br>
[,x (error 'translate "invalid expression: ~s" x)])))</tt>
</p><p>Within each subform followed by an ellipsis, each
comma-prefixed item must be a list and all such items within the same
subform must have the same length.
The following procedure extracts two lists from its input and merges
them to form a list of pairs.
</p><p>
</p><p><tt>(define (f x)<br>
(match x<br>
[((,a ...) (,b ...)) `((,a . ,b) ...)]))<br>
(f '((1 2 3) (a b c))) <img src="match_files/0.gif" alt="<graphic>"> ((1 . a) (2 . b) (3 . c))</tt>
</p><p>It fails if the two lists have different lengths.
</p><p>
</p><p><tt>(f '((1 2 3) (a b))) <img src="match_files/0.gif" alt="<graphic>"> <i>error</i></tt>
</p><p>The following also fails because one of the items is not even a list.
</p><p>
</p><p><tt>(define (f x)<br>
(match x<br>
[(,a ,b ...) `((,a ,b) ...)]))<br>
(f '(1 2 3 4)) <img src="match_files/0.gif" alt="<graphic>"> <i>error</i></tt>
</p><p>A subform followed by an ellipses may be contained with a larger subform
that is also followed by an ellipsis.
In this case, each comma-prefixed item must be a list of lists, each such
item must have the same length, and the corresponding sublists of each
such item must have the same lengths.
This requirement generalizes to comma-prefixed items nested within
more than two levels of ellispis-followed subforms.
</p><p>
The following procedure illustrates two levels of nested ellipses in both
the input and output.
It converts unnamed <tt>let</tt> expressions into
direct <tt>lambda</tt> applications, where the <tt>let</tt> has been
generalized to allow an implicit <tt>begin</tt> in each right-hand-side
expression.
</p><p>
</p><p><tt>(define (f x)<br>
(match x<br>
[(let ([,x ,e1 ...] ...) ,b1 ,b2 ...)<br>
`((lambda (,x ...) ,b1 ,b2 ...)<br>
(begin ,e1 ...) ...)]))<br>
(f '(let ((x (write 'one) 3) (y (write 'two) 4)) (list x y))) <img src="match_files/0.gif" alt="<graphic>"><br>
((lambda (x y) (list x y))<br>
(begin (write 'one) 3)<br>
(begin (write 'two) 4))</tt>
</p><p>In the output, a subform may be followed directly by two or more
ellipses; the requirements are the same as for nested ellipses, but
the result is flattened rather than nested, as illustrated by the
following example.
</p><p>
</p><p><tt>(define (f x)<br>
(match x<br>
[(foo (,x ...) ...)<br>
`(list (car ,x) ... ...)]))<br>
(f '(foo (a) (b c d e) () (f g))) <img src="match_files/0.gif" alt="<graphic>"><br>
(list (car a) (car b) (car c) (car d) (car e) (car f) (car g))</tt>
</p><p>Sometimes it is useful to explicitly name the operator in a
"cata" subpattern.
Whereas <tt>,[<i>id</i> ...]</tt> recurs to the top of the current
<tt>match</tt>, <tt>,[<i>cata</i> -> <i>id</i> ...]</tt> recurs
to <tt><i>cata</i></tt>.
<tt><i>cata</i></tt> must evaluate to a procedure that accepts
one argument, the input expression, and returns as many values
as there are identifiers following the <tt>-></tt>.
</p><p>
This allows processing to be split into several
mutually recursive procedures, as in the following parser for the simple
language defined by the grammar below.
</p><p>
</p><table><tbody><tr><td nowrap="nowrap">
<Prog></td><td align="center"><img src="match_files/1.gif" alt="<graphic>"></td><td nowrap="nowrap"><tt>(program</tt> <Stmt>* <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
<Stmt></td><td align="center"><img src="match_files/1.gif" alt="<graphic>"></td><td nowrap="nowrap"><tt>(if</tt> <Expr> <Stmt> <Stmt><tt>)</tt></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(set!</tt> <var> <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
<Expr></td><td align="center"><img src="match_files/1.gif" alt="<graphic>"></td><td nowrap="nowrap"><var></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><integer></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(if</tt> <Expr> <Expr> <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(</tt><Expr> <Expr>*<tt>)</tt>
</td></tr></tbody></table>
<p>
</p><p><tt>(define parse<br>
(lambda (x)<br>
(define Prog<br>
(lambda (x)<br>
(match x<br>
[(program ,[Stmt -> s*] ... ,[Expr -> e])<br>
`(begin ,s* ... ,e)]<br>
[,x (error 'parse "invalid program ~s" x)])))<br>
(define Stmt<br>
(lambda (x)<br>
(match x<br>
[(if ,[Expr -> e] ,[Stmt -> s1] ,[Stmt -> s2])<br>
`(if ,e ,s1 ,s2)]<br>
[(set! ,v ,[Expr -> e])<br>
(guard (symbol? v))<br>
`(set! ,v ,e)]<br>
[,x (error 'parse "invalid statement ~s" x)])))<br>
(define Expr<br>
(lambda (x)<br>
(match x<br>
[,v (guard (symbol? v)) v]<br>
[,n (guard (integer? n)) n]<br>
[(if ,[e1] ,[e2] ,[e3])<br>
`(if ,e1 ,e2 ,e3)]<br>
[(,[rator] ,[rand*] ...) `(,rator ,rand* ...)]<br>
[,x (error 'parse "invalid expression ~s" x)])))<br>
(Prog x)))
<br>
<br>
(parse '(program (set! x 3) (+ x 4))) <img src="match_files/0.gif" alt="<graphic>"> (begin (set! x 3) (+ x 4))</tt>
</p><p>A mentioned above, the operator specified in the cata syntax can be any
expression.
We can make use of this to pass along an environment, if needed, say
to handle a version of the language above extended with a
<tt>let</tt> expression that creates bindings that might shadow keywords.
</p><p>
</p><table><tbody><tr><td nowrap="nowrap">
<Prog></td><td align="center"><img src="match_files/1.gif" alt="<graphic>"></td><td nowrap="nowrap"><tt>(program</tt> <Stmt>* <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
<Stmt></td><td align="center"><img src="match_files/1.gif" alt="<graphic>"></td><td nowrap="nowrap"><tt>(if</tt> <Expr> <Stmt> <Stmt><tt>)</tt></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(set!</tt> <var> <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
<Expr></td><td align="center"><img src="match_files/1.gif" alt="<graphic>"></td><td nowrap="nowrap"><var></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><integer></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(if</tt> <Expr> <Expr> <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(let</tt> <tt>((</tt><tt><i>var</i></tt> <Expr><tt>))</tt> <Expr><tt>)</tt></td></tr><tr><td nowrap="nowrap">
</td><td align="center">|</td><td nowrap="nowrap"><tt>(</tt><Expr> <Expr>*<tt>)</tt>
</td></tr></tbody></table>
<p>
In the following version of <tt>parse</tt>, the output is more structured,
with an explicit <tt>call</tt> keyword so that there will not be any
confusion in the output between a call to the value of an <tt>if</tt>
variable and a <tt>if</tt> expression keyed by the <tt>if</tt> keyword.
</p><p>
</p><p><tt>(define parse<br>
(lambda (x)<br>
(define Prog<br>
(lambda (x)<br>
(match x<br>
[(program ,[Stmt -> s*] ... ,[(Expr '()) -> e])<br>
`(begin ,s* ... ,e)]<br>
[,x (error 'parse "invalid program ~s" x)])))<br>
(define Stmt<br>
(lambda (x)<br>
(match x<br>
[(if ,[(Expr '()) -> e] ,[Stmt -> s1] ,[Stmt -> s2])<br>
`(if ,e ,s1 ,s2)]<br>
[(set! ,v ,[(Expr '()) -> e])<br>
(guard (symbol? v))<br>
`(set! ,v ,e)]<br>
[,x (error 'parse "invalid statement ~s" x)])))<br>
(define Expr<br>
(lambda (env)<br>
(lambda (x)<br>
(match x<br>
[,v (guard (symbol? v)) v]<br>
[,n (guard (integer? n)) n]<br>
[(if ,[e1] ,[e2] ,[e3])<br>
(guard (not (memq 'if env)))<br>
`(if ,e1 ,e2 ,e3)]<br>
[(let ([,v ,[e]]) ,[(Expr (cons v env)) -> body])<br>
(guard (not (memq 'let env)) (symbol? v))<br>
`(let ([,v ,e]) ,body)]<br>
[(,[rator] ,[rand*] ...)<br>
`(call ,rator ,rand* ...)]<br>
[,x (error 'parse "invalid expression ~s" x)]))))<br>
(Prog x)))
<br>
<br>
(parse<br>
'(program <img src="match_files/ghostRightarrow.gif"> (begin<br>
(let ([if (if x list values)]) <img src="match_files/0.gif" alt="<graphic>"> (let ([if (if x list values)])<br>
(if 1 2 3)))) <img src="match_files/ghostRightarrow.gif"> (call if 1 2 3)))</tt>
</p><p>When recurring via a cata call without an explicit operator, e.g.,
within the <tt>Expr</tt> <tt>if</tt> and application cases, the value of
<tt>Expr</tt>'s <tt>env</tt> argument does not change, which is good,
since nothing needs to be added to the environment at those call sites.
The value of <tt>Expr</tt>'s <tt>x</tt> argument does not
change either, so the clause that reads
</p><p>
</p><p><tt> [,v (guard (symbol? v)) v]</tt>
</p><p>should not be replaced by one that reads
</p><p>
</p><p><tt> [,v (guard (symbol? v)) x]</tt>
</p><p>or nested expressions will not be handled properly.
In general, the values of any variables bound outside a <tt>match</tt>
expression do not change when a <tt>cata</tt> call is used to recur
directly to the <tt>match</tt> itself.
</p><p>
<a name="mrvs"></a>In some cases, a procedure that uses <tt>match</tt> will need to return
multiple values.
Programs return multiple values using the <tt>values</tt>
procedure and receive them using the <tt>let-values</tt>
syntactic form.
These features are described in
<a class="ref" href="http://www.scheme.com/tspl4/control.html#SECTMRVS"><i>The
Scheme Programming Language</i></a>.
Here is a simple example adapted from <i>The Scheme Programming Language</i>.
</p><p>
</p><p><tt>(define split<br>
(lambda (ls)<br>
(if (or (null? ls) (null? (cdr ls)))<br>
(values ls '())<br>
(let-values ([(odds evens) (split (cddr ls))])<br>
(values (cons (car ls) odds)<br>
(cons (cadr ls) evens))))))
<br>
<br>
(split '(a b c d e f)) <img src="match_files/0.gif" alt="<graphic>"> (a c e)<br>
<img src="match_files/ghostRightarrow.gif"> (b d f)</tt>
</p><p>The <tt>values</tt> procedure is used to return multiple values; it
takes an arbitrary number of arguments and returns them as the values.
If passed one value, <tt>values</tt> behaves like the identity.
<tt>let-values</tt> is like <tt>let</tt>, except that each binding binds
zero or more variables to zero or more return values.
</p><p>
The pattern matcher cata syntax can also be used to receive multiple
values.
When making implicit recursive calls using the cata (<tt>,[]</tt>) syntax,
one can include zero or more variables between the brackets
(after the <tt>-></tt>, if one is present),
each representing one of the expected return values.
<tt>split</tt> may thus be defined using <tt>match</tt> as follows.
</p><p>
</p><p><tt>(define split<br>
(lambda (ls)<br>
(match ls<br>
[() (values '() '())]<br>
[(,x) (values `(,x) '())]<br>
[(,x ,y . ,[odds evens])<br>
(values (cons x odds)<br>
(cons y evens))])))
<br>
<br>
(split '(a b c d e f)) <img src="match_files/0.gif" alt="<graphic>"> (a c e)<br>
<img src="match_files/ghostRightarrow.gif"> (b d f)</tt>
</p><p>
</p><p></p><hr>© 2013 R. Kent Dybvig
<p>
</p><div id="link64_vdp_tabid" style="display:none;">1865</div></body><div id="abineFillElement"></div></html>