当预期返回5时,repl返回2.
(defn counter []
(let [count 1]
(fn []
(+ count 1)
)
)
)
(defn test-counter []
(let [increment (counter)]
(increment)
(increment)
(increment)
(increment)
)
)
Run Code Online (Sandbox Code Playgroud)
count不是一个可变变量,所以(+ count 1)不会改变它的值.如果你想要变异,你可以将计数存储在一个atom并使用swap!以下方法更新它:
(defn counter []
(let [count (atom 0)]
(fn [] (swap! count inc))))
Run Code Online (Sandbox Code Playgroud)