-
Notifications
You must be signed in to change notification settings - Fork 1
/
Exercise 1.30 sum-iter.rkt
executable file
·79 lines (71 loc) · 1.59 KB
/
Exercise 1.30 sum-iter.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
; Exercise 1.30. 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:
; (define (sum term a next b)
; (define (iter a result)
; (if <??>
; <??>
; (iter <??> <??>)))
; (iter <??> <??>))
; SOLUTION
(define (sum-recur term a next b)
(if
(> a b) 0
(+ (term a) (sum-recur term (next a) next b))
)
)
(define (sum-iter term a next b)
(define (iter x result)
(if (> x b)
result
(iter (next x) (+ (term x) result))
)
)
(iter a 0)
)
(define (inc x)
(+ x 1)
)
(define (identity x)
x
)
; Tests
> (sum-recur identity 1 inc 1)
1
> (sum-recur identity 1 inc 10)
55
> (sum-recur identity 1 inc 100)
5050
> (sum-recur identity 1 inc 1000)
500500
> (sum-recur identity 1 inc 10000)
50005000
> (sum-recur identity 1 inc 100000)
5000050000
> (sum-recur identity 1 inc 1000000)
500000500000
> (sum-iter identity 1 inc 1000000)
500000500000
> (sum-iter identity 1 inc 10000000)
50000005000000
> (sum-iter identity 1 inc 100000000)
5000000050000000
> (sum-iter identity 1 inc 1000000000)
500000000500000000
> (sum-iter identity 1 inc 10000000000)
50000000005000000000
> (sum-iter identity 1 inc 1000000)
500000500000
> (sum-iter identity 1 inc 100000)
5000050000
> (sum-iter identity 1 inc 10000)
50005000
> (sum-iter identity 1 inc 1000)
500500
> (sum-iter identity 1 inc 100)
5050
> (sum-iter identity 1 inc 10)
55
> (sum-iter identity 1 inc 1)
1
>