Understanding Vars and bindings

The previous expressions work. However, there's some assumed knowledge that may be helpful to deconstruct. Firstly, I'm using def to bind a value (lazy sequences, in this case) to a symbol. To be precise, these values are called Vars. Vars are just a way to bind a named location (a symbol) to something else, such as numbers, functions, or in our case, lazy sequences. The notion of binding is important. It allows us to use a value on a per context basis, that is, we have the ability to dynamically rebind Vars in different contexts. So, the following code is possible (taken from http://clojure.org/vars):

  (def ^:dynamic x 1)
  (def ^:dynamic y 1)

  (+ x y)
  ;;=> 2

  (binding [x 2 y 3]
    (+ x y))
  ;;=> 5

  (+ x y)
  ;;=> 2

The root context is the namespace in which we evaluate our expressions. By default, the user namespace along with Clojure's core functions (which are bound to the Vars symbol), are always available. The def, defn, and with-redefs functions allow us to rebind Vars in a local or root context (of our namespace). Vars and context binding are important because they give us the ability to bind different functions (or entire components or programs) to a symbol for a specific context. This includes redefining functions in a running program. So, for example, you could wrap a function with logging behavior only in certain call contexts (or threads that aren't discussed here). For further information on Vars, visit http://clojure.org/vars.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.47.218