Clojure闭合不符合预期?

时间:2015-09-25 11:24:08

标签: clojure

当预期返回5时,repl返回2.

(defn counter [] 
  (let [count 1]
    (fn [] 
      (+ count 1)
    )
  )
)

(defn test-counter []
  (let [increment (counter)]
    (increment)
    (increment)
    (increment)
    (increment)
  )
)

1 个答案:

答案 0 :(得分:5)

count不是可变变量,因此(+ count 1)不会更改其值。如果您想要变异,可以将计数存储在atom中并使用swap!进行更新:

(defn counter []
  (let [count (atom 0)]
    (fn [] (swap! count inc))))