Recording Battery Function in Clojure

I would like to know how to write a battery example included in the essay Revenge of the Nerds . It’s easy to understand how this works, but I can’t recreate it in Clojure - it does not accumulate, but simply returns the sum i and the initial set value n.

The key is in incf (in the Common Lisp version) or + = (in JavaScript).

In other words: how to change the state of a referenced function? I have seen several examples of mutating variables, but they do not look exactly fine .

+7
source share
1 answer

Do not do this! Save yourself before this too late! Mutating a state for no reason is not something that Clojure encourages, so of course it's not as convenient as lisp would normally be.

But seriously, this is a classic example of explaining closures, and although this is not very useful in Clojure, it's nice to know the translation. You need to write something like:

(defn foo [n] (let [acc (atom n)] (fn [i] (swap! acc + i)))) 
+22
source

All Articles