Edit: This post has come up in a recent (2008-04-27) post on reddit. For an account of where the term, closure, came from
look here.
While reading the the
Django/RoR comparison by Sam over at magpiebrain the "Ruby has closures, Python doesn't" argument was mentioned. I admit to not being really familiar with the concept, but I believe I understand what it is. The thing is, I don't see what's important about it.
A link was given in the post to
an interview with Yukihiro Matsumoto where "Matz" is asked about what a closure is and how it's beneficial. Here's the most relevant portion of the interview:
Bill Venners: OK, but what is the benefit of having the context? The distinction that makes Ruby's closure a real closure is that it captures the context, the local variables and so on. What benefit do I get from having the context in addition to the code that I don't get by just being able to pass a chunk of code around as an object?
Yukihiro Matsumoto: Actually, to tell the truth, the first reason is to respect the history of Lisp. Lisp provided real closures, and I wanted to follow that.
Bill Venners: One difference I can see is that data is actually shared between the closure objects and the method. I imagine I could always pass any needed context data into a regular, non-closure, block as parameters, but then the block would just have a copy of the context, not the real thing. It's not sharing the context. Sharing is what's going on in a closure that's different from a plain old function object.
Yukihiro Matsumoto: Yes, and that sharing allows you to do some interesting code demos, but I think it's not that useful in the daily lives of programmers. It doesn't matter that much. The plain copy, like it's done in Java's inner classes for example, works in most cases. But in Ruby closures, I wanted to respect the Lisp culture.
I respect cool implementations of higher-order concepts as much as the next guy, but I can't help but feel cheated by that response. I've seen some bickering between Python and Ruby clerics that try to demonstrate why closures are important and how Python doesn't have them; nothing I saw gave a practical example.
Anyone have any?
Edit: I may have found a practical example, but I'm not sure what's so special about it.
Here's a wiki entry about the
benefits of closures in Ruby and here are the
Pythonized versions that work the same way. This is just a special case of closures, I'm still looking for something completely different.