I have seen samples of closure from - What is a 'Closure'?
Can anyone provide simple example of when to use closure?
Specifically, scenarios in which closure makes sense?
Lets assume that the language doesn't have closure support, how would one still achieve similar thing?
Not to offend anyone, please post code samples in a language like c#, python, javascript, ruby etc.
I am sorry, I do not understand functional languages yet.
The most simple example of using closures is in something called currying. Basically, let's assume we have a function
f()
which, when called with two argumentsa
andb
, adds them together. So, in Python, we have:But let's say, for the sake of argument, that we only want to call
f()
with one argument at a time. So, instead off(2, 3)
, we wantf(2)(3)
. This can be done like so:Now, when we call
f(2)
, we get a new function,g()
; this new function carries with it variables from the scope off()
, and so it is said to close over those variables, hence the term closure. When we callg(3)
, the variablea
(which is bound by the definition off
) is accessed byg()
, returning2 + 3 => 5
This is useful in several scenarios. For example, if I had a function which accepted a large number of arguments, but only a few of them were useful to me, I could write a generic function like so:
useful_function
is now a function which only needs 3 arguments, instead of 9. I avoid having to repeat myself, and also have created a generic solution; if I write another many-argument function, I can use thecurry
tool again.Typically, if one doesn't have closures, one must define a class to carry with it the equivalent of the closure's environment, and pass it around.
For example, in a language like Lisp, one can define a function that returns a function (with a closed-over environment) to add some predefined amount to its argument thusly:
and use it like this:
In a language without closures, you would do something like this:
and then use it like this:
The closure implicitly carries its environment with it; you seamlessly refer to that environment from inside the executing part (the lambda). Without closures you must make that environment explicit.
That should explain to you when you would use closures: all the time. Most instances where a class is instantiated to carry with it some state from another part of the computation and apply it elsewhere are elegantly replaced by closures in languages which support them.
One can implement an object system with closures.
Closures are simply great tools. When to use them? Any time you like... As has already been said, the alternative is to write a class; for example, pre C# 2.0, creating a parameterised thread was a real struggle. With C# 2.0 you don't even need the `ParameterizedThreadStart' you just do:
Compare that to creating a class with a name and value
Or likewise with searching for a list (using a lambda this time):
Again - the alternative would be to write a class with two properties and a method:
This is fairly comparable to how the compiler does it under the bonnet (actually, it uses public read/write fields, not private readonly).
The biggest caveat with C# captures is to watch the scope; for example:
This might not print what you expect, since the variable i is used for each. You could see any combination of repeats - even 10 10's. You need to carefully scope captured variables in C#:
Here each j gets captured separately (i.e. a different compiler-generated class instance).
Jon Skeet has a good blog entry covering C# and java closures here; or for more detail, see his book C# in Depth, which has an entire chapter on them.
As one of the previous answers notes, you often find yourself using them without hardly noticing that you are.
A case in point is that they are very commonly used in setting up UI event handling to gain code reuse while still allowing access to the UI context. Here's an example of how defining an anonymous handler function for a click event creates a closure that includes the
button
andcolor
parameters of thesetColor()
function:Note: for accuracy it's worth noting that the closure is not actually created until the
setColor()
function exits.This article includes two examples of where closures are actually useful: Closure
I agree with a previous answer of "all the time". When you program in a functional language or any language where lambdas and closures are common, you use them without even noticing. It's like asking "what is the scenario for a function?" or "what is the scenario for a loop?" This isn't to make the original question sound dumb, rather it's to point out that there are constructs in languages that you don't define in terms of specific scenarios. You just use them all the time, for everything, it's second nature.
This is somehow reminiscent of:
(http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html)