Rodrigo Flores's Corner Code, Cats, Books, Coffee

First steps in Clojure

I remember the first time I had to deal with Clojure. I just came back after a job interview and I was asked to deliver a solution on a functional language to an exercise. Naturally, I opened a terminal and typed:

$ brew install clojure

brew is the package manager that install open source stuff on OS X. But instead of installing Clojure, homebrew returned this error:

Error: No available formula with the name "clojure"
Clojure isn't really a program but a library managed as part of a
project and Leiningen is the user interface to that library.

To install Clojure you should install Leiningen:
  brew install leiningen
and then follow the tutorial:

Unlike Ruby or Python, Clojure does not have a native compiler for OSX or Linux: it runs on the Java Virtual Machine (also called JVM). So, you don't need to install a compiler, you just need to install Java, download a JAR and you should be ready to run Clojure.

Running Clojure from the JAR

But wait, the error said that I need to install Leiningen? Yes, we will get on Leiningen on a moment. But, for now let's run Clojure directly from a JAR. You can download the most recent version of the Clojure JAR from this website: and unzip it. Then, you can run on a terminal:

java -cp clojure-1.7.0.jar clojure.main

This -cp option allows you to specify a list of directories, JAR archives and ZIP archives to the Java application launcher, the other argument clojure.main will be the namespace whose function -main will be called. You can also run a Clojure file like a script by passing the Clojure source file as another argument. To make it happen, I'm adding this content to a file called hello_world.clj:

(println "Hello world")

And I will run:

java -cp clojure-1.7.0.jar clojure.main hello.clj

And now you have run your first Clojure program. It is a simple program, the only dependency is on Clojure language. What if I want to write a program that needs to do an HTTP request? HTTP Kit is probably the most popular HTTP client in Clojure (and also can be used as a Server). Let's write a code to do a HTTP request:

(require '[org.httpkit.client :as http])
(println @(http/get ""))

For now, no need to focus on the code, just trust me that it will work: I will explain what is this @ later. To run it, you will need something more: you will need to specify the http-kit JAR.

java -cp clojure-1.7.0.jar:http-kit-2.1.19.jar clojure.main hello.clj

And voilá, it should work.


Definitely this is not a straightforward way to run code. You will need to manually download JARs, and remember to insert all of them on your command to run your program. Happily, Leiningen can help us to make it really easy to bootstrap a Clojure application, to manage the dependency and to create different profiles (think of a profile as a "different" way to run your application). If you're familiar with Ruby on Rails, it does basically what Bundler (dependency management), Rake (make-like tool to run different profiles of your application) and Thor (code bootstrap generator). It also compiles your Clojure code into JVM bytecode and also can create a JAR file for you to export it. If you wabt to a comprehensive explanation on everything that Leiningen does, you can check this excellent article about it.

So, to bootstrap a Clojure application with Leiningen you first need to install Leinigen: you can do so by downloading a script, through a package manager or if you're a M$ Windows user, you can use a installer.

After installing it, you should be able to run

lein new app blog-example

lein is the command to invoke Leinigen, new tells Leinigen to bootstrap a new project, app is the template (this argument is optional and it defaults to a library project) and finally blog-example is the name of the application we're bootstrapping.

It should have generated something similar to this:   project.clj src
LICENSE     doc     resources   test







To build our hello world application, let's for now focus on two files project.clj and src/blog_example/core.clj. project.clj is the project declaration: it contains the configuration that will be used to run your project, the name, description, the license information, etc.

(defproject blog-example "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url ""
  :license {:name "Eclipse Public License"
            :url ""}
  :dependencies [[org.clojure/clojure "1.7.0"]]
  :main ^:skip-aot blog-example.core
  :target-path "target/%s"
  :profiles {:uberjar {:aot :all}})

Let's focus on two things on this file: :dependencies and :main: the first one is a vector (for now, think of vectors as the same as what is called as an array: I will explain more about sequences later) of all the dependencies along with the versions, and :main contains the namespace that will be run when you run lein run: the function that will actually run is the one called -main. Let's take a look at the file core.clj in the directory src/blog_example:

(ns blog-example.core

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!"))

The -main only contains a println call that outputs "Hello World", and this function will be called when you call lein run.

The coolest thing about Leiningen is that you don't even need to install Clojure to run the project: just install the java, Leiningen and the first time you run the program, it will install all the dependencies (including Clojure). Also, you don't even need Leiningen to run your program: you can easily pack it with lein uberjar and run with java -jar jarfile.jar and it will run your Clojure program. So, to summarize Leiningen helps a lot.

If you want to add the http-kit you can add it to the dependencies vector:

lein deps only install the dependencies: but if you run lein run and there is a missing dependency it will install it anyway.

Last, you can add the same code inside the -main function:

(ns blog-example.core
  (:require [org.httpkit.client :as http])

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println "Hello, World!")
  (println @(http/get "")))

And then running lein run will actually do the request.

Missing Parts

I know: I've skipped some parts to make your understanding of this basic tutorial easier. I will make a quickly explanation here of those parts:

  • @ signal on http call: this is related to the asynchronous nature of HTTP Kit: a call without to the http/get function will be asynchonous and a callback can be passed as an argument and the code inside the callback will be run once the request returns something. Using @ actually turns it synchronously: it will do the request and wait the result. This construction is called promise and I will cover it later.

  • project.clj: besides your app metadata like description and license, it also includes the dependencies, where your compiled code will be generated target-path, the main function (:main) that will be called on lein run and the profiles: that are different possible switches that you can enable or disable: like testing libraries, debug libraries and so on: by default the only profile tells that when generating an jar through the uberjar command it should do the ahead of time compilation. Remember this is just a subset of all possible options for a a Project.clj: it has lot of possible options and configurations and all of them are explained here.

  • core.clj: ns is the namespace declaration: it contains what namespaces should also be required and may also contain a gen-class that will generated a named Java class: this is useful here because the JVM requires a public main method and this gen-class directive will generate this method. Last, the -main function contain an & args as argument: it will contain the arguments given on the command line this & is actually a way to tell a clojure function that the function may receive an arbitrary number of arguments (besides the ones declared before the &) and will be stored on a vector.


So I hope you learned a few things here:

  • How to "install" Clojure
  • How to run Clojure code only with Java
  • How to install Leiningen
  • How to run code inside Leiningen
  • How to add a new dependency
  • How to require it on your library

Next time I will speak more about the Clojure ecosystem: what they are and how they work:

  • Where to look for Libraries;
  • Editor recommendations;
  • Project.clj overview;
  • Core.clj overview;

8 Small git tips

As git is one of my daily tools, I've compiled 8 useful (and short) tips that I use almost everyday.

Selectively add with -p

When you want to commit something, you can either: select all the files through git commit -am or add a specific file through git add file. However, you may want to only add only a part of a file to the commit. You can use git add -p and select interactively what parts you want to add to your commit.

After selecting interactively all the chunks you want to commit, just do a git commit (without -a) and you will only commit the selected parts. There is also the git checkout -p to select changes to be reverted. After adding, you can see what you have selected using git diff --cached.

Interactive Rebase

If you're working on a branch and you made some WIP commits that you want to squash or you want to remove a commit plus the reversion of this commit, you can do a interactive rebase to reorganize your commits.

To do it, you just need to run git rebase -i <commit> where the <commit> is the sha1 of a commit before the one you want begin rewriting. Then it will open on your editor (the one specified on $EDITOR env var or the one specified on your git config) some instructions to change your commits history where you can pick, squash (merge two commits on a single one), reword (change the commit message), edit or even remove a commit.

Be aware that this change the history, so if you have pushed this commits, you will have to force to push it again, so never do this on master branches or branches that you're not the only one using.


If you in the middle of something and you have to change a context to fix something else, you can git stash the current changes. However, you may end up forgetting about this stashed changes some time later. So I try to keep a stash zero (just like inbox zero but for stashes) policy. Every time I have a stash a dollar sign appears on my prompt and then I check it through git stash show -p and then I can pop it through git stash pop or discard it through git stash clear.

Global gitignore

You can specify what files git should ignore through a .gitignore file on the root of a project. But if you have files that git should ignore but you're the only one that generates that files (like vim's bkp files or something that your editor or OS generates like .DS_Store files for OSX), you can specify on your configure a global gitignore file that uses the same syntax of a project .gitignore that will .

git config --global core.excludesfile=/Users/flores/.gitignore

Warn whitespace

I have to admit: sometimes I forget some trailing whitespaces on my code. But I normally don't commit them because I use this option: apply.whitespace=warn. Every time I'm adding a chunk of a file through git add -p, and this chunk contains trailing whitespaces, git warns me of it so I can fix it before committing.

Auto setup rebase

