CSC151.01 2006S, Class 37: Higher-Order Procedures, Summarized Admin: * Due: Exam 2. * EC: Drag Extravaganza Friday, Football Saturday, Women's Soccer 2pm today. * No reading for the weekend; exam to be returned Monday. * HW for Tuesday! * Since many of you did not understand the Trogdor! references, I'm going to try to show the background video. * Today is a day off from K-8 in Grinnell, so I'm heading home soon after class. * Link to today's code in the outline. Overview: * Background: Guiding Principles. * Higher-Order Programming * Procedures as Parameters. * Anonymous Procedures. * Procedures as Return Values. * Encapsulating Control. * Optional: Making your brain really hurt. /Guiding Principles for Programmers (and language designers)/ * Strive to be concise * Easier to look at * Which may make it easier to understand * Less to think about when debugging * More efficient? * Don't name things that don't need names * Compute the length of the hypoteneuse of a right triangle given the lengths of the two sides (define hype (lambda (a b) (sqrt (+ (* a a) (* b b))))) (define hype (lambda (a b) (let* ((square-of-the-first side (* a a)) (square-of-the-second side (* b b)) (sum-of-the-squares (+ square-of-the-first-side ...))) (sqrt sum-of-the-squares)))) * Don't repeat code * When writing the same code again and again (or copy and paste) * Determine the "common part" and make it a separate procedure * "Refactor" /Example one: From the exam Procedures as parameters/ * What permitted me to write count-X instead of count-smokes + count-bedtime + count-favecolor + count-political-dewpoint * In Scheme, procedures can be parameters /Why bother naming our procedures?/ * Is it useful to define a procedure and only use it once? Probably not. * We found this helpful in generating color grids * Technique: Just write (lambda (params) body) /If we can take procedures as parameters, can we also return them?/ * Yes * How (define proc-that-returns-a-proc (lambda (params) (lambda (other-params) body-of-returned-procedures)))a * One exmaple (define redder (lambda (amt) (lambda (color) (rgb (+ amt (red color)) (green color) (blue color)))))a * Very general proc-that-returns-a-proc * compose: takes two functions and returns a new function that applies the second and then the first * left-section: takes a two-parameter function and first parameter and returns a function that expects the second parameter Abstract control: map * right-section