Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created January 8, 2011 23:53
Show Gist options
  • Select an option

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

Select an option

Save ashmoran/771262 to your computer and use it in GitHub Desktop.
SICP exercise 2.1
(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-equal actual expected)
(assert (equal? actual expected)))
(define (make-rat n d)
(let ((g (gcd n d))
(sign (if (< d 0) -1 1)))
(cons
(* (/ n g) sign)
(* (/ d g) sign))))
(define one-half (make-rat 1 2))
(define one-third (make-rat 1 3))
(define (numer r) (car r))
(define (denom r) (cdr r))
(expect (numer one-half) to-equal 1)
(expect (denom one-half) to-equal 2)
(define (add-rat x y)
(make-rat
(+
(* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat
(* (numer x) (numer y))
(* (denom x) (denom y))))
(expect (add-rat one-half one-third) to-be-equal (make-rat 5 6))
(expect (mul-rat one-half one-third) to-be-equal (make-rat 1 6))
(expect (add-rat one-third one-third) to-be-equal (make-rat 2 3))
(expect (make-rat -1 3) to-be-equal (make-rat -1 3))
(expect (make-rat 1 -3) to-be-equal (make-rat -1 3))
(expect (make-rat -1 -3) to-be-equal (make-rat 1 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment