Clojure Programming/Examples

This page is a collection of examples of clojure code. It's living list, so feel free to contribute. In order to make this as relevant as possible, please observe the following guidelines


 * Create a separate page for your entry. Place it in Clojure_Programming/Examples/Your_Example_Name
 * Create a one paragraph summary of your example, and place it in this page.
 * Remember to link to your example

Thanks for doing your part to help the Clojure community!

Using JDBC
JDBC information can be found here. The page is still a work in progress.

Norvig's Spelling Corrector
Peter Norvig wrote an excellent example of a spelling corrector. You can see How to Write a Spelling Corrector for a more detailed explanation.

You can see the Clojure example here

Simple REPL on a Socket
Accessing a REPL over network is a very useful feature for many situations, from designing a web site to debugging a satellite in space. Here is an example how.

Simple GUI : Temperature Converter
Simple example GUI application (from discussion group, updated for 20080329 release). It is based on Swing, and you can find it here

Lazy Fibonacci
Fibonacci numbers are a classic example of an infinite recursive sequence. Clojure's Lazy functions are an excellent way to implement this mathematical construct. You can see a detailed example here.

Talking to Excel
Interfacing to other programs via COM can be easily done in Java using the JACOB library. However coping with all the low-level interface when talking to an application is quite tedious. Especially since the interface is designed for C not for Java, not to mention Clojure. So we will try to improve the situation a little bit using the power of Clojure.

A detailed explanation is here.

Creating an Applet
This tutorial explains how to create a simple "Hello World!"-applet. The article also explains how you can sign your applet (if Reflection is needed).

genclass and finalize
The functions provide the most general and powerful mechanism in Clojure for defining new Java classes. If you need to implement an existing interface you can probably use the simpler function instead, but if you need to define new Java instance methods you may need to use  or.

By way of a quick introduction, here is an example of a new class named  in a package named. This class has two methods:, a standard Java :

At this point the class exists and is loaded into the JVM, but isn't useful yet as the methods do not have definitions. Define them like this:

This class can now be used like any Java class in Clojure:

That example creates a new instance, calls, and prints the return value. The  method will probably not be called yet, but an explicit call to the garbage collector may trigger it:

Invoking Java method through method name as a String
See Google Groups original thread for a more conversational approach.

Credit goes to Timothy Pratley, pmf, and Michael Wood for helping figure this out.