3 ms·
> That is how it is implemented. It doesn't have to be, I have a list of example languages where it is not the case. No, you don't. Closures in those are also
by wtetzner 11y ago
> That is how it is implemented. It doesn't have to be, I have a list of example languages where it is not the case.
No, you don't. Closures in those are also a direct consequence of lexical scoping. But those languages don't have mutable variables, regardless of closures.
- rdtsc 11y ago> No, you don't. Functions defined in modules in Erlang are different from closures. Here is a example: -module(e). -compile(export_all). f()-> 1. g()-> fun ()-> 1 end. $ erl > c(e). > erlang:fun_info(fun e:f/0). [{module,e},{name,f},{arity,0},{env,[]},{type,external}] > erlang:fun_info(e:g()). [{pid,<0.42.0>}, {module,e}, {new_index,0}, {new_uniq,<<136,230,191,77,132,145,66,52,216,215,111,24, 18,188,4,169>>}, {index,0}, {uniq,71775738}, {name,'-g/0-fun-0-'}, {arity,0}, {env,[]}, {type,local}] To get info on e:f it has to be become a closure-like object, but if you see internally it is still represented differently than a closure. > Closures in those are also a direct consequence of lexical scoping. Not sure what you mean a direct consequence. Are you saying that closures follow scoping rules? The point was that it doesn't necessarily follow that they have to be implemented as object instances in object oriented languages, or function pointers, or functions (say like in Erlang).
- qwertyuiop924 11y agoWell, yes, closures can be implemented however you want, in a true lexical scoped language, every function is a closure, not just lambdas, only most don't really close over anything, and can be optimized away. The case of C is, again, instructive. //foo.c int global = 0; int quuxify(){ return global++; } //bar.c extern int quuxify(); printf("%d", quuxify());//prints "0" printf("%d", quuxify());//prints "1" even though quuxify() depends on global, which is out of scope in bar.c, the call still compiles. Why? because C is a lexically scoped language, and so variable references in functions refer to the scope the function was declared in, NOT the one it was called in. And you thought C didn't have closures ;-D