Chapter 1, Building Abstractions with Procedures
Section - Formulating Abstractions with Higher-Order Procedures
Exercise 1.31
This can easily be done by following the definition of sum.
Recursive process:
1
2
3
4
5
6
7
8
9
10
11
12
#lang sicp
(define (product term a next b)
(if
(> a b)
1
(*
(term a)
(product term (next a) next b)
)
)
)
Iterative Process:
1
2
3
4
5
6
7
8
(define (product-it term a next b)
(define (iter a result)
(if (> a b) result
(iter (next a) (* result (term a)))
)
)
(iter a 1)
)
Factorial using the above product procedure(n is number of terms):
1
2
3
4
5
(define (identity x) x)
(define (factorial n)
(product-it identity 1 inc n)
)
Function for computing pi:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(define (pi n)
(define (num k)
(cond
((even? k) (+ k 2))
(else (+ k 3))
)
)
(define (den k)
(cond
((even? k) (+ k 3))
(else (+ k 2))
)
)
(define (term k) (/ (num k) (den k)))
(* 4.0 (product term 0 inc n))
)