;; **************************************** ;; * Csu 211 : 2/25/2008 ;; * Lecture #19 Code ;; * Abstracting Functions ;; **************************************** ;;** We introduce Parameterized Lists... ; +-----------------+ ; v | ;; (listof X) is either | ;; -- empty, or + ;; -- (cons X (listof X)) ;; contains?: LOA (Any -> Boolean) -> Boolean ;; Does the given list have something that the given function ;; returns true for (define (contains? loa f) (cond [(empty? loa) false] [(cons? loa) (or (f (first loa)) (contains? (rest loa) f))])) ;; A Few Tests (define alist (list 2 'a 5 (rectangle 4 5 'solid 'red) "string")) (check-expect (contains? alist symbol?) true) (check-expect (contains? alist image?) true) (check-expect (contains? alist string?) true) (check-expect (contains? alist boolean?) false) ;; Some random Structures (define-struct b (x y c)) (define-struct c (xx yy cc)) ;; draw: (list-of X) (X -> Number) (X -> Number) (X -> Color)-> Scene ;; Draw a list, given accessors for x/y of each X (define (draw lox f-x f-y f-c) (cond [(empty? lox) (empty-scene 400 400)] [(cons? lox) (local ((define fst (first lox))) (place-image (rectangle 10 10 'solid (f-c fst)) (f-x fst) (f-y fst) (draw (rest lox) f-x f-y f-c)))])) ;; Some different lists (define bl (list (make-b 103 134 'blue) (make-b 13 134 'blue) (make-b 37 121 'blue))) (define cl (list (make-c 103 14 'red) (make-c 13 34 'red) (make-c 37 12 'red))) ;; Test (draw bl b-x b-y b-c) (draw cl c-xx c-yy c-cc) ;; mult-4: Number -> Number (define (mult-4 n) (* n 4)) ;; mult-5: Number -> Number (define (mult-5 n) (* n 5)) ;; magic: LON (Number -> Number) -> LON (define (magic lon f) (cond [(empty? lon) empty] [(cons? lon) (cons (f (first lon)) (magic (rest lon) f))])) ;; lon-mult-5: (listof Number) -> (lsitof Number) ;; Multiply all the elements of this list by 5 (define (lon-mult-5 lon) (magic lon mult-5)) (check-expect (magic '(1 6) mult-4) '(4 24)) (check-expect (lon-mult-5 '(4 1 5 2)) '(20 5 25 10)) (generate-report)