書中的scheme實現以下:
html
(define (square x) (* x x)) (define (abs x) (if (< x 0) (- x) x)) (define (average x y) (/ (+ x y) 2)) (define (improve guess x) (average guess (/ x guess))) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (sqrt x) (sqrt-iter 1.0 x))
common lisp 的實現以下:ide
(defun my-square (x) (* x x)) (defun my-abs (x) (if (< x 0) (- x) x)) (defun my-average (x y) (/ (+ x y) 2.0)) (defun my-improve (guess x) (my-average guess (/ x guess))) (defun good-enough-p (guess x) (< (my-abs (- (my-square guess) x)) 0.001)) (defun sqrt-iter (guess x) (if (good-enough-p guess x) guess (sqrt-iter (my-improve guess x) x))) (defun my-sqrt (x) (sqrt-iter 1.0 x))