;;;; Example 1: Extracting information about students under 21 (define-struct student (name age gpa)) ;; A Student is (make-student Symbol Number Number) #| First version, using a local definition for the required helper ;; minors : (listof Student) -> (listof Student) ;; produces a list of just those students under 21 (define (minors alost) {local [;; minor? : Student -> Boolean ;; determines if a student is under 21 (define (minor? st) (< (student-age st) 21))] (filter minor? alost)}) |# ;; Second version, using lambda instead of a named local helper ;; minors : (listof Student) -> (listof Student) ;; produces a list of just those students under 21 (define (minors alost) (filter (lambda (st) (< (student-age st) 21)) alost)) ;; Example/test of minors (equal? (minors (list (make-student 'Joe 22 3.5) (make-student 'Mary 19 3.0) (make-student 'Tom 21 2.5))) (list (make-student 'Mary 19 3.0))) ;;;; Combining filter with map: ;; minor-names : (listof Student) -> (listof Symbol) ;; produce a list of names of all the students under 21 (define (minor-names alost) (map student-name (minors alost))) #| If we didn't need the separate helper minors we could define minor-names more directly as follows: (define (minor-names alost) (map student-name (filter (lambda (st) (< (student-age st) 21)) alost))) |# ;; Example/test of minor-names (equal? (minor-names (list (make-student 'Joe 22 3.5) (make-student 'Mary 19 3.0) (make-student 'Tom 21 2.5))) (list 'Mary)) ;;;; Example 2: Multiplying a list of numbers by a given factor #| First version, using a local definition for the required helper ;; scalar* : Number (listof Number) -> (listof Number) ;; multiply every number in the list by x (define (scalar* x alon) {local [;; mult-by-x : Number -> Number ;; multiply n by x (define (mult-by-x n) (* x n))] (map mult-by-x alon)}) |# ;; Second version, using lambda instead of a named local helper ;; scalar* : Number (listof Number) -> (listof Number) ;; multiply every number in the list by x (define (scalar* x alon) (map (lambda (n) (* x n)) alon)) ;; Example/test (equal? (scalar* 5 (list 3 4 5 2 1)) (list 15 20 25 10 5)) ;;;; Example 3: Testing a list of numbers against a given threshold ;; (Here we skip the step of first using locally defined helpers.) ;; all-larger? : (listof Number) Number -> Boolean ;; determines whether all the numbers in the list are > threshold (define (all-larger? alon threshold) (andmap (lambda (x) (> x threshold)) alon)) ;; Examples/tests of all-larger? (equal? (all-larger? (list 5 4 3 2 1) 0) true) (equal? (all-larger? (list 5 4 3 2 1) 2) false) ;; any-larger? : (listof Number) Number -> Boolean ;; determines whether any of the numbers in the list are > threshold (define (any-larger? alon threshold) (ormap (lambda (x) (> x threshold)) alon)) ;; Examples/tests of any-larger? (equal? (any-larger? (list 5 4 3 2 1) 2) true) (equal? (any-larger? (list 5 4 3 2 1) 5) false)