Saturday, June 25, 2011

Starting from scratch

I've been wanting to write about Clojure for some time now, and I've decided to do so from the perspective of a PHP programmer (that's me) making the transition to functional programming, using Clojure. I like to start at the beginning, so in this post, I'm going to set up a Clojure programming environment from scratch.

[NOTE: Early feedback on this post suggests that I may be making things look harder than they really are. Clojure works just fine in any environment that runs Java, and can be developed using any editor or IDE. My goal in starting from scratch is purely didactic. I'm starting with a simple, bare-bones environment so that anyone who wants to follow along can easily do so without being distracted by issues like "I played with emacs a while ago and my .emacs file has some cruft in it" or "My classpath seems to be pointing at some old jar files I installed a couple years ago."

If you're not interested in setting up a clean, minimal environment, feel free to skip ahead to the "Installing leiningen" section.]

Monday, June 20, 2011

I didn't think that would work.

Just saw a quick code snippet on the #clojure IRC channel. I didn't believe it would work at first, but apparently it does.

=> (defmacro rnd [] (rand-int 10))
#'user/rnd
=> (defn foo [] (rnd))
#'user/foo
=> (foo)
8
=> (foo)
8
=> (foo)
8


So every time you use your macro, it expands to a random number *at compile time*. The foo function is thus defined as a constant value, but it will be a different constant every time you re-load the code and run it.
Not sure what that's useful for, but I bet it could do something cool.