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

  • SFoT #35

    Shoebox Full of Tapes #35: Bigger Plans. One not-so-great thing about always playing music by yourself, or even with one other person, is that…

  • SFoT #34

    Shoebox Full of Tapes #34: Leaving Chicago. You know, that whole "monthly podcast of songs I'm working on" description is just getting more…

  • SFoT #33

    Shoebox Full of Tapes #33: The glass, all empty. (And so is this one, it turns out. And this one's close, just missing a couple lines out of…

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded