;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname lect29-dist) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ()))) (define fake-pokemon (list "pickatyou" "abracadabrix" "charzander" "pollywog")) (map string-length fake-pokemon) ; returns (list 9 12 10 8) (map sqr (list 2 3 4)) ; returns (list 4 9 16) ; map : (α -> β) (listof α) -> (listof β) ; filter, so that we keep only the pokemon of string-length <= 9. ; my-filter : (α -> boolean) (listof α) -> (listof α) ; (define (my-filter keep? data) (cond [(empty? data) empty] [(cons? data) (if (keep? (first data)) (cons (first data) (my-filter keep? (rest data))) (my-filter keep? (rest data)))])) (my-filter even? (list 23 6 2 3 4 5 6 7 8)) ; even? : number -> boolean ; The use of higher-order functions like `map` and `filter`, ; along w/ the handy `λ` to easily/quickly create functions to give them, ; [And even more: higher-order functions like `compose`.] ; is often considered a hallmark of functional programming. ; (Along w/: ; - immutable data ; - writing smaller, short, testable methods.) (define (is-name-short? pokey) (<= (string-length pokey) 9)) ;;; is equivalent to: (define is-name-short? (λ (pokey) (<= (string-length pokey) 9))) (my-filter is-name-short? fake-pokemon) ; by one step in the stepper: (my-filter (lambda (pokey) (<= (string-length pokey) 9)) fake-pokemon) (map (λ (x) (+ 3 (sqr x))) (list 2 3 4 5)) ; bricks-remaining : ball, list-of-brick -> list-of-brick ; #;(define (bricks-remaining a-ball bricks) (cond [(empty? bricks) empty] [(cons? bricks) (if (brick-collide-ball? a-ball (first bricks)) (bricks-remaining a-ball (rest bricks)) (cons (first brick) (bricks-remaining a-ball (rest bricks))))])) ;; This is a filter! #;(define (bricks-remaining a-ball bricks) (my-filter (λ (br) (not (brick-collide-ball? a-ball br))) bricks)) #| Type-variables in Java: e.g. List You write methods with a `T`, instead of `α`: T get( List data, int i ) |# #| interface Dummy { boolean makeDecision( T cp); } } List myFilter( Dummy keepP, List data ) { if (data.isEmpty()) { return new LinkedList(); } else { List resultOfRecur = myFilter( keepP, data.sublist(1,data.size()) ); if (keepP.makeDecision( data.get(0) ) { return (resultOfRecur).clone().add(0,data.get(0)); else { return resultOfRecur; } } class CounterFeitPokemonKeeper extends Dummy { boolean makeDecision( String cp) { return cp.length() <= 8; } } .... myFilter( new CounterFeitPokemonKeepr(), fakePokemon) .... OR, use anonymuous (inner) classes: .... myFilter( new CounterFeitPokemonKeeper { boolean makeDecision( String cp) { return cp.length() <= 8; }() }, fakePokemon ) ;;;; Java 8: .... myFilter( (cp) -> (cp.length() <= 8), fakePokemon ) |#