Thursday, November 1, 2007

Closure Puzzlers: Greetings


If you have read my previous post on the basics of the Java closures proposal, then you might enjoy the puzzler below. A double-reference to Neal Gafter: it uses his recent prototype and is in the vein of Java Puzzlers.

This is not designed to be an elegant example: I was experimenting with closure literals, function types, and free lexical bindings. 'Tis a simple introduction... A greeting, if you will.

What is the output from the following program?


public class Greetings {
static private Object freeVar = null;

static public void main(String[] args) {
{ String => String } greetings = null;

// @param greeting
// @free freeVar
// @returns a simple message String
greetings = { String greeting =>
greeting + ", I am " + freeVar };

freeVar = "a free variable!";
System.out.println( greetings.invoke("Hello") );

freeVar = new StringBuffer("a new ").append("value");
System.out.println( greetings.invoke("Bonjour") );

freeVar = greetings;
System.out.println( greetings.invoke("Hola") );

freeVar = { String self => self }.invoke("my self");
System.out.println( greetings.invoke("Shalom") );

freeVar = { => freeVar + " too" }.invoke();
System.out.println( greetings.invoke("Namaste") );
}
}


Don't cheat but here is the output. If you understand this output, then you understand the content of the original post.


$ newJava.bat Greetings

Hello, I am a free variable!
Bonjour, I am a new value
Hola, I am Greetings$1@10385c1
Shalom, I am my self
Namaste, I am my self too

I won't explain everything but here is a brief annotation:
  • The local variable, greetings, is declared with its function type, and initialized to null. This is a separate line in order to emphasize that it is a local variable with a new, strange type.
  • We assign a closure literal to greetings. Note that it uses a 'free lexical binding' called freeVar. One issue with the current prototype is that it does not yet bind local variables (hence the static member field).
  • We alter freeVar in various ways and let greetings construct a message based on its toString() method.
  • Note that the last greeting uses a truly literal closure that is invoked in situ.
Fun! If you liked this one, stay tuned for more.

2 comments:

Unknown said...
This comment has been removed by a blog administrator.
Michael Easter said...

For the last commenter,

Good to hear from you! Feel free to contact me at codetojoy @t gmail