tags:

views:

68

answers:

3

Hello to all, what is closure and its correspondence example ?

I have research a lot and could not understand. Please explain in generic programming language concept aspect and specific programming language aspect.

Please help.

Thanks.

+6  A: 

A closure is basically a function B nested inside a function A that can access A's local variables:

function A() {
    var x = 5;

    function B() {
        print(x);
    }

    return B;
}

If you come from a C++ background, this is rather hard to digest. When we try to call the function returned by A, what x will it refer to? Won't that x be invalid since A() terminated?

The answer is that x actually lives on. That B we returned actually carries x around with it implicitly. Cool, eh?

In a more general sense, a closure is a function (that typically takes arguments) bound to some data. In a language without closures like C, every program has a fixed number of functions. With closures, you can, in a sense, "create functions" by binding them to dynamic data. Of course, nobody's stopping you from emulating closures in C, but it can be a pain sometimes.

Closures are really useful. For instance, suppose we want to implement our own "for loop":

function loop(count, f) {
    for (var i = 0; i < count; i++)
        f(i);
}

var array = [0,1,2,3,4];

loop(5, function(i) {
    print(array[i]);
});

Being allowed to access outside variables without doing a bunch of extra nonsense keeps code nice and simple. Without closures, you might have to pass a context variable to the loop function instead:

function loop(count, f, ctx) {
    for (var i = 0; i < count; i++)
        f(i, ctx);
}

var array = [0,1,2,3,4];

loop(5, function(i, ctx) {
    print(ctx[i]);
}, array);

Another example: suppose we want to register a callback in jQuery, but it may be executed long after the function and its caller and its caller's caller are done running:

$(document).ready(function(){

    var clicked = 0;

    $('#button').click(function(){
        clicked++;
        alert("You've pressed the button " + clicked + " times.");
    });

});

If JavaScript were more like C++ (before C++0x), that clicked variable would be long gone by the time the function given to $(document).ready() was called, and the button clicking callback would have undefined behavior.

Joey Adams
Interestingly C++0x now has lambdas that capture variables from their enclosing scope. So the *"If you come from a C++ background"* argument becomes less relevant.
Alexandre Jasmin
That's pretty cool. Thanks.
helixed
@Alexandre Jasmin - Those are a very weird form of closure. Much more explicit than most languages that support them. Though I actually like that way better. I think you __should__ have to say which variables you're intending to use from the enclosing scope.
Omnifarious
Alexandre Jasmin
+1  A: 

Here is how I think of a closure....

A function object consists of two things. The first thing is the code for the function, the second is the scope in which it executes. In a closure, the scope in which the function executes and the code are detached from each other. The same code can execute in a variety of scopes.

If this were allowed in a completely unrestricted way it would result in great confusion. Even when it's something as loose as dynamic scoping (the function inherits the scope of the place where it was called from) it becomes very confusing.

Closures are a convenient way of specifying scope rules that make a lot of sense because they only require reading the code instead of tracing it. In a closure, the function gets the scope of where it was declared. If it was declared while executing another function, it gets the scope of that specific instance of the function's stack. This is a lot simpler and easier to understand than being able to give the closure and arbitrary scope, or dynamic scoping.

Here is an example of a trivial closure in Python:

def outer():
    def closure():
        pass
    return closure

Here the function closure is a closure. It doesn't actually use any variables from the scope in which it was defined, so it's pretty trivial, but it still is one.

Here is a not-so-trivial, but still simple closure in Python:

 def outer(x):
      def closure():
          return x
      return closure
 f1 = outer(5)
 f2 = outer(6)

Calling f1() will return 5 and calling f2() will return 6. As you can see, the function closure is part code, and part scope.

When outer(5) is called, it creates a stack entry for the call that contains a version of the variable x holding the value 5. It then declares the function closure which gets that scope.

When outer(6) is called, it creates a stack entry for the call that contains a version of the variable x holding the value 6. It then declares the function closure which gets that scope.

Omnifarious
Thanks for your explanation
peterwkc
A: 

If you want an example on closures i suggest you to check the book

Dive into Python: Chapter 6 - Closures & Generators

The book its open&free and you can download it at---> http://diveintopython3.org/

The example it's interesting,clear and gradually takes a more advanced approach. For first exposure its great i think.

Take a look at it there is no reason to reproduce it here as long as you can simply download it or read it online.

siropio