; Examples to illustrate closures. (define (book-sales book) (cadr book)) ; Return a list of all books with at least THRESHOLD copies sold. (define (best-selling-books2 threshold) ; let creates the lexical environment (let (( book-list '(((Gone With the Wind) 1000) ((Freakonomics) 1500) ((Cryptonomicon) 500)))) (filter ; higher-order function, similar to map but returns selected items (lambda (book) ; here's the anonymous function (>= (book-sales book) threshold)) ; book-list is a "free variable" within the anonymous function, accesses the lexical ; environment created by let book-list))) ; If the anonymous function accesses a global variable, it will point to the global ; variable location. Changes to the global variable WILL be seen in the function. (define the-book-list '(((Gone With the Wind) 1000) ((Freakonomics) 1500) ((Cryptonomicon) 500))) (define (best-selling-books threshold) (filter (lambda (book) (>= (book-sales book) threshold)) the-book-list)) ; TRY: (set! the-book-list (append '(((Blown To Bits) 400)) the-book-list)) ; Higher-order function examples (define (print-result operation) (display (operation 2 1)) (newline))(print-result +) (define (map-result operation theList) (map operation theList)) (define (exceedsLimit x) (if (> x 100) #t #f)) (define complement (lambda (f) (lambda (x) (not (f x))))) ; closure example from Schani web page (define cl (lambda (x) (lambda (y) (+ x y)))) ; examples using cl(cl 3) (apply (cl 3) '(4)) (map (cl 3) '(4 5)) (define (testClosure y) (let ((z 1)) (let ((f (lambda (y) (* y z)))) ; definition environment (let ((z 2)) (display "calling f with z value: ") (display z) (display #\space) (f y))))) ; activation environment ; Currying examples from: http://www.engr.uconn.edu/~jeffm/Papers/curry.html (define (mult y) (lambda (x) (* y x))) (define (double x) ((mult 2) x)) (define (curry fun . args) (lambda x (apply fun (append args x)))) (define triple (curry * 3)) (define lister1 (curry list 'args)) (define lister2 (curry lister1 'one)) (define lister3 (curry lister2 'two))