Discussion 3: Higher-Order Functions, Environment Diagrams
Environment Diagrams
Draw an environment diagram for the code below. You can use paper or a tablet or the whiteboard. Then, step through the diagram generated by Python Tutor to check your work.
def foo(x, y):
foo = bar
return foo(x, y)
def bar(z, x):
return z + y
y = 5
foo(1, 2)
Here's a blank diagram in case you're using a tablet:

Higher-Order Functions
Remember the problem-solving approach from last discussion; it works just as well for implementing higher-order functions.
- Pick an example input and corresponding output. (This time it might be a function.)
- Describe a process (in English) that computes the output from the input using simple steps.
- Figure out what additional names you'll need to carry out this process.
- Implement the process in code using those additional names.
- Determine whether the implementation really works on your original example.
- Determine whether the implementation really works on other examples. (If not, you might need to revise step 2.)
Q1: Multi-Apply
Sometimes we want to apply a function more than once to a number. Implement
multi-apply, which is a higher-order function takes in a function f. It returns
a function of the form g(x, y), which takes in two arguments. This new function
composes, or applies, f to x y times; for example, for y = 3, it would evaluate f(f(f(x))).
Q2: Make Keeper
Implement make_keeper, which takes a positive integer n and returns a
function f that takes as its argument another one-argument function cond.
When f is called on cond, it prints out the integers from 1 to n
(including n) for which cond returns a true value when called on each of
those integers. Each integer is printed on a separate line.