Search code examples
clojureclosuresdynamic-rebinding

Override local bindings from closure in Clojure?


I am interested in if it is possible to redefine or override the bindings that are the result of a closure when programming in Clojure?

For example I can do the following just fine:

(defn triple-adder-fn [a b] (fn [x] (+ x a b)))

(def triple-adder (triple-adder-fn 1 2))

(triple-adder 3)
;; => 6

However this creates a local closure that has the bindings of a = 1 and b = 2 and when I call triple-adder it uses them accordingly.

Now the question is could I do something like the following mock code that would allow me to override those local bindings?

(binding ['a 5
          'b 6]
  (triple-adder 3))
;; => 14

For my simple example it'd be real easy to call the triple-adder-fn to get a new function with new bindings. However, for my actual situation, I am in a position where I don't actually control the triple-adder-fn and only have access to the resulting function.


Solution

  • From your description there is no solution to your problem. Once a closure has "closed over" free params, they can't be changed.

    To solve this, you would have to make a new closure, or perhaps redefine triple-adder-fn to use global dynamic vars instead of local parameters. Or, you could copy triple-adder-fn and change the copy to work as you wish.