In conjunction with closures I often read that something closes over something else as a means to explain closures.
Now I don't have much difficulty understanding closures, but "closing over" appears to be a more fundamental concept. Otherwise one would not refer to it to explain closures, would one?
What is the exact definition of closing over, and what is the something and the something else? Where does the term come from?
Consider:
Here:
Consider a simple function:
Here:
add
has only one variable, namedx
, which is not a free variable because it is defined within the scope ofadd
itself.closure
has two variables, namedx
andy
, out of whichx
is a free variable because it is defined in the scope ofadd
(notclosure
) andy
is not a free variable because it is defined in the scope ofclosure
itself.Hence, in the second case the function named
closure
is said to “close over” the variable namedx
.Therefore:
closure
is said to be a closure of the variable namedx
.x
is said to be an upvalue of the function namedclosure
.That's all there is to it.