#lang racket ;; CSE 413 Au12 lecture 8 sample code ;; return a function that will add n to all of the elements of a list (define addn-to-list (lambda (n) (lambda (lst) (map (lambda (x) (+ n x)) lst)))) ; ((addn-to-list n) '(1 2 3 4)) ; (define add3-to-list (addn-to-list 3)) ; (add3-to-list '(1 2 3 4)) ;; filter (define filter413 (lambda (f lst) (cond ((null? lst) '()) ((f (car lst)) (cons (car lst) (filter413 f (cdr lst)))) (else (filter413 f (cdr lst)))))) ;; return a list with all elements x such that lo<=x<=hi (define filterinrange (lambda (lo hi lst) (filter413 (lambda (n) (and (>= n lo) (<= n hi))) lst))) ; (filterinrange 3 5 '(1 2 3 4 5 6)) ;; Curried functions revisited ;; curried addition function (define plus (lambda (x) (lambda (y) (+ x y)))) ;; curried higher-order functions ;; curried map (define cmap (lambda (f) (lambda (lst) (map f lst)))) ;; curried filter - return a function that uses function f to filter a list (define cfilter (lambda (f) (lambda (lst) (filter f lst)))) ;; return elements of a list in the range lo to hi (define rangefilter (lambda (lo hi) (cfilter (lambda (n) (and (>= n lo) (<= n hi)))))) ; ((rangefilter 3 5) '(1 2 3 4 5 6 7) ; (define range35filter (rangefilter 3 5)) ; (range35filter '(1 2 3 4 5 6 7)) ;; test functions (define (sqr n) (* n n)) (define (incr n) (+ 1 n)) (define (dbl n) (+ n n)) ;; function composition - return f o g (define compose (lambda (f g) (lambda (x) (f (g x))))) ;; ((compose sqr incr) 4) ;; ((compose incr sqr) 4) ;; (define sqrincr (compose sqr incr))