Setting up your environment to work with Clojure

Hi everybody,
in the last tutorial I’ve talked about Leiningen. Now the time has come to go deeper, learning how to work with Clojure with ease.

The mindless solution: Eclipse + counterclockwise

Eclipse is a general purpose IDE focused on JAVA, but you can easily customize it working with Clojure: read the tutorial here and you should be able to download and install the counterclockwise plugin. What you obtain will be an environment with syntax-highlight, REPL and the possibility to create and manage Clojure project like the Java ones.

Pros:
  • Easy to install/manage/update
Cons:
  • Even if you want to eval a single statement you have to start Eclipse

Emacs + SLIME + Swank

For someone Emacs is an extremely unfriendly editor, full of macros and shortcuts, for others is THE editor. I think that Emacs is a fantastic editor if you know how to work with it. In this part of the tutorial I’ll show you how to set up a working environment under Emacs where you can even eval Clojure code directly. If you are wondering about what is SLIME, you can simple image SLIME like your REPL. Swank is “a server that allows¬†SLIME (the Superior Lisp Interaction Mode for Emacs) to connect to Clojure projects. To use it you must launch a swank server, then connect to it from within Emacs”. In a nutshell through Swank we can start a REPL within Emacs, eval our code snippets and much more. Before getting our hands dirty, we need to install ELPA, the Emacs Lisp Package Archive. Through ELPA we can install all the stuff needed with ease.

Let’s go!

The first thing to do is open Emacs and select the *scratch* buffer from Buffer menu (Buffer -> *scratch*) and paste the following code:

