New personal site

After years thinking about it, finally I’ve done it: I’ve registered a custom domain (a simple URL redirect) and I’ve create an app on the popular cloud hosting site Heroku: it uses the new Clojure support feature and the new (and cool) Clojure mini MVC Framework Noir.

The site is a bit slow the first time you visit it, because the app is pushed out of cache after a period of inactivity, but man, it’s free!
I really like the site layout (and Jquery is too cool). What do you think about it? Let me know! Ah, here is the url, visit it!

www.alfredodinapoli.com

On the future of clj3D

Hi to everyone,
I know that in more than a month, no new post have appeared on this blog (I apologies for this), but I’ve been busy with some cool university projects.
I’ve slowed down the developing of clj3D, for one main reason: the library needs a geometric kernel.
A geometric kernel ensure that for every shape you’ll draw on the screen, there will be a structure/data/objects representing it. Furthermore, we need a hierarchical structure, like an Hasse diagram. I will begin developing the geometric kernel as soon as possible, meanwhile be patient and explore the already-coded part of clj3D.
Bye!
Alfredo

clj3D: The first (serious as a Monkey) Clojure 3D library

As we should know, a language can’t be neither omni-comprehensive nor usable in every situation. There are some kind of areas (e.g. graphics and speed-critical software) where Java sucks badly. Yeah, there are some interesting projects but they aren’t nearly comparable to the C or C++ ones. The world of 3D graphics is very fascinating and it’s my primary goal trying to find a satisfying job into it. But, what all this stuff have to do with Clojure?
Well, a Clojure flaw was a lack of 3D graphics library. I’m not talking about idiomatic wrappers (like the awesome penumbra) around OpenGL calls, since these kind of library are too low level (in my opinion). We need something to  easily create and transform 2D and 3D objects using some solid foundations.

In my free time I’m working on this kind of library, my project was called clj-3D (not too much original, I know :D). As the documentation says “Clj3D is a Clojure graphic library for manipulating 3D and 2D objects. It aims to be the Clojure standard in 3D and 2D rendering”: I think that every attempt to enrich the awesome language Clojure is, worth the effort.
Clj3D mesh together to worlds: the former is the JMonkeyEngine, a wonderful project that is trying to make Java less horrible into 3D Graphic field; the latter is PLaSM, a geometric language developed within my university.

With clj3D you are able to display something with few lines of code: you can write your own 3D models and display it directly with clj3D! Check this out:

(use '(clj3D fenvs viewer) :reload)
(view (cube 1))

This display a light gray 1x1x1 cube. clj3D is under massive development, so only few subsets of PLaSM and JMonkey have been wrapped/coded. I hope that this project will be embraced by the Clojure community, and made better as well. For the usage and installation the github page is always “work in progress”, but you can use leiningen to satisfy the dependencies and for compile the java extra classed needed. Actually clj3D is tested only under Mac OS X, so feedbacks are welcome! I will push monthly releases on Clojars, so stay tuned!

Bye!

Alfredo

A bit of Clojure magic and high order functions are served

Hi guys, what’s up?

I’m a little busy right now. I’ve started what is probably going to be my last semester of university courses and I’ve started coding a Clojure 3D library (coming soon on these screens). But this is the good time to take a break and write something on this blog. A really cool (and useful) features of Haskell is the ability to use High Order Functions. Take a look to this simple Haskell snippet:

> :t take
take :: Int -> [a] -> [a]

> :t take 10
take 10 :: [a] -> [a]

> :t take 10 ['a'..'z']
take 10 (enumFromTo 'a' 'z') :: [Char]

As you can see the arguments are “eaten” one by one in a way that remember the dear old Pacman. In a nutshell take 10 returns a function that applied to a sequence return a result. Simple enough, isn’t it?
Unfortunately this doesn’t happens by default in Clojure. Observe this little function:

(defn sum [a b] (+ a b))

If you’ll try to invoke

(sum 1)

you we’ll get the following:

Wrong number of args (1) passed to: user$sum

This is absolutely normal, since it is the Clojure default behaviour. Googling and Stack-overflowing around a bit, I came up to a simple snippet to implement with a macro the required behaviour:

(defmacro defn-decorated
  "like defn except it accepts an additional vector of
   decorator functions which will be applied to the base definition.
   the decorators are applied in left-to-right order."
  {:author "Robert McIntyre"
   :arglists '[[name [modifers*] doc-string? attr-map? [params*] body]
	       [name [modifers*] doc-string? attr-map? ([params*] body) + attr-map?]]}
  [fn-name decorators & defn-stuff]
  `(do
     (defn ~fn-name ~@defn-stuff)
     (alter-var-root (var ~fn-name) (reduce comp identity (reverse ~decorators)))
     (var ~fn-name)))

(defn curry**
  [number-of-args f]
  (fn
    ([& args]
       (let [number-of-inputs (count args)]
	 (if (= number-of-inputs number-of-args)
	   (apply f args)
	   (curry** (- number-of-args number-of-inputs)
		    (apply (partial+ partial+ f) args)))))))

(def curry* (curry** 2 curry**))

(By the way you can find the complete clj file here.) Here’s an example of application:

(defn-decorated sum [(curry 2)] [a b] (+ a b))

But a thing I didn’t like was the explicit passing of the number of argument which the function is composed, so I wrote my own macro:

(defmacro defn-ho
  [fn-name & defn-stuff]
  (let [number-of-args (count (first defn-stuff))]
    `(defn-decorated ~fn-name [(curry* ~number-of-args)] ~@defn-stuff)))

With this simple add-on, you can easily write any kind of high order function in a way like this:

(defn-ho new-sum [a b c] (+ a b c))

I haven’t tried it in particular situations (e.g. with destructuring) but don’t expect it to work with function with multiple arity: indeed, but really  you will need to create n-arity high order function??

Feedback are welcome, as always!

Cheers!

Alfredo

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
  (:gen-class
    :methods [#^{:static true} [greet [String] String]]))

(defn -main [&args] )

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

(defn -greet
  "Java wrapper around greet method"
  [param]
  (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 MyActivity.java and you should see something like this:

package com.example;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

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 MyActivity.java code, in order to greet using our greet method:

package com.example;

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

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

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.

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