Exercise 1.31

Read Exercise 1.31 ~ Solution


a) product, factorial and almost-pi

(define (product term a next b)
  (if (> a b)
      1
      (* (term a)
         (product term (next a) next b))))

(define (factorial n)
  (cond ((zero? n) 1)
        (else (product identity 1 inc n))))  

(define PI-LIMIT 1000)

(define (almost-pi)
  (define (pi-term k)
    (let* ((numer1 (* 2 k))  
           (denom (+ numer1 1))
           (numer2 (+ denom 1)))
      (/ (* numer1 numer2)
         (square denom))))
  (* 4.0 (product pi-term 1 inc PI-LIMIT)))

b) The iterative version, product-iter

(define (product-iter term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (* result (term a)))))
  (iter a 1))

Leave a comment