The latest expert opinions, articles, and guides for the Java professional.

Challenge your functional programming abilities with Clojure & Leiningen

Next JVM languages to learn graph

In a recent survey of over 2100 software engineers, Clojure was selected 3rd after Scala and Groovy as the “next JVM language to learn”. Wait, what? Clojure, basically Lisp for the JVM, isn’t even in TIOBE’s top 100 programming languages–yet, 1 out of 8 Java developers want to learn it? Interesting…

This reminded me of a blog post that was written almost a year ago by RebelLabs Author Erkki Lindpere, about his vision on a OOP vs. FP debate and the composability of objects. This great, controversial post produced some great discussions, and although I recommend you going over them, they are not critical to understanding this article.

What Erkki said that got me thinking is this:

“I think most programmers today (including me) don’t really understand how to make this approach work for complete programs. I would love for the functional programming advocates to put more effort into explaining how to build complete programs (that contain GUIs, database interactions and whatnot) in a functional way.”

And this is exactly what I want to talk about today. Most of us have a solid background in programming object oriented software. Almost everything is an object in Java and you’re anything like me, and spend most of your day using Java and JVM, it inevitably left a mark and hardwired certain design patterns into your brain.

So let’s not start with full programs right away, let’s build something simpler first: how about we build a data structure in Clojure?

A data structure is a good option, because data structures are important, operations on them are normally described in an imperative fashion and the implementation can be small enough to figure it out in one go. I’ll pick Clojure in light its persistence and fiery community in the JVM world–if you need to refresh your memory you might want to look at The Adventurous Developer’s Guide to JVM Languages – Clojure”, but I’ll quickly review the necessary parts here as well.

Say hi to Clojure

Clojure is a dialect of Lisp that gets compiled for and run on the JVM. Clojure is a functional language, with a code-as-data approach, macros, software transactional memory and reactive agents for concurrency. Clojure is dynamically typed, which brings joy to half of the world while saddening another half. Also there’s an effort to get an optional type system for clojure, so don’t dismiss Clojure just because you’re a static typing fan.

Don’t worry if you’re not fluent in Clojure, we won’t go deep. Necessary constructs for us will be following:

;; evaluates the expression, parentheses are important 

;; creates a named function called ‘name’ which takes param list as a param and evaluates the expression 
(defn name [param list]
         (expression optionally using params)) 

;; prefix notation
(+ 3 4) 
(zero? (mod 100 10)) 
(take-while neg? [-2 -1 0 1 2 3])

If you can guess an approximate meaning of these, you’re good. Otherwise, spend 10 minutes on this getting started guide, which will be useful anyway.
Now, let’s tackle a small problem using functional programming!

Creating a queue

This part was heavily inspired by a Reddit thread discussing the same topic. How do traditional concepts like encapsulation or inheritance convert into the functional world? Do we need them there at all?

The context of these questions is: how would you go to implement a queue in a functional programming language? The object-oriented paradigm was designed to answer this modeling question easily. Most of the things in the OO world are nouns (aka objects), so when designing something you extract nouns from a necessary functionality description and build your model around that. For a queue, you’ll take a list of nodes and make the parent queue object reference the head and the tail, and limit the operations so only a queue interface is exposed.

Functional programming works better when you focus on the verbs that describe possible actions and what, in general, is possible to do with the values. If we get a value that represents a queue, which operations will we carry on it?

First we need to construct a queue somehow, then there are two basic operations that are allowed: enqueueing an element and dequeueing it. Ok, ok, also peeking at the head of the queue without modifying the state. This is actually an answer to the question: how do you design a queue in a functional language?

You declare a module or namespace, or whatever concept your language uses to prevent you from polluting the general namespace with your functions and specify operations:

  • empty-queue
  • enqueue
  • dequeue
  • head / peek

Then, the implementation basically writes itself, seeing how many ways there are to create an empty queue value that is implemented by two lists. Now other functions must operate on a given queue value, so they take it as an argument. The problem statement didn’t specify that the implementation has to mutate data in-place, so we can peacefully return a new queue where the desired operation has already happened.

