Thursday, September 23, 2010

Lesson 1 - Hello Clojure

(spit "hello.txt" "Hello World! Hello Clojure")

Type the above code into a text editor and save it as "hello.clj". Now open a terminal command/window and run the program by typing "lein exec hello.clj" into the command line. You will see a file called "hello.txt" created in the same folder, with "Hello World! Hello Clojure" as its contents. Thats your first clojure program!

Of course you need to have Clojure, lein and lein exec installed on your computer, otherwise the "lein exec hello.clj" command will not work. If you don't have all of that installed, here are some instructions to get you upto speed.
http://fasttrackclojure.blogspot.in/2015/02/installing-clojure.html

Now let us look at the code. We see a Clojure expression in the parenthesis, whose first element is a function called spit. spit takes two arguments, a file name "hello.txt" and string which is the content of the file to be written (spit into).  You can see the documentation of the spit function here. http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/spit.

The above expression is called a list, and the expression is evaluated immediately on execution. This list is also a function call. In Clojure a function call is just a list whose first element resolves to a function. Now try this

'(spit "hello.txt" "Hello World! Hello Clojure")

Add a quote ' to the beginning of the list and run your program again. (Delete the hello.txt file before executing your program). Now see what happens. Nothing. The list expression is not evaluated now. Your list expression is a piece of data now.

Lets do this now.

(eval
  '(spit "hello.txt" "Hello World! Hello Clojure"))

Bam! Your quoted piece of data is evaluated again! We wrapped the quoted expression in another list, which calls a function called eval, and we passed our quoted list as an argument to it. Here is the doc for the eval function. http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/eval.

Your code can be data and your data can be code. Welcome to Lisp! Clojure is a language based on Lisp. And we are already beginning to see the power and simplicity of the language.

Are you already excited about Clojure like I am? Then go to Lesson 2.

No comments:

Post a Comment