Abstraction: Procedures as Parameters CMSC Introduction to Computer Programming October 14, 2002
Roadmap Motivation: Two too similar procedures? Procedural Abstraction Laziness is a virtue –Procedures as parameters Contracts –Unnamed procedures: Lambda Scope –Binding variables –Creating local variables: Let
Two Too Similar Procedures (define (square x) (* x x)) (define (squarelist alon) (cond ((null? alon) ‘()) (else (cons (square (car alon)) (squarelist (cdr alon)))))) (define (double x) (+ x x)) (define (doublelist alon) (cond ((null? alon) ‘()) (else (cons (double (car alon)) (doublelist (cdr alon))))))
Procedure Comparison Both procedures: –Consume a list –Perform some operation on each element –Return new list Differences: –Different name –Different operation –Different recursive call
(define (abstractlist alon) (cond ((null? alon) ‘()) (else (cons (abstractop (car alon)) (abstractlist (cdr alon)))) Abstract Procedure Problem: –Want different functions for “abstractop”
Solution: Procedures as Parameters Can pass a procedure as a parameter –Bind to formal parameter (define (map proc alist) (cond ((null? alist) ‘()) (else (cons (proc (car alist)) (map proc (cdr alist)))))) (define (squarelist alist) (map square alist)) (define (doublelist alist) (map double alist))
Why Abstract? Laziness can be a virtue –Abstract procedures localize key structure Creates single point of control Changes can be made in single location –Generally simplifies programs –Avoid copying and modifying code segments
Contracts Describe input and output requirements of function –fn: { … } –where, are types of input & output Original: squarelist: alon alon Now: map: (X -> Y) (listof X) -> (listof Y) –where X,Y are parameters - any type
More Examples Triplelist Scale list Add2 list
Unnamed Functions: Lambda Issue: Defining lots of trivial procedures –E.g. add2, double, triple… Solution: unnamed function Can’t be recursive (lambda ( {.. }) exp) E.g. “Add2” (lambda (x) (+ x 2)) Apply like other procedures –((lambda (x) (+ x 2)) 10) -> 12
Redefining with Lambda (define (doublelist alon) (map (lambda (x) (+ x x)) alon)) (define (triplelist alon) (map ???? alon)) (define (scalelist scale alon) (map ???? alon))
Abstraction with Product & Sum
Let: Defining Local Variables Issue: Store partial results Solution: Embed in unnamed procedure –Parameters bind names to values Let easier to read e.g. f(x,y)=x(1+xy)^2+y(1-y)+(1+xy)(1-y) (define (f x y) (let ((a (+ 1 (* x y))) (b (- 1 y))) (+ (* x (square a)) (* y b) (* a b))))) (define (f x y) (lambda (a b) (+ (* x (square a)) (* y b) (* a b))) (+ 1 (* x y))(- 1 y)))
Scope: What’s in a Name? Where does a variable get its value?
Summary Procedural abstraction –Procedures as parameters Contracts –Single point of control Laziness is a virtue –Unnamed functions with lambda
Next Time Defining local variables with let –Scope Bound and free variables Procedures as return values