forked from ldct/isicp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-2-closure.html
3139 lines (2481 loc) · 132 KB
/
2-2-closure.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.2 - Hierarchical Data and the Closure Property </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">
<a href='index.html' style="float:left"> <img src='images/chevron-up.svg' height=64 width=64> </a>
<span style="float:right">
<a href='2-1-data.html'> <img src='images/chevron-left.svg' height=64 width=64> </a>
<a href='2-3-symbolic.html'> <img src='images/chevron-right.svg' height=64 width=64> </a>
</span>
<br> <br>
<div id="scheme-define-square">
(define (square x)
(* x x))
</div>
<script>
hidden_prompt("scheme-define-square");
</script>
<h2> Hierarchical Data and the Closure Property </h2>
<p> As we have seen, pairs provide a primitive ``glue'' that we can use to construct compound data objects. Figure 2-2 shows a standard way to visualize a pair---in this case, the pair formed by <tt>(cons 1 2)</tt>. In this representation, which is called <tt>box-and-pointer notation</tt> , each object is shown as a <tt>pointer</tt> to a box. The box for a primitive object contains a representation of the object. For example, the box for a number contains a numeral. The box for a pair is actually a double box, the left part containing (a pointer to) the <tt>car</tt> of the pair and the right part containing the <tt>cdr</tt>.
<p> <img class='center' src='http://mitpress.mit.edu/sicp/full-text/book/ch2-Z-G-11.gif'>
<p style="text-align:center"> <b> Figure 2.2: </b> Box-and-pointer representation of <tt>(cons 1 2)</tt>.
<p> We have already seen that <tt>cons</tt> can be used to combine not only numbers but pairs as well. (You made use of this fact, or should have, in doing Exercise 2-2 and Exercise 2-3.) As a consequence, pairs provide a universal building block from which we can construct all sorts of data structures. Figure 2-3 shows two ways to use pairs to combine the numbers 1, 2, 3, and 4.
<p> <img class='center' src='http://mitpress.mit.edu/sicp/full-text/book/ch2-Z-G-12.gif'>
<p style="text-align:center"> <b>Figure 2.3:</b> Two ways to combine 1, 2, 3, and 4 using pairs.
<p> The ability to create pairs whose elements are pairs is the essence of list structure's importance as a representational tool. We refer to this ability as the <tt>closure property</tt> of <tt>cons</tt>. In general, an operation for combining data objects satisfies the closure property if the results of combining things with that operation can themselves be combined using the same operation.<a name="footnote_link_2-6" class="footnote_link" href="#footnote_2-6">6</a> Closure is the key to power in any means of combination because it permits us to create <tt>hierarchical</tt> structures---structures made up of parts, which themselves are made up of parts, and so on.
<p> From the outset of Chapter 1, we've made essential use of closure in dealing with procedures, because all but the very simplest programs rely on the fact that the elements of a combination can themselves be combinations. In this section, we take up the consequences of closure for compound data. We describe some conventional techniques for using pairs to represent sequences and trees, and we exhibit a graphics language that illustrates closure in a vivid way.<a name="footnote_link_2-7" class="footnote_link" href="#footnote_2-7">7</a>
<h3> Representing Sequences </h3>
<p> <img class='center' src='http://mitpress.mit.edu/sicp/full-text/book/ch2-Z-G-13.gif'>
<p style="text-align:center"> <b>Figure 2.4:</b> The sequence 1, 2, 3, 4 represented as a chain of pairs.
<p> One of the useful structures we can build with pairs is a <tt>sequence</tt> ---an ordered collection of data objects. There are, of course, many ways to represent sequences in terms of pairs. One particularly straightforward representation is illustrated in Figure 2-4, where the sequence 1, 2, 3, 4 is represented as a chain of pairs. The <tt>car</tt> of each pair is the corresponding item in the chain, and the <tt>cdr</tt> of the pair is the next pair in the chain. The <tt>cdr</tt> of the final pair signals the end of the sequence by pointing to a distinguished value that is not a pair, represented in box-and-pointer diagrams as a diagonal line and in programs as the value of the variable <tt>nil</tt>. The entire sequence is constructed by nested <tt>cons</tt> operations:
<div id="scheme-cons-1-2-3-4">
(cons 1
(cons 2
(cons 3
(cons 4 nil))))
</div>
<script>
prompt("scheme-cons-1-2-3-4");
</script>
<p> Such a sequence of pairs, formed by nested <tt>cons</tt>es, is called a <em> list </em> , and Scheme provides a primitive called <tt>list</tt> to help in constructing lists.<a name="footnote_link_2-8" class="footnote_link" href="#footnote_2-8">8</a> The above sequence could be produced by <tt>(list 1 2 3 4)</tt>. In general,
<div id="scheme-list-syntax">
(list <a_1> <a_2> ... <a_n>)
</div>
<script>
makeStatic("scheme-list-syntax");
</script>
<p> is equivalent to
<div id="scheme-list-syntax-expand">
(cons <a_1>
(cons <a_2>
(cons ...
(cons <a_n>
nil)
...)))
</div>
<script>
makeStatic("scheme-list-syntax-expand");
</script>
<p> Lisp systems conventionally print lists by printing the sequence of elements, enclosed in parentheses. Thus, the data object in Figure 2-4 is printed as <tt>(1 2 3 4)</tt>:
<div id="scheme-define-one-through-four">
(define one-through-four (list 1 2 3 4))
</div>
<script>
prompt("scheme-define-one-through-four");
</script>
<p>
<div id="scheme-test-one-through-four">
one-through-four
</div>
<script>
promptDep("scheme-test-one-through-four", ["scheme-define-one-through-four"]);
</script>
<p> Be careful not to confuse the expression <tt>(list 1 2 3 4)</tt> with the list <tt>(1 2 3 4)</tt>, which is the result obtained when the expression is evaluated. Attempting to evaluate the expression <tt>(1 2 3 4)</tt> will signal an error when the interpreter tries to apply the procedure <tt>1</tt> to arguments <tt>2</tt>, <tt>3</tt>, and <tt>4</tt>.
<p> We can think of <tt>car</tt> as selecting the first item in the list, and of <tt>cdr</tt> as selecting the sublist consisting of all but the first item. Nested applications of <tt>car</tt> and <tt>cdr</tt> can be used to extract the second, third, and subsequent items in the list.<a name="footnote_link_2-9" class="footnote_link" href="#footnote_2-9">9</a> The constructor <tt>cons</tt> makes a list like the original one, but with an additional item at the beginning.
<div id="scheme-car-one-through-four">
(car one-through-four)
</div>
<script>
promptDep("scheme-car-one-through-four", ["scheme-define-one-through-four"]);
</script>
<p>
<div id="scheme-cdr-one-through-four">
(cdr one-through-four)
</div>
<script>
promptDep("scheme-cdr-one-through-four", ["scheme-define-one-through-four"]);
</script>
<p>
<div id="scheme-car-cdr-one-through-four">
(car (cdr one-through-four))
</div>
<script>
promptDep("scheme-car-cdr-one-through-four", ["scheme-define-one-through-four"]);
</script>
<p>
<div id="scheme-cons-10-one-through-four">
(cons 10 one-through-four)
</div>
<script>
promptDep("scheme-cons-10-one-through-four", ["scheme-define-one-through-four"]);
</script>
<p>
<div id="scheme-cons-5-one-through-four">
(cons 5 one-through-four)
</div>
<script>
promptDep("scheme-cons-5-one-through-four", ["scheme-define-one-through-four"]);
</script>
<p> The value of <tt>nil</tt>, used to terminate the chain of pairs, can be thought of as a sequence of no elements, the <tt>empty list</tt> . The word <tt>nil</tt> is a contraction of the Latin word <em>nihil</em>, which means ``nothing.''<a name="footnote_link_2-10" class="footnote_link" href="#footnote_2-10">10</a>
<h4> List operations </h4>
<p> The use of pairs to represent sequences of elements as lists is accompanied by conventional programming techniques for manipulating lists by successively ``<tt>cdr</tt>ing down'' the lists. For example, the procedure <tt>list-ref</tt> takes as arguments a list and a number n and returns the nth item of the list. It is customary to number the elements of the list beginning with 0. The method for computing <tt>list-ref</tt> is the following:
<ul>
<li>
<p> For n = 0, <tt>list-ref</tt> should return the <tt>car</tt> of the list.
</li>
<li>
<p> Otherwise, <tt>list-ref</tt> should return the (n - 1)st item of the <tt>cdr</tt> of the list.
</li>
</ul>
<div id="scheme-define-list-ref">
(define (list-ref items n)
(if (= n 0)
(car items)
(list-ref (cdr items) (- n 1))))
</div>
<script>
prompt("scheme-define-list-ref");
</script>
<div id="scheme-define-squares">
(define squares (list 1 4 9 16 25))
</div>
<script>
prompt("scheme-define-squares");
</script>
<div id="scheme-list-ref-squares-3">
(list-ref squares 3)
</div>
<script>
promptDep("scheme-list-ref-squares-3", ["scheme-define-list-ref", "scheme-define-squares"]);
</script>
<p> Often we <tt>cdr</tt> down the whole list. To aid in this, Scheme includes a primitive predicate <tt>null?</tt>, which tests whether its argument is the empty list. The procedure <tt>length</tt>, which returns the number of items in a list, illustrates this typical pattern of use:
<div id="scheme-define-length">
(define (length items)
(if (null? items)
0
(+ 1 (length (cdr items)))))
</div>
<script>
prompt("scheme-define-length");
</script>
<div id="scheme-define-odds">
(define odds (list 1 3 5 7))
</div>
<script>
prompt("scheme-define-odds");
</script>
<div id="scheme-length-odds">
(length odds)
</div>
<script>
promptDep("scheme-length-odds", ["scheme-define-length", "scheme-define-odds"]);
</script>
<p> The <tt>length</tt> procedure implements a simple recursive plan. The reduction step is:
<ul>
<li>
<p> The <tt>length</tt> of any list is 1 plus the <tt>length</tt> of the <tt>cdr</tt> of the list.
</li>
</ul>
<p> This is applied successively until we reach the base case:
<ul>
<li>
<p> The <tt>length</tt> of the empty list is 0.
</li>
</ul>
<p> We could also compute <tt>length</tt> in an iterative style:
<div id="scheme-define-length-iterative">
(define (length items)
(define (length-iter a count)
(if (null? a)
count
(length-iter (cdr a) (+ 1 count))))
(length-iter items 0))
</div>
<script>
prompt("scheme-define-length-iterative");
</script>
<p> Another conventional programming technique is to ``<tt>cons</tt> up'' an answer list while <tt>cdr</tt>ing down a list, as in the procedure <tt>append</tt>, which takes two lists as arguments and combines their elements to make a new list:
<div id="scheme-append-squares-odds">
(append squares odds)
</div>
<script>
promptDep("scheme-append-squares-odds", ["scheme-define-squares", "scheme-define-odds"]);
</script>
<p>
<div id="scheme-append-odds-squares">
(append odds squares)
</div>
<script>
promptDep("scheme-append-odds-squares", ["scheme-define-squares", "scheme-define-odds"]);
</script>
<p> <tt>append</tt> is also implemented using a recursive plan. To <tt>append</tt> lists <tt>list1</tt> and <tt>list2</tt>, do the following:
<ul>
<li>
<p> If <tt>list1</tt> is the empty list, then the result is just <tt>list2</tt>.
</li>
<li>
<p> Otherwise, <tt>append</tt> the <tt>cdr</tt> of <tt>list1</tt> and <tt>list2</tt>, and <tt>cons</tt> the <tt>car</tt> of <tt>list1</tt> onto the result:
</li>
</ul>
<p>
<div id="scheme-define-append">
(define (append list1 list2)
(if (null? list1)
list2
(cons (car list1) (append (cdr list1) list2))))
</div>
<script>
prompt("scheme-define-append");
</script>
<p>
<div class="exercise">
<p> <b>Exercise 2.17:</b> Define a procedure <tt>last-pair</tt> that returns the list that contains only the last element of a given (nonempty) list:
<div id="scheme-ex-define-last-pair">
(define (last-pair l)
'your-code-here)
(last-pair (list 23 72 149 34))
</div>
<script>
makeEditable("scheme-ex-define-last-pair");
addOutput("scheme-ex-define-last-pair");
editorOf["scheme-ex-define-last-pair"].setOption("onBlur", function(){
var code = "{0} \n (equal? (last-pair '(1 2 3 4)) '(4))".format(
editorOf["scheme-ex-define-last-pair"].getValue());
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true\n") {
$_("scheme-ex-define-last-pair-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-last-pair-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$_("scheme-ex-define-last-pair-output").append(res.slice(0,-1));
});
});
/*
(define (last-pair l)
(if (null? (cdr l))
l
(last-pair (cdr l))))
*/
</script>
</div>
<p>
<div class="exercise">
<p> <b>Exercise 2.18:</b> Define a procedure <tt>reverse</tt> that takes a list as argument and returns a list of the same elements in reverse order:
<div id="scheme-ex-define-reverse">
(define (reverse l)
'your-code-here)
(reverse (list 1 4 9 16 25))
</div>
<script>
makeEditable("scheme-ex-define-reverse");
addOutput("scheme-ex-define-reverse");
editorOf["scheme-ex-define-reverse"].setOption("onBlur", function(){
var code = "{0} \n (equal? (reverse '(1 2 3 4)) '(4 3 2 1))".format(
editorOf["scheme-ex-define-reverse"].getValue());
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true\n") {
$_("scheme-ex-define-reverse-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-reverse-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$_("scheme-ex-define-reverse-output").append(res.slice(0,-1));
});
});
/*
(define (append-to-end l x)
(if (null? l)
(list x)
(cons (car l)
(append-to-end (cdr l) x))))
(define (reverse l)
(if (null? l)
l
(append-to-end (reverse (cdr l))
(car l))))
*/
</script>
</div>
<p>
<div class="exercise">
<p> <b>Exercise 2.19:</b> Consider the change-counting program of section 1-2-2. It would be nice to be able to easily change the currency used by the program, so that we could compute the number of ways to change a British pound, for example. As the program is written, the knowledge of the currency is distributed partly into the procedure <tt>first-denomination</tt> and partly into the procedure <tt>count-change</tt> (which knows that there are five kinds of U.S. coins). It would be nicer to be able to supply a list of coins to be used for making change.
<p> We want to rewrite the procedure <tt>cc</tt> so that its second argument is a list of the values of the coins to use rather than an integer specifying which coins to use. We could then have lists that defined each kind of currency:
<div id="scheme-define-coins">
(define us-coins (list 50 25 10 5 1))
(define uk-coins (list 100 50 20 10 5 2 1 0.5))
</div>
<script>
prompt("scheme-define-coins");
</script>
<p> We could then call <tt>cc</tt> as follows:
<div id="scheme-cc-us-coins">
(cc 100 us-coins) ;292
</div>
<script>
prompt("scheme-cc-us-coins", ["scheme-define-coins", "scheme-ex-define-cc"]);
</script>
<p> To do this will require changing the program <tt>cc</tt> somewhat. It will still have the same form, but it will access its second argument differently, as follows:
<div id="scheme-ex-define-cc">
(define (cc amount coin-values)
(cond ((= amount 0) 1)
((or (< amount 0) (no-more? coin-values)) 0)
(else
(+ (cc amount
(except-first-denomination coin-values))
(cc (- amount
(first-denomination coin-values))
coin-values)))))
</div>
<script>
makeEditable("scheme-ex-define-cc");
addOutput("scheme-ex-define-cc");
editorOf["scheme-ex-define-cc"].setOption("onBlur", function(){
var code = "{0} \n (equal? (cc 100 '(50 25 10 5 1)) 292)".format(
editorOf["scheme-ex-define-cc"].getValue());
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true\n") {
$_("scheme-ex-define-cc-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-cc-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$_("scheme-ex-define-cc-output").append(res.slice(0,-1));
compute("scheme-cc-us-coins")
});
});
/*
(define no-more? null?)
(define except-first-denomination cdr)
(define first-denomination car)
*/
</script>
<p> Define the procedures <tt>first-denomination</tt>, <tt>except-first-denomination</tt>, and <tt>no-more?</tt> in terms of primitive operations on list structures. Does the order of the list <tt>coin-values</tt> affect the answer produced by <tt>cc</tt>? Why or why not?
</div>
<p>
<div class="exercise">
<p> <b>Exercise 2.20:</b> The procedures <tt>+</tt>, <tt>*</tt>, and <tt>list</tt> take arbitrary numbers of arguments. One way to define such procedures is to use <tt>define</tt> with <em>dotted-tail notation</em> . In a procedure definition, a parameter list that has a dot before the last parameter name indicates that, when the procedure is called, the initial parameters (if any) will have as values the initial arguments, as usual, but the final parameter's value will be a <tt>list</tt> of any remaining arguments. For instance, given the definition
<div id="scheme-dotted-tail-syntax">
(define (f x y . z) <body>)
</div>
<script>
no_output_frozen_prompt("scheme-dotted-tail-syntax");
</script>
<p> the procedure <tt>f</tt> can be called with two or more arguments. If we evaluate
<div id="scheme-dotted-tail-application">
(f 1 2 3 4 5 6)
</div>
<script>
makeStatic("scheme-dotted-tail-application");
</script>
<p> then in the body of <tt>f</tt>, <tt>x</tt> will be 1, <tt>y</tt> will be 2, and <tt>z</tt> will be the list <tt>(3 4 5 6)</tt>. Given the definition
<div id="scheme-define-dotted-tail-syntax-one">
(define (g . w) <body>)
</div>
<script>
makeStatic("scheme-define-dotted-tail-syntax-one");
</script>
<p> the procedure <tt>g</tt> can be called with zero or more arguments. If we evaluate
<div id="scheme-g">
(g 1 2 3 4 5 6)
</div>
<script>
no_output_frozen_prompt("scheme-g");
</script>
<p> then in the body of <tt>g</tt>, <tt>w</tt> will be the list <tt>(1 2 3 4 5 6)</tt>.<a name="footnote_link_2-11" class="footnote_link" href="#footnote_2-11">11</a>
<p> Use this notation to write a procedure <tt>same-parity</tt> that takes one or more integers and returns a list of all the arguments that have the same even-odd parity as the first argument. For example,
<div id="scheme-ex-define-same-parity">
(define (same-parity x . y)
'your-code-here)
(same-parity 1 2 3 4 5 6 7)
(same-parity 2 3 4 5 6 7)
</div>
<script>
makeEditable("scheme-ex-define-same-parity");
addOutput("scheme-ex-define-same-parity");
editorOf["scheme-ex-define-same-parity"].setOption("onBlur", function(){
var code = "{0} \n (equal? (same-parity '1 2 3 4 5 6 7) '(1 3 5 7))".format(
editorOf["scheme-ex-define-same-parity"].getValue());
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true\n") {
$_("scheme-ex-define-same-parity-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-same-parity-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$_("scheme-ex-define-same-parity-output").append(res.slice(0,-1));
});
});
/*
(define (filter l p)
(cond ((null? l) l)
((p (car l)) (cons (car l)
(filter (cdr l) p)))
(else (filter (cdr l) p))))
(define (same-parity x . y)
(cons x (filter y (lambda (t) (= (modulo t 2)
(modulo x 2))))))
*/
</script>
</div>
<h4> Mapping over lists </h4>
<p> One extremely useful operation is to apply some transformation to each element in a list and generate the list of results. For instance, the following procedure scales each number in a list by a given factor:
<div id="scheme-define-scale-list">
(define (scale-list items factor)
(if (null? items)
nil
(cons (* (car items) factor)
(scale-list (cdr items) factor))))
(scale-list (list 1 2 3 4 5) 10)
</div>
<script>
prompt("scheme-define-scale-list");
</script>
<p> We can abstract this general idea and capture it as a common pattern expressed as a higher-order procedure, just as in section 1-3. The higher-order procedure here is called <tt>map</tt>. <tt>map</tt> takes as arguments a procedure of one argument and a list, and returns a list of the results produced by applying the procedure to each element in the list:<a name="footnote_link_2-12" class="footnote_link" href="#footnote_2-12">12</a>
<div id="scheme-define-map">
(define (map proc items)
(if (null? items)
nil
(cons (proc (car items))
(map proc (cdr items)))))
</div>
<script>
prompt("scheme-define-map");
</script>
<p>
<div id="scheme-test-map">
(map abs (list -10 2.5 -11.6 17))
(map (lambda (x) (* x x))
(list 1 2 3 4))
</div>
<script>
prompt("scheme-test-map", ["scheme-define-map"]);
</script>
<p> Now we can give a new definition of <tt>scale-list</tt> in terms of <tt>map</tt>:
<div id="scheme-define-scale-list-with-map">
(define (scale-list items factor)
(map (lambda (x) (* x factor))
items))
</div>
<script>
prompt("scheme-define-scale-list-with-map");
</script>
<p> <tt>map</tt> is an important construct, not only because it captures a common pattern, but because it establishes a higher level of abstraction in dealing with lists. In the original definition of <tt>scale-list</tt>, the recursive structure of the program draws attention to the element-by-element processing of the list. Defining <tt>scale-list</tt> in terms of <tt>map</tt> suppresses that level of detail and emphasizes that scaling transforms a list of elements to a list of results. The difference between the two definitions is not that the computer is performing a different process (it isn't) but that we think about the process differently. In effect, <tt>map</tt> helps establish an abstraction barrier that isolates the implementation of procedures that transform lists from the details of how the elements of the list are extracted and combined. Like the barriers shown in Figure 2-1, this abstraction gives us the flexibility to change the low-level details of how sequences are implemented, while preserving the conceptual framework of operations that transform sequences to sequences. Section 2-2-3 expands on this use of sequences as a framework for organizing programs.
<div class="exercise">
<p> <b>Exercise 2.21:</b> The procedure <tt>square-list</tt> takes a list of numbers as argument and returns a list of the squares of those numbers.
<div id="scheme-hidden-define-square-list">
(define (square-list items)
(map (lambda (x) (* x x))
items))
</div>
<script>
hidden_prompt("scheme-hidden-define-square-list", ["scheme-define-map"]);
</script>
<div id="scheme-test-square-list">
(square-list (list 1 2 3 4))
</div>
<script>
prompt("scheme-test-square-list", ["scheme-hidden-define-square-list"]);
</script>
<p> Here are two different definitions of <tt>square-list</tt>. Complete both of them by filling in the missing expressions:
<div id="scheme-ex-define-square-list">
(define (square-list items)
(if (null? items)
nil
(cons <??> <??>)))
(define (square-list-map items)
(map <??> <??>))
</div>
<script>
makeEditable("scheme-ex-define-square-list");
addOutput("scheme-ex-define-square-list");
editorOf["scheme-ex-define-square-list"].setOption("onBlur", function(){
var code = "{0} \n {1} \n (and (equal? (square-list '(1 2 3 4)) '(1 4 9 16)) (equal? (square-list-map '(1 2 3 4)) '(1 4 9 16)))".format(
editorOf["scheme-define-map"].getValue(),
editorOf["scheme-ex-define-square-list"].getValue());
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true\n") {
$_("scheme-ex-define-square-list-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-square-list-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$_("scheme-ex-define-square-list-output").append(res.slice(0,-1));
});
});
/*
(define (square-list items)
(if (null? items)
nil
(cons (* (car items) (car items))
(square-list (cdr items)))))
(define (square-list-map items)
(map (lambda (x) (* x x))
items))
*/
</script>
</div>
<p>
<div class="exercise">
<p> <b>Exercise 2.22:</b> Louis Reasoner tries to rewrite the first <tt>square-list</tt> procedure of Exercise 2-21 so that it evolves an iterative process:
<div id="scheme-define-louise-square-list">
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons (square (car things))
answer))))
(iter items nil))
</div>
<script>
prompt("scheme-define-louise-square-list", ["scheme-define-square"]);
</script>
<p> Unfortunately, defining <tt>square-list</tt> this way produces the answer list in the reverse order of the one desired. Why?
<p> Louis then tries to fix his bug by interchanging the arguments to <tt>cons</tt>:
<div id="scheme-define-louise-square-list-2">
(define (square-list items)
(define (iter things answer)
(if (null? things)
answer
(iter (cdr things)
(cons answer
(square (car things))))))
(iter items nil))
</div>
<script>
prompt("scheme-define-louise-square-list-2", ["scheme-define-square"]);
</script>
<p> This doesn't work either. Explain.
</div>
<p>
<div class="exercise">
<p> <b>Exercise 2.23:</b> The procedure <tt>for-each</tt> is similar to <tt>map</tt>. It takes as arguments a procedure and a list of elements. However, rather than forming a list of the results, <tt>for-each</tt> just applies the procedure to each of the elements in turn, from left to right. The values returned by applying the procedure to the elements are not used at all – <tt>for-each</tt> is used with procedures that perform an action, such as printing. For example,
<div id="scheme-test-for-each">
(for-each (lambda (x) (newline) (display x))
(list 57 321 88))
</div>
<script>
prompt("scheme-test-for-each", ["scheme-ex-define-for-each"]);
</script>
<p> should print <tt>57</tt>, <tt>321</tt> and <tt>88</tt>. The value returned by the call to <tt>for-each</tt> should be <tt>true</tt>. Give an implementation of <tt>for-each</tt>.
<div id="scheme-ex-define-for-each">
(define (for-each proc lst)
'your-code-here)
</div>
<script>
makeEditable("scheme-ex-define-for-each");
addOutput("scheme-ex-define-for-each");
editorOf["scheme-ex-define-for-each"].setOption("onBlur", function(){
var code = "{0} \n (for-each (lambda (x) (newline) (display x)) '(57 321 88))".format(
editorOf["scheme-ex-define-for-each"].getValue());
eval_scheme(code).then(function(res){
console.log(res);
var $output = $_("scheme-ex-define-for-each-output")
if (res.length >= 7 && res[res.length - 1] === "true\n" && res[res.length - 2].value === "88") {
$output.empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$output.empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$output.append(res.slice(0,-1));
compute("scheme-test-for-each");
});
});
/*
TODO: why does a map-style definition throw exceptions?
(define (for-each proc items)
(if (null? items)
nil
(begin (proc (car items))
(for-each proc (cdr items))
#t)))
*/
</script>
</div>
<h3> Hierarchical Structures </h3>
<p> The representation of sequences in terms of lists generalizes naturally to represent sequences whose elements may themselves be sequences. For example, we can regard the object <tt>((1 2) 3 4)</tt> constructed by
<div id="scheme-show-1-2-pair-3-4">
(cons (list 1 2) (list 3 4))
</div>
<script>
prompt("scheme-show-1-2-pair-3-4");
</script>
<p> as a list of three items, the first of which is itself a list, <tt>(1 2)</tt>. Indeed, this is suggested by the form in which the result is printed by the interpreter. Figure 2-5 shows the representation of this structure in terms of pairs.
<p> <img class='center' src='http://mitpress.mit.edu/sicp/full-text/book/ch2-Z-G-15.gif'>
<p style="text-align:center"> <b>Figure 2.5:</b> Structure formed by <tt>(cons (list 1 2) (list 3 4))</tt>.
<p> Another way to think of sequences whose elements are sequences is as <tt>trees</tt> . The elements of the sequence are the branches of the tree, and elements that are themselves sequences are subtrees. Figure 2-6 shows the structure in Figure 2-5 viewed as a tree.
<p> <img class='center' src='http://mitpress.mit.edu/sicp/full-text/book/ch2-Z-G-16.gif'>
<p style="text-align:center"> <b>Figure 2.6:</b> The list structure in Figure 2-5 viewed as a tree.
<p> Recursion is a natural tool for dealing with tree structures, since we can often reduce operations on trees to operations on their branches, which reduce in turn to operations on the branches of the branches, and so on, until we reach the leaves of the tree. As an example, compare the <tt>length</tt> procedure of section 2-2-1 with the <tt>count-leaves</tt> procedure, which returns the total number of leaves of a tree:
<div id="scheme-define-x">
(define x (cons (list 1 2) (list 3 4)))
</div>
<script>
prompt("scheme-define-x");
</script>
<p>
<div id="scheme-length-x">
(length x)
</div>
<script>
prompt("scheme-length-x", ["scheme-define-x"]);
</script>
<p>
<div id="scheme-count-leaves-x">
(count-leaves x)
</div>
<script>
prompt("scheme-count-leaves-x", ["scheme-define-x", "scheme-define-count-leaves"]);
</script>
<p>
<div id="scheme-list-x-x">
(list x x)
</div>
<script>
prompt("scheme-list-x-x", ["scheme-define-x"]);
</script>
<p>
<div id="scheme-length-list-x-x">
(length (list x x))
</div>
<script>
prompt("scheme-length-list-x-x", ["scheme-define-x"]);
</script>
<p>
<div id="scheme-count-leaves-list-x-x">
(count-leaves (list x x))
</div>
<script>
prompt("scheme-count-leaves-list-x-x", ["scheme-define-count-leaves", "scheme-define-x"]);
</script>
<p> To implement <tt>count-leaves</tt>, recall the recursive plan for computing <tt>length</tt>:
<ul>
<li>
<tt>length</tt> of a list <tt>x</tt> is 1 plus <tt>length</tt> of the <tt>cdr</tt> of <tt>x</tt>.
</li>
<li>
<tt>length</tt> of the empty list is 0.
</li>
</ul>
<p> <tt>count-leaves</tt> is similar. The value for the empty list is the same:
<ul>
<li>
<tt>count-leaves</tt> of the empty list is 0.
</li>
</ul>
<p> But in the reduction step, where we strip off the <tt>car</tt> of the list, we must take into account that the <tt>car</tt> may itself be a tree whose leaves we need to count. Thus, the appropriate reduction step is
<ul>
<li>
<tt>count-leaves</tt> of a tree <tt>x</tt> is <tt>count-leaves</tt> of the <tt>car</tt> of <tt>x</tt> plus <tt>count-leaves</tt> of the <tt>cdr</tt> of <tt>x</tt>.
</li>
</ul>
<p> Finally, by taking <tt>car</tt>s we reach actual leaves, so we need another base case:
<ul>
<li>
<tt>count-leaves</tt> of a leaf is 1.
</li>
</ul>
<p> To aid in writing recursive procedures on trees, Scheme provides the primitive predicate <tt>pair?</tt>, which tests whether its argument is a pair. Here is the complete procedure:<a name="footnote_link_2-13" class="footnote_link" href="#footnote_2-13">13</a>
<div id="scheme-define-count-leaves">
(define (count-leaves x)
(cond ((null? x) 0)
((not (pair? x)) 1)
(else (+ (count-leaves (car x))
(count-leaves (cdr x))))))
</div>
<script>
prompt("scheme-define-count-leaves");
</script>
<p>
<div class="exercise">
<p> <b>Exercise 2.24:</b> Suppose we evaluate the expression <tt>(list 1 (list 2 (list 3 4)))</tt>. Give the result printed by the interpreter, the corresponding box-and-pointer structure, and the interpretation of this as a tree (as in Figure 2-6).
</div>
<p>
<div class="exercise">
<p> <b>Exercise 2.25:</b> Give combinations of <tt>car</tt>s and <tt>cdr</tt>s that will pick 7 from each of the following lists. Represent the list as <tt>l</tt>.
<div id="scheme-ex-pick-7-medium">
(1 3 (5 7) 9)
</div>
<script>
equalp_answer("scheme-ex-pick-7-medium", "(car (cdr (car (cdr (cdr l)))))");
</script>
<div id="scheme-ex-pick-7-easy">
((7))
</div>
<script>
equalp_answer("scheme-ex-pick-7-easy", "(car (car l))");
</script>