; We are not programming in ALGOL, BASIC or PASCAL, we program LISP. ; Common Abstractions: ; 2A:(1m30s) Sum of all i, for every i smaller than B, starting at A. (DEFINE (SUM-INT A B) (IF (> A B) 0 (+ A (SUM-INT (1+ A) B)))) ; 2A:(3m41s) Sum the squares of i=A to B. (DEFINE (SUM-SQ A B) (IF (> A B) 0 (+ (SQUARE A) (SUM-SQ (1+ A) B)))) ; 2A:(7m5s) Generating pi as a series. (DEFINE (PI-SUM A B) (IF (> A B) 0 (+ (/ 1 (* A (+ A 2))) (PI-SUM (+ A 4) B)))) ; 2A:(9m) The general pattern: ; (define ( a b) ; (if (> a b) ; 0 ; (+ ( a) ; ( a) b)))) ; ; Generalizing (DEFINE (SUM TERM A NEXT B) (IF (> A B) 0 (+ (TERM A) (SUM TERM (NEXT A) NEXT B)))) (DEFINE (SUM-INT A B) (DEFINE (IDENTITY A) A) (SUM IDENTITY A 1+ B)) (DEFINE (SUM-SQ A B) (SUM SQUARE A 1+ B) (DEFINE (PI-SUM A B) (SUM (LAMBDA (I) (/ 1 (* I (+ 1 2)))) A (LAMBDA (I) (+ I 4)) B)) ; procedures named by symbols, they are not "special". ; BREAK 2A:(22m30s) ; Can the SQRT from Lecture 1A be expressed more clearly? ; 2A:(27m) (DEFINE (SQRT X) (FIXED-POINT (LAMBDA (Y) (AVERAGE (/ X Y) Y)) 1)) (DEFINE (FIXED-POINT F START) (DEFINE TOLERANCE 0.00001) (DEFINE (CLOSE-ENUF? U V) (< (ABS (- U V)) TOLERANCE)) (DEFINE (ITER OLD NEW) (IF (CLOSE-ENUF? OLD NEW) NEW (ITER NEW (F NEW)))) ;INITIALISATION (ITER START (F START))) ; 2A:(32m28s) Why this? Oscillation Problem. ; next try: (DEFINE (SQRT X) ;resulting from average-damping... (FIXED-POINT (AVERAGE-DAMP (LAMBDA (Y) (/ X Y))) 1)) (DEFINE AVERAGE-DAMP (LAMBDA (F) (LAMBDA (X) (AVERAGE (F X) X)))) ;or the same ... (DEFINE (AVERAGE-DAMP F) (LAMBDA (X) (AVERAGE (F X) X))) ;or ... (DEFINE (AVERAGE-DAMP F) (DEFINE (FOO X) (AVERAGE (F X) X)) FOO) ; BREAK 2A:(43m) ; including Newton's method. (DEFINE (SQRT X) (NEWTON (LAMBDA (Y) (- X (SQUARE Y))) 1)) (DEFINE (NEWTON F GUESS) (DEFINE DF (DERIV F)) (FIXED-POINT (LAMBDA (X) (- X (/ (F X) (DF X)))) GUESS)) (DEFINE DERIV (LAMBDA (F) (LAMBDA (X) (/ (- (F (+ X DX)) (F X)) DX)))) (DEFINE DX .0000000001) ; 2A:(53m50s) Now we have decomposed a mathematical problem and ; defined SQRT by wishful thinking. ; 2A:(56m) The first class citizen. ; 2A:(57m56s) A memorable question. Very important. ; (END)