Dan wrote up some descriptions on closures for his what the heck is...? series. In that piece, he mentions that environments like JVM and .NET can't support closures because lexical variables are allocated on the stack (like C), and cannot be captured.
In the comments on that piece, Miguel de Icaza and Don Box both mention that .NET compilers can "fake" a closure by creating an anonymous class to encapsulate the state-about-to-be-lost when a closure is created. For example, this:
sub make_closure { my $foo = 0; return sub { return ++$foo; } }Becomes this, through the magic of a crafty .NET compiler:
// C# source delegate void Greet (); Greet English () { int count = 1; return new delegate { Console.WriteLine ("Hello {0}", count++); } } // C# Result class GreetProxy { int local_count; GreetProxy (int count) { local_count = count; } void Run () { Console.WriteLine ("Hello {0}", local_count++); } } Greet English () { int count = 1; new GreetProxy (count); }This sounds quite interesting, but after a little googling around, I can only find a faint whisper of what's promised with an upcoming release of C#. And most of those pages point to Dan's blog in some respect. (Result: primary sources are incredibly hard to find if they do in fact exist...)
This kind of trickery can emulate a decent number of simple closures with no changes to the .NET CLR. But this simple example isn't very satisfying. For example, with this approach, is this kind closure emulatable?
sub make_closure_pair { my $counter = 0; return sub { return ++$foo; }, sub { return --$foo; }; }I suppose this kind of trickery is possible with proxy classes, but the dataflow analysis looks a lot harder to do.