University of California, Berkeley
EECS Department - Computer Science Division
CS3 Lecture 13 : Higher-Order Functions (cont'd)
Overview of today's lecture
Review
- global vs. local variables
- every, a higher-order function which operates on
every word in a sentence
Higher-Order Functions
(cont'd)
Defining functions as one another
- If you want to define a function as another with the exact
same arguments, don't define it as a function call, as in
: (define (plus x y) (+ x y))
plus
- Note that + can handle multiple arguments, but plus
can only handle two...
: (+ 1 2)
3
: (plus 1 2)
3
: (+ 1 2 3)
6
: (plus 1 2 3)
*** ERROR -- Wrong number of arguments passed to procedure
(plus 1 2 3)
- ...instead you should define it directly as a variable bound
to the same procedure
: (define plus +) ;; Now plus and + are identical!
: (+ 1 2 3)
6
: (plus 1 2 3)
6
Temporary variables : another way
to do it
- We showed you how to use let to define local variables.
- Another way to do it without let is to define a
helper procedure that takes additional parameters which hold
your temporary values.
- Example: The following expression takes two hours (2 calls
to hour-long-function)
: (+ (hour-long-function 3) (/ (hour-long-function 3) 2))
12
- whereas we can save time by storing the result from calling
hour-long-function once and storing the return value
in a temporary variable hlf. The following expression
evaluates in only one hour (only one call to hour-long-function)
: (let ((hlf (hour-long-function 3))
(+ hlf (/ hlf 2)))
12
- Another way would be to use a helper procedure as follows
: (define (hlf-helper hlf)
(+ hlf (/ hlf 2)))
hlf-helper
: (hlf-helper (hour-long-function 3))
12
- Summary:
- There is another way to do it if for some reason you don't
have let.
- Normally you would use let; we're just showing
you another way to do it.
Summary
- Today we've seen two smaller points about functions
- We've seen the power of these functionals which we're going
to need to learn to plug together to solve much larger problems.
Next Time
- Lambda Lambda Lambda!, it's not just a fraternity...
Puzzle : Infinite Baseball
- Name 5 ways of extending a baseball game indefinitely without
umpire intervention.
Game : Tac Tix [BerlekampConwayGuy82]
- Place random coins on a grid
- On your turn, remove as many coins as you can from any row
or column, as long as they are adjacent (i.e., no gaps between
the coins)
- The winner is the person who removes the last coin.
References
- [BerlekampConwayGuy82] Elwyn Berlekamp, John H. Conway, Richard
K. Guy "Winning Ways for Your Mathematical Plays",
Academic Press, London, 1982.
WWW Maven: Dan
Garcia (ddgarcia@cs.berkeley.edu)
Send me feedback