(def empty-queue [() ()])
(defn enqueue [[a b] x]
  [(cons x a) (concat b [x])])

(defn head [[_ b]]
  (first b))

(defn dequeue [[a b]]
  [(butlast a) (rest b)])

The code above is straightforward and trivial. Cons and concat are functions to manage lists; first, rest and butlast are as well and they mean exactly what they say: first returns the first element of a list, and rest returns all the rest of the list. This simple implementation is sufficient to use in a designed system and you can always revisit the implementation of these functions later.

Naturally, you can always go deeper into the language toolbelt and find concepts like protocols, closures, records or datatypes and produce something that resembles an OO solution that you’re accustomed to. However, remember that most of the problems that we deal can be expressed with a handful of verbs, which should map nicely into the function declarations. So keep it simple.

Getting a real app running

At this point we’ve tried our hand at modeling a small, well-defined problem in the functional style and the solutions we came up with are fairly comprehensible. Let’s try something closer to a real-life application.

One good thing is that for all mature languages, there are appropriate build tools that are great at providing you with a solution to a problem already solved by somebody else. Clojure project management is automated by Leiningen. Install that, and the easiest way to get to the Clojure REPL becomes: lein repl. As you can see on the image below, it does indeed produce a healthy REPL instance and you can immediately show off your functional programming skills or test if some Clojure construct works as expected.


Now that is just a beginning; here’s how you create a command line application that reads some input and spits the output back.

To create a new project, run:

shelajev@shrimp ~/repo/tmp » lein new cmd-app
Generating a project called cmd-app based on the 'default' template.
To see other templates (app, lein plugin, etc), try `lein help new`.

Then you need to locate a file called core.clj and edit it a little. My core.clj looks like this:

(ns cmd_app.core
    (:gen-class :main true))

(defn greeting []
    (println "Hello beautiful world!")
    (println "Enter something: ")
    (let [phrase (read-line)]
        (println (str "Echo: " phrase)))
    (println "Ciao!"))

