页面

2011-02-08

functional programming

My program to calculate the root of a number:

(define (sqrt n g)
(let* ((q (/ n g)) (a (/ (+ g q) 2.0)))
  (if (< (abs (- (* g g) n)) 0.00001)
      (if (< (abs (- g (floor g))) 0.00001)
             (floor g)
          g)
      (sqrt n a))))

The following is the program from SICP:

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
                 x)))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.00001))

(define (improve guess x)
  (average guess (/ x guess)))

(define (average x y)
  (/ (+ x y) 2))


Why is the SICP's better, from the view of functional programming? It is pure functional programming, while mine is not: There is `assignment operation' (let*) in mine.

没有评论: