Archive for November 2009

Programming Language du Jour

Today whilst researching how to implement a proper brainfuck interpreter, I stumbled across Babbage. I would say it’s love at first sight.

Using Extension Methods

I came up with the following extensions method in C#:

public static class NeatExtensions{
    public static bool In<T>(this T element, params T[] elements){
        return new HashSet<T>(elements).Contains(element);
    }
}

It actually yields a nice syntax for checking enum values and the likes:

enumValue.In(Enum.X, Enum.Z)

I am wondering whether there is actually a de-factor standard library in the C# world that has extensions like this.

Objects as Functions in Java

Earlier this year I wrote a build tool in java. The core idea at the time was to express the build in terms of functions and function composition. This is not exactly a good fit with java. So last week I had some spare time and came up with this way of defining a function (application) in java:

 public static class FancyFunction extends FunctionBase {
        @In
        public final Str a;
        @In
        public final Str b;
 
        @Out
        public final Str c = null;
        @Out
        public final Str d = null;
 
        public FancyFunction(Str a, Str b) {
            this.a = a;
            this.b = b;
            super.reflect();
        }
 
        protected void evaluate() {
            setResult(c, new StrImpl(a.getValue() + "-" + b.getValue()));
            setResult(d, new StrImpl("XX"));
        }
    }

There is obviously a lot of magic going on and I do feel a bit bad abou setting final fields using reflection.

What it actually does is defining two functions. In a friendlier syntax somwhat like this:

fancy.c(a, b) = a + "-" + b;
fancy.d(a, b) = "XX";

But back to the java example, you can now compose applications like this:

FancyFunction fun = new FancyFunction(new StrImpl("x"), new StrImpl("y"));
FancyFunction fun2 = new FancyFunction(fun.c, new StrImpl("z"));
assertEquals("x-y-z", fun2.c.getValue());

As this is all very reflective I could actually traverse the metadata and get dot to render this:

test

There is no code, as it is all very dirty. But to me it looks like a viable syntax for specifying tasks and wrapping imperative code into a functional style. The current implementation relies heavily on interfaces, because it generates a lot of proxies that allow for lazy evaluation.