sicp/1_31.sch

34 lines
578 B
Scheme

(define (square x) (* x x))
(define (product-rec 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 product product-iter)
;(define product product-rec)
(define (fact n)
(product
(lambda (x) x)
1
(lambda (x) (+ x 1))
n))
; Approximation to pi/4
(define (pi-prod n)
(product
(lambda (a) (/ (* a (+ a 2)) (square (+ a 1))))
2
(lambda (a) (+ a 2))
n))