Wednesday, April 15, 2009

Learning Clojure

Well I've started down the path of learning a new language (Clojure) the past few weeks I blame it all on going to NFJS and going to too many Stuart Halloway talks.

Learning Clojure has definitely been challenging. It seems like the total opposite from Java. Beside being a functional language, it feels like it was built to be terse. It makes heavy, heavy use of symbols, who knew the ":" could mean so much!

A friend and I have been working on a snake example (apparently, everyone writes a snake example, just google "clojure snake" there are jokes like, YACS (yet another clojure snake)). I think it took us a good 7-8 hours just to understand all the code. Destructuring was I think the hardest concept to learn.

Destructuring is also called abstract structural binding check out (let [bindings* ] exprs*) where bindings == binding-form and initial-expr. In my limited exposure destructuring is often used in (defn ([params*] body) where params == binding-form and body = expr, AND using your function is applying the initial-expr. Somehow it helped a lot to understand defn in terms of let.
For example:

user> (defn foo [a b] (+ a b)) user>(foo 1 2) 3
So in that example [a b] is your vector binding form (+ a b) is your exprs and (foo 1 2) is the application of the initial expression.

You could view the same behavior with let

user>(let [[a b][1 2]] (+ a b)) 3
Anyway, once I made this connection a lot of things started to fall into place when looking at clojure code. This might have been more obvious to me if I had read more carefully the fn special form, so I would certainly spend time looking through the special forms documentation if you're interested in learning Clojure.

Also to blame on Stuart + NFJS is I setup a github repository which will probably change drastically, but if you're interested in checking out my progress on snake.clj it's up there. We now have 2 snakes, are detecting collisions and are working on setting up a wall.

Oh running clojure is really easy, just download the clojure jar, java -cp clojure.jar clojure.lang.Repl will give you a terminal, and java -cp clojure.jar clojure.main snake.clj will let you run the snake example.

4 comments:

scgilardi said...

Invoking clojure.main with no arguments also gives you a REPL:

java -cp clojure.jar clojure.main

You can explicitly ask for a repl with "-r" or "--repl":

java -cp clojure.jar clojure.main --repl

To see brief usage info for clojure.main, use "--help":

java -cp clojure.jar clojure.main --help

Zachary D. Shaw said...

Oh those are handy, thanks for the tips squeegee

-Zach

R. Mark Volkmann said...

If you haven't already, check out my article on Clojure at http://ociweb.com/mark/clojure/article.html. It will help you get started quickly.

Zachary D. Shaw said...

hey Mark, that article looks great, I'm looking forward to giving it a read through.

Thanks,

Zach

 
Web Statistics