A closure is a record storing a function, together with an environment: A mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. (Wikipedia)
Here is what I understand. A function can access to 3 types of variables (Let's assume JavaScript):
- Parameters: The parameters of a function.
- Local variables: The variables defined inside of a function. (but not the variables defined in a nested function. That is, a function cannot access variables defined in another function, where this another function is defined inside the function we are talking about)
- Free variables: The variables defined outside of the function. That is, the function can access the variables defined in the function which surrounds our function, and the variables defined in the function which surrounds the function that surround our function, etc.
Of these 3 types, the values of the variables of type 1 and 2 are well known at the time a function is called. However, the variables of type 3 can have any value at the time a function is called. To the best of my knowledge, this is a property of dynamically scoped languages. That is, AFAIK, in lexically scoped languages, we cannot have such situation.
That's where a closure comes into scene. A closure binds the free variables of a function. Hence, there isn't any variable which doesn't have a well known value, at the time a function is called.
So, my question is the following:
Are closures a must have in lexically scoped languages, which allow nested functions and which have first class functions?
To me, it seems like so. Because if nested first class functions are allowed in a language without having closures, then this means that the free variables will have non-deterministic values at the time a function is called. But AFAIK, having non-deterministic values is a property of dynamically scoped languages. Hence, I claim:
If a language claims to be lexically scoped, and if a language allows nested first class functions, then, by definition, every function in that language is (must be) a closure.
I am correct in this?