Posts tagged ‘clojure’

I would like to add just a few more arguments regarding the issue of notation.

There is a certain austerity tradition coming from the CS community (at least from the BEST part of it). Most people see syntactic sugar as a waste of time and energy. Furthermore everything is just trees and a linear representation with the root at the head is just fine to represent trees. Lisp embodies this tradition to the full. And for the most part is a great tradition.

This is all fine, and I would understand the defensiveness considered that we live in a world polluted with overly complex languages which just bring problems and no advantages to compensate.

But some level of syntactic sugar is important for humans. And while meta-programming is nice, I suppose most programming languages are still used by human programmers ;) .

It would suggest to have a look at the literature on human cognition, namely the strategies used to read text: it is messy. But I prefer to go in a different direction. I just want to expose how some subtle representation issues might have a massive impact: Have you ever tried to do basic arithmetic with roman numerals? Have a look here, namely “How can I use Roman numerals to do arithmetic problems?”. While this is a different problem, it serves to emphasize that representation matters in the most strangest ways.

Even if it doesn’t, humans are a conservative species, they are not ready to change everything at the same time. Having a to jump to imperative+heteroiconic+infix to functional+homoiconic+prefix is too much. Lisp derived languages loose potential to attract more people. And in this case is is really worth it? Is it really THAT IMPORTANT to be prefixed? Is that the main conceptual selling point of Lisp?

But most importantly there are solutions that are not dirty:.

First nobody is forcing infix notation, one can have both at the same time (check Prolog :- op – you can do BOTH +(1 2) and 1+2).

Second hard-coding operators is not necessary at all: again check the Prolog suggestion. You can have all infix operators that you want (including none)

It is easy to conceptualize a superset of Lisp with infix notation and ZERO INITIAL infix operators.

If I can shout something is this: Check Prolog’s :- op ! Simple, elegant. And fully coherent with the Lisp philosophy at its core.

Tim Bray presented his 11 Theses on Clojure. Thesis number 2 is “Being a Lisp Is a Handicap”. This argument has actually 3 parts: the Lisp-parenthesis syntax, which he finds bad. Homoiconicity (he finds good) and macros (again good).

I would like to discuss a bit the first (syntax) and the last (macros). The macro part discussed somewhere in the future. For now I would like to concentrate on syntax.

Lisp syntax is strange for most humans, we simply do not write (+ (* 2 3) (/ 4 2)). Lisp proposers are probably aware that this will not be very popular, as people are used to something completely different. It is not only different but is also very uneconomical to both read and write: 2*3 + 4/2 is arguably easier to read. One can even make some intuitive declarative things. Notice that I’ve written 2*3 (no space around *) but 2*3 + 4*2 (spaces around +). This allows to give queues to readers about the precedence of operators. You can say that these issues are just simple and ridiculous syntactic sugar. Well, it seems that Homo sapiens has evolved to appreciate it. And I don’t really see a reason not to accommodate this requirement.

Yes, I read you already: infix syntax forces hard-coding of operators and precedences (e.g. + precedes *) . Makes parsing much more complex (there goes the beautifully simple Lisp parser out of the window) and in fact forcing a certain structure with hard-coded operators.

Well… no.

Take a look at Prolog op built-in. :- op allows you to define operator precedence and association rules. So the parser is really not much complex: it starts with a simple, uber-flexible, blank slate which you can fill in.

So, for (- 4 3 2) you can say – is an infix operator with first argument with precedence over the second (i.e. (4 – 3) – 2) and, voila, you can write 4 – 3 – 2. No need for hard-coded operators, all dynamically defined. You could, maybe for sadistic reasons, change the argument precedence so 4 – 3 – 2 would become 4 – (3 – 2). The flexibility is there.

You can also state that + and – have higher precedence than * and /. So that 2*3 + 2 is interpreted as (+ (* 2 3) 2). Again, you can change the precedence rules.

Ah… and you can have operators that are atoms (alphanumeric symbols). In Prolog you can say “X is 3 +2″. “is” is an operator. You can redefine operator rules, define new operators.

Operators are nothing more than a set of syntactic sugar rules to convert a more intuitive representation to another. But they really make things much more pleasant and humane.

I would imagine that adding this to Clojure would be DEAD EASY, by the way.

Regarding the issues about macros, I will leave it for another post.

What is the importance of the names that are given to things when programming? There seem to be quite some different approaches to this issue. Some people think that calling data items/variables a, b1, c is OK. Less people are seen defending the idea that functions should be called f1, f2, f2. Some other people think variables should have names connected with their meaning, so, if you have a data item whose content is related to a person object, maybe that variable should be called something with “person” on its name, like currentPerson, or whatever.

So far, nothing new. I for one, am in the group of the explicit naming of everything.

Sometimes the name has some impedance between the average expectation and the functionality exposed. That can be a source of lots of grief. Lets have a look at a concrete example to make things clear.

Clojure has a function named contains? . How do you expect such a function to operate? Let me give a few examples (and if you know how it really operates in reality, try to forget for now what you know).

What you think would be the result of:

1
2
3
4
5
(contains? [3 5] 3)
(contains? [3 5] 1)
(contains? "bla" 1)
(contains? "bla" "a")
(contains? '(1 2) 1)

Does [3 5] contains 3?
Does [3 5] contains 1?
Does “bla” contains 1?
Does “bla” contains “a”?
Does (1 2) contains 1?

Actually (contains? [3 5] 3) is false. Why? Lets have a look at the documentation:

clojure.core/contains?
([coll key])
Returns true if key is present in the given collection, otherwise
returns false.  Note that for numerically indexed collections like
vectors and Java arrays, this tests if the numeric key is within the
range of indexes. [...]

So contains? is looking at the KEYS of a collection. The vector [3 5] has two keys: 0 and 1 (the indexes with occupation of the said vector), that is why (contains? “bla” 1) is true (the string “bla” has 3 keys 0, 1 and 2.

By the way, the list (1 2) is not a collection, so that false is caused by a type error.

Note that contains? actually has some utility ;) : it is used to check if a map has a certain key.

There is an slight impedance between what most people would expect from “containing something” and contains? It so happens that slight impedances are much worse than big ones, because big ones are so damn obvious that they are easy to spot and normally end up being corrected (imagine a function drawLine, that draws a circle: it is a dead obvious problem that one will easily notice and the developer most probably correct). Slight impedance problems are more obnoxious:

  • They will confuse newbies (like myself), whose expectations will be aligned with the general knowledge of a certain name or action.
  • They will increase the cognitive load of experts which will need to be aware of the dissonance between the meaning of a certain word in the programming language and the meaning in the natural language.
  • It will make reading and understanding a program more difficult.
  • They will be a source of bugs, as developers, even experienced one, will sometimes forget the local meaning of a word and unconsciously apply the general meaning.

By the way, my personal solution for contains? Well, quite simply rename it hasKey? and only apply it to maps. Note that this post is not about contains? in particular, but about this “impedance” problem in general.

I would imagine that some readers might think this as irrelevant and nitpicking. In my subjective and personal point of view, this issue is a potential source of hard to find bugs and a waste of mental energy. In fact this blog is called Cognitive _Consonance_ for some reason…

Here is my first clojure application: A phylogenetic tree viewer (PhyloXML format). The obligatory screenshot:

Simple Phylogenetic viewer

Simple Phylogenetic viewer

Preamble:

  1. This is newbie code: Handle with care! My main objective is not to make a tree viewer but a tree comparer. So this is no more than a learning step.
  2. You can test it yourself as it is a Java WebStart application, just click here. You don’t need to have a phylogenetic tree file yourself. I supply an example inside.
  3. This makes use of JGraph and Archaeopteryx (the PhyloXML parser)

I do maintain this code on github. I have one project for the viewer and another for general utilities. All the code is still very crude, but you might be interesting in stealing some of the swing code, either as a crude example of how to interact with swing or taking my micro-DSL for menus. If you want to interact with JGraph, this might be a starting point. I don’t want, in any way, suggest that this code is any good.

Some lessons that I’ve learned and that I would like to share:

  1. Some of the clojure.contrib code is a bit green. I tried to use the graph library, but it is very small and specific. I ended up starting doing my own. Mine is even smaller and specific, no claims of generality.
  2. I don’t appreciate some of the core functions of Clojure (I’ve written on this before and will write more in the near future). The great thing about Clojure is that you can import only what you want from the core and extend it yourself. I intend to do just that for my personal use. This is a PLUS point for Clojure: the flexibility that is made available to change many of the decisions of the language implementor (in the great tradition of declarative and homoiconic languages)
  3. While I can change the core for my uses, I think defnk should really be core for everybody! I fact I wander if defn should not become defnk…
  4. I am pretty sure that when *warn-on-reflection* is activated and action taken to correct the warnings, lots of code will increase in performance. With the more important side effect of annotating the code with type info.
  5. I have quite a lot of recursive code that doesn’t use recur. Something to learn and master…
  6. JGraph layout algorithms are not fantastic. I’ve tried with much bigger trees and the result was far from perfect (I also noticed performance problems in my own code).

The biggest hurdle that I’ve found was the construction of user interfaces and how verbose Clojure Java interop can become. Of course one can create functions (and that was done) to create buttons, frames, menus, etc. But the creation of Java container structures (think frame contains menubar which contains menu with menus inside and so on) would benefit from a dialect where, when a certain (container) object was created it’s (Java) namespace would become easily available.

Imagine constructing a Structure like this:

MenuBar[
    Menu(File) [
        Menu(New)
        Menu(Close)
        Separator
        Menu
    ]
    Menu(Edit) [
        Menu(Cut)
        Menu(Paste)
    ]
]

it would be nice to be able to write something like:

((new JMenuBar)
   (add ((new JMenu "File")
       (add (new JMenu "New"))
       (add (new JMenu "Close"))
       (addSeparator)
    )
   (add ((new JMenu "Edit")
       (add (new JMenu "Cut"))
       (add (new JMenu "Paste"))
    )
)

“add” and “addSeparator” are Java methods. All this would be dynamic against the Java object hierarchy (not a hand-written library!). Note that there is no doto special form (or variants) and, most importantly, note that, given a list (a b c d), if a is a Java object b c d are evaluated as methods of a. If b is (i (y x s)), x and s would be evaluated as methods of y, if they failed then as methods of a, if this fails interpreted as normal Clojure. Something like this (rough sketch).
This would be useful, e.g., to construct Swing hierarchies by hand in a expedient way (not suggesting anything more, especially not to do big programs with outside scope).
I am going to try to write some code that does this in the next few days.

Here can be found an interesting effort to implement the 99 Prolog problems in Clojure.

It is not clear to me that the exercise is conducted in the same way as the original one [Update: the author actually says this in the preamble]. Let me explain:

The original Prolog problems are solved without the help of the (existing) Prolog libraries, just using the basic language mechanisms. They are a good at illustrating the underlying declarative power of Prolog.

For instance, problem 1, finding the last element of a list is solved with this in Prolog:

% P01 (*): Find the last element of a list
 
% my_last(X,L) :- X is the last element of the list L
%    (element,list) (?,?)
 
% Note: last(?Elem, ?List) is predefined
 
my_last(X,[X]).
my_last(X,[_|L]) :- my_last(X,L).

Notice the in-code comment that “last is predefined”. In fact, using the Prolog library this could be done with a one liner:

?- last([1,2,3],E).
E = 3.

The offered solution in Clojure is also a one liner:

user=> (last [1 1 2 3 5 8])
8

Given a sufficiently large and clever library (and Clojure has a very nice library) all problems on the list could be solved with a one-liner.

In my opinion, an apples-to-apples comparison with the original solutions would not use the core library.
It would probably be like this for the same problem:

(defn mylast [l]
  (let [mynext (next l)]
    (if (nil? mynext)
      (first l)
      (mylast mynext)
    )
  )
)

Yep, next is in the core library also, but being a call to clojure.lang.RT, I think it is fair game to use it.

Ok, better yet, with recur, as it is on core (this is essentially a copy of the core version):

(defn mylast [s]
  (if (next s)
    (recur (next s))
    (first s)
  )
)

The Prolog exercise exposes the declarativeness and expressive power of Prolog. The Clojure example exposes mostly the cleverness of the core library.

Both are interesting points of view (I am not criticizing the Clojure solution), but they cannot be used for comparison purposes.

There is, in my view, an inconsistency with the clojure core API with regards to type checking.

Consider the two functions contains? and even?

contains? returns true if a certain collection has a certain key:

=> (contains? {'a 1} 'a)
true
=> (contains? {'a 1} 'b)
false

If you pass an object which is not a collection, contains? silently returns false.

=> (contains? 1 'a)
false

I.e., a type error is not distinguishable from a collection which does not contain a certain element.

even? , the function to check if a certain number is, well, even, behaves in a completely different fashion:

=> (even? 'a)
java.lang.ClassCastException: clojure.lang.Symbol cannot be cast to java.lang.Number (NO_SOURCE_FILE:0)

A type error on the parameter raises an exception with even?.

From a design philosophy I really do not like this inconsistent behavior: For the same type of error (a typical error pattern) the API behaves in a clearly different way.

The 2 points that are important (but, alas, are not the fundamental issue of this post) are:

  • Core functions should have a coherent and consistent way of dealing with type errors. This is the most important point.
  • If they have a consistent way of dealing with type errors, my preference would be for a behavior like even? (ie, throw) and not like contains?.

Yes, I do understand that other reasons might have taken precedence (like performance). I still don’t like it.

But the beauty of clojure is that one can redefine these “core” functions. For instance, I prefer to have

(defn contains? [coll key]
  (if (coll? coll)
    (clojure.core/contains? coll key)
    (throw (new ClassCastException
                     (str (type coll) " cannot be cast as collection")))
  )
)

[Newbie alert: there might be better ways to design a function like this (suggestions welcome).]

Now, one as to be careful not to import the original contains? into a namespace. Easy done in clojure:

(ns myuser (:refer-clojure :exclude [contains?]))

This has to be done before the definition of the new contains? (note that, when calling the old contains? it includes the full namespace).

Of course, redefining core functions (even if inside namespaces not seen outside) is a bit like laying a mine field and probably has to be done with care. Irrespective of that, it is good to be able to have a language which allows one to express itself with the syntax and semantics that one desires, and not to be constrained to the whims of the original developer.

So far, no big problems found with Clojure (at least until now).

Having read Tim Bray’s tips for Clojure newbies from a newbie, I decided to write a version of my own.

First, I generally agree with Tim’s observations, so this post is more like minor extension. In fact I recommend reading Tim’s version first.

My background so that you know my point of view: Added to Java, C and Python experience I have lots of exposure to Prolog (which is, like Clojure, homoiconic) and some experience with OCaml (a functional language). I have had some practical contact with other “modern languages over JVM”: Scala and Groovy. No Lisp experience (other than basic elisp).

Reading suggestions: Other than Tim’s comments I would add: The clojure site information is really not very useful as a starting point, the reference part assumes that you already know quite a bit and it is though on newbies, the only thing that I tend to use is the API section. Like Tim, I also use Mark Volkmann’s introduction (It is my main documentation, and I would be a bit more positive than Tim about it. For an intro article it is great. I strongly recommend it as a starting point and as the reading anchor during the first weeks). Next week I plan to order Stuart Halloway’s book, so I still cannot comment on that.

On a more general note, while learning Clojure, I’ve found Paul Graham’s On Lisp (available for free), a gem and I would strongly recommend it. It is not an easy read, it probably takes months to digest the content. But it is really a great book.

Clojure is a fast moving target. Documentation of many modules and functions might not be up to date with the current code. I have noticed that sometimes the best “documentation” ends up being reading the code (clojure is hosted on github and so are many satellite projects – In fact getting familiar with github is probably another recommendation).

Some of the contrib stuff is a bit too green, and I would recommend inspection of some of the modules before using them. Just because it is accepted on clojure.contrib it does not mean it is production quality, has even bare functionality or the exposed API is stable. As an example the graph API is minimal and I question if the graph structure directed-graph is enough to represent a general directed graph (future changes to it will probably break existing code built on top of it). This is not a criticism, a new product is bound to be fast changing, and agile methods of development will entail lots of instability at the beginning. But a caveat should be added to the stability and completeness of parts of clojure-contrib.

Regarding editors and IDEs, I would probably recommend for you to stick with what you feel more comfortable with (vi, emacs, netbeans, eclipse, …). Note that Clojure, being a Lisp derivative has a big share of its user base on emacs. I mainly use Netbeans using the wonderful enclojure plug-in. I can only say that encloure is stable enough for usage and I recommend it if you are a Netbeans type of person.

I also second Tim’s comments on namespace hell. Uses/imports/requires can be quite confusing. Hell is too harsh of a word, but purgatory seems an accurate description ;) . Also, as Tim says, the clojure mailing list and IRC channels are very, very helpful.

One of the most annoying kinds of bugs come from typing problems, things like this:

(defn hiddenBug [a b]
  (println a) ;lets do a println for debug purposes
  (println b) ;lets do a println for debug purposes
  (if-not (= a b) (println "they are different!"))
)

Now lets call this:

(hiddenBug 'x "x")
x
x
they are different!

Notice that, when you are debugging a and b will seem equal on a println, but they are not (one is a symbol, another a string)!

The biggest gotcha that I have been getting is the expectation (Java based) that stupid things raise exceptions, but sometimes they don’t. Here is an example:

user=> (contains? '(a b) 'a)
false
user=> (contains? 'blab 'a)
false
user=> (contains? (list 'a 'b) 'a)
false
user=> (contains? ['a 'b] 'a)
false
user=> (contains? '(a b) :a)
false
user=> (contains? '(:a b) :a)
false

In all these cases, the Java-expecting gnome inside me was hoping something of a throw (as the first argument is not of the type required by contains? ) . It is not clear to me if this is a design issue with contains? only, or it is something that is standard along the whole API. But I notice this from the API reference:

(even? n)
Returns true if n is even, throws an exception if n is not an integer

So it seems that the design is not homogeneous throughout the API as some functions throw exceptions. I would probably prefer a throw when the type of arguments is wrong, but people with lots of Lisp experience might have a different view on the issue. Anyway I would like to understand if the lack of homogeneity is a feature or a bug.

More than 10 years ago I participated in the development of an University IT system (the front- and backend to maintain grades and that sort of stuff). The system was based on a DB/2 backend (a very nice database system) with the business code stored on a Prolog interpreter (Prolog interpreter which was in-house developed) and the web backend being a Java servlet engine (the old JServ, the thingy pre-Tomcat from Apache). Prolog is famed to be slow, and Java (at that point in time) was very slow. Surprise, surprise… the bottleneck was on the DB/2 server. Eventually, as the system grow (and the database hardware was beefed up) the bottleneck come forward to the business and web tiers, but the problem was sorted by just adding more machines: The contention was on a bunch of parallel independent process, they could be run on separate machines.

The example above illustrates why the concurrency problem posed by multiple core CPUs and GPUs, might not be that much important:

  1. Many problems are not CPU bound anyway, and even if they are, the bottleneck might be elsewhere. Another example: I am the proud owner of 3 cheap, slow laptops (one being a netbook). For my use case I really don’t need faster applications, I wonder how many users really need more than they already have?
  2. Even if more CPU/GPU power is needed, a loosely coupled model (without much interprocess communication and contention issues) might be enough. This is typically the case of many web apps, which can scale by just adding more computers which run independent processes.

Concurrency, even with modern abstractions, is hard. It should be avoided if possible and it can be avoided in many applications. If it cannot be avoided, maybe a loosely coupled model is enough… Guido van Rossum has a nice take on this issue.

This is important as concurrency is being touted as an important criteria to evaluate languages. Modern functional languages (think Scala and Clojure) are being touted as a better option precisely because they are better to do concurrency (both because of functional – “no changing state” – programming and the availability of libraries implementing nice concurrency paradigms like actors).

When addressing this importance of this issue, I would propose, that people would ask themselves this: “Am I developing computationally intensive software?” and “If I am developing computationally intensive software, can I live with loosely coupled models of computation, preferably processes with no shared memory?”

This is not to say that there are not some cases where tightly coupled computing is a good idea. It is just that, this complex solution might be an overkill for many problems.

I would just like to add that I am not defending my cause, in fact it is quite the opposite. There is actually some content produced here, in the past, on how to tackle concurrent programming:

  1. LOSITAN – A multicore-aware Jython-based (Python for the JVM) Web Start application to do selection detection.
  2. An introductory tutorial on concurrent computing targeting computational biologists – Part 1, 2 and 3

When you read about programming language comparisons, the main narrative for comparison is normally about the paradigm(s) supported. Lisp, Haskell, Scala, Clojure fall mainly in the functional realm. Prolog is logic. Smalltalk OO. C and Fortran, imperative. Most of them are not “pure” paradigm (e.g. you can make nice OO designed programs in C – just check GTK’s GLib library if you disagree, imperative coding in Prolog, and so on…), but that is besides the point.

The point is that, when comparing programming languages, the main issue of discussion is the bloody paradigm thing.

Paradigm is not really that important! In fact, as said above, you normally can tweak a language to write in your favorite paradigm. Sure the ability to do that varies from case to case, but in most cases that I can think of, it is really not difficult to cross paradigm boundaries. In fact, I would go as far as to argue that it is easier to do proper OO design with C using GLib then with the highly complex and convoluted C++.

Before going into the fundamental point that I want to make, I would also note that ecology matters: Are there good libraries? Good documentation? Does it run on a virtual machine? Portability? Nice community? User base? That is, when comparing programming languages all that is around the language is more important than the language itself. Just ask all the poor of us poor Prolog/Lisp/Haskell fans why are we doing Java/C++ during most of our day? It puts bread on the table, and, for the most of us, that is the most important criteria (I prefer not to starve!).

But, going to the main point here, I would like to propose that one of the fundamental points in comparing programming languages from a technical standpoint is homoiconicity.

Just to remember, an homoiconic language is a language where the program is represented as the core language data-type. Code is a data type.

If you classify languages according to homoiconicity, then they split in completely different ways:

  1. The homoiconic bunch: Lisp, Prolog, Ioke, Clojure, …
  2. The non-homoiconic bunch: Cobol, Fortran, C, Java, Goovy, Scala, Haskell, OCaml, [A very long list follows]…

From this point of view, the comparison of say, Clojure to Scala as sister-languages makes little sense, as they fall in different groups.

Homoiconic languages lend themselves to – by construction – metaprogramming and extensibility (think very easy embedded DSLs). And some of these features are difficult (with varying levels of difficulty) to implement in non-homoiconic languages. At best (as “best” I am thinking of some scripting languages like Python), they are awkward to do in a non homoiconic language.

As a side jab, last time a checked, Scala was very very poor on metaprogramming (has that changed?), making it the only “modern” language which seems to be scorning metaprogramming. Scala can still be DSL-extensible (I offer my own example both in Scala and Grovy: Ronald: A Domain-Specific Language to study the interactions between malaria infections and drug treatments.

One could argue of the value of doing programs that reason about themselves (and that idea has very bad karma coming from assembler – an idea so old and so disconnected from current reality that I am not even going to discuss it). I am surely on the side that proper metaprogramming is one of the core features of any elegant, productive and declarative solution.

Also, a very nice side effect of having code as data, is that the syntax of homoiconic languages is normally very, very simple (as in trivial to learn). This is just a side effect, but compare this with the learning curve of, say, C++ syntax. There is also a philosophical issue here: you get a simple, highly flexible environment, where complexity is tacked not by having a complex mammoth that tries to address all possible cases, but by a set of plastic, bendable building blocks.

Homoiconicity is not a black-and-white feature. For instance, Lisp macros are not first-class objects (I am a Clojure newbie, so feel free to correct me) so you cannot metaprogram with them. Prolog seems to come close. In fact, to a Prolog programmer, Lisp macros seem especially inelegant as the are “out of the system”.

I am doing some development in Clojure (a Lisp type language for the JVM). Lisp as in a clone tailored for the JVM, not Lisp as only “functional programming”. I note, by the way, that more than functional programming, Lisp is an homoiconic language.

I developed a simple system to specify Swing menus in clojure, here is an example:

Simple Menu

Simple Menu

The following “micro-language” was developed to specify this:

 (getMenuBar actionManager '(
    (menu {
      :text "Project" :key "P"
      :content (
        (item {:text "New" :key "N"})
        (item {:text "Open" :key "O"  })
        (item {:text "Close" :key "O" :id "Close" :enabled false})
        (item {:text "Recent" :key "R"})
        (separator)
        (item {:text "Exit" :key "E"})
      )
    })
    (menu {
      :text "Options" :key "O"
      :content (
        (item {:text "Rendering" :key "R"})
      )
    })
))

The code is very easy to read, I hope: two menu items, with a few menu entries with text, ability to enable/disable and accelerator keys, plus a separator.

Notice the actionManager on top, is it the (very simple) event processing function which receives only a text as parameter (to identify the selection). The text is simply the menu text, or, if specified an id. Not the most general solution, but enough for simple menu structures.

The code? Below is the _complete_ implementation.

 
(ns org.tiago.swing
  ;(:require clojure.contrib.def)
  (:use
    [clojure.contrib.seq-utils :only (flatten)]
    [clojure.contrib.def :only (defnk)]
  )
  (:import
    (java.awt.event ActionListener KeyEvent)
    (javax.swing JFrame JMenu JMenuBar JMenuItem)
  )
)
 
(defnk createFrame [title :menuBar nil]
  (def frame (new JFrame title))
  (. frame setDefaultCloseOperation (. JFrame EXIT_ON_CLOSE))
  (if menuBar (. frame setJMenuBar menuBar))
  (. frame pack)
  (. frame setVisible true)
  frame
)
 
(defmulti addMItem (fn [manager x & rst] (first x)))
(defmethod addMItem 'item [manager content menu]
  (let [params (second content)]
    (def mItem (new JMenuItem (:text params)))
    (if (contains? params :id) (. mItem putClientProperty "id" (:id params)))
    (if (contains? params :key) (. mItem setMnemonic (. (:key params) charAt 0)))
    (. menu add mItem)
    (. mItem addActionListener manager)
 
  )
)
(defmethod addMItem 'separator [manager sep menu]
  (. menu addSeparator)
)
 
(defmulti getMBItem first)
(defmethod getMBItem 'menu [desc]
  (let [params (second desc) manager (last desc)]
    (def menu (new JMenu (:text params)))
    ;Assuming mnemonic is ASCII CODE.
    ;java7 has . KeyEvent getExtendedKeyCodeForChar
    (if (contains? params :key) (. menu setMnemonic (. (:key params) charAt 0)))
    (if (contains? params :id) (. menu putClientProperty "id" (:id params)))
    (dorun (map #(addMItem manager % menu) (:content params)))
    menu
  )
)
(defmethod getMBItem :default [arg] (new JMenu "UNK"))
 
(defn getMenuBar [actionManager menuItems]
  (let [manager (
      proxy [ActionListener]
      []
      (actionPerformed [e] (let [obj (.getSource e)
                                 id (.getClientProperty obj "id")]
        (actionManager (if (nil? id) (. obj getText) id))
      ))
   )]
   (def menuBar (new JMenuBar))
   (dorun (map #(. menuBar add %)
            (map #(getMBItem (concat % (cons manager ()))) menuItems)))
    menuBar
  )
)

OK, comments have to be added ;) .
From a declarative point of view, not bad at all.

My first Lisp program. It completely baffles me that, 25 years of programming with all the languages imaginable (including some functional like Caml or highly declarative like Prolog), I never tried Lisp.