-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsection-1.3.1.rkt
98 lines (78 loc) · 2.05 KB
/
section-1.3.1.rkt
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
#lang sicp
(define (cube x)
(* x x x))
(define (sum term a next b)
(if (> a b)
0
(+ (term a) (sum term (next a) next b))))
; ex 1.29
(define (simpson f a b n)
(define h (/ (- b a) n))
(define (helper i) (+ a (* i h)))
(define (term i)
(cond
[(or (= i 0) (= i n)) (f (helper i))]
[(odd? i) (* 4 (f (helper i)))]
[(even? i) (* 2 (f (helper i)))]))
(* (/ h 3)
(sum term 0 inc n)))
; ex 1.30
(define (sum-iter term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (+ result (term a)))))
(iter a 0))
; ex 1.31.a
(define (product term a next b)
(cond
((or (= a 0) (= b 0)) 0)
((> a b) 1)
(else (* (term a) (product term (next a) next b)))))
(define (factorial n)
(cond
((= n 0) 1)
(else (product identity 1 inc n))))
(define (approximation-pi)
(define (term i)
(* (/ (* 2 i) (- (* 2 i) 1))
(/ (* 2 i) (+ (* 2 i) 1))))
(product term 1 inc 100))
; ex 1.31.b
(define (product-iter term a next b)
(define (product/a a accu)
(cond
[(or (= a 0) (= b 0)) 0]
[(> a b) accu]
[else (product/a (next a) (* (term a) accu))]))
(product/a a 1))
; ex 1.32.a
(define (accumulate combiner null-value term a next b)
(if (> a b)
null-value
(accumulate combiner
(combiner (term a) null-value)
term
(next a)
next
b)))
(define (sum/a term a next b)
(accumulate + 0 term a next b))
(define (product/a term a next b)
(accumulate * 1 term a next b))
; ex 1.32.b
(define (accumulate-iter combiner null-value term a next b)
(define (iter a accu)
(if (> a b)
accu
(iter (next a) (combiner (term a) accu))))
(iter a null-value))
; ex 1.33
(define (filtered-accumulate combiner null-value term a next b predicate)
(if (> a b)
null-value
(accumulate combiner
(if (predicate a) (combiner (term a) null-value) null-value)
term
(next a)
next b)))