Prevalent Synchronicity 0

Maybe it’s just an idea whose time has come, but in the past few days there’ve been 2 prevalent database systems announced for Clojure: FleetDB and Persister.

Prevalent Databases

The idea behind prevalent databases has been around for a while being, if not ‘popularised’ exactly, at least pushed by the guys behind Prevayler. Here’s how they describe them:

Prevayler is an open source object persistence library for Java. It is an implementation of the Prevalent System design pattern, in which business objects are kept live in memory and transactions are journaled for system recovery.

Fleet DB

While Mark McGranaghan’s Fleet DB doesn’t use the term prevalent database, but right now that’s basically what it is. The core of Fleet DB is a Clojure based append-only log based database; it provides a native clojure query language (with built in query optimiser), schema-less records, indexes, and a server with a JSON based network protocol.

For a new new project Fleet DB also has a good set of documentation and it sounds like Mark has some big plans for it in the future. As an added benefit there are also clients for the network protocol in languages other than Clojure (Ruby officially, and a set of Python bindings in development).

Persister

Sergey Didenko’s Simple Persistence for Clojure project is a much less ambitious offering, but with the really cool feature of being a single (255 line, ~11KB) file that you could just drop into your project and start using - that’s pretty lightweight! From the read me file:

Simple Persistence for Clojure is a journal-based persistence library for Clojure programs. It follows “Prevalent system” design pattern.

The intended usage is assist you in making a prevalent system. Thus you work with your in-memory data and wrap every writing call into one of (apply-transaction*) macros.

A nice feature is that the log files are just Clojure code:

Transactions are logged as a valid Clojure code, so they are easy to read and run separately.

Squeeze! 0

One of the neat features of Clojure is the sequence abstraction — it makes solving a whole host of data processing tasks much easier, simply get you data into a sequence and you’ve got a huge toolbox available to work on it. Of course being a guy I’m firmly of the belief that more tools are better, with that in mind let’s add another one to our toolbox.

Given a sequence the squeeze function returns another sequence with any adjacent items which match a supplied predicate merged together using a supplied function. It’s probably easier to illustrate by example, suppose I have a sequence of strings and I want to merge them together when the trailing string starts with whitespace, I can squeeze them like this:

(squeeze #(and %2 (re-matches #"\A\s.*" %2))
         #(apply str (apply concat %&))
         ["hello" " world." "foo" " bar"])

Another example, given a sequence of characters (read from an InputStream for example), I could group them into words by squeezing then thusly (the first line is just to remind you that calling seq on a string produces a sequence of characters):

user=> (seq "Cheers, chars!")
(\C \h \e \e \r \s \, \space \c \h \a \r \s \!)
 
user=> (map str/trim
         (squeeze #(and %2 (not= \space %2))
                  #(apply str (apply concat %&))
                   (seq "I'm sorry Dave, I can't let you do that.")))
("I'm" "sorry" "Dave," "I" "can't" "let" "you" "do" "that.")

So how does it work? Well, here’s the interface:

(defn squeeze
  [pred merge-fn coll]
  (squeeze- pred merge-fn coll nil))

And here’s the actual function that does the work, it’s declared private because I don’t want to expose the matched parameter to the outside world.

(defn- squeeze-
  ([pred merge-fn coll matched]
    (lazy-seq
      (when-let [s (seq coll)]
        (let [f (first s)
              s (second s)
              rest (rest coll)]
          (if (pred f s)
            (squeeze- pred merge-fn rest (cons f matched))
            (let [next (if matched (merge-fn (cons f (reverse matched))) f)]
              (cons next (squeeze- pred merge-fn rest nil)))))))))

I should probably point out that all of this playing around with sequences was inspired by Sean Devlin’s excellent proposal for some new sequence functions for Clojure 1.2.

The full code for this is available here (it’s just the above, but with an added doc comment on the squeeze function definition).

Working with Java Arrays 3

One improvement that I’d like to see in Clojure is more examples in the doc strings (or maybe in a separate :example metadata item). Still, nothing to stop me building up a set of my own.

