Halting Problem

Late Bound

Part of Roland Sadowski's website

August 3rd, 2009

gen-struct: a Clojure macro for generating classes with mutable state

Sometimes the only way to get the desired performance is to shun immutability.

In case of Clojure, that means using arrays or importing mutable classes from an existing Java library - assuming the library already has classes with properties/fields that fit our needs. Otherwise, we have to write some Java code.

Dropping to another language for performance is pretty disappointing. But sometimes it’s the only sane choice.

I’ve created gen-struct library to avoid some of those situations. This simple macro, which in reality is a modified version of the gen-class macro created by Rich Hickey, allows you to create simple, mutable and immutable structures. You can customize only one aspect of those classes: their fields. Here’s an example:

(gen-struct
 :name my.test.struct
 :mutable-fields [[float x]
                  [float y]]
 :final-fields [[int timeout]
                [static int MAX_TIMEOUT :is 1000]
                [java.io.File input]])

gen-struct automatically generates a constructor which lets you initialize all the final, non-static fields. In the above example, single constructor accepting an int value and a File object would be generated (you pass the arguments in order in which they were declared in the macro).

gen-struct classes need to be compiled, just like with gen-class.

This is an ugly duckling, since it doesn’t allow for inheritance, probably not everyone will be happy with no possibility of overriding equals, and static final fields can only be of primitive type. At least it doesn’t let you mix state and behavior in one entity.

My main motivation for creating it was that some of my experiments in clj-processing needed a lot of mutation.

§