sicp 1.31

;递归求积
(define (product term a next b)
  (if (> a b)
      1
      (* (term a) (product term (next a) next b))))

;迭代求积
(define (product-iter term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (* result (term a)))))
  (iter a 1))

;阶乘
(define (factorial n)
  (product (lambda (x) x) 1 (lambda (x) (+ x 1)) n))

;求pi
(define (pi n)
  (define (next a)
    (+ a 2))
  (define (term x)
    (/ (* x (+ x 2))
       (* (+ x 1) (+ x 1))))
  (* 4 (product term 2.0 next (* 2 n))))
 

你可能感兴趣的:(SICP)