CSC153, Class 17: Higher-Order Procedures Overview: * Patterns of programming * Encapsulating patterns: Higher-order procedures * map and apply * Lab Notes: * Read more higher-order procedures * Scan (or read) chapters 1-3 of Algorithms for Functional Programming * Course schedule re-arranged * Prospective: Cable from Roseville, MN YA: "Carleton, Macalester, or Grinnell" Grinnellians are collaborative Grinnell is fabulous because ... "our tour guides are non-competitive" "our president makes more than any other liberal arts college president" "Titular Head" "Professors are more likely to pick on you in class" "Scheme rules!" * Are there questions on exam 1? + Yes, you can come and ask me to look over your exam + No, I don't mind if you send me fifteen email messages each with five questions Are there questions on the reading on higher-order procedures? Observation: We often design "patterns" of procedures, and implement new ones based on those procedures. When working with vectors, you might want to put a value at each position in a vector (define evans-vector (vector 'a 'b 'c)) (fill-with-ones! evans-vector) (define fill-with-ones! (lambda (vec) (letrec ((kernel (lambda (position) (if (>= position 0) (begin (vector-set! vec position 1) (kernel (- position 1))))))) (kernel (- (vector-length vec) 1))))) (define fill-with-position! (lambda (vec) (letrec ((kernel (lambda (position) (if (>= position 0) (begin (vector-set! vec position position) (kernel (- position 1))))))) (kernel (- (vector-length vec) 1))))) (define fred (vector 'e 'f 'g 'h 'i)) (define fill-with! (lambda (vec proc) (letrec ((kernel (lambda (position) (if (>= position 0) (begin (vector-set! vec position (proc position)) (kernel (- position 1))))))) (kernel (- (vector-length vec) 1))))) Three big morals (plus one from David) * David's: Don't do work unless you really have to * Procedures can take procedures as parameters * You can therefore write procedures that generalize procedure design. * Procedures can be *anonymous* Two smalller morals: * The "apply a procedure to each element of a list" pattern is so common, it's built into Scheme (in various ways) Called map > (map (lambda (x) (* x x)) (list 5 6 7)) * The "apply a procedure to a list of arguments without treating them as a list" pattern is common enough that we also have it built in. (define sum (lambda (lst) (apply + lst)))