HtDP Solution Set

Section 5


#| Problem 1|#

;temp: Number -> Symbol
; given a celcius temperature, return descriptive word
(define (temp c)
(cond
[(< c 10) 'Cold]
[(and (>= c 10) (< c 25)) 'Mild]
[(>= c 25) 'Warm]))

;TESTS
(temp 0)
"should be" 'Cold
(temp 10)
"should be" 'Mild
(temp 25)
"should be" 'Warm


Problem 2 (Solution):
;math-fun: Number Symbol -> Number
; produce square root or tangent of n if given appropriate s, otherwise n
(define (math-fun s n)
(cond
[(symbol=? s 'tangent) (tan n)]
[(symbol=? s 'squareroot) (sqrt n)]
[else n]))
 
;Tests
(math-fun 'tangent 22/7)
"should be" 0.001
(math-fun 'squareroot 64)
"should be" 8
(math-fun 'sin 3)
"should be" 3
 


Problem 3 (Solution):
;check-guess
;; check-guess : number number -> symbol
;; to determine whether guess is larger, smaller, or equal to target
 
(define (check-guess guess target)
(cond
[(= guess target) 'Perfect]
[(<= (abs (- guess target)) 10)
'WithinTen]
[(< guess target) 'TooSmall]
[(> guess target) 'TooLarge]))
 
(check-guess 1 1) "should be" 'Perfect
(check-guess 4 14) "should be" 'WithinTen
(check-guess 14 4) "should be" 'WithinTen
(check-guess 3 14) "should be" 'TooSmall
(check-guess 14 3) "should be" 'TooLarge
 


Problem 4 (Solution):
;knaves : Symbol Symbol -> Symbol
; return 'Yes if both inputs are 'Yes otherwise 'No
(define (knaves a b)
(cond
[(symbol=? a 'Yes)
(cond
[(symbol=? b 'Yes) 'Yes]
[else 'No])]
[else 'No]))
 
(knaves 'Yes 'Yes)
"should be" 'yes
(knaves 'Yes 'No)
"should be" 'no
(knaves 'No 'No)
"should be" 'no
(knaves 'No 'Yes)
"should be" 'no
 


Problem 5 (Solution):
;go : Symbol Number Number -> Number
; produce new location given direction, amount, and current location
(define (go cmd amt cpos)
(cond
[(symbol=? cmd 'Forward)
(cond
[(move-past-right-end? amt cpos) 99]
[else (+ cpos amt)])]
[else
(cond
[(move-past-left-end? amt cpos) 0]
[else (- cpos amt)])]))
 
;move-past-right-end? : Number Number -> Boolean
(define (move-past-right-end? amt cpos)
(> (+ amt cpos) 99))
 
;move-past-left-end? : Number Number -> Boolean
(define (move-past-left-end? amt cpos)
(< (- cpos amt) 0))
 
(go 'Forward 30 0)
"should be" 30
(go 'Backward 30 30)
"should be" 0
(go 'Forward 30 99)
"should be" 99
(go 'Backward 30 0)
"should be" 0
 
 



Jamie Raymond
Matthias Felleisen
 

23 september 2002