Lindsey Kuper (lindseykuper) wrote,
Lindsey Kuper

improver? I hardly KNOW 'er!

Today and yesterday have been amazing for SICP checkins. I've finished 17 problems in the last 48 hours! Here's my answer to the last problem in chapter 1:

;;;; 1.46
;; ...Write a procedure /iterative-improve/ that takes two procedures as
;; arguments: a method for telling whether a guess is good enough and a method
;; for improving a guess.  /Iterative-improve/ should return as its value a
;; procedure that takes a guess as argument and keeps improving the guess
;; until it is good enough. Rewrite the /sqrt/ procedure of section 1.1.7 and
;; the /fixed-point/ procedure of section 1.3.3 in terms of
;; /iterative-improve/.

(define iterative-improve
  (lambda (good-enough? improve)
    (letrec ((improver (lambda (guess)
                         (if (good-enough? guess)
                             (improver (improve guess))))))
      (lambda (guess)
        (improver guess)))))

(define sqrt-using-iterative-improve
  (lambda (x)
    (define (improve guess)
      (average guess (/ x guess)))
    (define (good-enough? guess)
      (< (abs (- (square guess) x)) 0.001))
    ((iterative-improve good-enough? improve) 1.0)))

(define fixed-point-using-iterative-improve
  (lambda (f first-guess)
    (define (next guess)
      (f guess))
    (define (close-enough? guess)
      (< (abs (- guess (next guess))) tolerance))
    ((iterative-improve close-enough? next) first-guess)))

I just love writing stuff that looks like this, especially iterative-improve. Why write code that does something when you can write code that does anything? Whee!

There's just one problem left to finish -- the second half of this one. It's sticky, but I think I can get it done before the start of ICFP. You know, even if the contest is a wash, I'll feel good going into it knowing I can do all the exercises in the first chapter of this book. I feel so much stronger than I did four months ago.

Tags: programming

  • The Rust object system struggles to its feet (plus, a little brainteaser)

    When I last wrote about my work on Rust a month ago, I had just finished implementing some very basic support for extending Rust objects with new…

  • Redexing

    For the last two weeks at work, my little PLT Redex model of Rust has been taking shape. It's been a lot of fun. I started with lambda calculus,…

  • My first month at Mozilla

    As it turns out, I picked an interesting month to start working at Mozilla. On Tuesday of my second week, Firefox 4 launched, followed by the…

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded