;; CSE 413 21sp ;; Lectures 7: More with curried functions and letrec, then start ;; environments and closures #lang racket ;; From last time - first example of a local binding (local scope) ;; version 2 - local name for reversed list (define (revrev lst) (let ([r (reverse lst)]) (append r r))) (define x 10) ;; recursion and applicative programming (new handout) ;; numeric example: n! (define (fact n) (if (= n 0) 1 (* n (fact (- n 1))))) ;; tail recursion ;; n! tail-recursive (define (factt n) (factaux n 1)) ;; = n! * acc (define (factaux n acc) (if (= n 0) acc (factaux (- n 1) (* n acc)))) ;; n! with local aux function (i.e., aux function is not in global namespace) (define (factloc n) (letrec ([aux (lambda (n acc) (if (= n 0) acc (aux (- n 1) (* n acc))))]) (aux n 1))) ;; applicative (higher-order) programming and lambdas (anonymous functions) ;; some data (define abc '(a b c)) (define alist '(a (b c) d e)) (define nums '(1 2 3 4 5)) ;; Partial application and curried functions ;; ordinary addition (define add (lambda (x y) (+ x y))) ;; curried add - result is a function that can be applied to a number (define cadd (lambda (x) (lambda (y) (+ x y)))) ;; Examples: ; (add 2 3) ; ((cadd 2) 3) ; (define plus2 (cadd 2)) ; (plus2 3) ; (define plusx (cadd x)) ; global x ; (plusx 4) ; (maplst plus2 nums) (define numlst '(1 2 3 -17 42 413 -143 341 12)) ;; Two versions of a function to filter a list and return list with values in a range ;; return copy of lst containing elements in range lo <= x <= hi (define (filter-in-range lo hi lst) (filter (lambda (n) (and (>= n lo) (<= n hi))) lst)) ;; curried version - filter lst in range lo <= x <= hi (define (cfilter-in-range lo hi) (lambda (lst) (filter (lambda (n) (and (>= n lo) (<= n hi))) lst))) ;; Examples: ; (filter-in-range 0 100 numlst) ; (define filter-0-100 (cfilter-in-range 0 100)) ; (filter-0-100 numlst) ;; letrec and multual recursion ;; = "n is even" for n >= 0 (define (is-n-even? n) (letrec ([is-even? (lambda (n) (if (= n 0) #t (is-odd? (- n 1))))] [is-odd? (lambda (n) (if (= n 0) #f (is-even? (- n 1))))]) (is-even? n))) ;; Examples: ; (is-n-even? 0) ; (is-n-even? 42) ; (is-n-even? 17)