better (positivity aware) make rat
(define (make-rat n d) (if (< 0 d) (cons (- n) (- d)) (cons n d)))
(define (make-point x y) (cons x y)) (define (x-point pt) (car pt)) (define (y-point pt) (cdr pt)) (define (make-segment a b) (cons a b)) (define (start-segment seg) (car seg)) (define (end-segment seg) (cdr seg)) (define (print-point p) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) (define (print-segment seg) (newline) (print-point (start-segment seg)) (display "->") (print-point (end-segment seg))) (define (midpoint-segment seg) (define (average a b) (/ (+ a b) 2)) (make-point (average (x-point (start-segment seg)) (x-point (end-segment seg))) (average (y-point (start-segment seg)) (y-point (end-segment seg)))))
(define (make-rect p1 p2) (cons p1 p2)) (define (side-length rect point-getter) (let ((p1 (car rect)) (p2 (cdr rect))) (if (> (point-getter p1) (point-getter p2)) (- (point-getter p1) (point-getter p2)) (- (point-getter p2) (point-getter p1))))) (define (width rect) (side-length rect x-point)) (define (height rect) (side-length rect y-point)) (define (area rect) (* (width rect) (height rect))) (define (perim rect) (+ (* (width rect) 2) (* (height rect) 2))) (perim (make-rect (make-point 5 10) (make-point 1 1)))
26
(define (cdr z) (z (lambda (p q) q)))
(define (pow a b) (if (= 0 b) 1 (* a (pow a (- b 1))))) (define (crazy-cons a b) (* (pow 2 a) (pow 3 b))) (define (crazy-car x) (define (cc-iter x val) (if (= (remainder x 2) 1) val (cc-iter (/ x 2) (1+ val)))) (cc-iter x 0)) (define (crazy-cdr x) (define (cc-iter x val) (if (< x 2) val (cc-iter (/ x 3) (1+ val)))) (cc-iter (/ x (pow 2 (crazy-car x))) 0)) (crazy-car (crazy-cons 0 29)) (crazy-cdr (crazy-cons 30 7)) ;; only for positive integers
7
works for all tested input. there could be a crazy edge case im missing? what a nutty problem.
here's alyssa's code for reference over the next few exercises
(define (add-interval x y) (make-interval (+ (lower-bound x) (lower-bound y)) (+ (upper-bound x) (upper-bound y)))) (define (mul-interval x y) (let ((p1 (* (lower-bound x) (lower-bound y))) (p2 (* (lower-bound x) (upper-bound y))) (p3 (* (upper-bound x) (lower-bound y))) (p4 (* (upper-bound x) (upper-bound y)))) (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))) (define (div-interval x y) (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))) (define (make-interval a b) (cons a b))
(define (upper-bound a) (if (> (car a) (cdr a)) (car a) (cdr a))) (define (lower-bound a) (if (< (car a) (cdr a)) (car a) (cdr a))) (lower-bound (make-interval 4 5))
4
(define (sub-interval x y) (define (sml-sub a b) (if (< a b) (- b a) (- a b))) (make-interval (sml-sub (lower-bound x) (lower-bound-y)) (sml-sub (upper-bound x) (upper-bound y))))