Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Long story short, OP is conflating closures with lambdas.

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.


Thanks for the explanation, closures have been a little tricky for me to wrap my head around.

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 is a property of how javascript and python do closures. In the above code i refers to the same piece of memory in every case. So f and g are closed over i. The reference is preserved but the value is not.

This behavior is the motivation behind the do keyword in CoffeeScript.

Here's more on this:

http://stackoverflow.com/questions/233673/lexical-closures-i...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: