1
votes

This code is from Clojure in action listing 3.5. When I try to run it i get the following error:

Can't dynamically bind non-dynamic var: joy.q/twice

Am I doing something wrong or has Clojure changed its binding rules since this book was printed?

(defn twice [x]
  (println "original function")
  (* 2 x))

(defn call-twice [y]
  (twice y))

(defn with-log [function-to-call log-statement]
  (fn [& args]
    (println log-statement)
    (apply function-to-call args)))

(call-twice 10)

(binding [twice (with-log twice "Calling the twice function")]
  (call-twice 20))
1

1 Answers

3
votes

From the binding documentation:

As of Clojure 1.3, vars need to be explicitly marked as ^:dynamic in order for them to be dynamically rebindable

So you need:

(defn ^:dynamic twice [x]
  (println "original function")
  (* 2 x))