the other day I was trying to come up with an example of closure in Clojure. I came up with and example I had seen before and thought it was appropriate.
Alas, I was tol
Another example of closure. There are two functions that share the same environment (state
).
(defn create-object [init-state]
(let [state (atom init-state)]
{:getter (fn []
@state)
:setter (fn [new-val]
(reset! state new-val))}))
(defn test-it []
(let [{:keys [setter getter]} (create-object :init-value)]
(println (getter))
(setter :new-value)
(println (getter))))
(test-it)
=> :init-value
:new-value