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.

No comments:

Post a Comment