So, here are some simple examples of working with Java arrays in Clojure…

Given some sample data:

(def my-list '(1 2 3 4 5))
(def my-vector [1 2 3 4 5])
(def my-map {:a "apple" :b "banana" :c "chopped liver"})

To convert to Java arrays:

(to-array my-list)
#<Object[] [Ljava.lang.Object;@962522b>
(to-array my-vector)
#<Object[] [Ljava.lang.Object;@37e55794>
(to-array my-map)
#<Object[] [Ljava.lang.Object;@52cd19d>

Note that this always returns Object[] regardless of the contents of the collection. Note also that the map isn’t flattened (the pp function used here is in clojure.contrib.pprint):

user=> (pp)
[[:a "apple"], [:b "banana"], [:c "chopped liver"]]

If the array is 2-dimensional there is a corresponding function:

user=> (def my-vec-2d [[1 2 3] [4 5 6] [7 8 9]])
#'user/my-vec-2d
user=> (to-array-2d my-vec-2d)
#<Object[][] [[Ljava.lang.Object;@3a42f352>
user=> (pp)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
nil

If you need to use a specific type of array (e.g. to pass a String[] into a Java method) or need to use an array with more than 3 dimensions it’s a little trickier:

user=> (into-array my-list)
#<Integer[] [Ljava.lang.Integer;@60c0c8b5>
user=> (pp)
[1, 2, 3, 4, 5]
nil
user=> (into-array my-vector)
#<Integer[] [Ljava.lang.Integer;@2151b0a5>
user=> (pp)
[1, 2, 3, 4, 5]
nil
user=> (into-array my-map)
#<MapEntry[] [Lclojure.lang.MapEntry;@7ae0c7c3>
user=> (into-array (vals my-map))
#<String[] [Ljava.lang.String;@731de9b>
user=> (pp)
["apple", "banana", "chopped liver"]
nil

There, that should serve as a handy reference for myself for when I’m feeling forgetful…

Paredit.el Comes to IntelliJ 0

I’ve been working on adding paredit.el like structural editing to the next version of the La Clojure plugin for Intellij IDEA. IDEA already does most of the paren matching stuff (automatically inserting a closing paren when you type an opening paren and so on). So far I’ve got the basic barf and slurp commands working, and splicing, as you can see in the screenshot below:

Slurping and Barfing

The next step is probably to make IDEA’s expand selection code be a little smarter in the face of s-expressions.

In related news: I found a good introduction to paredit.el on SlideShare which may be of interest.

I’ll try to get the guys at IntelliJ to push out a new version of the plugin after the 9.0.1 release is out (it’s in beta now).

Clojure Purists? 0

I’ve been following Tim Bray’s excellent Concur.next article series covering approaches to concurrency in various languages, and currently (no pun intended!) covering Clojure. The latest article talks about a super efficient log parsing implementation done by Alex Osborne an includes the following comment:

“Lots of the performance wins come from dipping into Java-land (AtomicLongs, LinkedBlockingQueue), which is perfectly OK, but a Clojure purist would probably see those occasions as maybe highlighting gaps in that language’s coverage.”

I’d take issue with that, one of the real strengths of Clojure it that it has easy and fast access to the whole Java ecosystem. As Rich says:

“Clojure is designed to be a hosted language, sharing the JVM type system, GC, threads etc. It compiles all functions to JVM bytecode. Clojure is a great Java library consumer, offering the dot-target-member notation for calls to Java.”

That seems pretty clear to me. I wonder if the people claiming to be Clojure purists are all coming from a Lisp background rather than the Java world?

Clojure Evaluation 0

I’ve been loking at the early-access version of Manning’s forthcoming Clojure in Action book as well as some of the criticism of it. One of the complaints is that the current drafts describe macros as a run-time concept and that this is wrong. The confusion arises from the fact that Clojure (and Lisps in general) don’t follow the same path from source to execution as a more conventional programming languages like C and Java. I’ll compare four different languages to see how they differ: C, Java, a traditional Lisp compiler, and Clojure.

C Like Languages

This is what most people are used to, the traditional compiled language. Here, source code is read in and then parsed (this is normally broken out into multiple stages, e.g. a separate lexing stage, but for our purposes we can gloss over these details). The parser emits some form of intermediate representation, usually an abstract syntax tree (AST), this is then used by the compiler to generate executable code.

C Like Languages

Again, this potentially glosses over some details: optimizers can world on the intermediate representation for example, or the compiler could require a separate linking stage to generate an executable. For our purposes though this is sufficient: we go from source to AST to executable.

Also, it could be argued that the C pre-processor operates on the source code before the parser sees it, but in practice the C macros system is so primitive it doesn’t really warrant being called out as a separate stage.

Java Like Languages

Java Like Languages

The Java like languages differ from C in that they run on top of a virtual machine rather than being executed directly by the OS; as a reult their compiler emits ‘bytecode’ rather than a finished executable. This bytecode is then executed by the virtual machine. In all modern desktop and server virtual machines this is means just in time compiling the bytecode down to native machine code.

Traditional Lisps

The Lisp view of things is a little different; it’s more complicated but also more powerful. The first thing to note is that Lisp code is already basically in the form of an AST - there is no (or not much) syntax getting in the way. Next, there are 2 types of macros which are applied to Lisp code: macros and reader macros. I’ll duscuss them in the opposite order to the way they are applied…

Lisp Like Languages

The standard type of Lisp macros are what most people rave about when extolling the virtues of the language: these are chunks of code that are executed after the source has been loaded into an AST (remember, Lisp source code is basically in this form already, so this just involves moving from a textual representation to something that the Lisp runtime can work with). If a node in the AST is a macro then it is evaluated as the code is loaded and the result of the evaluation is used to replace the macro node in the AST. Stop and think about that for a minute - this happens before the code is evaluated by the regular Lisp runtime, but yet at this point you already have access to the full Lisp programming language. All of this means that you can do some pretty cool tricks: how about writing your own control constructs? Writing a DSL compiler? Logging constructs that have zero runtime overhead when not used (but that can be switched on and off by users of the program, unlike #define DEBUG 0 in C)?

The second, and much less common, type of macro is the reader macro. Reader macros operate on the character stream as it is read in, before the AST is constructed. Basically, when the reader sees a specific character (usually #) it then looks at the next character and uses that as a key into a table of functions (the read table) that tell it how to handle future input. Using reader macros it’s possible to create DSLs that don’t use s-expression syntax (s-expressions are the paren enclosed lists that Lisp is (in)famous for); or do something as simple as allowing the use of brackets to write quoted lists without needing an explicit quote (i.e. writing [1 2 3] instead of '(1 2 3)).

Only once all of this has finished is a traditional lisp ready to let it’s compiler go to work turning the (now macro-free) AST into executable code.

Clojure

Clojure is very similar to the traditional Lisp model, with two main differences. The first difference is the fact that, like Java, the output is bytecode which is then loaded and executed by a standard Java virtual machine. The second difference is that while Clojure does have reader macros, the read table isn’t exposed to user programs; that is, while it operates in the same way as a traditional Lisp there is no way for user code to alter the behaviour of the reader. This is probably good thing as Clojure includes a relatively large number of predefined reader macros including a literal syntax for lists, sets, and maps, as well as lambda-expressions (anonymous functions) and metadata.

Summary

C and Java like languages have a huge amount of syntax baked in, but don’r provide any way to modify this or to manipulate the program before it is compiled. Lisp has almost no syntax but provides a mechanism for users to add their own, and provides a mechanism to manipulate programs before they are compiled. Clojure has some syntax (more than other Lisps, but way less than C/Java/&c.) and provides the same mechanism for program manipulation as other Lisps.

The OmniGraffle file for the images in this post is available here if anybody is interested.

Update: this post is intended to compare traditional C-style languages with Lisps, it doesn’t cover, for examples, so-called scripting languages such as Perl, Python, and Ruby.

Strawman Arguments and Coding Styles 0

So there’s this blog post over on the Best in Class blog that talks about ceremony in programming languages and compares Clojure with Java on this basis. While I’d agree with the basic premise of the article (that there is less ceremony in Clojure), I’m less keen on the way it’s presented: by way of a needlessly verbose strawman example. To be fair the article does kind of admit that this is what is being done, but it’s still annoying.

With this in mind let’s see how well we can do with the Java version of the code, relying on a better coding style and a couple of freely available libraries (one of the platforms much touted strengths). For the original — 28 line — version of the code I’ll refer you to the original post (but warn you that it’s presented in that well known code storage format, PNG!).

The same code rewritten in a smarter manner, but still using only the core Java libraries. This gets it down to 10 lines of code and also makes the intent of the code clearer. There’s still a fair amount of ceremony about this however: the multiple imports, and all of the class and static main method boilerplate.

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
 
class Distinct {
  public static void main(String... args) {
    Set<String> distinct = new HashSet<String>(Arrays.asList(new String[] {
        "foo", "bar", "baz", "foo"
    }));
  }
}

Let’s see if we can’t do a little better with the addition of some open source libraries. Enter Google Collections, a really neat library that improves the collections API from the JDK. We’re now down to 7 lines of code, and 2 of those are just closing braces! In any reasonably size program the class and main statements disappear into the noise, so we’re really saying that we have 2 import statements and a single line of code. That’s not too different from the Clojure version all things considered.

import java.util.Set;
import static com.google.common.collect.Sets.newHashSet;
 
class Distinct {
  public static void main(String... args) {
    Set<String> distinct = newHashSet("foo", "bar", "baz", "foo");
  }
}

It’s interesting to note that the second Java version weighs in at 10 lines of code, versus 8 for the equivalent clojure version; not much of a difference really.

I think that the benefits of Clojure come from it’s functional style, macro system, and excellent concurrency support — not from the fact that you can save a few lines of code here and there.

Embedding Clojure (part 2) 0

Following on from the last post, it actually turns out to be much easier to do most of the work in Clojure itself — no need for all of that tiresome messing around with Vars and Symbolss on the Java side of things! The trick is to define an abstract class in Java to set a few things up and use as a hook, than implement this in Clojure. I’ll go through both sides of this, starting with the Java stuff.

The Abstract Class in Java

Basically, I’m using the Java side of things to set up my text pane with a standard stylesheet (I’d like it to use a proportional font, with different colours for input, output, and error text) and to install a key listener to send commands to the Clojure repl whenever the user hits enter or return.

The basic class then, is

1
2
3
4
5
6
7
8
9
10
11
12
public abstract class InteractiveConsole {
    private final Document _document = createStyledDocument():
    private final JTextPane _textpane;
    private final PipedWriter _inWriter = new PipedWriter();
    private final Reader _in;
    private final Writer _out = new PrintWriter(new DocWriter("output"), true);
    private final Writer _err = new PrintWriter(new DocWriter("error"), true);
    protected InteractiveConsole(JTextPane textpane) throws IOException {
        _textpane = textpane;
        _in = new PipedReader(_inWriter);
    }
}

The createStyledDocument method, which I won’t include here, just sets up the style context and my colour scheme. The DocWriter class that is references is an trivial writer subclass that just calls insertString on the document with the named style. The other class that I’ll be wanting to use is a runnable so that I can launch the Clojure REPL on it’s own thread. It’s about as trivial as it gets, it just calls back into the two abstract methods that I’m going to provide to provide my Clojure code somewhere to hook onto.

1
2
3
4
5
6
7
8
9
10
11
12
13
private class ConsoleRunner implements Runnable {
    private final Map&lt;String, Object> _context;
    public ConsoleRunner(Map&lt;String, Object> context) {
      _context = context;
    }
    @Override
    public void run() {
        for (Map.Entry&lt;String, Object> var : _context.entrySet()) {
            bindVariable(var.getKey(), var.getValue());
        }
        doStart(_in, _out, _err);
    }
}

With this I can provide a start method that installs my key listener and then launches a new thread with an instance of this runnable. The two hook methods that I’m providing are

  • abstract void bindVariable(String,Object) to allow me to set up some domain objects on the clojure side of things; and

  • abstract void doStart(Reader,Writer,Writer) to actually start the REPL, using the provided input, output, and error streams.

The Clojure Implementation

Turns out to be trivial as well, the implementation of bindVariable just interns the object passed in into the user namespace, it’s a one liner in Clojure.

1
2
(defn -bindVariable [this name value]
    (intern 'user (symbol name) value))

The doStart method isn’t much more involved either, it just sets up the bindings and then launches the REPL.

1
2
3
4
5
(defn -doStart [this #^Reader in #^Writer out #^Writer err]
    (binding [*in*  (LineNumberingPushbackReader. in)
              *out* out
              *err* err]
        (clojure.main/repl)))

Notice that here I have added type annotations so that the correct method gets implemented, without these the Clojure code compiled but then I got abstract method errors at runtime. Check out the docstring for the repl function as well, there are a few useful options (for example in my actual code I have an :init function to switch to the user namespace, and a custom prompt).

For completeness, here’s the rest of the Clojure file with the code required to inherit from the Java base class.

1
2
3
4
5
6
7
8
9
10
11
(ns com.example.ClojureConsole
    (:import (clojure.lang LineNumberingPushbackReader)
             (java.io Reader Writer)
             (java.util Map))
    (:require (clojure main))
    (:gen-class
     :extends bg.beer.editor.InteractiveConsole
     :init init
     :constructors {[javax.swing.JTextPane] [String javax.swing.JTextPane]}))
(defn -init [textpane]
    [[textpane]])

Summary

This approach has the advantage that any additional configuration can happen in the clojure code. It would also be easy, for example, to have an additional script that was always run at start up, to allow the user to customize the console further (similar to the .emacs file in Emacs).

You could also move most of the work that I’m doing in Java into the Clojure code. I haven’t done this as I may want to support multiple languages in my console and it’s nice to have a common stylesheet and keybindings (e.g. for history) across languages. Your mileage may vary.

Embedding Clojure in an Existing Application 4

I’ve been taking a look at Clojure lately, as a JVM friendly flavour of lisp I’ve got to say it looks pretty interesting. One problem that I’ve had though is that all of the documentation out there (of which there’s very little, to be honest) seems to assume that you’ll be writing/running a pure Clojure program as you main application. There’s plenty of information about calling Java code from Clojure programs, and some information about extending Java classes and interfaces with Clojure code, but nothing about getting the two talking together at runtime.

So here’s how it’s done.

First off you need to set up the symbols and namespaces that you are going to need to start up a clojure environment.

1
2
3
4
5
6
Symbol main = Symbol.create("main");
Symbol clojureMain = Symbol.create("clojure.main");
Symbol user = Symbol.create("user");
Symbol require = Symbol.create("require");
Namespace userNS = Namespace.findOrCreate(user);
Namespace clojureMainNS = Namespace.findOrCreate(clojureMain);

Once you have these you can require the clojure main namespace, this is the same one that is used to run scripts or start a REPL from the comand line.

1
Var.intern(RT.CLOJURE_NS, require).invoke(clojureMain);

Then, and this is the bit that I had trouble working out, you need to bind your application’s domain model (or at least those bits of it that you want to expose) into the user namespace in Clojure.

1
2
3
4
5
for (Map.Entry&lt;String, Object> global : globals.entrySet()) {
    String key = global.getKey();
    Object value = global.getValue();
    Var.intern(userNS, Symbol.create(key), value);
}

Finally you’re ready to grab the main method and run it.

Var.intern(clojureMainNS, main).applyTo(RT.seq(new String[0]));

The emtpy string array here is emulating an emty sargument list at the command line.

Some things to note here: you need to intern vars before you can use them, even for core library features like require, this surprised me at first but when you remember that most Lisps are built around a very small core of special forms with everything else defined in Lisp, it makes some sense.