On Jan 5, 2012, at 12:09 PM, Liam Proven wrote:
Closures: again, I have yet to find a readable,
comprehensible
explanation of what they are, what they are good for, why they are
powerful and what strengths they confer onto a programming language.
I can take that one, though I fully expect someone to correct me if I get something wrong.
Closures are a way of encapsulating data in a particular function instance, not unlike
the member data associated with an object's method. For example, in Python I could
write the following function:
# foo is expected to be a list here
def function_generator(foo):
def _f(x):
foo.append(x)
return _f
And I would generate a callable function that would append x to the list foo. For
example:
bar = []
append_func = function_generator(bar)
append_func("abc")
print bar
Would print "['abc']".
It's a toy example, for sure, but they're great for things like callbacks
(it's similar to a callback with a context pointer, which is a pretty popular idiom in
C; a closure just encapsulates the context pointer much like a C++ object does for its
methods).
I use this all the time in Python; great for generating tiny local functions to thunk a
string into the right format, too.
- Dave