forked from ldct/isicp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1-3-hop.html
1785 lines (1405 loc) · 75.6 KB
/
1-3-hop.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 1.3 - Higher-Order Procedures</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='1-2-procedures.html'> <img src='images/chevron-left.svg' height=64 width=64> </a>
<a href='2-1-data.html'> <img src='images/chevron-right.svg' height=64 width=64> </a>
</span>
<br> <br>
<h2> Formulating Abstractions with Higher-Order Procedures </h2>
<hr>
<p> We have seen that procedures are, in effect, abstractions that describe compound operations on numbers independent of the particular numbers. For example, when we
<div id="scheme-define-cube">
(define (cube x) (* x x x))
</div>
<script>
prompt("scheme-define-cube");
</script>
<div id="scheme-define-square">
(define (square x)
(* x x))
</div>
<script>
hidden_prompt("scheme-define-square");
</script>
<p> we are not talking about the cube of a particular number, but rather about a method for obtaining the cube of any number. Of course we could get along without ever defining this procedure, by always writing expressions such as
<div id="scheme-cube-ex">
(* 3 3 3)
(* x x x)
(* y y y)
</div>
<script>
no_output_prompt("scheme-cube-ex");
</script>
<p> and never mentioning cube explicitly. This would place us at a serious disadvantage, forcing us to work always at the level of the particular operations that happen to be primitives in the language (multiplication, in this case) rather than in terms of higher-level operations. Our programs would be able to compute cubes, but our language would lack the ability to express the concept of cubing. One of the things we should demand from a powerful programming language is the ability to build abstractions by assigning names to common patterns and then to work in terms of the abstractions directly. Procedures provide this ability. This is why all but the most primitive programming languages include mechanisms for defining procedures.
<p> Yet even in numerical processing we will be severely limited in our ability to create abstractions if we are restricted to procedures whose parameters must be numbers. Often the same programming pattern will be used with a number of different procedures. To express such patterns as concepts, we will need to construct procedures that can accept procedures as arguments or return procedures as values. Procedures that manipulate procedures are called higher-order procedures. This section shows how higher-order procedures can serve as powerful abstraction mechanisms, vastly increasing the expressive power of our language.
<h3> Procedures as Arguments </h3>
<p> Consider the following three procedures. The first computes the sum of the integers from a through b:
<div id="scheme-define-sum-integers">
(define (sum-integers a b)
(if (> a b)
0
(+ a (sum-integers (+ a 1) b))))
</div>
<script>
prompt("scheme-define-sum-integers");
</script>
<p> The second computes the sum of the cubes of the integers in the given range:
<div id="scheme-define-sum-cubes">
(define (sum-cubes a b)
(if (> a b)
0
(+ (cube a) (sum-cubes (+ a 1) b))))
</div>
<script>
promptDep("scheme-define-sum-cubes", ["scheme-define-cube"]);
</script>
<p> The third computes the sum of a sequence of terms in the series
$$
\frac{1}{1 \cdot 3} + \frac{1}{5 \cdot 7} + \frac{1}{9 \cdot 11} + \cdots
$$
<p> which converges to $\pi/8$ (very slowly):<a name="footnote_link_1-49" class="footnote_link" href="#footnote_1-49">49</a>
<div id="scheme-define-pi-sum">
(define (pi-sum a b)
(if (> a b)
0
(+ (/ 1.0 (* a (+ a 2))) (pi-sum (+ a 4) b))))
</div>
<script>
prompt("scheme-define-pi-sum");
</script>
<p> These three procedures clearly share a common underlying pattern. They are for the most part identical, differing only in the name of the procedure, the function of a used to compute the term to be added, and the function that provides the next value of a. We could generate each of the procedures by filling in slots in the same template:
<div id="scheme-sum-template">
(define (<name> a b)
(if (> a b)
0
(+ (<term> a)
(<name> (<next> a) b))))
</div>
<script>
prompt("scheme-sum-template");
</script>
<p> The presence of such a common pattern is strong evidence that there is a useful abstraction waiting to be brought to the surface. Indeed, mathematicians long ago identified the abstraction of summation of a series and invented “sigma notation,” for example
$$
\sum_{n=a}^b f(n) = f(a) + \cdots + f(b)
$$
<p> to express this concept. The power of sigma notation is that it allows mathematicians to deal with the concept of summation itself rather than only with particular sums — for example, to formulate general results about sums that are independent of the particular series being summed.
<p> Similarly, as program designers, we would like our language to be powerful enough so that we can write a procedure that expresses the concept of summation itself rather than only procedures that compute particular sums. We can do so readily in our procedural language by taking the common template shown above and transforming the “slots” into formal parameters:
<div id="scheme-define-sum">
(define (sum term a next b)
(if (> a b)
0
(+ (term a)
(sum term (next a) next b))))
</div>
<script>
prompt("scheme-define-sum");
</script>
<p> Notice that sum takes as its arguments the lower and upper bounds a and b together with the procedures term and next. We can use sum just as we would any procedure. For example, we can use it (along with a procedure inc that increments its argument by 1) to define sum-cubes:
<div id="scheme-define-inc">
(define (inc n) (+ n 1))
</div>
<script>
prompt("scheme-define-inc");
</script>
<div id="scheme-define-sum-cubes-sum">
(define (sum-cubes a b)
(sum cube a inc b))
</div>
<script>
prompt("scheme-define-sum-cubes-sum");
depsOf["scheme-define-sum-cubes-sum"] = ["scheme-define-cube", "scheme-define-inc", "scheme-define-sum"];
</script>
<p> Using this, we can compute the sum of the cubes of the integers from 1 to 10:
<div id="scheme-sum-cubes-1-10">
(sum-cubes 1 10)
</div>
<script>
prompt("scheme-sum-cubes-1-10");
depsOf["scheme-sum-cubes-1-10"] = ["scheme-define-sum-cubes-sum"];
</script>
<p> With the aid of an identity procedure to compute the term, we can define sum-integers in terms of sum:
<div id="scheme-define-sum-integers-sum">
(define (identity x) x)
(define (sum-integers a b)
(sum identity a inc b))
</div>
<script>
prompt("scheme-define-sum-integers-sum");
depsOf["scheme-define-sum-integers-sum"] = ["scheme-define-inc", "scheme-define-sum"];
</script>
<p> Then we can add up the integers from 1 to 10:
<div id="scheme-sum-integers-1-10">
(sum-integers 1 10)
</div>
<script>
prompt("scheme-sum-integers-1-10");
depsOf["scheme-sum-integers-1-10"] = ["scheme-define-sum-integers-sum"];
</script>
<p> We can also define pi-sum in the same way:<a name="footnote_link_1-50" class="footnote_link" href="#footnote_1-50">50</a>
<div id="scheme-define-pi-sum-sum">
(define (pi-sum a b)
(define (pi-term x)
(/ 1.0 (* x (+ x 2))))
(define (pi-next x)
(+ x 4))
(sum pi-term a pi-next b))
</div>
<script>
prompt("scheme-define-pi-sum-sum");
depsOf["scheme-define-pi-sum-sum"] = ["scheme-define-sum"];
</script>
<p> Using these procedures, we can compute an approximation to :
<div id="scheme-pi-sum-pi">
(* 8 (pi-sum 1 1000))
</div>
<script>
prompt("scheme-pi-sum-pi");
depsOf["scheme-pi-sum-pi"] = ["scheme-define-pi-sum-sum"];
</script>
<p> Once we have sum, we can use it as a building block in formulating further concepts. For instance, the definite integral of a function f between the limits a and b can be approximated numerically using the formula
$$
\int_a^b = \left[f(a + \frac{dx}{2}) + f(a + dx + \frac{dx}{2}) + f(a + 2dx + \frac{dx}{2}) + \cdots\right] dx
$$
<p> for small values of dx. We can express this directly as a procedure:
<div id="scheme-define-integral">
(define (integral f a b dx)
(define (add-dx x) (+ x dx))
(* (sum f (+ a (/ dx 2.0)) add-dx b)
dx))
</div>
<script>
prompt("scheme-define-integral");
depsOf["scheme-define-integral"] = ["scheme-define-sum"];
</script>
<p>
<div id="scheme-integral-cube">
(integral cube 0 1 0.01)
</div>
<p>
<div id="scheme-integral-cube-finer">
(integral cube 0 1 0.001)
</div>
<script>
prompt("scheme-integral-cube");
depsOf["scheme-integral-cube"] = ["scheme-define-cube", "scheme-define-integral"];
prompt("scheme-integral-cube-finer");
depsOf["scheme-integral-cube-finer"] = ["scheme-define-cube", "scheme-define-integral"];
</script>
<p> (The exact value of the integral of cube between $0$ and $1$ is $1/4$.)
<div class="exercise">
<p> <b> Exercise 1.29. </b> Simpson's Rule is a more accurate method of numerical integration than the method illustrated above. Using Simpson's Rule, the integral of a function f between a and b is approximated as
$$
\frac{h}{3} \left[ y_0 + 4y_1 + 2y_2 + 4y_3 + 2y_4 + \cdots + 2y_{n-2} + 4y_{n-1} + y_n\right]
$$
<p> where $h = \frac{b - a}{n}$, for some even integer $n$, and $y_k = f(a + kh)$. (Increasing n increases the accuracy of the approximation.) Define a procedure that takes as arguments f, a, b, and n and returns the value of the integral, computed using Simpson's Rule. Use your procedure to integrate cube between 0 and 1 (with n = 100 and n = 1000), and compare the results to those of the integral procedure shown above.
<div id="scheme-define-feq">
(define (feq a b)
(< (abs (- a b))
0.000001))
</div>
<script>
hidden_prompt("scheme-define-feq")
</script>
<div id="scheme-ex-simpson-input">
(define (simpson f a b n)
'your-code-here)
</div>
<script>
/*
(define (simpson f a b n)
(define h (/ (- b a) n))
(define (inc x) (+ x 1))
(define (y k)
(f (+ a (* k h))))
(define (term k)
(* (cond ((odd? k) 4)
((or (= k 0) (= k n)) 1)
((even? k) 2))
(y k)))
(/ (* h (sum term 0 inc n)) 3))
*/
function simpson(f, a, b, n) {
var h = (b - a) / n;
function y(k) {
return f(a + k*h);
}
function coeff(i) {
if (i == 0 || i == n) {
return 1;
}
return [2,4][i % 2];
}
var sum = 0;
for (i = 0; i <= n; i++) {
sum += coeff(i) * y(i);
}
return sum * h / 3;
}
addOutput("scheme-ex-simpson-input");
makeEditable("scheme-ex-simpson-input").setOption("onBlur", function() {
function ss(f, fl, a, b, n) {
return "(feq (simpson {0} {1} {2} {3}) {4}) ".format(fl, a, b, n, simpson(f, a, b, n));
}
function poly(x) {
return 2 * x
}
polyl = "(lambda (x) (* 2 x))"
var code = editorOf["scheme-ex-simpson-input"].getValue() + "\n" + editorOf["scheme-define-feq"].getValue() + "\n" + editorOf["scheme-define-sum"].getValue() +
"(and " + ss(poly,polyl,2,3,10) +
ss(poly,polyl,4,5,8) +
ss(poly,polyl,2,10,12) + ") "
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true") {
$_("scheme-ex-simpson-input-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-simpson-input-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
}
$_("scheme-ex-simpson-input-output").append(res.slice(0,-1));
});
});
</script>
</div>
<p>
<div class="exercise">
<p> <b> Exercise 1.30. </b> The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:
<div id="scheme-ex-sum-iter">
(define (sum term a next b)
(define (iter a result)
(if <??>
<??>
(iter <??> <??>)))
(iter <??> <??>))
</div>
<script>
addOutput("scheme-ex-sum-iter");
makeEditable("scheme-ex-sum-iter").setOption("onBlur", function() {
var code = editorOf["scheme-ex-sum-iter"].getValue() + "\n" +
"(= (sum (lambda (x) (* x x x)) 1 (lambda (n) (+ n 1)) 10) 3025)";
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true") {
$_("scheme-ex-sum-iter-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-sum-iter-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
$_("scheme-ex-sum-iter-output").append(res);
}
});
});
</script>
</div>
<p>
<div class="exercise">
<p> <b> Exercise 1.31. </b>
<p> The sum procedure is only the simplest of a vast number of similar abstractions that can be captured as higher-order procedures.<a name="footnote_link_1-51" class="footnote_link" href="#footnote_1-51">51</a> Write an analogous procedure called product that returns the product of the values of a function at points over a given range. Try both a recursive and an iterative approach. Show how to define factorial in terms of product. Also use product to compute approximations to using the formula<a name="footnote_link_1-52" class="footnote_link" href="#footnote_1-52">52</a>
$$
\frac{\pi}{4} = \frac{2 \cdot 4 \cdot 4 \cdot 6 \cdot 6 \cdot 8 \cdots}{3 \cdot 3 \cdot 5 \cdot 5 \cdot 7 \cdot 7 \cdots}
$$
<div id="scheme-ex-define-product">
(define (product term a next b)
'your-code-here)
</div>
<script>
addOutput("scheme-ex-define-product");
makeEditable("scheme-ex-define-product").setOption("onBlur", function() {
var code = editorOf["scheme-ex-define-product"].getValue() + "\n" +
"(= (product (lambda (x) (* x x)) 1 (lambda (n) (+ n 1)) 5) 14400)"
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true") {
$_("scheme-ex-define-product-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-product-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
$_("scheme-ex-define-product-output").append(res);
}
});
});
/*
(define (product term a next b)
(if (> a b)
1
(* (term a)
(product term (next a) next b))))
*/
</script>
</div>
<p>
<div class="exercise">
<p> <b> Exercise 1.32. </b>
<p> Show that sum and product (exercise 1.31) are both special cases of a still more general notion called accumulate that combines a collection of terms, using some general accumulation function:
<div id="scheme-accumulate-signature">
(accumulate combiner null-value term a next b)
</div>
<script>
no_output_frozen_prompt("scheme-accumulate-signature");
</script>
<p> Accumulate takes as arguments the same term and range specifications as sum and product, together with a combiner procedure (of two arguments) that specifies how the current term is to be combined with the accumulation of the preceding terms and a null-value that specifies what base value to use when the terms run out. Write accumulate and show how sum and product can both be defined as simple calls to accumulate. Write two procedures, one that generates a recursive process and one iterative.
<div id="scheme-ex-define-accumulate">
(define (accumulate combiner null-value term a next b)
'your-code-here)
</div>
<script>
addOutput("scheme-ex-define-accumulate");
makeEditable("scheme-ex-define-accumulate").setOption("onBlur", function() {
var code = editorOf["scheme-ex-define-accumulate"].getValue() + "\n" +
"(= (accumulate + 0 (lambda (x) (* x x)) 1 (lambda (n) (+ n 1)) 5) 55)"
eval_scheme(code).then(function(res){
if (res[res.length - 1] === "true") {
$_("scheme-ex-define-accumulate-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-accumulate-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
$_("scheme-ex-define-accumulate-output").append(res);
}
});
});
/*
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumulate combiner null-value term (next a) next b))))
*/
</script>
</div>
<p>
<div class="exercise">
<p> <b> Exercise 1.33. </b> You can obtain an even more general version of accumulate (exercise 1.32) by introducing the notion of a filter on the terms to be combined. That is, combine only those terms derived from values in the range that satisfy a specified condition. The resulting filtered-accumulate abstraction takes the same arguments as accumulate, together with an additional predicate of one argument that specifies the filter. Write filtered-accumulate as a procedure.
<div id="scheme-ex-define-filtered-accumulate">
(define (filtered-accumulate combiner null-value term a next b filter?)
'your-code-here)
</div>
<script>
addOutput("scheme-ex-define-filtered-accumulate");
makeEditable("scheme-ex-define-filtered-accumulate").setOption("onBlur", function() {
var code = editorOf["scheme-ex-define-filtered-accumulate"].getValue() + "\n" +
"(= (filtered-accumulate + 0 (lambda (x) (* x x)) 1 (lambda (n) (+ n 1)) 5 (lambda (x) #t)) 55)"
eval_scheme(code).then(function(res){
if (res[res.length] === "true") {
$_("scheme-ex-define-filtered-accumulate-output").empty().append($("<div class='right-answer'> \u2713 </div>"));
} else {
$_("scheme-ex-define-filtered-accumulate-output").empty().append($("<div class='wrong-answer'> \u2717 </div>"));
$_("scheme-ex-define-filtered-accumulate-output").append(res);
}
});
});
/*
(define (filtered-accumulate combiner null-value term a next b filter?)
(cond ((> a b) null-value)
((filter? a) (combiner (term a)
(filtered-accumulate combiner null-value term (next a) next b filter?)))
(else (filtered-accumulate combiner null-value term (next a) next b filter?))))
*/
</script>
<p> Show how to express the following using filtered-accumulate:
<ol style="list-style-type: lower-alpha">
<li>
<p> the sum of the squares of the prime numbers in the interval a to b (assuming that you have a <tt>prime?</tt> predicate already written)
</li>
<li>
<p> the product of all the positive integers less than n that are relatively prime to n (i.e., all positive integers $ < n$ such that $\text{GCD}(i,n) = 1$).
</li>
</ol>
</div>
<h3> Constructing Procedures Using Lambda </h3>
<p> In using sum as in section 1.3.1, it seems terribly awkward to have to define trivial procedures such as pi-term and pi-next just so we can use them as arguments to our higher-order procedure. Rather than define pi-next and pi-term, it would be more convenient to have a way to directly specify “the procedure that returns its input incremented by 4” and “the procedure that returns the reciprocal of its input times its input plus 2.” We can do this by introducing the special form lambda, which creates procedures. Using lambda we can describe what we want as
<div id="scheme-lambda-plus-4">
(lambda (x) (+ x 4))
</div>
<script>
prompt("scheme-lambda-plus-4");
</script>
<p> and
<div id="scheme-lambda-inv-poly">
(lambda (x) (/ 1.0 (* x (+ x 2))))
</div>
<script>
prompt("scheme-lambda-inv-poly");
</script>
<p> Then our pi-sum procedure can be expressed without defining any auxiliary procedures as
<div id="scheme-define-pi-sum-lambda">
(define (pi-sum a b)
(sum (lambda (x) (/ 1.0 (* x (+ x 2))))
a
(lambda (x) (+ x 4))
b))
</div>
<script>
prompt("scheme-define-pi-sum-lambda");
depsOf["scheme-define-pi-sum-lambda"] = ["scheme-define-sum"];
</script>
<p> Again using lambda, we can write the integral procedure without having to define the auxiliary procedure add-dx:
<div id="scheme-define-integral-lambda">
(define (integral f a b dx)
(* (sum f
(+ a (/ dx 2.0))
(lambda (x) (+ x dx))
b)
dx))
</div>
<script>
prompt("scheme-define-integral-lambda");
depsOf["scheme-define-integral-lambda"] = ["scheme-define-sum"];
</script>
<p> In general, lambda is used to create procedures in the same way as define, except that no name is specified for the procedure:
<div id="scheme-lambda-syntax">
(lambda (<formal-parameters>) <body>)
</div>
<script>
makeStatic("scheme-lambda-syntax");
</script>
<p> The resulting procedure is just as much a procedure as one that is created using define. The only difference is that it has not been associated with any name in the environment. In fact,
<div id="scheme-define-plus4">
(define (plus4 x) (+ x 4))
</div>
<script>
prompt("scheme-define-plus4");
</script>
<p> is equivalent to
<div id="scheme-define-plus4-lambda">
(define plus4 (lambda (x) (+ x 4)))
</div>
<script>
prompt("scheme-define-plus4-lambda");
</script>
<p> We can read a lambda expression as follows:
<p><p><tt> (lambda (x) (+ x 4))<br>
<img src="http://mitpress.mit.edu/sicp/full-text/book/book-Z-G-D-16.gif" border="0"> <img src="http://mitpress.mit.edu/sicp/full-text/book/book-Z-G-D-16.gif" border="0"> <img src="http://mitpress.mit.edu/sicp/full-text/book/book-Z-G-D-16.gif" border="0"> <img src="http://mitpress.mit.edu/sicp/full-text/book/book-Z-G-D-16.gif" border="0"> <img src="http://mitpress.mit.edu/sicp/full-text/book/book-Z-G-D-16.gif" border="0"><br>
the procedure of an argument <tt>x</tt> that adds <tt>x</tt> and 4<br>
</tt><p><p>
<p> Like any expression that has a procedure as its value, a lambda expression can be used as the operator in a combination such as
<div id="scheme-apply-lambda">
((lambda (x y z) (+ x y (square z))) 1 2 3)
</div>
<script>
prompt("scheme-apply-lambda");
depsOf["scheme-apply-lambda"] = ["scheme-define-square"];
</script>
<p> or, more generally, in any context where we would normally use a procedure name.<a name="footnote_link_1-53" class="footnote_link" href="#footnote_1-53">53</a>
<h4> Using let to create local variables </h4>
<p> Another use of <tt>lambda</tt> is in creating local variables. We often need local variables in our procedures other than those that have been bound as formal parameters. For example, suppose we wish to compute the function
$$
f(x,y) = x (1 + xy)^2 + y(1-y) + (1 + xy)(1 - y)
$$
<p> which we could also express as
\begin{align}
a &= 1 + xy \\
b &= 1 - y \\
f(x,y) &= xa^2 + yb + ab
\end{align}
<p> In writing a procedure to compute $f$ we would like to include as local variables not only $x$ and $y$ but also the names of intermediate quantities like $a$ and $b$. One way to accomplish this is to use an auxiliary procedure to bind the local variables:
<div id="scheme-define-f-helpers">
(define (f x y)
(define (f-helper a b)
(+ (* x (square a))
(* y b)
(* a b)))
(f-helper (+ 1 (* x y))
(- 1 y)))
</div>
<script>
prompt("scheme-define-f-helpers");
depsOf["scheme-define-f-helpers"] = ["scheme-define-square"];
</script>
<p> Of course, we could use a <tt>lambda</tt> expression to specify an anonymous procedure for binding our local variables. The body of <tt>f</tt> then becomes a single call to that procedure:
<div id="scheme-define-f-lambda">
(define (f x y)
((lambda (a b)
(+ (* x (square a))
(* y b)
(* a b)))
(+ 1 (* x y))
(- 1 y)))
</div>
<script>
prompt("scheme-define-f-lambda");
depsOf["scheme-define-f-lambda"] = ["scheme-define-square"];
</script>
<p> This construct is so useful that there is a special form called <tt>let</tt> to make its use more convenient. Using <tt>let</tt>, the <tt>f</tt> procedure could be written as
<div id="scheme-define-f-let">
(define (f x y)
(let ((a (+ 1 (* x y)))
(b (- 1 y)))
(+ (* x (square a))
(* y b)
(* a b))))
</div>
<script>
prompt("scheme-define-f-let");
depsOf["scheme-define-f-let"] = ["scheme-define-square"];
</script>
<p> The general form of a <tt>let</tt> expression is
<div id="scheme-let-syntax">
(let ((<var1> <exp1>)
(<var2> <exp2>)
...
(<varN> <varN>))
<body>)
</div>
<script>
makeStatic("scheme-let-syntax");
</script>
<p> which can be thought of as saying
<pre>
let <var_1> have the value <exp_1> and
<var_2> have the value <exp_2> and
...
<var_n> have the value <exp_n>
in <body>
</pre>
<p> The first part of the <tt>let</tt> expression is a list of name-expression pairs. When the <tt>let</tt> is evaluated, each name is associated with the value of the corresponding expression. The body of the <tt>let</tt> is evaluated with these names bound as local variables. The way this happens is that the <tt>let</tt> expression is interpreted as an alternate syntax for
<div id="scheme-let-expanded-syntax">
((lambda (<var_1> ... <var_n>)
<body>)
<exp_1>
...
<exp_n>)
</div>
<script>
makeStatic("scheme-let-expanded-syntax");
</script>
<p> No new mechanism is required in the interpreter in order to provide local variables. A <tt>let</tt> expression is simply syntactic sugar for the underlying <tt>lambda</tt> application.
<p> We can see from this equivalence that the scope of a variable specified by a <tt>let</tt> expression is the body of the <tt>let</tt>. This implies that:
<ul>
<li>
<tt>let</tt> allows one to bind variables as locally as possible to where they are to be used. For example, if the value of <tt>x</tt> is 5, the value of the expression
<div id="scheme-let-close-prelude">
(define x 5)
</div>
<div id="scheme-let-close">
(+ (let ((x 3))
(+ x (* x 10)))
x)
</div>
<p> is <span id="scheme-let-close-output" class="output"> </span>
<script>
hidden_prompt("scheme-let-close-prelude");
no_output_prompt("scheme-let-close", ["scheme-let-close-prelude"]);
editorOf["scheme-let-close"].setOption("onBlur", function(){
eval_editor("scheme-let-close").then(function(res){
$_("scheme-let-close-output").empty().append($("<span>" + res + "</span>"));
});
});
</script>
<p> Here, the <tt>x</tt> in the body of the <tt>let</tt> is 3, so the value of the <tt>let</tt> expression is 33. On the other hand, the <tt>x</tt> that is the second argument to the outermost <tt>+</tt> is still 5.
</li>
<li>
<p> The variables' values are computed outside the <tt>let.</tt> This matters when the expressions that provide the values for the local variables depend upon variables having the same names as the local variables themselves. For example, if the value of <tt>x</tt> is 2, the expression
<div id="scheme-let-shadow-prelude">
(define x 2)
</div>
<script>
hidden_prompt("scheme-let-shadow-prelude");
</script>
<div id="scheme-let-shadow">
(let ((x 3)
(y (+ x 2)))
(* x y))
</div>
<script>
no_output_prompt("scheme-let-shadow", ["scheme-let-shadow-prelude"]);
editorOf["scheme-let-shadow"].setOption("onBlur", function(){
eval_editor("scheme-let-shadow").then(function(res){
$_("scheme-let-shadow-output").empty().append($("<span>" + res + "</span>"));
});
});
</script>
<p> will have the value <span id="scheme-let-shadow-output" class="output"></span> because, inside the body of the <tt>let, x</tt> will be 3 and <tt>y</tt> will be 4 (which is the outer <tt>x</tt> plus 2).
</li>
</ul>
<p> Sometimes we can use internal definitions to get the same effect as with <tt>let.</tt> For example, we could have defined the procedure <tt>f</tt> above as
<div id="scheme-define-f-close-define">
(define (f x y)
(define a (+ 1 (* x y)))
(define b (- 1 y))
(+ (* x (square a))
(* y b)
(* a b)))
</div>
<script>
prompt("scheme-define-f-close-define");
depsOf["scheme-define-f-close-define"] = ["scheme-define-square"];
</script>
<p> We prefer, however, to use <tt>let</tt> in situations like this and to use internal <tt>define</tt> only for internal procedures.<a name="footnote_link_1-54" class="footnote_link" href="#footnote_1-54">54</a>
<div class="exercise">
<p> <b> Exercise 1.34: </b> Suppose we define the procedure
<div id="scheme-define-f-g2">
(define (f g)
(g 2))
</div>
<script>
prompt("scheme-define-f-g2");
</script>
<p> Then we have
<div id="scheme-f-square">
(f square)
</div>
<script>
prompt("scheme-f-square", ["scheme-define-f-g2", "scheme-define-square"]);
</script>
<div id="scheme-f-lambda-poly">
(f (lambda (z) (* z (+ z 1))))
</div>
<script>
prompt("scheme-f-lambda-poly", ["scheme-define-f-g2"]);
</script>
<p> What happens if we (perversely) ask the interpreter to evaluate the combination
<tt>(f f)?</tt> Explain.
<div id="scheme-ex-f-f-mcq"></div>
<script>
makeMCQ("scheme-ex-f-f-mcq",
["An error occurs, because <tt>2</tt> is not a procedure."],
["It evaluates to <tt>(2 2)</tt>, which is <tt>4</tt>.",
"The interpreter enters an infinite loop.",
"The result is <tt>2</tt>."
]);
</script>
</div>
<h3> Procedures as General Methods </h3>
<p> We introduced compound procedures in section @ref{1-1-4} as a mechanism for abstracting patterns of numerical operations so as to make them independent of the particular numbers involved. With higher-order procedures, such as the <tt>integral</tt> procedure of section @ref{1-3-1}, we began to see a more powerful kind of abstraction: procedures used to express general methods of computation, independent of the particular functions involved. In this section we discuss two more elaborate examples — general methods for finding zeros and fixed points of functions — and show how these methods can be expressed directly as procedures.
<h4> Finding roots of equations by the half-interval method </h4>
<p> The <em> half-interval method </em> is a simple but powerful technique for finding roots of an equation <em> f(x) = 0 </em>, where <em> f </em> is a continuous function. The idea is that, if we are given points $ a $ and $ b $ such that $ f(a) < 0 < f (b) $, then $ f $ must have at least one zero between $ a $ and $ b $. To locate a zero, let $ x $ be the average of $ a $ and $ b $ and compute $ f(x) $. If $ f(x) > 0 $, then $ f $ must have a zero between $ a $ and $ x $. If $ f(x) < 0$, then $ f $ must have a zero between $ x $ and $ b $. Continuing in this way, we can identify smaller and smaller intervals on which $ f $ must have a zero. When we reach a point where the interval is small enough, the process stops. Since the interval of uncertainty is reduced by half at each step of the process, the number of steps required grows as $\Theta(\log(L/T))$, where $L$ is the length of the original interval and $T$ is the error tolerance (that is, the size of the interval we will consider “small enough”). Here is a procedure that implements this strategy:
<div id="scheme-define-average">
(define (average x y)
(/ (+ x y)
2))
</div>
<script>
hidden_prompt("scheme-define-average");
</script>
<div id="scheme-define-search">
(define (search f neg-point pos-point)
(let ((midpoint (average neg-point pos-point)))
(if (close-enough? neg-point pos-point)
midpoint
(let ((test-value (f midpoint)))
(cond ((positive? test-value)
(search f neg-point midpoint))
((negative? test-value)
(search f midpoint pos-point))
(else midpoint))))))
</div>
<script>
prompt("scheme-define-search");
depsOf["scheme-define-search"] = ["scheme-define-average", "scheme-define-close-enough"];
</script>
<p> We assume that we are initially given the function <em> f </em> together with points at which its values are negative and positive. We first compute the midpoint of the two given points. Next we check to see if the given interval is small enough, and if so we simply return the midpoint as our answer. Otherwise, we compute as a test value the value of <em> f </em> at the midpoint. If the test value is positive, then we continue the process with a new interval running from the original negative point to the midpoint. If the test value is negative, we continue with the interval from the midpoint to the positive point. Finally, there is the possibility that the test value is 0, in which case the midpoint is itself the root we are searching for.
<p> To test whether the endpoints are “close enough” we can use a procedure similar to the one used in section 1-1-7 for computing square roots:<a name="footnote_link_1-55" class="footnote_link" href="#footnote_1-55">55</a>
<div id="scheme-define-close-enough">
(define (close-enough? x y)
(< (abs (- x y)) 0.001))
</div>
<script>
prompt("scheme-define-close-enough");
</script>
<p> <tt>search</tt> is awkward to use directly, because we can accidentally give it points at which <em> f </em>'s values do not have the required sign, in which case we get a wrong answer. Instead we will use <tt>search</tt> via the following procedure, which checks to see which of the endpoints has a negative function value and which has a positive value, and calls the <tt>search</tt> procedure accordingly. If the function has the same sign on the two given points, the half-interval method cannot be used, in which case the procedure signals an error.<a name="footnote_link_1-56" class="footnote_link" href="#footnote_1-56">56</a>
<div id="scheme-define-negative-positive">
(define (negative? x)
(< x 0))
(define (positive? x)
(> x 0))
</div>
<script>
hidden_prompt("scheme-define-negative-positive")
</script>
<div id="scheme-define-half-interval-method">
(define (half-interval-method f a b)
(let ((a-value (f a))
(b-value (f b)))
(cond ((and (negative? a-value) (positive? b-value))
(search f a b))
((and (negative? b-value) (positive? a-value))