(let ((buffer (url-retrieve-synchronously
	       "http://tromey.com/elpa/package-install.el")))
  (save-excursion
    (set-buffer buffer)
    (goto-char (point-min))
    (re-search-forward "^$" nil 'move)
    (eval-region (point) (point-max))
    (kill-buffer (current-buffer))))

Now bring the cursor just after the last parenthesis and press C-j (control + j) or manually select the command with Lisp-Interaction -> Evaluate and Print and wait for the operations to complete. Now close and reopen your Emacs and open a minibuffer with Alt+x or ESC+x. You will see the lower part of the Emacs window labeled with M-x.
Type


package-list-packages

inside the box and press ENTER. The window will split up in two frames and you’ll see a list of packages. Navigate through each row, bring the cursor over each of the following packages and (one by one) press “i”. You will see a “I” (a.k.a Installing) beside each package name:


clojure-mode
slime
slime-repl
swank-clojure

Now press x (a.k.a eXecute) to install the packages. If something fails, retry opening the minibuffer and tying¬†package-list-packages again. The packages installed will be displayed red. You need at least the first three. Now you have syntax-highlight and your REPL, but you can’t use it yet.

Putting all together

The last thing to do is creating a Leiningen project (do you remember my last tutorial?) specifying like a development dependency swank clojure. So, remembering some Leiningen commands we create a simple general purpose Clojure project to play with:


lein new clj-on-fly

Now open the project.clj file and make it looks like this:


(defproject clj-on-fly "1.0.0-SNAPSHOT"
    :description "FIXME: write"
    :dependencies [[org.clojure/clojure "1.2.0"]
                   [org.clojure/clojure-contrib "1.2.0"]]
    :dev-dependencies [[swank-clojure "1.2.1"]])

Now within the project directory execute

lein deps

in order to download swank clojure into the project lib directory. Now you are ready to start a swank server, and you can do it within emacs pressing ESC+x and typing “shell” inside the minibuffer.
To try it out, you can open the “core.clj” file inside your project with Emacs, now create a new shell and type


lein swank

You should see and output like this:


user=> Connection opened on local port  4005#<ServerSocket ServerSocket[addr=localhost/127.0.0.1,port=0,localport=4005]>

Now return to your core.clj buffer, open a minibuffer and type:


slime-connect

press always “y” to the questions and finally you should see your interactive REPL, which you can query and play with, as well as evaluating all the code or even a snippet. Enjoy!
I hope you have liked this article.

Bye!

Alfredo Di Napoli

Dive into Clojure – Lezione 1

Premessa

Questa serie di articoli denominata “Dive into Clojure” ha lo scopo di introdurre il lettore a Clojure e ai concetti base della programmazione funzionale. La decisione di scrivere su Clojure √® che lo reputo un buon linguaggio di programmazione ma che in Italia ha poco seguito. La mia aspirazione √® creare una serie di lezioni che vadano a comporre un piccolo libro su Clojure che possa essere venduto in una qualche collana pocket (e.g. Apogeo Pocket et simili). Queste lezione non hanno la pretesa di essere esaustive n√® sono state scritte da un programmatore esperto Clojure. Vogliono essere solo un mezzo di divulgazione per un linguaggio affascinante.

Cos’√® Clojure

La cosa migliore per definire Clojure è attenersi alla definizione che il suo creatore Rich Hickey dà sul sito ufficiale di Clojure:

Clojure is a dynamic programming language that targets the Java Virtual Machine (and the CLR ). It is designed to be a general-purpose language, combining the approachability and interactive development of a scripting language with an efficient and robust infrastructure for multithreaded programming. Clojure is a compiled language – it compiles directly to JVM bytecode, yet remains completely dynamic. Every feature supported by Clojure is supported at runtime. Clojure provides easy access to the Java frameworks, with optional type hints and type inference, to ensure that calls to Java can avoid reflection.
Clojure is a dialect of Lisp, and shares with Lisp the code-as-data philosophy and a powerful macro system. Clojure is predominantly a functional programming language, and features a rich set of immutable, persistent data structures. When mutable state is needed, Clojure offers a software transactional memory system and reactive Agent system that ensure clean, correct, multithreaded designs.

In soldoni Clojure √® un dialetto del Lisp, da cui parzialmente eredita sintassi e comandi, ma rimane ancorato al mondo della produttivit√† moderna essendo costruito sulla base di Java. Per chi come me riconosce in Java un linguaggio robusto ma troppo inflazionato ed √® stanco di scrivere 400 linee di codice e 1600 parentesi per fare quello che in Python si fa in 20 righe, allora forse Clojure pu√≤ interessarvi. Clojure incoraraggia la programmazione funzionale, ove cio√® le funzioni sono cittadine di prima classe seppur prevede meccanismi che lo rendono adatto a praticamente tutte le situazioni, dal calcolo vettoriale alla scrittura di GUI. Altra caratteristica che rende appetibile Clojure √® la possibilit√† di invocare codice Java e di essere invocato da Java stesso, rendendolo difatto adatto a scrivere piccoli connettori software o pi√Ļ in generale “glue code”.

Perchè dovrei imparare Clojure?

E’ normale chiedersi se lo sforzo di imparare un nuovo linguaggio sia ripagato in qualche modo, in altri termini se il gioco valga la candela, e se stai leggendo queste righe probabilmente una tua idea te la sei fatta o sei semplicemente curioso di imparare. Per rispondere alla domanda d’inizio paragrafo poniti le seguenti domande:

  • Vuoi imparare qualcosa di diverso dai soliti linguaggi di programmazione?
  • Vuoi imparare a programmare seguendo il paradigma funzionale?
  • Vuoi un linguaggio con cui sviluppare applicazioni concorrenti?
  • Vuoi un linguaggio che si interfacci e che possa essere interfacciato con un linguaggio maturo e robusto come Java?
  • Vuoi divertirti?

Se la maggior parte delle tue risposte √® “SI” allora sei venuto nel posto giusto. Durante queste lezioni cercher√≤ a mia volta d’imparare cose nuove per potervi proporre esempi pratici e facili e sopratutto divertenti, e questi articoli sono e saranno una buona scusa per approfondire la mia conoscenza verso Clojure e spero inneschino un meccanismo per cui finalmente anche la carta stampata cominci a muoversi investendo su questo linguaggio che per ora √® considerato di nicchia. Basti pensare che attualmente l’unico libro in lingua inglese disponibile per Clojure √® Programming Clojure edito nel Maggio del 2009. Attualmente altri 2-3 libri sono in stampa e in fase di completamento ma nessuno qui in italia si √® ancora interessato. Spero di ricevere qualche commento positivo di persone che come me sono interessate a questo linguaggio.
Nella prossima lezione cominceremo a parlare un pò di programmazione funzionale, installeremo Clojure ed eseguiremo qualche semplice istruzione con il REPL di Clojure.
Ciao e alla prossima,

Alfredo Di Napoli

Introduction to Leiningen

Leiningen is a powerful way to build your clojure projects. A common drawback working on interpreted languages is that you can’t figure out how to distribute your final work, unless you use a third party software. Leiningen allows you to create compile and distribute your clojure project with ease.

Installation

The first thing to do is to download the self-install script from the github repository:

cd ~/bin
wget http://github.com/technomancy/leiningen/raw/stable/bin/lein
chmod +x lein

where ~/bin is a directory present in your PATH (if not, you have to edit your .bash_profile or .bashrc properly).
Now you are ready to do a self-install:

lein self-install

The self-install script will download for you all the necessary stuff to start building your project.

Creating a Project

Creating a project with Leiningen is pretty easy, just type:

lein new helloworld
Created new project in: helloworld

And leiningen will create the whole project structure for you:

.
|-- project.clj
|-- README
|-- src
| `-- helloworld
| `-- core.clj
`-- test
`-- helloworld
`-- test
`-- core.clj

Two files you must be aware of:

  • project.clj, the most important configuration file
  • core.clj, where we’ll write our code
  • Now we’ll get our hand dirty writing a few lines of code, so open project.clj and you’ll see something like that:

    (defproject helloworld "1.0.0-SNAPSHOT"
    :description "FIXME: write"
    :dependencies [[org.clojure/clojure "1.2.0"]
    [org.clojure/clojure-contrib "1.2.0"]])

    Even if you are a clojure newbie the code is straighforward, clojure 1.2.0 and clojure-contrib 1.2.0 are the only two dependencies of our project. Let’s define where to search for the main class:

    (defproject helloworld "1.0.0-SNAPSHOT"
    :description "FIXME: write"
    :dependencies [[org.clojure/clojure "1.2.0"]
    [org.clojure/clojure-contrib "1.2.0"]]
    :main helloworld.core)

    helloworld.core is the namespace where to search for the main file.
    Now open your core.clj:

    (ns helloworld.core)

    It’s a bit laconic, isn’t it? Let’s add a simple main class:

    (ns helloworld.core
    (:gen-class ))

    (defn -main [& args]
    (println "Hello world!"))

    Now we are ready to compile our project, so go into the project root dir (i.e. helloworld, not the deepest one) and type:

    lein compile
    Copying 2 files to /home/alfredo/Programming/Clojure/Projects/helloworld/lib
    Compiling helloworld.core

    Finally build our standalone jar:

    lein uberjar

    Leiningen will download all the dependencies for us, this mean that you don’t need to have any clojure version installed because Leiningen will download it for you in every single project!
    The last final test:

    java -jar helloworld-1.0.0-SNAPSHOT-standalone.jar
    Hello world!

    And then you go!
    I hope you have found this post useful!
    Stay tuned,
    Alfredo

    News about the blog

    Several time has passed from my last article on this blog. It was 23th of February, 2009.
    I’ve have took two decisions:
    1) I’ve changed the blog title, now it’s a bit more professional ūüôā
    2) I’ve started to write in English, my project is to have a 100% english blog. Why? Because the time is changing (see http://news.yahoo.com/s/time/20101008/wl_time/09171202413600)

    Meanwhile I’ve tried to write a small hobby-style blog (see post below) but it is too buggy and I have no time to implement every single feature that I have here ūüôā
    Stay tuned,
    A.