;; compute the square of x - y (define (sq x y) (* (- x y) (- x y)) ) (sq 7 2) ;; expected 25 ;; the same definition without recomputing x - y (define (sq1 x y) (local ((define diff (- x y))) ;; local is followed by a list of defs (* diff diff)) ) (sq1 7 2) ;; expected 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))] ) ) (max-list (list 2 5 10 -2 8)) ;; expected 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] )) ] )) (max-list1 (list 2 5 10 -2 8)) ;; expected 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 (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)) ;; testing functions (check-expect (sq 7 2) 25) ;(check-expect (sq 3 2) 8) (check-within (/ 2 3) 0.33 0.34) (check-error (/ 2 0) "/: division by zero")