2

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.

Kasuko
  • 166
  • 7

1 Answers1

4

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.

Alan Thompson
  • 29,276
  • 6
  • 41
  • 48
  • 1
    Thanks, I expected this to be the result but I had to ask. The problem for me is that triple-adder-fn is actually in a 3rd party library and does a lot more additional work then just returning the function. Duplicating the library function in local code to redefine just the output function is a sure fire way to cause myself pain in the future. – Kasuko Apr 05 '17 at 15:48