;;; IMPORTANT: use "intermediate student" level or above ;; subtract-and-square: number number -> number ;; compute the square of x - y (define (subtract-and-square x y) (* (- x y) (- x y)) ) (check-expect (subtract-and-square 7 2) 25) ;; the same definition without recomputing x - y (define (subtract-and-square1 x y) (local ((define diff (- x y))) ;; local is followed by a *list* of defs (* diff diff)) ) (check-expect (subtract-and-square1 7 2) 25) ;; diff is only visible within the expression it refers ;; max-list: a list of numbers -> number ;; finds the maximum element in a list ;; returns a very small number for an empty list (define (max-list alon) (cond [(empty? alon) -10000000000] ;base case returns a very small number - why? [(>= (first alon) (max-list (rest alon))) (first alon)] [else (max-list (rest alon))] ) ) (check-expect (max-list (list 2 5 10 -2 8)) 10) ;; max-list1: a list of numbers -> number ;; finds the maximum element in a list ;; returns a very small number for an empty list ;; uses "local" (define (max-list1 alon) (cond [(empty? alon) -10000000000] [else (local ((define fst (first alon)) ; compute only once (define max-rst (max-list1 (rest alon)))) ; compute only once (cond [(>= fst max-rst) fst] [else max-rst] )) ] )) (check-expect (max-list1 (list 2 5 10 -2 8)) 10) ;; some things you can do with 'local': ;; two functions that call each other (= mutually recursive) ;; is-odd? and is-even? depend on each other ;; IMPORTANT: the definitions are local, i.e. not visible outside of ;; "local" expression (local ((define (is-odd? n) ;; true if n is odd, false otherwise (cond [(= n 0) false] [else (is-even? (- n 1))])) (define (is-even? n) ;; true if n is even, false otherwise (cond [(= n 0) true] [else (is-odd? (- n 1))]))) (is-even? 5))