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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
Here the function
closureis 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:
Calling
f1()will return 5 and callingf2()will return 6. As you can see, the functionclosureis part code, and part scope.When
outer(5)is called, it creates a stack entry for the call that contains a version of the variablexholding the value 5. It then declares the functionclosurewhich gets that scope.When
outer(6)is called, it creates a stack entry for the call that contains a version of the variablexholding the value 6. It then declares the functionclosurewhich gets that scope.