More Higher Order Functions Practice
Here are a series of functions, what would Python do? Draw the environment diagram that this produces.
def f(x, y): x, y = y, x def x(x): return y(x) return x def y(x): return 6 + x def z(y): return 4 g = f(y, z) h = g(5)
Remember, when you call a function, you always need to make a new frame! Let’s take a closer look at the function call here:
g = f(y, z)
First, remember that when you have an assignment statement, you evaluate the right side first. We also have to remember that we have to evaluate our arguments before we make the frame for the function call. For this line, that means evaluating what
y is equal to and what
z is equal to.
So we make a new frame for
f and bind our parameters to the arguments that are passed into the function. That means binding the local variable
x is bound to the global function
y and the local variable
y bound to the global function
The next line I want to point out is:
x, y = y, x
Remember that in an assignment statement, we always evaluate the right side first. In the context of this line, that means that we have to figure out what
x evaluate to. We notice that if we evaluate both of the items on the right side, then assign them to the left, we’re effectively swapping their values.
Again, follow the rules of environment diagrams to finish solving this one.
Here’s a visualization of the final output. Leave comments below if you are confused on a certain step.
I don't claim to be perfect so if you find an error on this page, please send me an email preferably with a link to this page so that I know what I need to fix!