;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname lect19-accepting-functions) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) ;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Practice -- possible quiz next time: ;;; How to write `draw-ghosts`: ;;; Assume we have a data-def'n for `ghost`, ;;; examples of the data (bound to `g1`, `g2`, `g3`), ;;; and a well-tested function: ; draw-ghost : ghost, image -> image ; ; Return an image like `bkgrnd`, ; but with `g` correctly drawn on into it. ; (define (draw-ghost g bkgrnd) ...) ;;;;;;;;;;;;; ; A list-of-ghost is: ; - empty, ; OR ; - (cons [ghost] [list-of-ghost]) ; Examples are: empty (cons g1 empty) (cons g3 (cons g2 (cons g1 empty))) ; The template of any function handling list-of-ghosts ; (define (func-for-log a-log) (cond [(empty? a-log) ...] [(cons? a-log) ...(first a-log) ...(func-for-log (rest a-log)) ])) ; draw-ghosts : list-of-ghost, image -> image ; ; Return an image like `bkgrnd`, ; but with all ghosts in `a-log` correctly drawn on into it. ; (define (draw-ghosts a-log bkgrnd) (cond [(empty? a-log) bkgrnd] [(cons? a-log) (draw-ghost (first a-log) (draw-ghosts (rest a-log) bkgrnd))])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Recall, from hw03b: ; mapsqr : list-of-numbers -> list-of-numbers ; Square each element of `nums`. ; (define (mapsqr nums) (cond [(empty? nums) empty] [(cons? nums) (cons (sqr (first nums)) (mapsqr (rest nums)))])) ;; What if I wanted to do something different to each number, ;; instead of squaring: ;; say, add 17? Or, test-if-its-odd (getting back a list of T/F)? ;; What if I have a list of strings, and want a list of all their lengths? ;; Or a list of strings, and I want a list of the first half of each? ; my-map : (alpha -> beta), (list-of alpha) -> (list-of beta) ; Return a list with the results of applying `f` ; to each element of `data`. ; (define (my-map f data) (cond [(empty? data) empty] [(cons? data) (cons (f (first data)) (my-map f (rest data)))])) (check-expect (my-map sqr (list 3 4 5)) (list 9 16 25)) (check-expect (my-map string-length (list "hello!" "bye" "aloha")) (list 6 3 5)) (define (first-half str) (substring str 0 (quotient (string-length str) 2))) (my-map first-half (list "hello!" "bye" "aloha")) (my-map (lambda (s) (substring s 0 (quotient (string-length s) 2))) (list "hello!" "bye" "aloha")) ;;;;;;;;;; Two flavors of `define`? No, just one! ; ;(define (add17 n) (+ n 17)) (define add17 (λ (n) (+ n 17))) (add17 100) ; Let's step through the following. ; (will ; (define n 45) (define m (+ 2 3)) (add17 (+ n m n m (* 6 7))) ; ; Note how (+ 2 3) is only computed once; ; `(define m 5)` is carried from one step to the next.