Critical.
Authoritative.
Strategic.
Subscribe to CIO Magazine »

Introduction to Clojure

Getting started with the latest Lisp dialect

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:

java -cp clojure-1.0.0.jar clojure.lang.Repl

You will then get a "user=>" prompt which you can use to type commands for evaluation. For example, you can do basic arithmetic:

user=> (+ 1 2)
3
user=> (/ 8 2)
4

Note the order of the operands:

user=> (- 8 2)
6
user=> (- 2 8)
-6

You can also do nesting:

user=> (* (+ 2 2) 8)
32

Or use multiple arguments:

user=> (+ 1 2 3 4 5)
15

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:

(function arg1 arg2 ...)

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:

user=> (= 1 2)
false
user=> (= 1 1)
true

Boolean arithmetic can be done through the ‘or’, ‘and’ and ‘not’ functions:

user=> (and true true)
true
user=> (and true false)
false
user=> (or true false)
true
user=> (or false false)
false
user=> (not true)
false

With these building blocks, you can now write your own functions:

user=>
(defn factorial [n]
    (if (<= n 1)
        1
        (* n (factorial (- n 1)))
    )
)
#'user/factorial
user=> (factorial 0)
1
user=> (factorial 1)
1
user=> (factorial 3)
6

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:

user=>
(defn factorial [n]
    (if (< n 0)
        (throw (Exception. "Can't find the factorial of a negative number")))
    (if (<= n 0)
        1
        (* n (factorial (dec n)))
    )
)
#'user/factorial
user=> (factorial -3)
java.lang.Exception: Can't find the factorial of a negative number (NO_SOURCE_FILE:0)

A similar example is a function to find the nth number in the Fibonacci number series:

(defn fibonacci [n]
    (if
        (or (= n 1) (= n 2))
        1
        (+ (fibonacci (- n 1)) (fibonacci (- n 2)))
    )
)
#'user/fibonacci
user=> (fibonacci 1)
1
user=> (fibonacci 2)
1
user=> (fibonacci 3)
2
user=> (fibonacci 4)
3
user=> (fibonacci 5)
5

What if we wanted to view the first 10 numbers? We can create a lambda function, by using the "map" and "fn" functions:

user=> (map (fn [x] (fibonacci x)) [1 2 3 5 6 7 8 9 10])
(1 1 2 5 8 13 21 34 55)

For those of you have been hanging out for a "Hello World" example: you can do that quite simply:

user=> (println "Hello, world")
Hello, world
nil
user=>

And one last example:

user=> (. System/out (println "Hello, world!"))
Hello, world!
nil

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:

System.out.println("Hello, world!")

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.

Join the CIO Australia group on LinkedIn. The group is open to CIOs, IT Directors, COOs, CTOs and senior IT managers.

References show all

Comments

1

Anonymous

Sun 18/10/2009 - 05:56

This guy is clueless.

2

Foobar

Sun 18/10/2009 - 06:58

What really is he trying to explain.
Very true, This guy is clueless. Moron

3

Anonymous

Mon 19/10/2009 - 10:40

Rude comments

The code may have some issues but what is with the rude comments? If you have an issue just say what is without the unnecessary personal attacks.

4

Nathan Youngman

Thu 22/10/2009 - 06:31

Clojure

@pascal, the JVM doesn't have tail call optimization yet, look into using "recur" instead of calling factorial/fibonnaci from within itself. This will save your stack.

Also look into lazy sequences (lazy-cons, lazy-cat) to do something like fibonnaci. You can use "take 10" vs. the map.

Post new comment

The content of this field is kept private and will not be shown publicly.
Users posting comments agree to the CIO comments policy.
Login or register to link comments to your user profile, or you may also post a comment without being logged in.
Related Coverage
Related Whitepapers
Latest Stories
Community Comments
Tags: a-z of programming languages, lisp, programming
Latest Blog Posts
Whitepapers
  • Best Practices for Energy Efficient Storage Operations Version 1.0
    The energy required to support data center IT operations is becoming a central concern worldwide. For some data centers, additional energy supply is simply not available, either due to finite power generation capacity in certain regions or the inability of the power distribution grid to accommodate more lines. Read on.
    Learn more »
  • Solutions Guide for Data-At-Rest
    The purpose of this document is to provide guidance into some of the factors you should consider when evaluating storage security technology and solutions. As with any security project, acquiring technology is not the only step to properly protecting your data. Part of this process should include an evaluation of the current processes and security controls in place, such as physical access controls, environmental controls, and administrative controls. While there is no single set of requirements that applies to all organizations, this Guide can provide some baseline considerations.
    Learn more »
  • Securing and Managing Your Enterprise: An Integrated Approach
    Your organization has a dizzying number of platforms, directories, systems and applications- all requiring your attention and administration. You know you need to manage this complex infrastructure correctly, or your diverse resources will cease to be assets, and instead become a serious drain on administrative time and budget. And even worse, if the management program you deploy isn't comprehensive, unsecured devices can expose your systems to significant security issues. So how you can you integrate and automate fragmented management tasks while addressing a full range of governance, risk and compliance (GRC) issues?
    Learn more »
All whitepapers
rhs_login_lockGet exclusive access to Invitation only events CIO, reports & analysis.
Recent comments

HP and IDG news, product videos and resources