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
  • Enterprise Buyers Guide for Tablets
    In this enterprise buyers guide Computerworld provides a framework for assessing the suitability of tablet computers with different work styles and demands. The guide takes into account upgrade cycles, pricing and contract issues with telecommunications providers. It features a shopping checklist covering screen types, connectivity and hardware as well as a guide to application management. This is in addition to a full roundup of the major players including road maps for the most popular operating systems.
    Learn more »
  • Award-winning unified information security from Clearswift.
    Fully integrated web and email gateway security solution, providing - protection from inbound threats, policy based encryption, and data loss prevention.
    Learn more »
  • Top 5 Myths of Safe Web Browsing
    There are a lot of misconceptions out there about safe web browsing. You might think you're being safe. But without the facts it’s next to impossible to stay protected against today’s changing threats. In this paper we describe the top five myths of safe web browsing, what the facts really are, and what you can do to stay secure.
    Learn more »
All whitepapers
rhs_login_lockGet exclusive access to Invitation only events CIO, reports & analysis.
Recent comments