Clojure – getting started

This post marks the start of my journey into learning Clojure. I should warn the reader that this is very much a journey in progress and I’m not a Clojure expert. However I do have extensive experience in programming in OO languages such as C# and, most importantly, Java. Why is Java important? Because Clojure is a language that is built on, and interacts with, Java. Having said that, this (hopefully) series of posts may prove useful to others in the same situation, since it’s likely that someone with years of OO experience behind him will face many of the same hurdles in learning what is, at first glance, an alien language.

I’ve looked through 3 books on Clojure, and all of them suffer to a greater or lesser extent from the same problem: they engage in voluminous waffle at the start about all sorts of technical stuff that may be of interest to a full professional but is of little value (and even less comprehensibility) to someone who just wants to see how Clojure works and start writing a few simple programs. So I’ll keep the introductory waffle to a minimum and try to just dive in and see how things work.

First, though, we do need to understand a little about what Clojure is, so that even the simplest program makes some sense. Clojure is a functional language, and is very similar to Lisp (a functional language that’s been around for about 50 years). A functional language is one in which pretty well all code is written as function definitions, and calls to other functions. This contrasts with imperative languages, which include object-oriented languages like Java and C#, and procedural languages like C. Rather than go into waffle mode at this point, I’ll just say that we’ll see how Clojure works by developing a number of programs, rather than by trying to provide abstract explanations that rarely mean anything without some code to anchor it to.

Although it’s possible to write Clojure code with a text editor and run it from the command line, I have grown so used to having an IDE for software development that the first thing I did when I thought of learning it is to find a decent environment in which Clojure can be written. My Java IDE of choice has always been Netbeans, and there is a Clojure plugin for Netbeans that is relatively painless to install. It is called Enclojure, and is available by following the instructions at on the Getting Started page. One word of warning however: do NOT, repeat NOT, visit the Download link from Enclojure’s page; there is nothing there that you need, and in fact if you try to install one of the plugin files from that page, it won’t work. Just follow the instructions on the Getting Started page. After you install Netbeans and Maven, the bit about the “one time setup for Enclojure plugin” works all on its own, without the need for you to manually download anything. Finally, in the section on “getting started with the enclojure plugin in Netbeans”, it is very important that you do a ‘clean and build’ on the project before trying to open the REPL (I’ll say what a REPL is in a moment). The first time you build a project, a pile of files will be downloaded that are needed to run Clojure, but again, this is all handled for you so don’t worry.

If you’re an Eclipse fan, there is a plugin called Counterclockwise that allows you to write Clojure code. I’ve installed it and run a simple project with it so I know it works, but I haven’t used it beyond that.

Right. So how do we write a simple “Hello world” program in Clojure? Assuming you’re using Netbeans with Enclojure, create a new Clojure project (make it a Clojure Maven 1.1 Project). In the New Project dialog, call your project HelloWorld1 (we’ll be writing a few HelloWorlds). Delete the “com.yourcompany.defpackage” in the Default namespace box and enter something like “glenn.rowe.hello_world1” (without the quotes, and using your own name if you like) instead. Choose a location for your project on disk (you might want to store your Clojure projects in a separate folder), and then click Finish. Netbeans will then create your project, which should appear in Projects panel. Open the ‘Source Packages’ node and then open all subnodes until you get to a file called hello_world1.clj:

Double click on the filename to open the code editor. You will see the following code in the editor:

(ns glenn.rowe.hello_world1
	;(:import )
	;(:require )

The ‘ns’ refers to a namespace, but don’t worry about that now; we’ll get to those later. Just notice that it’s the same namespace you entered when you created the project. Lines beginning with a semi-colon are comments. The ‘import’ and ‘require’ bits are optional things you can do with a namespace; again, don’t worry about this for now.

If you look at the folders into which Netbeans put your hello_world1.clj file, you’ll see that they follow the structure HelloWorld1\src\main\clojure\glenn\rowe. The last two folders are the first two elements of the namespace, while the last element of the namespace is used for the Clojure file name. If you’re familiar with packages in Java, you’ll see that similar strategy is being used here. Although they aren’t quite the same thing, for now you can think of a Clojure namespace as similar to a Java package, in that it provides a wrapper in which code can be written.

To get your first Clojure program to do something, enter a line of code on line 5 so the total code looks like this:

(ns glenn.rowe.hello_world1
	;(:import )
	;(:require )
(println "Hello world!")

As you might guess, println prints something to the output, and “Hello world!” is what it prints. But how do we get it to do this? This is where the REPL comes in.

REPL stands for “read, evaluate and print loop”. It acts like a console window in which you can interact with your Clojure program. You can start a REPL in an ordinary command console window in Windows if you like, but since we’re using Netbeans, we’ll use Enclojure to bring up a REPL.

Assuming you’ve already done a ‘clean and build’ when installing Enclojure, all you need to do now is right-click on the project name in the Projects panel and select “Start Project REPL” from near the bottom of the popup menu. (If you get some error message about jarfiles not being found, this means you haven’t done a ‘clean and build’ on a project yet, so cancel the REPL, do the clean and build, and then try to open the REPL.)

You should now get a Clojure REPL panel in Netbeans. It will show the following when it starts up:

user=> nil

You can actually type raw Clojure code directly into the REPL, but we want to get the code in the hello_world1.clj file to run. To do this, we need to load this file into the REPL. Make sure you save the file first, since unlike many builds in Netbeans, this doesn’t happen automatically. Right click on the HelloWorld1 project again and select “REPL->Load all Clojure files in Source Packages”.

As soon as you do this, you should see some output in the REPL:

Hello world!

You see that the println has printed its output.

So what exactly just happened? First, we remind you that Clojure is a functional language, so println is a function (a built-in function provided as part of the language). The string “Hello world!” is an argument to the function (that is, it’s what println will print). A function call in Clojure is always written as a list of what are called forms enclosed within parentheses. A form can be a literal (a fundamental element that evaluates to itself), such as a number or, as here, a string. It can also be a symbol, which evaluates to something defined elsewhere in the program. println is a symbol, since it refers to code that implements the printing capability. In this case, the println function has been written for you, but it is of course possible to define your own functions, which we’ll get to later.

A form can also be a compound form, consisting of a list of other forms. The overall statement

(println "Hello world!")

is an example of a compound form.

A function call can return a value, or it can return ‘nil’ (roughly equivalent to Java’s ‘null’). The println function returns nil, since all it does is print something to the screen and has nothing to do or say beyond that. This is where the ‘nil’ that is printed to the screen after ‘Hello world!’ comes from: the REPL will print the return value of a function call.

Although most statements in Clojure consist of lists enclosed in parentheses, a literal is also a valid statement on its own. Try typing some numbers directly into the REPL. You’ll see that they evaluate to themselves and the REPL just prints the same values back to the screen.

That will do for an introduction, but if you want to try a bit of arithmetic, you can try entering, directly into the REPL, statements like (* 34 56) to do multiplication or (+ 9.3 –783.2) to do addition and so on. Again, these are predefined functions, but this time the function name is the arithmetic operator, and the arguments are the two numbers you enter afterwards. You can also try nesting function calls by saying something like (+ (* 2 5) 3) (see if you can figure out what it will say before you type it in).

Post a comment or leave a trackback: Trackback URL.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: