On Tue, Aug 01, 2006 at 12:05:50PM +0900, dblack / wobblini.net wrote: > On Tue, 1 Aug 2006, Chad Perrin wrote: > > >Okay. Looks like a closure. It looks like a closure because of the > >relationship of bar to the return-value block of code. I've been told > >that all blocks are closures, though -- and I don't see how it's still a > >closure if the "bar = 1" is removed from foo. > > It's a closure because it carries the context of its creation with it. > It doesn't matter whether that context has zero, one, or fifty local > variables; the same thing still happens. It sounds like what you're saying is that the lexical scope of the code block (proc/lambda/blah) is what makes it a closure, and not the connection with, and OOPish protection/encapsulation of, something that started outside the code block and went out of scope externally to the code block. I guess that makes a certain amount of sense, but that seems like an absurdly broad definition of a closure. For one thing, it would mean that absolutely any unnamed subroutine passed by reference in Perl is a closure. In fact, by the implied definition of a closure that produces, this is a closure in Perl: sub bar { sub { print "Hello world!\n" }; } $foo = bar(); $foo->(); (Yes, I find the dereferencing syntax in Perl to be ugly and cumbersome too, but that's beside the point.) That's the equivalent of this, in Ruby: def bar lambda { puts "Hello world!" } end foo = bar foo.call (".call" is much prettier than "->()") Would you say those are both closures? > > I guess you could debate whether that block is a closure, since it > never leaves the context where it's created -- so there's nothing > really remarkable about the fact that a is still visible inside it. > And every time you put its closureness to the test, so to speak, > you've turned it into a Proc, so technically the Proc, rather than the > block, is the closure. > > (Like I said, subtle hair-splitting :-) Let's assume for the moment that we'll split the hair on the side of calling it a closure, and focus on the presence or absence of a variable declared outside the lambda's scope. See my above examples. I'm not saying that's where I'd split the hair, but it's not where I want to focus right now. -- CCD CopyWrite Chad Perrin [ http://ccd.apotheon.org ] Ben Franklin: "As we enjoy great Advantages from the Inventions of others we should be glad of an Opportunity to serve others by any Invention of ours, and this we should do freely and generously."