;; CSE 413 23sp ;; Lectures 7: More with curried functions and letrec, and ;; the execution model of environments and closures for evaluating them #lang racket ;; some data (define x 10) (define ab '(a b)) (define xyz '(x y z)) (define nums '(1 2 3 4 5 6)) (define nums2 '(1 2 3 -17 413 -143 42 12)) (define colors '(red green blue)) ;; various functions and examples from previous classes ;; ordinary recursive n! (define (fact n) (if (= n 0) 1 (* n (fact (- n 1))))) ;; tail recursive versions ;; n! tail-recursive with external aux function (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))) ;; Partial application and curried functions ;; ordinary addition (define add (lambda (x y) (+ x y))) ;; ordinary addition with global variable (define addx (lambda (y) (+ x y))) ;; curried add - result is a function that can be applied to a number (define cadd (lambda (x) (lambda (y) (+ x y)))) (define plus2 (cadd 2)) (define plusx (cadd x)) ;; Examples: ; (add 2 3) ; ((cadd 2) 3) ; (define plus2 (cadd 2)) ; (plus2 3) ; (define plusx (cadd x)) ; global x ; (plusx 4) ; (maplst plus2 nums) ;; return copy of lst containing elements from original list ;; in the range lo <= x <= hi (define (filter-in-range lo hi lst) (filter (lambda (n) (and (>= n lo) (<= n hi))) lst)) ;; curried version - return function to 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 10 100 nums2) ; ((cfilter-in-range 10 100) nums2) ; (define filter-10-100 (cfilter-in-range 10 100)) ; (filter-10-100 nums2) ;; letrec and mutual 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? 1) ; (is-n-even? 413) ; (is-n-even? 42)