Tagged as HTDP, LISP, Self-Learning
Written on 2008-05-19 14:13:12
Well, here's Section 04.
;;1.
(define (is-between-3-and-7? n)
(and (> n 3) (<= n 10)))
;;2.
(define (is-between-3-7? n)
(and (> n 3) (< n 10)))
;;3.
(define (is-between-3-9? n)
(and (>= n 3) (< n 9)))
;;4.
(define (is-1-3-or-9-11? n)
(or (is-1-3? n) (is-9-11? n)))
(define (is-1-3? n)
(and (> n 1) (< n 3)))
(define (is-9-11? n)
(and (> n 9) (< n 11)))
;;alternate implementation in case the first smacks of premature optimization:
;;(both suffer from an ominous arbitrary function naming schema!)
(define (is-1-3-or-9-11? n)
(or (and (> n 1) (< n 3))
(and (> n 9) (< n 11))))
;;5.
(define (is-outside-1-3? n)
(not (and (>= n 1) (<= n 3))))
;; 1. | | | | | | | | | | |
;; -5 0 5
;; (-----)
;; Contract: in-interval-1? : number -> boolean
;; Purpose: To test if a number is between -3 and 0.
(in-interval-1? -2)
(and (< -3 -2) (< -2 0))
(and true true)
true
;;2. | | | | | | | | | | |
;; 0 5 10
;; --) (----------------
;; Contract: in-interval-2? : number -> boolean
;; Purpose: To test if a number is less than 1 or greater than 2.
(in-interval-2? -2)
(or (< -2 1) (> -2 2))
(or true false)
true
;;3. | | | | | | | | | | |
;; 0 5 10
;; --) (----------
;; Contract: in-interval-3? : number -> boolean
;; Purpose: To test if a number is less than 1 or greater than 5.
(in-interval-3? -2)
(not (and (<= 1 -2) (<= -2 5)))
(not (and false true))
(not false)
true
;;1.
(define (is-solution-1? x)
(= (+ (* 4 x) 2) 62))
;;2.
(define (is-solution-2? x)
(= (* (sqr x) 2) 102))
;;3.
(define (is-solution-3? x)
(= (+ 2 (* 4 (sqr x)) (* 6 x)) 462))
;; I don't know what specific test cases the authors are referring to for problems 2.2.1 - 2.2.4 so I'll just make up a few.
(= (Fahrenheit->Celsius 32) 0)
(= (dollar->euro 20) 12.8399) ;; as of 05/18/08
(= (triangle 5 2) 5)
(= (convert3 9 2 7) 729)
(define (interest x)
(cond ((<= x 1000) (* .04 x))
((<= x 5000) (* .045 x))
(else (* .05 x))))
(define (tax x)
(cond ((<= x 240) 0)
((<= x 480) (* .15 x))
(else (* .28 x))))
(define (netpay hrs)
(- (grosspay hrs) (tax (grosspay hrs))))
(define (grosspay hrs)
(* 12 hrs))
(define (pay-back charges)
(cond ((<= charges 500) (* .025 charges))
((<= charges 1500) (* .05 charges))
((<= charges 2500) (* .075 charges))
(else (* .01 charges))))
(define (how-many a b c)
(cond ((> (sqr b) (* 4 a c)) 2)
((= (sqr b) (* 4 a c)) 1)
((< (sqr b) (* 4 a c)) 0))) ;; or else 0))
;; (how-many 1 0 1) = 0