Alfredo the (Android) Clojurist

In the last post, I was just wondering how it could be possible to write a simple Clojure-based Android app. Well, I’ve succeeded, so I want to share this simple experiment with you. The main idea behind this weird experiment is that  you can import a java .jar into your Android application, then call any public-exposed method within your Android app: due to the fact that Leningen allows you to export a Clojure project into a STANDALONE jar, who prevent you to use all this awesomeness??

Download the Android SDK

In order to develop full-fledged Android apps you need the Android SDK, you can download it from here (I really like the site’s graphics). Once you have chosen your favourite platform, unzip che SDK and run the android executable (you can find it into the bin directory). The scope of this post is not teaching you how to install the Android SDK, so I’ll move further 🙂

Setting the environment

Although you can use your favourite IDE or editor, I really like IntelliJIdea, cause it provides Clojure as well as Android support. You can easily install LaClojure plugin from Idea’s plugin manager.

Another Yet Greeter out there

Which is the dumbest program you can create? We’ll create a simple program that greet you (wow, cool!). Create a Leiningen project as usual:

lein new greeter

Then write this into your core.clj file:

(ns greeter.core
    :methods [#^{:static true} [greet [String] String]]))

(defn -main [&args] )

(defn greet [param]
  (str "Hello, " param))

(defn -greet
  "Java wrapper around greet method"
  (greet param))

The code is pretty straightforward, just two observation:

  • You can expose a method to outside with the minus before the function/method name (e.g. -greet)
  • You must specify the Javish signature for your metod, see the line under :gen-class

Now we can easily export this project as a standalone .jar (remember to set the :main method into project.clj!!):

lein uberjar greeter

Now we are ready to embed our greeter into an Android project.

Final step

Now we are going to create a new Android project. For the brevity sake, I suggest you to use an IDE.
In IntelliJ Idea you can create a new Android project from stratch: (File -> New Project -> Android Module). Leave all the options to default. Now open and you should see something like this:

package com.example;

import android.os.Bundle;

public class MyActivity extends Activity
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)

Now we have to import out greeter standalone, so right click on the name of project in the project panel and click on “Open Module settings”, go to the “Dependencies” tab and add your brand-new standalone: greeter-1.0-SNAPSHOT.jar. Apply and quit.

As the last step, we have to hack a little code, in order to greet using our greet method:

package com.example;

import android.os.Bundle;
import android.widget.TextView;
import greeter.core;

public class MyActivity extends Activity
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState)
        TextView tv = new TextView(this);
        tv.setText(core.greet("Alfredo the Clojurist"));

Now run the project (you have to configure down the emulator, I don’t think it will be too difficult) and BAM!:

This is only the tip of the iceberg. Stay tuned for other weird experiments. The Frankestein era has begun!

Towards a new era?

Few days ago, my iPhone 3G smashed on the ground, suddenly showing the white screen of death.
I’ve spent several nights thinking about it, then I’ve decided switching to an Android phone. My choice was an LG Optimus One. This morning I’ve purchased it and I’m very satisfied.

The coolest thing of all this stuff is that Android is Java based, so who prevents me to write my Clojure code, packing it into a jar and then importing this jar into an Android Project?
I’m looking forward to play with the Android SDK and Clojure.

Stay tuned.

Don’t panic! [Clojure version]

Hi guys!
When it rains my internet connection is a pain in the neck, by the way I want to show you the Clojure version of Don’t Panic.
If you don’t remember it, Don’t Panic is a simple application developed with university students in mind, it periodically checks a site, looking for an update. It was a good occasion to play with Leningen!
Here is the full code (Leningen version):

;; Don't panic
(ns dontpanic.core (:gen-class))

(defn fetch-url
  "Fetches an URL. Returns a string made by the page's html."
  (with-open [stream (.openStream ( address))]
    (let  [buf (
		( stream))]
      (apply str (line-seq buf)))))

(defn hash-code
  "Simple wrapper. Returns a string hashcode."
  (.hashCode string))

(defn -main
  "Periodically check if a site has been modified."
  [& args]
      [address (nth args 0)
       site-hashcode (hash-code (fetch-url address))]
    (while true
	 (if (not (= site-hashcode (hash-code (fetch-url address))))
	   (println "Maybe an update! Finger crossed.")
	   (println "Nothing changed, calm down."))
	 (Thread/sleep 5000)))))