(defn -main [& args]

I looked for a Leiningen template that will create a full command line application that parses arguments and then gives control to my code, but I failed to find one. So we’ll go with this simpler version, which starts, reads the input and serves as a great entry point for learning your way around building somewhat useful utilities in Clojure.

Now, we just need to package this application into a executable JAR. Doing that with Leiningen is also straightforward with the uberjar command. First of all, let’s mark which class will be main. Edit your project.clj to include that information:

(defproject cmd-app "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url ""
  :license {:name "Eclipse Public License"
            :url ""}
  :dependencies [[org.clojure/clojure "1.5.1"]]
  :aot [cmd_app.core]
  :main cmd_app.core)

Also, notice the “:aot [cmd_app.core]” line in the project.clj, it tells the Leiningen what namespaces to compile ahead of time.

Build a standalone JAR:

shelajev@shrimp ~/repo/tmp/cmd-app » lein uberjar
Compiling cmd_app.core
Compiling cmd_app.core
Created /Users/shelajev/repo/tmp/cmd-app/target/cmd-app-0.1.0-SNAPSHOT.jar
Created /Users/shelajev/repo/tmp/cmd-app/target/cmd-app-0.1.0-SNAPSHOT-standalone.jar

Now you have a runnable JAR file. It is a small application, but you can easily grow it further.

If you are not a fan of command line applications but still want a generic entry point into your application so you can only worry about the business logic, check out our look into the subject with The Adventurous Developer’s Guide to Clojure and start hacking your app with a http server around it.


In this post we looked at a really simple example of modeling your data structures in a functional style using Clojure. Then we created a sample project for the command line application so you can try Clojure and refresh your functional programming skills.

OOP is not the only available programming paradigm and often when solving problems you want to exercise the functional way of thinking. There are two main challenges that prevent you from diving into the beautiful world of functional programming: inexperience in designing your programs without the explicit help of objects and inability to kick off a small working project that you can gradually improve on.

Trying out different approaches to programming and even programming languages you are not fluent in is a slow, not very rewarding process. I don’t doubt that at least once or twice a year you think about switching to Haskell, Erlang or something esoteric. However, my own experience shows that it is not that easy to do; however, if you start with small projects that are actually useful, then the skill will accumulate over time.

Hopefully, next time you need to write a small command line utility, you’ll remember this post and unleash the power of Clojure and functional programming onto the task. By the way, when you do it, please mention it to me @shelajev. I’d love to hear that.

Read more about Clojure and 7 other JVM languages on RebelLabs. There’s a great report that’s just dying to have you download it!


Responses (9)

  1. Avatar  


    May 6, 2014 @ 4:31 pm

    I’m curious if you see any opportunity for JRebel in Clojure projects?

  2. Avatar  


    May 7, 2014 @ 12:50 am

    I like the post, and was wondering why you implemented the queue using two lists in an array as opposed to one list? Using conj, first, and rest on a single list seems idiomatic for Clojure, and there’s no need for 2 lists to implement a queue.

  3. Avatar  


    May 7, 2014 @ 5:42 am

    I think the author tried to implement the Banker’s Dequeue. A immutable queue that has (amortized) constant time enqueue/dequeue. The trick is to enqueue to the second list and dequeue from the first. From time to time one has to copy the second list into the first list. If you do that right (i.e.. not too often) you get amortized constant time operations.

  4. Avatar  

    Alex Miller

    May 7, 2014 @ 5:40 pm

    Clojure provides a better implementation of this already although it’s a little hidden. Obtain an empty queue with clojure.lang.PersistentQueue/EMPTY, then use cons to add elements and peek to look at the head or pop to remove the head and return the new queue.

  5. Avatar  

    Alex Miller

    May 7, 2014 @ 5:47 pm

    For the leiningen template, use the “app” template to create a project that has a class with a main, and uses AOT:

    lein new app cmd-app

    This takes care of several of your steps. The resulting project should be immediately ready for ‘lein uberjar’ to produce a runnable jar.

  6. Avatar  

    Colin Fleming

    May 16, 2014 @ 7:49 am

    If you’re used to using IntelliJ for your Java code, you might like to try Cursive ( which provides great Clojure support, including mostly-complete Leiningen support (disclaimer: I’m the author). It provides great integration between Clojure and Java for mixed projects, and is generally a pretty smooth learning curve for folk coming from Java (or Scala or whatever).

  7. Avatar  

    Oleg Šelajev

    May 20, 2014 @ 10:09 am

    I’m not doing any serious Clojure development at the moment. So for my occasional code I use LightTable. When it first appeared on KickStarter, I liked the idea a lot. However the implementation didn’t blow my mind, for which I blame me being spoiled by the superb Java IDEs.

    One thing I liked about having a new language and a new IDE at the same time is that I didn’t expect myself to be proficient right away. Changing all the tools gave me an opportunity to really focus on the whole experience and think about every small thing I did, instead of just having a hard-wired memory for some of the actions.

    So for a professional job I’d probably switch to the Cursive or Idea + Clojure plugin (afaik there is one), but for the learning purposes LightTable is great!
    Oh, and the whole configuration is done in ClojureScript, so while configuring the IDE I’ve learnt things.

  8. Avatar  

    Oleg Šelajev

    May 20, 2014 @ 10:10 am

    Thanks a lot for this, it does indeed work better!

  9. Avatar  

    Colin Fleming

    May 21, 2014 @ 1:41 am

    Sure, LightTable is definitely great for getting started, no doubt. I agree with what you’re saying about trying something new, too – LightTable is definitely an interesting change.

    The Jetbrains Clojure plugin is La Clojure, but they’re not developing it further (at least for now) since I’ve been working on Cursive. Cursive is also a plugin for IntelliJ – I’ll make it a standalone IDE at some point, but right now it’s plugin only.

RSS feed for comments on this post.

Leave a comment