;;; Talk to Lauren Siegert. ;;; Reread 3.13 (define title "Functions are People, Too") (define description "") ;; STAGE COMPETITION ;; find-cat : List-of-symbols -> Boolean ;; is there 'cat in l ? (define (find-cat l) (cond [(empty? l) false] [else (or (symbol=? (first l) 'cat) (find-cat (rest l)))])) ;; find-dog : List-of-symbols -> Boolean ;; is there 'dog in l ? (define (find-dog l) (cond [(empty? l) false] [else (or (symbol=? (first l) 'dog) (find-dog (rest l)))])) ;; TESTS (equal? (find-cat '(elephant spider alligator)) false) (equal? (find-cat '(elephant cat alligator)) true) (equal? (find-dog '(elephant spider alligator)) false) (equal? (find-dog '(elephant dog alligator)) true) ;; --- ABSTRACT! --- ;; find : Symbol List-of-symbols -> Boolean ;; is there 'dog in l ? (define (find s l) (cond [(empty? l) false] [else (or (symbol=? (first l) s) (find s (rest l)))])) ;; Can we still define find-cat or find-dog ? (define (find-cat? l) (find 'cat l)) (define (find-dog? l) (find 'dog l)) ;; run tests, done. (equal? (find-cat '(elephant spider alligator)) false) (equal? (find-cat '(elephant cat alligator)) true) (equal? (find-dog '(elephant spider alligator)) false) (equal? (find-dog '(elephant dog alligator)) true) #| how did we get here? -- what are the differences -- add parameters to abstract out differences -- re-create original functions -- re-test to be sure BENEFIT: we can find all kinds of things now! |# (find 'elephant '(spider elephant)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; List-of-numbers -> Number (define (sum l) (cond [(empty? l) 0] [else (+ (first l) (sum (rest l)))])) ;; List-of-numbers -> Number (define (product l) (cond [(empty? l) 1] [else (* (first l) (product (rest l)))])) (equal? (sum '(1 2 3)) 6) (equal? (product '(1 2 3)) 6) ;; List-of-numbers Number OPERATION -> Number (define (process l n op) (cond [(empty? l) n] [else (op (first l) (process (rest l) n op))])) (define (sum l) (process l 0 +)) (define (product l) (process l 1 *)) (equal? (sum '(1 2 3)) 6) (equal? (product '(1 2 3)) 6) (process (list "hello" "world" "good bye") "" string-append) #| how did we get here? -- what are the differences -- add parameters to abstract out differences -- re-create original functions -- re-test to be sure BENEFIT: we can process all kinds of things now! DIFFERENCE: we use OPERATIONS as arguments not just numbers, images, lists, structures. |# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; STAGE COMPETITION #| A List-of-numbers is one of: -- empty -- (cons Number List-of-numbers) |# #| A List-of-symbols is one of: -- empty -- (cons Symbol List-of-symbols) |# ;; abstract #| A [List-of X] is one of: -- empty -- (cons X [List-of X]) |# ;; this is a new form of function, more next time.