;; 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 week6_tu_full) (read-case-sensitive #t) (teachpacks ((lib "image.ss" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.ss" "teachpack" "2htdp"))))) ; local ; interpretation rules: ; 1) see local -- don't look inside (i.e. don't evaluate) ; 2) lift definitions to top, keeping body of local (assign unique names ; if any collisions). ; in short: always look for the nearest containing definition to ; decide which variables refer to the same thing. ; Q1: What does the following set of statements return? (define (g x) (+ x (local [(define x 7)] (* 2 x)))) ; (map f alist) -- applies f to each element of alist, returns result ; (filter f alist) -- returns elements of alist for which f is true ; (foldr combine base alist) -- iteratively combines first element of ; list with result of same foldr on rest of list ; Q2: Use map, filter, or foldr and the function (sqrt ...) to compute ; the square roots of the following list: (define mylist (list 1 4 9 16 25)) (map sqrt mylist) ; Q3: Use map, filter, or foldr and (max ...) to compute the max of ; the following list (say you know list has non-negative entries): (define mylist2 (list 4 0 29 1 30 2)) ; lambda ; "anonymous" functions. ; (define (myfun x) (+ x 1)) ; equivalent to (define myfun (lambda (x) (+ x 1))) ; derivatives ; deriv : (number -> number) -> (number->number) ; computes the derivative of a given function (define (deriv f) (lambda (x) (/ (- (f (+ x delta)) (f (- x delta)) ) (* 2 delta)))) (define delta 0.00001) (define (twox x) (* 2 x)) ;(define sqr (* n n)) ; Q4: Use lambda, not, and odd?, along with one of map, filter, or ; foldr to select all of the even numbers from the following list: (define mylist3 (list 0 3 2 5 6)) ; Q5: Now, a barrage of signature/lambda questions. ; What are the signatures for: ;(define (f x y) (+ x y)) ; f : number number -> number ;(define (f g x y) (g x y)) ; f : (X Y -> Z) X Y -> Z ;(define (f g x) (lambda (y) (g x y))) ; f : (X Y -> Z) X -> (Y -> Z) ;(define (f g x y) (lambda (z) (cond [(and (g x) (g y)) 7] ; [else z]))) ; f : (X -> boolean) X X -> (Z -> number or Z)