Learning Clojure: Part 1

Clojure is a functional programming language based on Lisp and written to run on top of the JVM. I’ve tried learning it in the past, but have failed mostly due to biting off more than I could chew. But not this time! I’m taking my time, reading lots of code, and doing 1st year computer science assignments with it. I figure this worked well when I first learned how to program, so it will probably work well now.

The Return to Trivial Programs

After spending the past 6 years neck deep in non-trivial professional programming, I’m returning to trivial toy programs to learn Clojure. My first task is to write a program that takes user input from the terminal and calculates their salary at a year which they input. More specifically:

  • Starting salary is $1000
  • Salary doubles every year
  • Validate input to make sure it is a number.
  • Write history to file called: salary_history.txt
  • In format…. [years_working]:$[salary]

All in all its pretty straight forward. I currently could write this program in a handful of different languages (Python, PHP, Java, Javascript [Node], Ruby), but am struggling with one bit of the Clojure implementation.

(ns salary.core
(defn get-integer
    "Returns a string in integer form, else false."
        (#(Integer/parseInt %) input)
        (catch Exception e false)))
;; Incomplete.  Will eventually write to a file.
(defn output
    "Takes the console input and error message and outputs them to file and console."
    [console-input message]
    (println (str console-input ": " message)))
;; ????? WTF DO I DO HERE
(defn calculate-salary
(defn -main
  [& args]
  (println "How many years do you want to work?")
  (let [user-input (read-line)]
    (let [years (get-integer user-input)]
        (if years
            (calculate-salary (- years 1) 1000)
            (output user-input "This is NOT an integer.")))))

The Python implementation of calculate salary would look something like this:

def calculate_salary(years):
    salary = 1000
    for i in range(years-1):
        salary = salary * 2
    return salary

But in Clojure things are bit more complicated. In Clojure values are immutable. I can’t just loop over the years and keep doubling the salary while storing it in the same variable. I need to use recursion. Or reduce. Or map. Hell, I don’t know. I need to use something functional, lest I want the Clojure experts to laugh at me. I need something that will call a function that doubles whatever value comes into it, then returns. Then I need to call said function up to N times (where N is the number of years that the person enters).

Any ideas?

With the help of Ryan (below), I came up with:

(defn calculate-salary
    [years salary]
    (if (= years 0)
        (calculate-salary (- years 1) (* salary 2))))


There is a grand myth about requirements–if you write them down, users will get exactly what they want. That’s not true. At best, users will get exactly what was written down, which may or may not be anything like what they really want.
– Mike Cohn, “Succeeding with Agile”

Methods & Properties with Javascript OOP

Note: This isn’t quite OOP. It’s actually called the “module pattern”.

If you come from a language such as Python, PHP, or Java, you’re used to having public and private methods and variables. In Javascript this is possible too, but it’s not nearly as straight-forward. To make this happen, you usually need to wade through Javascript’s prototype inheritance. However, there is another way.

Step 1: Create your class.

function MyClass(somevar) {

Now that your class is created, you can instantiate an instance of it by doing the following:

var x = new MyClass(123);

Step 2: Public Methods and Properties

To expose properties and methods to the public, you need to attach them to an object and return it. Some people will attach to this, but I prefer to create a new object called self and return that. It keeps me from getting confused with what this scope I’m in. One thing to remember, is that anything inside of your class that isn’t in a function gets executed as soon as you create a new instance of it.

function MyClass(somevar) {
	var self = {};
	// Check to make sure somevar is defined and then
	// assign it to the my_property public property.
	if(somevar === undefined) { somevar = false; }
	self.my_property = somevar;
	// A public method!
	self.alert_loop = function(count) {
		if(count === undefined) { count = 1; }
		for(var i = 0; i < count; i++) {
	return self;

You’ll see that we have two things exposed here: my_property and alert_loop. To access them, do this:

var x = new MyClass("Hi!");
alert(x.my_property); // Alerts "Hi!"
x.alert_loop(2); // Alerts "Hi!" twice

Step 3: Private Methods and Variables

Creating private methods and variables is very easy using this method Javascript OOP. All you do is not attach the variable or method to the self object.

function MyClass(somevar) {
	var self = {};
	/* Private */
	var loop_max = 2;
	function add_numbers(x,y) {
		return x + y;
	/* Public stuff */
	if(somevar === undefined) { somevar = false; }
	self.my_property = somevar;
	self.alert_loop = function(count) {
		if(count === undefined) { count = 1; }
		for(var i = 0; i < count; i++) {
	self.alert_numbers = function() {
		for(var i = 0; i < loop_max; i++) {
	return self;

And to use it:

var x = new MyClass("Hi!");
x.add_numbers(1,2); // Will fail.
alert(x.loop_max);  // Will fail.
x.alert_numbers();  // works!


That’s it! Using this style of OOP in Javascript is easy to learn and easy to understand. If you have any questions, drop a comment and I’ll get back to you.

Using JSHint with Sublime Text 2

Awhile ago I was looking an editor that was cross platform, light weight, and awesome. I’d dabbled with Netbeans in the past, but found it to be a little heavy for what I needed it for. I ended up settling on Sublime Text 2. I have a hard time coming up with words for how awesome Sublime Text 2 is, so here’s a screenshot of my current window.


One of the languages I find myself writing frequently is Javascript. As most of you know, Javascript has an assortment of odd conventions that can be pretty hard to remember. Code quality checkers like JSLint and JSHint exist for this reason. Prior to Sublime Text 2 I never bothered integrating either of those tools into my editor, but found myself needing to streamline my development process.

Sublime Text 2 provides an easy way to write build systems depending on which language you’re using. The sublime-jshint plugin takes advantage of this. All you do to make this work is go to the sublime-jshint GitHub page, and follow the instructions. Once it’s installed, run CTRL+B (CMD+B on Mac) while inside a Javascript file and you should see output like this.

HTML 5 Canvas: Saving to a File with PHP

So you’ve finally discovered the wonder that is the HTML5 Canvas element. Great! If you’re like me, the first thing I wanted to do with it was doodle on it. I eventually worked out how to map touch/mouse events to the canvas and draw lines, but I wanted to save my creations!

As it turns out, the Canvas element has a method called toDataURL(), which base64 encodes the entire Canvas element and returns it as a string. From there, you can just pump it over to a server and handle it from there. Here’s the step-by-step, which assumes you are also running jQuery on your site.

Step 1: Save the canvas and POST the data

var data = document.getElementById("myCanvasID").toDataURL();
$.post("process.php", {
	imageData : data
}, function(data) {
	window.location = data;

Step 2: Process the POST data, and save it to a file.

$data = substr($_POST['imageData'], strpos($_POST['imageData'], ",") + 1);
$decodedData = base64_decode($data);
$fp = fopen("canvas.png", 'wb');
fwrite($fp, $decodedData);
echo "/canvas.png";

Note: The first line of this script removes the header information that is sent with the encoded data.

Thats all there is to it. You can now easily save your HTML 5 awesomeness.

jQuery Map Function

Sometimes when you are making a web application you neeed to search some data. A lot of the time, it exists as an array in memory. I recently came across such a problem on a Phonegap project I’m working on. The app has to work offline, so my sorting needed to take place in Javascript. Since we’re using jQuery with this app, I decided to play with jQuery’s Map function. Map takes your array and performs an operation over each value in it. This was super handy in my case because it allowed me to search through my data at fast pace, without having to make an ajax call out to my database to do a search with MySQL.


var searchTerm = $("#searchField").val().toUpperCase();
var results = $.map(self.defaultProductList, function(product,i) {
	if(product.name.toUpperCase().search(searchTerm) != -1) {
		return product;

searchTerm is the value that I’m searching for. .map takes an array as it’s first argument, and then a function as it’s second. I created an anonymous function that checks to see if the search term is in the current object. If it is, I return the value so it can be added to the final array. All in all, an excellent way of searching through data when you don’t have the luxury of a database to query.

CoffeeScript with WebSQL and jQuery

Lately I’ve developed a distaste for Javascript.  I like what Javascript has done for the web, but I hate the syntax.  I hate that there are little “Gotch Ya!”‘s all over the language.  I don’t have to worry about that too much anymore though since I’ve started using CoffeeScript.  If you interested in learning more about it, check out the official web site, and then my “Getting Started” guide.

Now that I’ve had a chance to dive in to CoffeeScript a bit more, I’ve started to integrate what I’m doing with other features and libraries to see what I can create.  For work I’ve been using a lot of WebSQL and jQuery, so that was the first place I took my new found CoffeeScript powers to.

Using jQuery with CoffeeScript is really, really, easy.  For instance, let’s say we want to Ajax a page into an array:

$.get("mypage.html", (data) -&gt;
    myArray.push data

The syntax changes just a hair, but overall it looks a lot cleaner.

As mentioned previously, the other thing I’ve been doing a lot at work recently was working with WebSQL.  It’s been dropped by the W3C, but Webkit has implemented it already so it’s here to stay.  Anyways, CoffeeScript makes WebSQL a little more palatable.

#Start a transaction
db.transaction( (tx) -&gt;
    query = "SELECT * FROM table"
    tx.executeSql(query, [], (tx, results) -&gt;
        rLength = results.rows.length
        for(i=0; i &lt; rLength; i++)
            alert results.rows.item(i).someColName

With WebSQL and CoffeeScript, the syntax doesn’t change a ton, but I like the look of it better without the braces.

Another feature that I wanted to share with out about CoffeeScript is it’s equivalent to PHP’s key, value loop construct.  In PHP, it would look like:

foreach($key =&gt; $value as $myArray) {
    //do stuff

In CoffeeScript, the equivalent is:

for own key, value of myArray
    #Do stuff.

The benefit of the CoffeeScript version is that it can loop over object properties as well, not just arrays.  If you have any other cool features or examples of CoffeeScript usage, drop a link (or example) into the comments.

Getting Started with CoffeeScript

Note: You may also be interested in “CoffeeScript with WebSQL and jQuery“, which gives more examples of CoffeeScript code.

Lately in web development circles there has been a movement to make Javascript easier for everyone. Well, easier is probably the wrong word.  Lets just say that they want to “modernize” it’s syntax.  A little language has been gaining a lot of attention lately that does just this, and it’s called CoffeeScript.  A quick example of assigned on a condition:

big = true
number = 100 if big

Instead of:

var big = true;
if(big) {
   number = 100;

Anyways, this tutorial is about getting the CoffeeScript compiler up and running. To do this, you’re going to need Node.js and the Node Package Manager(NPM).

Step 1: Node.js

Getting Node to install is pretty straight forward. All you need to do is download the latest stable version from here and then run:

make install (may need to run as super user)

Step 2: Node Package Manager

Node Package Manager is the equivalent of EasyInstall for Python. It allows a user to install pre-made programs, like CoffeeScript, easily without worrying about build dependencies or any annoying stuff like that.

If you have Curl installed (most Linux/Mac users will), the easiest way to make this happen is to do the following:

curl http://npmjs.org/install.sh | sh

I personally ran into problems with this because of some permissions errors. If you run into this, check https://github.com/isaacs/npm/blob/master/README.md out which has extensive documentation on how to get around it.

Step 3: Install Coffee

Now that we have all of Coffee’s dependencies solved, you can install CofeeScript by doing:

npm install coffee-script

Step 4: Brew Some Cofee

Let’s make a math object…

math =
	cube: (x) -&gt; x * x * x
	square: (x) -&gt; x * x
startNumber = 2
cubeStartNumber = math.cube(startNumber)
squareStartNumber = math.square(startNumber)
alert "Cube: " + cubeStartNumber
alert "Square: " + squareStartNumber

Now, save this file to test.cs and then run coffee -c test.cs on the file. You will get a new file called test.js that looks like:

(function() {
  var cubeStartNumber, math, squareStartNumber, startNumber;
  math = {
    cube: function(x) {
      return x * x * x;
    square: function(x) {
      return x * x;
  startNumber = 2;
  cubeStartNumber = math.cube(startNumber);
  squareStartNumber = math.square(startNumber);
  alert("Cube: " + cubeStartNumber);
  alert("Square: " + squareStartNumber);

That’s it!

If you run in to any problems during the install process, drop a line in the comments and I’d be happy to help.