The following content is provided under a Creative
Commons license.
Your support will help MIT OpenCourseWare
continue to offer high-quality educational resources for free.
To make a donation or view additional materials
from hundreds of MIT courses, visit MIT OpenCourseWare
at ocw.mit.edu.
ANA BELL: So here's some code.
I'm defining a function named sq,
and it takes in two parameters.
I'm defining a function named f, takes in one parameter,
and then I'm doing these two lines.
The first one is just calling function sq,
and the next one is just printing the value.
So let's first see what-- nice.
OK.
Let's work through it.
So The first things we see here is two function definitions,
right?
So we don't currently care about what's
inside them right now because we haven't made a function
call yet.
So the first thing we do is we have the function
call calc equal sq f and 2.
OK?
So inside sq, we're going to have func and x.
And func is going to get mapped to f,
and x is going to get mapped to 2, right?
So we're taking the variables in order
and mapping them to those.
Func is f, and x is 2.
First thing the function does, sq,
is create this variable y is equal to x squared.
So we're going to have y is equal to 4.
And then we're going to return func y.
So func of y, this is going to be-- we're
just replacing the parameters f of 4, right?
So now this is another function call.
We know what f is.
This program knows what f is.
f is going to be this part right here, which returns x squared.
OK?
So in f, x gets mapped to whatever variable we put in,
which in this case is 4.
And we're going to return to whoever
called us, which is over here, 4 squared, which is 16.
OK?
So f of 4 gets replaced with 16.
And f of 4 was up here, right?
We're just popping out of scopes now.
So f of 4 was up here.
So then that line there, return func y, is going to return 16.
And whoever called us was down here, calc is equal to 16.
And then we're just printing calc.
So 16 was right.
Yay.