On 5 January 2012 18:22, David Riley <fraveydank at gmail.com> wrote:
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.
Thanks for the example, but I am afraid I can't follow a line of it.
Sorry. I have tried to cram some Python into my head several times,
but it won't stick.
--
Liam Proven ? Profile:
http://lproven.livejournal.com/profile
Email: lproven at cix.co.uk ? GMail/G+/Twitter/Flickr/Facebook: lproven
MSN: lproven at
hotmail.com ? Skype/AIM/Yahoo/LinkedIn: liamproven
Tel: +44 20-8685-0498 ? Cell: +44 7939-087884