;; The first three lines of this file were inserted by DrScheme. 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 lect07c) (read-case-sensitive #t) (teachpacks ((lib "universe.ss" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "universe.ss" "teachpack" "2htdp"))))) ;; lect07c -- Oct.16 ; What we've learned about loops: ; - a special case of recursion ; - common types of loops: map,filter (and fold, which won't be on exam). ; (and how we can actually make each of those official loops (functions) ; in languages with higher-order functions). ; We've seen 'lambda', to create anonymous functions. ; We've seen that '(define (foo x) ...)' is syntactic sugar ; for '(define foo (lambda (x) ...))' ; (and thus 'define' and functions are entirely orthogonal). ;---- ; Practice with 'lambda': ; Using `sort` to sort... ; - sort a list of trucks `alot` by x-coord: (sort alot (λ (t1 t2) (< (truck-x t1) (truck-x t2)))) ; - sort a strings, ignoring "The" (sort (list "The Cars" "The Who" "Two Skinny J's" "Two Nice Girls") (lambda (s1 s2) ;; Our anonymous lambda: (let* {[remove-pref-if (lambda (str prf) (let* {[len (string-length prf)]} (if (and (>= (string-length str) len) (string=? (substring str 0 len) prf)) (substring str len) str)))] } (string<=? (remove-pref-if s1 "The ") (remove-pref-if s2 "The ")))) ; ; How is passing-a-function done in Java? ; We want to pass a function, but Java doesn't allow that, ; so here's the contortion we'll go through: ; We'll pass an object which contains exactly one method ; of a pre-defined type. That class is 'Comparator'. ; [Why is 'compareTo' not good enough?] ; And we'll create that method on the fly, ; subclassing Comparator using an 'anonymous inner class'. ; For an example, see: ; http://www.radford.edu/itec380/2009fall-ibarland/Lectures/lect07-anon-lambda/Anon.java ; ; Write quicksort: (define (quicksort nums) (if (<= (length nums) 1) nums (let* {[pivot (list-ref (random (length nums)) nums)] [smalls (filter (λ (n) (< n pivot)) nums)] [eqls (filter (λ (n) (= n pivot)) nums)] [bigs (filter (λ (n) (> n pivot)) nums)] } (append (quicksort smalls) eqls (quicksort bigs))))) ; If time: ; Ancestor trees, continued.