The idea behind the scenes is very simple: fetch-url returns the entire page’s html as a string, the hash-code function returns the string hash code. The eternal loop (while true) fetch the url, computes the hash code: if it’s different from the previous one, an maybe an update is occurred!
Shortly I will post a standalone jar!!
Usage (code version):

(-main [<site url as string>])

Usage (jar version):

java -jar dontpanic.jar <site-url>


Fun with Clojure and MongoDB

Personally I think that writing SQL queries is the most boring task in the IT world, because there exists a large variety of software elements (have you ever heard the word ORM?) that do the job for you.
Since Clojure have no objects, so no impedance mismatch, I thought it would be interesting to combine the Clojure learning and the everyday use with a NoSQL database, such as MongoDB.
There are no particular reasons why I’ve choose MongoDB, but it seems to me quite well-written and easy to use. Clojure provides a simple wrapper to the MongoDB API, the module is called congomongo, and it is installable via leningen in the usual way (add a line into the dependency section of your project.clj).

Remember to start mongod!

Like most databases in the world, MongoDB needs a deamon to dispatch the request to the database: such deamon’s name is mongod. Once installed MongoDB start mongod from console: now your applications can talk with MongoDB.

Fun with Clojure

The following code has the purpose to show some simple operations of fetch, insert and fetch with conditions:

;;Fun with MongoDB
(ns mongofun
  (:use somnium.congomongo))

;;It tells to mongo wich DB you want to use/create
(mongo! :db "mongofun")

;; A simple insert, you have to pass a map of key-value
(insert! :exams {:name "OOP" :vote 29})

;; A simple binding used to show all your exams
(def my-exams (fetch :exams))

;; A general purpose function for inserting an exam
(defn insert-exam [exam-map]
     (insert! :exams exam-map))

;; A list of maps, 1 map = 1 exam
(def exams-list [{:name "Computer Graphics" :vote 30}
		  {:name "IA" :vote 30}
		  {:name "BD2" :vote 30}])

;; Loop over exams-list, insert all the exams
(for [e exams-list] (insert-exam e))

;;Retrieve all the exams where I've took 30
(fetch :exams :where {:vote 30})

This is only a short snipped, but the interesting things is that I haven’t wrote a single line of SQL.
You can see all the exams with my-exams func.


[Clojure] Project Euler Problem 5 solution

For par condicio I have to show you the same problem solution but in my favorite language, Clojure.
Once again, it seems to me the coolest-freaking-awesome functional language in the world:

(defn div-1-20? [x]
  (defn aux [x acc]
     (= x 0) false
     (= 0 acc) true
     (= 0 (mod x acc)) (aux x (dec acc))
     :else false))
  (aux x 20))

(first (filter div-1-20? (range)))

Even this solution runs in constant space, due to the range that generates a lazy sequence.
I love Clojure ❤



Racket vs Clojure

[Project Euler Problem 4 Solution] Thanks God, Clojure exists!!

I’ve tried several functional languages (OCaml, Haskell, Racket/Scheme) but Clojure is pure awesomeness.
This is a semi-trivial, not optimized solution to the problem 4 of Project Euler.
Note: you need the pattern-match jar, a wonderful way to bring pattern matching into your Clojure functions.
You can download it from Clojars or adding a dependency in Leningen:

(use 'pattern-match)

(defn palindrome? [num-as-string]
  (match num-as-string
	 [] true
	 [x] true
	 [x x] true
	 [x & xs] (if (= x (last xs)) (palindrome? (butlast xs)) false)
	 _ false))

(sort (map (fn [x] (Integer. x))
	   (filter palindrome?
		   (for [n1 (range 100 999)
			 n2 (range 100 999) :let [k (* n1 n2)]] (str k)))))

In my opinion this version is very readable even if you are a beginner:

  • The nested for iter over two range, binding k to (* n1 n2), building a list of strings
  • The resulting list is passed to the filter function with the predicate palindrome? that checks if a number is palindrome
  • The outer map convert such filtered list in a integer list
  • The final sort sort the results because the problem wants the largest palindrome number



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.

  • Easy to install/manage/update
  • 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
    (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.


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:


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/,port=0,localport=4005]>

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


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.


Alfredo Di Napoli