λ λ CS 251 Fall 2019 CS 251 Fall 2019 Principles of Programming Languages Principles of Programming Languages Ben Wood Ben Wood Higher-order Functions +hof.rkt https://cs.wellesley.edu/~cs251/f19/ 1 Higher-order Functions
Topics • Functions are first-class. • Using first-class/higher-order functions • Map and filter • Next time: getting the semantics right Higher-order Functions 2
First-class and higher order functions Functions are fi first-cl clas ass val alue ues , can be used or created wherever we use or create any other values: – Arguments to ( higher order ) function calls – Results of ( higher order ) function bodies – Stored in cons cells or other data structures – Bound (named) by variables – … Hi Higher order functions take or return other functions. Powerful ways to: – factor out common functionality – parameterize general patterns with specific behavior Higher-order Functions 3
Function closures support lexical scope for nested functions. Sneak peak : – Function bodies can use any bindings in scope where function is defined, including from outside the function definition . – Distinct concept from first-class functions – Back to this powerful idea soon! Higher-order Functions 4
Functions as arguments (define (map-pair f pair) (cons (f (car pair)) (f (cdr pair)))) Elegant strategy for factoring out code for common patterns of data manipulation. Combines well with anonymous functions. [S [See code examples in ho hof.r f.rkt kt] Higher-order Functions 5
A style point (if x #t #f) (lambda (x) (f x)) ✘ (n-times (lambda (x) (cdr x)) 2 (list 1 2 3 4)) ✓ (n-times cdr 2 (list 1 2 3 4)) Higher-order Functions 6
HO HOF HO HOF Map ( define ( map f elems) ( if (null? elems) null (cons ( f (first elems)) ( map f (rest elems))))) ⋯ argument list v1 v2 vn f f f (f vn) (f v2) (f v1) ⋯ result list Higher-order Functions 7
HO HOF HO HOF Filter ( define ( filter f elems) ( if (null? elems) null ( if ( f (first elems)) (cons (first elems) ( filter f (rest elems))) ( filter f (rest elems))))) ⋯ v1 v2 vn argument list f f f #t #f #t ⋯ v1 result list vn Higher-order Functions 8
Rewrite the list practice functions • Which functions could be built using map/filter? • For which functions does this feel more or less elegant than your original implementation? Higher-order Functions 9
Generalizing Our examples of first-class functions so far: – Take one function as an argument to another function – Process a number or a list But first-class functions are useful anywhere for any kind of data – Pass several functions as arguments – Put functions in data structures (tuples, lists, etc.) – Return functions as results – Write higher-order functions that traverse other data structures Powerful idioms to: – factor out and reuse common functionality – parameterize general patterns with specific behavior – clearly communicate high-level meaning/intent Higher-order Functions 10
Recommend
More recommend