So I have this thing - I want to learn at least two programming languages every year. Last year I learnt Ruby and Python. I was a bit confused what languages to play with this year. A friend of mine suggested Clojure and I am happily diving in! I will decide with time the other language I will learn. This post will about writing simple Clojure code.
Step one is getting a good Clojure guide. A simple Google search will sort you out. I am using "Programming Clojure Second Edition, The Pragmatic Programmers". I'm loving the book! If you want to get your hands dirty with some code, step two is installing a Java Runtime and Leiningen. Google around how to install a Java Runtime for your OS and visit the Leiningen GitHub page on details of how to get leiningen running on your machine. Leiningen is a tool for managing your Clojure dependencies and launching tasks against your code. Someone wrote, Leiningen is for automating Clojure projects without setting your hair on fire. If your're following, you should know where it's from! ;)
You can test out this code by running a Clojure REPL. When you have Leiningen up and running, it has a REPL launch script. Run
lein repl.
Now you are all good to go.We're going to write a simple function,
favourite-activity
that takes your name
and favourite activity
as arguments and prints out your-name's favourite activity is favourite-activity!
This should be fun! To define a function is Clojure, we use the key word defn
followed by the function name, the parameters and finally the body. Here is our function:user=> (defn favourite-activity [name activity] (str name "'s favourite activity is " activity "!"))
This is how we we will call the function:
user=> (favourite-activity "Martha" "coding")
-> "Martha's favourite activity is coding!"
Nice! If that syntax excites you as much as it excites me, then get down to coding in Clojure! I will be going into details of the language in late posts.
And if Clojure excites you, then you need to play with some LISP. I recommend reading Structure and Interpretation of Computer Programs, which was recommended to me by another friend.
Cultivate the garden of your mind.