Search code examples
clojurefunctional-programming

Questions about Vars Clojure


I'm new in Clojure and i read that it is a functional language. It says that Clojure doesn't have variables, still when i find (def n 5), what's the difference between it and a variable?

I can change the value of the var after, so is it really that different from a variable? I don't understand the difference.


Solution

  • Assuming that by variable you mean a refer to a mutable storage location, I guess the main difference(depending against which language you compare) is that if you dynamically rebind the var in Clojure is on a per-thread basis.

    But the long answer is that you don't usually use a var in Clojure unless you really need a reference to a mutable storage location.

    Clojure favors immutability and programming using values instead of references.

    You can watch Rich Hickey's talk about values.

    A summary would be, when you're programming in Clojure what you have are values , not references to locations that may change (maybe even changed by another thread).

    So.

    (let [a 1 
          _ (println a) => prints 1
          a 2 
          _ (println a) => prints 2
         ]) 
    

    Even if you get the illusion of "changing a" in that code, you're not changing the "old" a you just have a new value. (if someone would have looked at the first definition it would still be seeing the value 1).

    Actually you can see that sequence of assignments as a composed function calls where a is being replaced in scope, but not the same "variable" at all.

     ((fn [a]
        (println a) => prints 1
        ((fn [a]
            (println a) => prints 2
          ) 2) 1)
    

    None the less, if you need to have a mutable storage with potentially many threads accessing that storage, Clojure gives you vars, atoms, refs, etc.