Tag Archives: clojure

Clojure: a pretty good lisp

I had had a look at clojure when it had first come out. It looked interesting, but was in its infancy. I recently started looking at it again. It is slightly different from Common Lisp. A very interesting thing about clojure is that, being “hosted” on the Java virtual machine, it has access to java libraries.

Here is a little clojure program I wrote (following the book “The Joy of Clojure”):

(ns tut1.gui
  (:gen-class))

(defn f-values [f xmax ymax]
  "Return a vector "
  (for [x (range xmax)
        y (range ymax)]
    [x y (rem (f x y) 256)]))

(defn draw-values [frame f xmax ymax]
  (let [gfx (.getGraphics frame)]
    (.clearRect gfx 0 0 xmax ymax)
    (doseq [[x y v] (f-values f xmax ymax)]
      (.setColor gfx (java.awt.Color. v v v))
      (.fillRect gfx x y 1 1))))

(defn draw-graphic [frame f xmax ymax]
  "Draw f(x y) for all x,y combinations on a 200 by 200 GUI frame."
  (let []
    (.setVisible frame true)
    (.setSize frame (java.awt.Dimension. xmax ymax))
    (draw-values frame f xmax ymax)))

(defn remove-graphic [frame]
  (.dispose frame))

And I call it from the repl like so:

tut1.gui=> (def frame (java.awt.Frame.))
#tut1.gui/frame
tut1.gui=> frame
#<Frame java.awt.Frame[frame0,0,22,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal]>
tut1.gui=> (draw-graphic frame bit-xor 300 300)
nil

which draws a pretty graphic. But, but, but! The important point in all this is that we are using Java libraries and object, from a REPL, dynamically. We can instantiate java objects, call methods on them, etc. For example, when I get tired of the graphic drawn above, I can remove it by running this on the REPL:

tut1.gui=> (.dispose frame)