5 ms·
Closures aren't necessary for lexical scoping, and in practice they're only real use (in imperative languages, obviously quite different in e.g. Haskell) is to
by traes 6y ago
Closures aren't necessary for lexical scoping, and in practice they're only real use (in imperative languages, obviously quite different in e.g. Haskell) is to pass around blocks of code combined with captured variables. I think this definition is quite reasonable.
- a-nikolaev 6y agoBut such a closure block is a function (it might be sugared like a ruby block or something like that, but it remains a function that captures its environment, thus implementing lexical scoping). Well, okay, if a language does not normally have lexical scoping, but has a special "closure" feature to implement it (dunno, maybe C++ lambdas may be regarded as such a special closure construct?) That could be a justification for the term closure on its own. But if the language has lexical scoping by default (e.g. Gravity says that it has lexical scoping in its overview), then, I think, there is no need in a separate notion of "closure" in the language semantics.
- codr7 6y agoLexical scoping doesn't necessarily include lexically scoped function definitions. Lambdas have been spreading lately, but plain old functions are still not lexically scoped in a lot of languages otherwise regarded as such, C/C++/Java/Pascal etc.
- a-nikolaev 6y agoWhat do you mean by lexically scoped functions? A nested function? My point is that instead of reusing the term closure, one could use the term anonymous function. To rephrase my question: Do you have a specific example where a nested function (or an anonymous function) is not lexically scoped (In a language that is otherwise lexically scoped)?
- a-nikolaev 6y agoActually, I know Ruby messes up its functions this way: def f() x = 1 def g() return x end g() end puts f() undefined local variable or method `x' for main:Object (repl):6:in `g' So, the nested function g() cannot capture the scope. I think they had some justification for this funny behavior, because def is not a function, but actually a method (I could be wrong). But in any case, there are examples of languages that don't allow nested functions to capture environment (while a proc or block would capture it).
- codr7 6y agoThey would have to be nested to be in the same scope, so yes. But some languages have nested functions that aren't proper closures. All closures are not anonymous either. The reason we use different terms is because there are subtle differences that are important to capture.