我正在更新 Clojure 中地图参考中的计数器。
(defn increment-key [this key]
(dosync
(let [value (get @this key)]
(if (= value nil)
(alter this assoc key (ref 1))
(alter this assoc key (alter value inc))))))
但是,看起来 alter value inc 语句正在丢失引用:
(defn -main [& args]
(def my-map (ref {}))
(increment-key my-map "yellow")
(println my-map)
(increment-key my-map "yellow")
(println my-map))
哪个打印:
$ lein run
#<Ref@65dcc2a3: {yellow #<Ref@3e0d1329: 1>}>
#<Ref@65dcc2a3: {yellow 2}>
在这种情况下,如何在更新参考时保持相同的参考?