function f(x) { 2*x; } let tolerance = 0.0001; function sqrt(x) { let guess = x/2; while(abs((guess*guess)-x) > tolerance) { guess = (guess + x/guess)/2; } return guess; } function fixed_point(f, guesss) { let next = f(guess); while(abs(guess - next) > tolerance) { guess = next; next = f(guess); } return next; } fixed_point(cos, 1); => .739; // sqrt(x) is a fixed point of f(y) = x/y; function sqrt(x) { fixed_point(function(y){x/y}, x/2); } sqrt(9); /* 4.5 2 4.5 2 ... That won't work. We can do better by preventing the guess from changing too much, by averaging it with the old value every time... */ function sqrt(x) { fixed_point(function(y){(y + x/y)/2}, x/2); } // cube root is a fixed point of f(y) -> x/y^2 function cbrt(x) { fixed_point(function(y){(y + x/y^2)/2}, x/2); } /* * Hmm. Some annoying repetition there ... */ function average_damp(f) {function(x){(x + f(x))/2}} function sqrt(x) { fixed_point(average_damp(function(y){x/y}), x/2); } function cbrt(x) { fixed_point(average_damp(function(y){x/y^2}), x/2); } function fourth_root(x) { fixed_point(average_damp(function(y){x/y^3}), x/2); } // Same problem as original sqrt! function fourth_root(x) { fixed_point(average_damp(average_damp(function(y){x/y^3})), x/2); } // That was easy! function one() { function(){1;} } function constant(x) { function(){x} } function range(a, b) { let x = a; return function() { let x1 = x; if(x1 > b) { return NULL; } else { x = a+1; return x1; } } } function integers() { let x = 1; function() { let a = x; x = x + 1; return a; } } function sum(f1, f2) { function() {f1() + f2();} } function filter(s, p) { function() { let x = s(); while(!p(x)) { x = s(); } return x; } } function range(a, b) { filter(integers(), function(x) {x >= a and x <= b}); } function fibs() { let x1 = 1; let x2 = 1; function() { let t = x1; x1 = x1 + x2; x2 = t; return t; } } function skip(s, n) { while(n > 0) { s(); n--; } return s; } function stream(s, transform) { let x = s; function() { let t = x; x = transform(x); return t; } } function integers() {stream(0, function(x){1 + x})} struct RectComplex { has real, imag; } (define (even-fibs n) (define (next k) (if (> k n) nil (let ((f (fib k))) (if (even? f) (cons f (next (+ k 1))) (next (+ k 1)))))) (next 0)) filter, accumulate, map,