Another cool tip is to auto setup rebase: if you have a branch with some commits that aren't pushed and someone else also commits and pushes on that branch, when you pull, git will create a commit merging your commits to the commits upstream. As this commit is meaningless, I prefer to setup auto rebase on pull through the configuration: branch.autosetuprebase=always. Doing so, on every pull, git will try to reapply your commits with the current version of the upstream branches.

Better logging

Have you tried to find an specific commit merged from a branch ? git log provides some basic information, but you can use git log with a more useful message:

git log --graph --decorate --pretty=oneline --abbrev-commit

--graph will generate lines between commits and will expose branches, --decorate shows where branches are located in this commits, --pretty=oneline will show only the sha1 and the title line and --abbrev-commit will reduce the sha1 to the first 7 chars (which is normally unique in your repository). You can check a more detailed explanation of these options (and a whole lot more) on explain shell.

Rewrite a commit message

So you've commited something but did a poor job describing it. Or else, you just made a typo. You can rewrite the message with git commit --amend. You can use the -m to set a message through the command line or it will open the default editor with the commit message so you can change. You can also include new things with git add and add it to the previous commit. Remember that just like Interactive Rebase, it changes the history, so if you have pushed that commit, you will need to force push this changes.

If you use git on your job, you probably know a git trick that increases your productivity. Can you share it on the comments ?

Book Review: Javascript: The good parts

After reading Douglas Crockford chapter on Coders at Work (and his criticism on Javascript) and being recommended to read it by several friends, I got eager to read his book about Javascript: Javascript: The good parts. So, I spent last carnival holiday to read it.

I think the main proposal of this book is to not get really deep on all Javascript features, but to overview good features of the language (and also the most common pitfalls). It could also serve as a introduction to Javascript to someone that knows his way around programming (i.e. knows what a for, a while and a switch means), as it briefly covers the Javascript syntax (but does not goes deep on it). It also covers arrays, objects, regular expressions and how to deal with exceptions.

Object oriented Javascript

As Javascript is normally used for small manipulation of pages (like filling a cities select input through AJAX after selecting a state), it can be written as a procedural script. But as things evolve, more and more code like this end up being added, and like a snowball you Javascript code end up becaming a mess and every time you have to touch it, you start considering rewriting it.

On being a Object Oriented language, it is possible to split responsabilities in objects and use important concepts of the Object Oriented world like encapsulation and inheritance. The book also gives a good overview on how prototypes work and how to use them to create objects based on other objects.

Functions as objects

One of the greatest features of Javascript is that functions are objects (just like a number, a string or an array), so it is possible to store functions on a variable, pass them as an argument or make functions return functions. If you know how to listen to events, you probably did this by adding a function to be executed when an event is triggered.

The book explains the benefits of this property: cascading, currying, how to create a memoization mechanism, and callbacks. It also explains important concepts on functions: dealing with an arbitrary number of arguments, closures and how scopes in JS work.

Language downsides and JSLint

This chapters are on the appendix, but I think they deserve a mention as they explain why caring for good code in JavaScript is important (and how JSLint you can help you with this).

JavaScript has a lot of pitfalls: a naive a = 1 expression, when a was not declared turns a it into a global variable, the typeof behaviour for NaN is strange (who would think that typeof NaN is Number), the weak-typing misleadings ('1' + 1 being '11') and the evil == that does type coercion to both sides of the expression and end up doing nasty things like evaluation to true '0' == false and 0 == false. The book goes through all these things and explains the problems with them.

Fortunately, there is a tool (created by the author) to catch this problems before your code goes to production: JSLint . You can use this tool to check for some traps in your Javascript code (and you can also specify when you want to do some things in purpose, so JSLint will not complain about them). The book has an appendix that explains the options on JSLint.

API Documentation

One part that I think could be improved on this book is the API documentation or a big method overview . I think book pages are not the right place for an API documentation, as it is really boring to read and although you may learn a thing or another, the biggest part of it you end up reading and forgetting a few days later.

There is a chapter that goes through small set of methods of all the standard types: Strings, Arrays, Numbers, Regexps etc. It is really well written and contains good examples but I don't think a book telling the language good parts should do a method overview.


This book is a must-read if you touch any JavaScript code, as it is normally easy to write JS code, but difficult to write good quality Javascript code due to its inumerous traps and OO and function features of the that are not known to a major extent of the developer community. Even if you consider yourself fluent in JavaScript and write it for a living, you will for sure learn a new trick or something new on the language by reading this book.

The author wrote an article about how JavaScript is misunderstood, that is also worth reading if you are not a big JS fan.