I’m always a bit confused about Symbols and Vars in Clojure.
For example, is it safe to say that + is a symbol which is used to denote a var, and this var points to a value which is a function that can add numbers?
So what happens, step by step when I just enter “+” in a REPL?
- The symbol gets qualified to a namespace, in this case clojure.core
- Then in some symbol table there is the information that + refers to a var
- When this var is evaluated, the result is a function-value?
There’s a symbol + that you can talk about by quoting it:
So it resolves to #’+, which is a Var:
The Var references the function object:
(The @ sign is just shorthand for deref.) Of course the usual way to get to the function is to not quote the symbol:
Note that lexical bindings are a different mechanism, and they can shadow Vars, but you can bypass them by referring to the Var explicitly:
In that last example the deref can even be left out:
This is because Var implements IFn (the interface for Clojure functions) by calling deref on itself, casting the result to IFn and delegating the function call to that.
The visibility mechanism used when you define private functions with defn- is based on metadata on the symbol. You can bypass it by referring directly to the Var, as above: