#lang racket ;; CSE 413 Au12 lecture 6 sample code ;; simple functions to use with map (define (sqr n) (* n n)) (define (dbl n) (+ n n)) (define (incr n) (+ 1 n)) ;; map functions ;; return copy of lst where each element is (f old element) (define (map413 f lst) (if (null? lst) '() (cons (f (car lst)) (map413 f (cdr lst))))) ;; Use: (map413 dbl lst) (map413 sqr lst) etc. ;; reduce functions: reduce a list to a single value ;; sum of elements in a list (define (sumlist lst) (if (null? lst) 0 (+ (car lst) (sumlist (cdr lst))))) ;; product of elements in a list (define (multlist lst) (if (null? lst) 1 (* (car lst) (multlist (cdr lst))))) ;; higher-order function that captures the reduce pattern ;; Reduce lst to a value by combining elements with f where ;; id is the appropriate value for the empty list (usually ;; the identity value for function f) (define (reduce413 f id lst) (if (null? lst) id (f (car lst) (reduce413 f id (cdr lst))))) ;; uses: (reduce413 + 0 lst) (reduce413 * 1 lst) ;; higher-order filter function ;; Filter lst by returning a copy for which (f element) is true (define (filter413 f lst) (cond ((null? lst) '()) ((f (car lst)) (cons (car lst) (filter413 f (cdr lst)))) (else (filter413 f (cdr lst))))) ;; uses (filter413 odd? lst) (filer413 null? lst) ;; higher-order functions and partial evaluation (define plus (lambda (x y) (+ x y))) (define sum (lambda (x) (lambda (y) (+ x y)))) ;; examples ((sum 3) 4) => 7 (sum 3) => function that returns 3+argument