I'm trying to understand closures, but literally every definition of a closure that I can find uses the same cryptic and vague phrase: "closes over".
What's a closure? "Oh, it's a function that closes over another function."
But nowhere can I find a definition of what "closes over" means. Can someone explain what it means for Thing A to "close over" Thing B?
A closure is a pair consisting of a code pointer and an environment pointer. The environment pointer contains all of the free variables of a given function. For example:
The function
g
contains two free variables:a
andb
. If you are not familiar with the term free variable, it is a variable that is not defined within the scope of a function. In this context, to close over something, means to remove any occurrences of a free variable from a function. The above example provides good motivation for closures. When the functionf
returns, we need to be able to remember what the values ofa
andb
are for later. The way this is compiled, is to treat functiong
as a code pointer and a record containing all the free variables, such as:When we apply the function
g
, we supply the environment that was returned when calling functionf
. Note that now functiong
no longer has any occurrences of a variable that is not defined in its scope. We typically call a term that doesn't have any free variables as closed. If you are still unclear, Matt Might has an excellent in depth explanation of closure conversion at http://matt.might.net/articles/closure-conversion/Same example in Javascript
Before closure conversion
After closure conversion: