Introduction to Clojure
- 10 August, 2009 17:27
Clojure is a Lisp-dialect which runs on the Java Virtual Machine (JVM). It is a dynamic programming language intended for general-purpose use. It also provides easy access to the Java standard library functions. In this introduction, we show you how to get started with Clojure.
Clojure is quite easy to install. The main requirement is a recent Java Virtual Machine (JVM) - 1.5 or later. You can download Clojure from the project download page at http://code.google.com/p/clojure/downloads/list. The latest released version is clojure_1.0.0.zip.
You can find a file called clojure-1.0.0.jar inside the zip file which contains the Clojure libraries. That file is all you need to get started. A key feature of Clojure is its shell-like interface, called the read-eval-print loop (or REPL), which you can start as follows:
You will then get a "user=>" prompt which you can use to type commands for evaluation. For example, you can do basic arithmetic:
Note the order of the operands:
You can also do nesting:
Or use multiple arguments:
The examples above are written in a form known as a S-expression, which is
similar to all forms of LISP. The basic structure of an S-expression is:
There are several pre-built functions that you can use as building blocks.
For example you can check whether two values are equal using the "=" function:
Boolean arithmetic can be done through the ‘or’, ‘and’ and ‘not’ functions:
With these building blocks, you can now write your own functions:
You may have noticed there's a problem in the above function. Giving
it a negative number as an argument will cause a stack overflow. We can solve
it by using Exceptions:
A similar example is a function to find the nth number in the Fibonacci number series:
What if we wanted to view the first 10 numbers? We can create a lambda function, by using the "map" and "fn" functions:
For those of you have been hanging out for a "Hello World" example: you can do that quite simply:
And one last example:
Since Clojure runs on the JVM, it's also possible to access the standard Java library from Clojure code. The example above is the Clojure equivalent of this Java code:
We've only covered a small fraction of Clojure, but it should be enough to get you started. To learn more, check out the Clojure getting started page (and the links in the reference section, as well as Clojure wikibook.