Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created January 7, 2011 22:01
Show Gist options
  • Select an option

  • Save ashmoran/770191 to your computer and use it in GitHub Desktop.

Select an option

Save ashmoran/770191 to your computer and use it in GitHub Desktop.
SICP exercise 1.31
(define (expect actual expectation expected)
(display "• ")
(display actual)
(display " should equal ")
(display expected)
(display ": ")
(expectation actual expected)
(display "pass\n")
)
(define (to-equal actual expected)
(assert (= actual expected)))
(define (to-be-close actual expected)
(assert
(and
(> actual (- expected 0.0001))
(< actual (+ expected 0.0001)))))
(define (to-be actual expected)
(if expected
(assert actual)
(assert (not actual))))
(define (product term a next b)
(if (> a b)
1
(* (term a) (product term (next a) next b))))
(define (product-integers a b)
(product identity a inc b))
(define (identity x) x)
(define (inc n)
(+ n 1))
(expect (product-integers 1 1) to-equal 1)
(expect (product-integers 1 2) to-equal 2)
(expect (product-integers 1 3) to-equal 6)
(expect (product-integers 2 3) to-equal 6)
(define (product-iter term a next b)
(define (iter a result)
(if (> a b)
result
(iter (next a) (* result (term a)))))
(iter a 1))
(define (product-integers-iter a b)
(product-iter identity a inc b))
(expect (product-integers-iter 1 1) to-equal 1)
(expect (product-integers-iter 1 2) to-equal 2)
(expect (product-integers-iter 1 3) to-equal 6)
(expect (product-integers-iter 2 3) to-equal 6)
(define (factorial n)
(product identity 1 inc n))
(expect (factorial 1) to-equal 1)
(expect (factorial 2) to-equal 2)
(expect (factorial 3) to-equal 6)
(expect (factorial 4) to-equal 24)
(expect (factorial 5) to-equal 120)
(define (pi-by-four)
(define (pi-by-four-term n)
(/ (* (- n 1) (+ n 1)) (square n)))
(define (inc-by-two n)
(+ n 2))
(define (square n)
(* n n))
(product-iter pi-by-four-term 3.0 inc-by-two 100000))
(expect (* (pi-by-four) 4) to-be-close 3.1416)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment