I mean I use what I think are closures in Javascript, but I thought they were to 'prevent the pollution of the global namespace' (a noble endeavor). I don't get how it relates to map, reduce(fold?) & filter.
I mean I use what I think are closures in Javascript, but I thought they were to 'prevent the pollution of the global namespace' (a noble endeavor). I don't get how it relates to map, reduce(fold?) & filter.
A closure is a lambda that is closed over its free variables meaning that the variables which are not defined in the body of the function (variables that are not local or the formal arguments) are bound to what their values are in that lexical scope at the time they are constructed and do not change with the calling environment.
In javascript if I do:
var x = 2;
var f = function() {
return x;
}
console.log(f())
(function() {
var x = 3;
console.log(f());
})();
It will print '2' and '2'. f is a closure. It is closed over its free variable 'x', 'x' in f is bound to the nearest 'x' that was in scope when it was written.A lambda is just a function, it does not necessarily imply there are free variables which it is closed over.
function() { var y = 23; return y * 40; }
is a lambda with no free variables.Technically the following implementation of evens is a closure:
isEven x = (x `mod` 2) == 0
evens xs = filter isEven xs
Can you see why? `isEven` is a free variable in evens which is bound to the isEven defined above it. evens is a closure, but generally we wouldn't refer to it as such.I'm confused a little with regards to the closure closing over the "value" of free variables, or the reference.
For example, in python:
i = 1
def f():
return i
i = 2
def g():
return i
Both f() and g() return 2, even though when f() is defined, shouldn't i=1 be closed over in this case? That's what I find confusing here, in the sense that the state of the environment changes outside the closure affect things inside the closure.This behavior is the motivation behind the do keyword in CoffeeScript.
Here's more on this:
http://stackoverflow.com/questions/233673/lexical-closures-i...