Computing Square Roots = the y such that and y2=x The mathematical definition does not describe a procedure. Declarative : describing properties of things Imperative: describing how to do things (define (sqrt x) (the y (and (>= y 0) (= (square y) x))))
Newton’s Method Successive approximation Guess y for the square root of a number x Get a better guess by averaging y with x/y Guess Quotient Average 1 2/1=2 (1+2)/2=1.5 1.5 2/1.5=1.3333 (1.5+1.3333)/2=1.4167 1.4167 2/1.4167=1.4118 (1.4167+1.4118)=1.4142 1.4142 2/1.4142=...
(define (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (define (improve guess x) (average guess (/ x guess))) (define (average x y) (/ (+ x y) 2)) (define (good-enough? guess x) (< (abs (- (square guess) x)) 0.001)) (define (sqrt x) (sqrt-iter 1.0 x))
Decomposition of sqrt sqrt Sqrt-iter improve Good-enough? square abs average
Procedural Abstraction Procedures as “black boxes” Each procedure accomplishes an identifiable task. The details can be suppressed at the moment. ;; implementation #1 (define (square x) (* x x)) ;; implementation #2 (define (square x) (exp (double (log x)))) (define (double x) (+ x x))
Formal Parameters The meaning of a procedure should be independent of the parameter names (bound variables) used. The meaning of a procedure definition is unchanged if a bound variable is consistently renamed throughout the definition. If a variable is not bound, we say that it is free. In a procedure definition, the formal parameters have the body of the procedure as their scope. (define (square x) (* x x)) (define (square y) (* y y))