I have a bad habit of starting long, ambitious blogs posts but not finishing them. Hopefully this will be be a short and easy one. This post is about the difference between def and let in Clojure!
What Are Def And Let
The phrases def and let are called "special forms" in the Clojure docs. I was a bit confused by this at first. Are they functions? Are they macros? Or something "more special"? Well, after asking in the Clojurian slack beginner channel one of the memebers gave me a pretty good explanation- "special forms are implemented in java as part of the compiler. They are outside the normal things that are all implemented as regular java classes or as clojure code - they are special symbols the compiler looks for that guide the compilation of code".
After a quick look at the Clojure docs for def, we can see that this special form pretty much creates a global variable within the current namespace. In the docs they note that many macros expand into def like "defn" or "defmacro". Intuitively, it makes sense that "defn" lets you define a function that you can use later anywhere in the same namespace.
Let is very similar to def in that it is a special form that allows you to bind values to named variables. According to this nice comment in the first example of the Clojure docs for let page, let provides a way to create ;; lexical bindings of data structures to symbols, and the binding is available only within the lexical context of the let. In other words, you can define variables which are "local variables" that are only available within the parentheses surrounding the let.
That's All, Folks
Welp, that's all I have for you guys today. I'm sorry that I didn't really share any amazing revelations here, but hopefully if you weren't sure the difference between def and let you have a better idea know. That's all for now. Peace out, cub scouts!
The posts on this site are written and maintained by Jim Lynch. About Jim...