Friday, July 06, 2007

Groovy and the Lambda Calculus

I've been playing around with the Groovy language, and have recently been involved in a discussion regarding the addition of closures to Java. Tangents lead to tangents, and all of a sudden, I find myself reading about Perl and the Lambda Calculus. Oy.

I had just started trying to get my head around the idea of the lambda calculus when the author brought up the subject of "currying", and discussed the "Lambda Calculus Way"™ of writing an addition function built on the concept that functions can only take a single argument. The author showed how to express such a thing in Perl:
    sub add {
my $x = shift;
my $f = sub {
my $y = shift;
return $x + $y;
return $f;

Groovy supports writing code like this too, so I thought I'd see what I could come up with in Groovy syntax. Here's the beast:
    def add (x) {
return {
y -> return x + y

And the test...
    assert 7 == add(3)(4) // whew.

If there's a Groovy expert out there reading this blog, let me know if there's a better way. All right, back to the essay...

Wednesday, July 04, 2007

Non-Static Members and Static Contexts

A question commonly asked on Java forums concerns an error message similar to the following:

non-static variable cannot be referenced from a static context

In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."

The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).