forked from ldct/isicp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4-1-metacircular.html
2391 lines (1992 loc) · 84.7 KB
/
4-1-metacircular.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 XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="web-worker-interpreter/deps/codemirror/lib/codemirror.css" />
<link rel="stylesheet" type="text/css" href="css/isicp.css" />
<link rel="stylesheet" type="text/css" href="css/footnotes.css" />
<link rel="stylesheet" type="text/css" href="css/theme.css" />
<script src="js/helper.js"></script>
<script src="js/jquery.min.js"></script>
<script src="web-worker-interpreter/deps/codemirror/lib/codemirror.js"></script>
<script src="web-worker-interpreter/deps/codemirror/mode/scheme/scheme.js"></script>
<script src="web-worker-interpreter/coding.js"> </script>
<script>
set_interpreter_path("web-worker-interpreter/");
set_language("scheme");
</script>
<script src="js/footnotes.js"></script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$']]}
});
</script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<title> iSICP 2.4 - Multiple Representations for Abstract Data </title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36868476-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="sidebox">
<div class="tab"></div>
<div class="content">
<p>
<a href="index.html" class="navlink"> <img src='images/home.svg' width=32 height=32> </a>
<span id="toc-link" class="navlink"> <img src='images/list.svg' width=32 height=32> </span>
<span id="currently-editing-link" class="navlink"> <img src='images/file-edit.svg' width=32 height=32> </span>
<script src="http://cdn.jotfor.ms/static/feedback2.js?3.2.310" type="text/javascript">
new JotformFeedback({
formId:'40222623177447',
base:'http://jotform.me/',
windowTitle:'Notify Me',
background:'#FFA500',
fontColor:'#FFFFFF',
type:false,
height:500,
width:700
});
</script>
<a class="lightbox-40222623177447" style="cursor:pointer;color:blue;text-decoration:underline;"><img src='images/envelope.svg' width=32 height=32></a>
<p>
<div id="currently-editing"> </div>
<script>
function hideAll() {
$("#currently-editing").hide();
$("#toc").hide();
}
$("#currently-editing-link").click(function() {
hideAll();
$("#currently-editing").show();
});
$("#toc-link").click(function() {
hideAll();
$("#toc").show();
});
</script>
<div id="toc"> </div>
<p style='font-size:12px'> (Click on the left edge of this green box to hide it!)
<script>
hideAll();
$("#toc").show();
</script>
</div>
</div>
<script>
$('#sidebox .tab').toggle(function(){
$('#sidebox').animate({'right':'0%'});
}, function(){
$('#sidebox').animate({'right':'-30%'});
});
$(document).ready(createTOC);
</script>
<div id="main">
<h2> The Metacircular Evaluator </h2>
Our evaluator for Lisp will be implemented as a Lisp program. It may seem circular to think about evaluating Lisp programs using an evaluator that is itself implemented in Lisp. However, evaluation is a process, so it is appropriate to describe the evaluation process using Lisp, which, after all, is our tool for describing processes.@footnote{Even so, there will remain important aspects of the evaluation process that are not elucidated by our evaluator. The most important of these are the detailed mechanisms by which procedures call other procedures and return values to their callers. We will address these issues in Chapter 5, where we take a closer look at the evaluation process by implementing the evaluator as a simple register machine.} An evaluator that is written in the same language that it evaluates is said to be <tt>metacircular</tt> .
The metacircular evaluator is essentially a Scheme formulation of the
environment model of evaluation described in section 3-2. Recall that
the model has two basic parts:
<ul>
@item
<p> To evaluate a combination (a compound expression other than a special form), evaluate the subexpressions and then apply the value of the operator subexpression to the values of the operand subexpressions.
@item
<p> To apply a compound procedure to a set of arguments, evaluate the body of the procedure in a new environment. To construct this environment, extend the environment part of the procedure object by a frame in which the formal parameters of the procedure are bound to the arguments to which the procedure is applied.
</ul>
These two rules describe the essence of the evaluation process, a basic cycle in which expressions to be evaluated in environments are reduced to procedures to be applied to arguments, which in turn are reduced to new expressions to be evaluated in new environments, and so on, until we get down to symbols, whose values are looked up in the environment, and to primitive procedures, which are applied directly (see Figure 4-1).@footnote{If we grant ourselves the ability to apply primitives, then what remains for us to implement in the evaluator? The job of the evaluator is not to specify the primitives of the language, but rather to provide the connective tissue---the means of combination and the means of abstraction---that binds a collection of primitives to form a language. Specifically:
<ul>
@item
The evaluator enables us to deal with nested expressions. For example, although simply applying primitives would suffice for evaluating the expression <tt>(+ 1 6)</tt>, it is not adequate for handling <tt>(+ 1 (* 2 3))</tt>. As far as the primitive procedure <tt>+</tt> is concerned, its arguments must be numbers, and it would choke if we passed it the expression <tt>(* 2 3)</tt> as an argument. One important role of the evaluator is to choreograph procedure composition so that <tt>(* 2 3)</tt> is reduced to 6 before being passed as an argument to <tt>+</tt>.
@item
The evaluator allows us to use variables. For example, the primitive procedure for addition has no way to deal with expressions such as <tt>(+ x 1)</tt>. We need an evaluator to keep track of variables and obtain their values before invoking the primitive procedures.
@item
The evaluator allows us to define compound procedures. This involves keeping track of procedure definitions, knowing how to use these definitions in evaluating expressions, and providing a mechanism that enables procedures to accept arguments.
@item
The evaluator provides the special forms, which must be evaluated differently
from procedure calls.
</ul>
} This evaluation cycle will be embodied by the interplay between the two
critical procedures in the evaluator, <tt>eval</tt> and <tt>apply</tt>, which are
described in section 4-1-1 (see Figure 4-1).
<p> The implementation of the evaluator will depend upon procedures that define the <tt>syntax</tt> of the expressions to be evaluated. We will use data abstraction to make the evaluator independent of the representation of the language. For example, rather than committing to a choice that an assignment is to be represented by a list beginning with the symbol <tt>set!</tt> we use an abstract predicate <tt>assignment?</tt> to test for an assignment, and we use abstract selectors <tt>assignment-variable</tt> and <tt>assignment-value</tt> to access the parts of an assignment. Implementation of expressions will be described in detail in section 4-1-2. There are also operations, described in section 4-1-3, that specify the representation of procedures and environments. For example, <tt>make-procedure</tt> constructs compound procedures, <tt>lookup-variable-value</tt> accesses the values of variables, and <tt>apply-primitive-procedure</tt> applies a primitive procedure to a given list of arguments.
@menu
* 4-1-1:: The Core of the Evaluator
* 4-1-2:: Representing Expressions
* 4-1-3:: Evaluator Data Structures
* 4-1-4:: Running the Evaluator as a Program
* 4-1-5:: Data as Programs
* 4-1-6:: Internal Definitions
* 4-1-7:: Separating Syntactic Analysis from Execution
@end menu
<h3> The Core of the Evaluator </h3>
<div class="exercise">
<b>Figure 4.1:</b> The <tt>eval</tt>-<tt>apply</tt> cycle
exposes the essence of a computer language.
<pre>
.,ad88888888baa,
_ ,d8P""" ""9888ba. _
/ .a8" ,ad88888888888a |\
/ aP' ,88888888888888888a \
/ ,8" ,88888888888888888888, \
| ,8' (888888888888888888888, |
/ ,8' `8888888888888888888888 \
| 8) `888888888888888888888, |
Procedure, | 8 "88888 Apply 8888888) | Expression
Arguments | 8 Eval `888888888888888888) | Environment
| 8) "8888888888888888 |
\ (b "88888888888888' /
| `8, 8888888888888) |
\ "8a ,888888888888) /
\ V8, d88888888888" /
_\| `8b, ,d8888888888P' _/
`V8a, ,ad8888888888P'
""88888888888888888P"
""""""""""""
[graphic by Normand Veillux, modified]
</pre>
</div>
The evaluation process can be described as the interplay between two
procedures: <tt>eval</tt> and <tt>apply</tt>.
<h4> Eval </h4>
<p> <tt>Eval</tt> takes as arguments an expression and an environment. It classifies the expression and directs its evaluation. <tt>Eval</tt> is structured as a case analysis of the syntactic type of the expression to be evaluated. In order to keep the procedure general, we express the determination of the type of an expression abstractly, making no commitment to any particular representation for the various types of expressions. Each type of expression has a predicate that tests for it and an abstract means for selecting its parts. This <tt>abstract syntax</tt> makes it easy to see how we can change the syntax of the language by using the same evaluator, but with a different collection of syntax procedures.
@b{Primitive expressions}
<ul>
@item
For self-evaluating expressions, such as numbers, <tt>eval</tt> returns the
expression itself.
@item
<tt>Eval</tt> must look up variables in the environment to find their values.
</ul>
@b{Special forms}
<ul>
@item
For quoted expressions, <tt>eval</tt> returns the expression that was quoted.
@item
An assignment to (or a definition of) a variable must recursively call
<tt>eval</tt> to compute the new value to be associated with the variable. The
environment must be modified to change (or create) the binding of the variable.
@item
<p> An <tt>if</tt> expression requires special processing of its parts, so as to evaluate the consequent if the predicate is true, and otherwise to evaluate the alternative.
@item
<p> A <tt>lambda</tt> expression must be transformed into an applicable procedure by packaging together the parameters and body specified by the <tt>lambda</tt> expression with the environment of the evaluation.
@item
A <tt>begin</tt> expression requires evaluating its sequence of expressions in
the order in which they appear.
@item
A case analysis (<tt>cond</tt>) is transformed into a nest of <tt>if</tt>
expressions and then evaluated.
</ul>
@b{Combinations}
<ul>
@item
For a procedure application, <tt>eval</tt> must recursively evaluate the operator
part and the operands of the combination. The resulting procedure and
arguments are passed to <tt>apply</tt>, which handles the actual procedure
application.
</ul>
Here is the definition of <tt>eval</tt>:
<div id="">
(define (eval exp env)
(cond ((self-evaluating? exp) exp)
((variable? exp) (lookup-variable-value exp env))
((quoted? exp) (text-of-quotation exp))
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
((if? exp) (eval-if exp env))
((lambda? exp)
(make-procedure (lambda-parameters exp)
(lambda-body exp)
env))
((begin? exp)
(eval-sequence (begin-actions exp) env))
((cond? exp) (eval (cond->if exp) env))
((application? exp)
(apply (eval (operator exp) env)
(list-of-values (operands exp) env)))
(else
(error "Unknown expression type -- EVAL" exp))))
</div>
<script>
prompt();
</script>
For clarity, <tt>eval</tt> has been implemented as a case analysis using
<tt>cond</tt>. The disadvantage of this is that our procedure handles only a few
distinguishable types of expressions, and no new ones can be defined without
editing the definition of <tt>eval</tt>. In most Lisp implementations,
dispatching on the type of an expression is done in a data-directed style.
This allows a user to add new types of expressions that <tt>eval</tt> can
distinguish, without modifying the definition of <tt>eval</tt> itself. (See
Exercise 4-3.)
<h4> Apply </h4>
<tt>Apply</tt> takes two arguments, a procedure and a list of arguments to which
the procedure should be applied. <tt>Apply</tt> classifies procedures into two
kinds: It calls <tt>apply-primitive-procedure</tt> to apply primitives; it
applies compound procedures by sequentially evaluating the expressions that
make up the body of the procedure. The environment for the evaluation of the
body of a compound procedure is constructed by extending the base environment
carried by the procedure to include a frame that binds the parameters of the
procedure to the arguments to which the procedure is to be applied. Here is
the definition of <tt>apply</tt>:
<div id="">
(define (apply procedure arguments)
(cond ((primitive-procedure? procedure)
(apply-primitive-procedure procedure arguments))
((compound-procedure? procedure)
(eval-sequence
(procedure-body procedure)
(extend-environment
(procedure-parameters procedure)
arguments
(procedure-environment procedure))))
(else
(error
"Unknown procedure type -- APPLY" procedure))))
</div>
<script>
prompt();
</script>
<h4> Procedure arguments </h4>
When <tt>eval</tt> processes a procedure application, it uses
<tt>list-of-values</tt> to produce the list of arguments to which the procedure
is to be applied. <tt>List-of-values</tt> takes as an argument the operands of
the combination. It evaluates each operand and returns a list of the
corresponding values:@footnote{We could have simplified the <tt>application?</tt>
clause in <tt>eval</tt> by using <tt>map</tt> (and stipulating that <tt>operands</tt>
returns a list) rather than writing an explicit <tt>list-of-values</tt>
procedure. We chose not to use <tt>map</tt> here to emphasize the fact that the
evaluator can be implemented without any use of higher-order procedures (and
thus could be written in a language that doesn't have higher-order procedures),
even though the language that it supports will include higher-order
procedures.}
<div id="">
(define (list-of-values exps env)
(if (no-operands? exps)
'()
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))
</div>
<script>
prompt();
</script>
<h4> Conditionals </h4>
<tt>Eval-if</tt> evaluates the predicate part of an <tt>if</tt> expression in the
given environment. If the result is true, <tt>eval-if</tt> evaluates the
consequent, otherwise it evaluates the alternative:
<div id="">
(define (eval-if exp env)
(if (true? (eval (if-predicate exp) env))
(eval (if-consequent exp) env)
(eval (if-alternative exp) env)))
</div>
<script>
prompt();
</script>
The use of <tt>true?</tt> in <tt>eval-if</tt> highlights the issue of the
connection between an implemented language and an implementation language. The
<tt>if-predicate</tt> is evaluated in the language being implemented and thus
yields a value in that language. The interpreter predicate <tt>true?</tt>
translates that value into a value that can be tested by the <tt>if</tt> in the
implementation language: The metacircular representation of truth might not be
the same as that of the underlying Scheme.@footnote{In this case, the language
being implemented and the implementation language are the same. Contemplation
of the meaning of <tt>true?</tt> here yields expansion of consciousness without
the abuse of substance.}
<h4> Sequences </h4>
<tt>Eval-sequence</tt> is used by <tt>apply</tt> to evaluate the sequence of
expressions in a procedure body and by <tt>eval</tt> to evaluate the sequence of
expressions in a <tt>begin</tt> expression. It takes as arguments a sequence of
expressions and an environment, and evaluates the expressions in the order in
which they occur. The value returned is the value of the final expression.
<div id="">
(define (eval-sequence exps env)
(cond ((last-exp? exps) (eval (first-exp exps) env))
(else (eval (first-exp exps) env)
(eval-sequence (rest-exps exps) env))))
</div>
<script>
prompt();
</script>
<h4> Assignments and definitions </h4>
The following procedure handles assignments to variables. It calls <tt>eval</tt>
to find the value to be assigned and transmits the variable and the resulting
value to <tt>set-variable-value!</tt> to be installed in the designated
environment.
<div id="">
(define (eval-assignment exp env)
(set-variable-value! (assignment-variable exp)
(eval (assignment-value exp) env)
env)
'ok)
</div>
<script>
prompt();
</script>
Definitions of variables are handled in a similar manner.@footnote{This
implementation of <tt>define</tt> ignores a subtle issue in the handling of
internal definitions, although it works correctly in most cases. We will see
what the problem is and how to solve it in section 4-1-6.}
<div id="">
(define (eval-definition exp env)
(define-variable! (definition-variable exp)
(eval (definition-value exp) env)
env)
'ok)
</div>
<script>
prompt();
</script>
We have chosen here to return the symbol <tt>ok</tt> as the value of an
assignment or a definition.@footnote{As we said when we introduced
<tt>define</tt> and <tt>set!</tt>, these values are implementation-dependent in
Scheme---that is, the implementor can choose what value to return.}
<div class="exercise">
<b>Exercise 4.1:</b> Notice that we cannot tell whether
the metacircular evaluator evaluates operands from left to right or from right
to left. Its evaluation order is inherited from the underlying Lisp: If the
arguments to <tt>cons</tt> in <tt>list-of-values</tt> are evaluated from left to
right, then <tt>list-of-values</tt> will evaluate operands from left to right;
and if the arguments to <tt>cons</tt> are evaluated from right to left, then
<tt>list-of-values</tt> will evaluate operands from right to left.
Write a version of <tt>list-of-values</tt> that evaluates operands from left to
right regardless of the order of evaluation in the underlying Lisp. Also write
a version of <tt>list-of-values</tt> that evaluates operands from right to left.
</div>
<h3> Representing Expressions </h3>
The evaluator is reminiscent of the symbolic differentiation program discussed
in section 2-3-2. Both programs operate on symbolic expressions. In
both programs, the result of operating on a compound expression is determined
by operating recursively on the pieces of the expression and combining the
results in a way that depends on the type of the expression. In both programs
we used data abstraction to decouple the general rules of operation from the
details of how expressions are represented. In the differentiation program
this meant that the same differentiation procedure could deal with algebraic
expressions in prefix form, in infix form, or in some other form. For the
evaluator, this means that the syntax of the language being evaluated is
determined solely by the procedures that classify and extract pieces of
expressions.
Here is the specification of the syntax of our language:
@itemize
@item
The only self-evaluating items are numbers and strings:
<div id="">
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
</div>
<script>
prompt();
</script>
@item
Variables are represented by symbols:
<div id="">
(define (variable? exp) (symbol? exp))
</div>
<script>
prompt();
</script>
@item
Quotations have the form <tt>(quote <text-of-quotation</tt>>):@footnote{As
mentioned in section 2-3-1, the evaluator sees a quoted expression as a
list beginning with <tt>quote</tt>, even if the expression is typed with the
quotation mark. For example, the expression <tt>'a</tt> would be seen by the
evaluator as <tt>(quote a)</tt>. See Exercise 2-55.}
<div id="">
(define (quoted? exp)
(tagged-list? exp 'quote))
(define (text-of-quotation exp) (cadr exp))
</div>
<script>
prompt();
</script>
<tt>Quoted?</tt> is defined in terms of the procedure <tt>tagged-list?</tt>, which
identifies lists beginning with a designated symbol:
<div id="">
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
</div>
<script>
prompt();
</script>
@item
Assignments have the form <tt>(set! <var</tt>>
<@var{value>)}:
<div id="">
(define (assignment? exp)
(tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
</div>
<script>
prompt();
</script>
@item
Definitions have the form
<div id="">
(define <var> <value>)
</div>
<script>
prompt();
</script>
or the form
<div id="">
(define (<var> <parameter_1> ... <parameter_n>)
<body>)
</div>
<script>
prompt();
</script>
The latter form (standard procedure definition) is syntactic sugar for
<div id="">
(define <var>
(lambda (<parameter_1> ... <parameter_n>)
<body>))
</div>
<script>
prompt();
</script>
The corresponding syntax procedures are the following:
<div id="">
(define (definition? exp)
(tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp) ; formal parameters
(cddr exp)))) ; body
</div>
<script>
prompt();
</script>
@item
<tt>Lambda</tt> expressions are lists that begin with the symbol <tt>lambda</tt>:
<div id="">
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
</div>
<script>
prompt();
</script>
We also provide a constructor for <tt>lambda</tt> expressions, which is used by
<tt>definition-value</tt>, above:
<div id="">
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
</div>
<script>
prompt();
</script>
@item
Conditionals begin with <tt>if</tt> and have a predicate, a consequent, and an
(optional) alternative. If the expression has no alternative part, we provide
<tt>false</tt> as the alternative.@footnote{The value of an <tt>if</tt> expression
when the predicate is false and there is no alternative is unspecified in
Scheme; we have chosen here to make it false. We will support the use of the
variables <tt>true</tt> and <tt>false</tt> in expressions to be evaluated by
binding them in the global environment. See section 4-1-4.}
<div id="">
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
</div>
<script>
prompt();
</script>
We also provide a constructor for <tt>if</tt> expressions, to be used by
<tt>cond->if</tt> to transform <tt>cond</tt> expressions into <tt>if</tt>
expressions:
<div id="">
(define (make-if predicate consequent alternative)
(list 'if predicate consequent alternative))
</div>
<script>
prompt();
</script>
@item
<tt>Begin</tt> packages a sequence of expressions into a single expression. We
include syntax operations on <tt>begin</tt> expressions to extract the actual
sequence from the <tt>begin</tt> expression, as well as selectors that return the
first expression and the rest of the expressions in the
sequence.@footnote{These selectors for a list of expressions---and the
corresponding ones for a list of operands---are not intended as a data
abstraction. They are introduced as mnemonic names for the basic list
operations in order to make it easier to understand the explicit-control
evaluator in section 5-4.}
<div id="">
(define (begin? exp) (tagged-list? exp 'begin))
(define (begin-actions exp) (cdr exp))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
</div>
<script>
prompt();
</script>
We also include a constructor <tt>sequence->exp</tt> (for use by <tt>cond->if</tt>)
that transforms a sequence into a single expression, using <tt>begin</tt> if
necessary:
<div id="">
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))
(define (make-begin seq) (cons 'begin seq))
</div>
<script>
prompt();
</script>
@item
A procedure application is any compound expression that is not one of the above
expression types. The <tt>car</tt> of the expression is the operator, and the
<tt>cdr</tt> is the list of operands:
<div id="">
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))
</div>
<script>
prompt();
</script>
</ul>
<h4> Derived expressions </h4>
Some special forms in our language can be defined in terms of expressions
involving other special forms, rather than being implemented directly. One
example is <tt>cond</tt>, which can be implemented as a nest of <tt>if</tt>
expressions. For example, we can reduce the problem of evaluating the
expression
<div id="">
(cond ((> x 0) x)
((= x 0) (display 'zero) 0)
(else (- x)))
</div>
<script>
prompt();
</script>
to the problem of evaluating the following expression involving <tt>if</tt> and
<tt>begin</tt> expressions:
<div id="">
(if (> x 0)
x
(if (= x 0)
(begin (display 'zero)
0)
(- x)))
</div>
<script>
prompt();
</script>
Implementing the evaluation of <tt>cond</tt> in this way simplifies the evaluator
because it reduces the number of special forms for which the evaluation process
must be explicitly specified.
We include syntax procedures that extract the parts of a <tt>cond</tt>
expression, and a procedure <tt>cond->if</tt> that transforms <tt>cond</tt>
expressions into <tt>if</tt> expressions. A case analysis begins with
<tt>cond</tt> and has a list of predicate-action clauses. A clause is an
<tt>else</tt> clause if its predicate is the symbol <tt>else</tt>.@footnote{The
value of a <tt>cond</tt> expression when all the predicates are false and there
is no <tt>else</tt> clause is unspecified in Scheme; we have chosen here to make
it false.}
<div id="">
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
(define (expand-clauses clauses)
(if (null? clauses)
'false ; no <tt>else</tt> clause
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last -- COND->IF"
clauses))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
</div>
<script>
prompt();
</script>
Expressions (such as <tt>cond</tt>) that we choose to implement as syntactic
transformations are called <tt>derived expressions</tt>
. <tt>Let</tt>
expressions are also derived expressions (see Exercise
4-6).@footnote{Practical Lisp systems provide a mechanism that allows a user
to add new derived expressions and specify their implementation as syntactic
transformations without modifying the evaluator. Such a user-defined
transformation is called a <tt>macro</tt>
. Although it is easy to add an
elementary mechanism for defining macros, the resulting language has subtle
name-conflict problems. There has been much research on mechanisms for macro
definition that do not cause these difficulties. See, for example, Kohlbecker
1986, Clinger and Rees 1991, and Hanson 1991.}
<div class="exercise">
<b>Exercise 4.2:</b> Louis Reasoner plans to reorder the
<tt>cond</tt> clauses in <tt>eval</tt> so that the clause for procedure
applications appears before the clause for assignments. He argues that this
will make the interpreter more efficient: Since programs usually contain more
applications than assignments, definitions, and so on, his modified <tt>eval</tt>
will usually check fewer clauses than the original <tt>eval</tt> before
identifying the type of an expression.
<ul>
@item
What is wrong with Louis's plan? (Hint: What will Louis's evaluator do with
the expression <tt>(define x 3)</tt>?)
@item
Louis is upset that his plan didn't work. He is willing to go to any lengths
to make his evaluator recognize procedure applications before it checks for
most other kinds of expressions. Help him by changing the syntax of the
evaluated language so that procedure applications start with <tt>call</tt>. For
example, instead of <tt>(factorial 3)</tt> we will now have to write <tt>(call
factorial 3)</tt> and instead of <tt>(+ 1 2)</tt> we will have to write <tt>(call +
1 2)</tt>.
</ul>
</div>
<div class="exercise">
<b>Exercise 4.3:</b> Rewrite <tt>eval</tt> so that the
dispatch is done in data-directed style. Compare this with the data-directed
differentiation procedure of Exercise 2-73. (You may use the <tt>car</tt>
of a compound expression as the type of the expression, as is appropriate for
the syntax implemented in this section.)
</div>
<div class="exercise">
<b>Exercise 4.4:</b> Recall the definitions of the
special forms <tt>and</tt> and <tt>or</tt> from Chapter 1:
<ul>
@item
<tt>and</tt>: The expressions are evaluated from left to right. If any
expression evaluates to false, false is returned; any remaining expressions are
not evaluated. If all the expressions evaluate to true values, the value of
the last expression is returned. If there are no expressions then true is
returned.
@item
<tt>or</tt>: The expressions are evaluated from left to right. If any expression
evaluates to a true value, that value is returned; any remaining expressions
are not evaluated. If all expressions evaluate to false, or if there are no
expressions, then false is returned.
</ul>
Install <tt>and</tt> and <tt>or</tt> as new special forms for the evaluator by
defining appropriate syntax procedures and evaluation procedures
<tt>eval-and</tt> and <tt>eval-or</tt>. Alternatively, show how to implement
<tt>and</tt> and <tt>or</tt> as derived expressions.
</div>
<div class="exercise">
<b>Exercise 4.5:</b> Scheme allows an additional syntax
for <tt>cond</tt> clauses, <tt>(<test</tt>> => <@var{recipient>)}. If
<test> evaluates to a true value, then <recipient> is evaluated.
Its value must be a procedure of one argument; this procedure is then invoked
on the value of the <test>, and the result is returned as the value of
the <tt>cond</tt> expression. For example
<div id="">
(cond ((assoc 'b '((a 1) (b 2))) => cadr)
(else false))
</div>
<script>
prompt();
</script>
returns 2. Modify the handling of <tt>cond</tt> so that it supports this
extended syntax.
</div>
<div class="exercise">
<b>Exercise 4.6:</b> <tt>Let</tt> expressions are derived
expressions, because
<div id="">
(let ((<var_1> <exp_1>) ... (<var_n> <exp_n>))
<body>)
</div>
<script>
prompt();
</script>
is equivalent to
<div id="">
((lambda (<var_1> ... <var_n>)
<body>)
<exp_1>
...
<exp_n>)
</div>
<script>
prompt();
</script>
Implement a syntactic transformation <tt>let->combination</tt> that reduces
evaluating <tt>let</tt> expressions to evaluating combinations of the type shown
above, and add the appropriate clause to <tt>eval</tt> to handle <tt>let</tt>
expressions.
</div>
<div class="exercise">
<b>Exercise 4.7:</b> <tt>Let*</tt> is similar to
<tt>let</tt>, except that the bindings of the <tt>let</tt> variables are performed
sequentially from left to right, and each binding is made in an environment in
which all of the preceding bindings are visible. For example
<div id="">
(let* ((x 3)
(y (+ x 2))
(z (+ x y 5)))
(* x z))
</div>
<script>
prompt();
</script>
returns 39. Explain how a <tt>let*</tt> expression can be rewritten as a set of
nested <tt>let</tt> expressions, and write a procedure <tt>let*->nested-lets</tt>
that performs this transformation. If we have already implemented <tt>let</tt>
(Exercise 4-6) and we want to extend the evaluator to handle <tt>let*</tt>,
is it sufficient to add a clause to <tt>eval</tt> whose action is
<div id="">
(eval (let*->nested-lets exp) env)
</div>
<script>
prompt();
</script>
or must we explicitly expand <tt>let*</tt> in terms of non-derived expressions?
</div>
<div class="exercise">
<b>Exercise 4.8:</b> ``Named <tt>let</tt>'' is a variant
of <tt>let</tt> that has the form
<div id="">
(let <var> <bindings> <body>)
</div>
<script>
prompt();
</script>
The <bindings> and <body> are just as in ordinary <tt>let</tt>,
except that <var> is bound within <body> to a procedure whose body
is <body> and whose parameters are the variables in the <bindings>.
Thus, one can repeatedly execute the <body> by invoking the procedure
named <var>. For example, the iterative Fibonacci procedure (section
1-2-2) can be rewritten using named <tt>let</tt> as follows:
<div id="">
(define (fib n)
(let fib-iter ((a 1)
(b 0)
(count n))
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1)))))
</div>
<script>
prompt();
</script>
Modify <tt>let->combination</tt> of Exercise 4-6 to also support named
<tt>let</tt>.
</div>
<div class="exercise">