在Clojure中访问`ref`的历史记录


9

ref文档显示了:max-history选项,并指出“ refs根据需要动态地累积历史记录,以处理读取需求。” 我可以看到REPL有历史记录,但是我看不到如何找到ref的先前值:

user=> (def the-world (ref "hello" :min-history 10))
#'user/the-world
user=> (do
          (dosync (ref-set the-world "better"))
          @the-world)
"better"
user=> (let [exclamator (fn [x] (str x "!"))]
          (dosync
           (alter the-world exclamator)
           (alter the-world exclamator)
           (alter the-world exclamator))
          @the-world)
"better!!!"
user=> (ref-history-count the-world)
2

大概世界的值是“ hello”,“ better”和“ better !!!”。我如何访问该历史记录?

如果无法访问该历史记录,是否有一个数据类型保留其值的历史记录,以便以后查询?还是这就是为什么创建原子数据库的原因?

Answers:


7

我相信:min-history和:max-history仅在事务期间引用引用的历史记录。

但是,这是一种使用原子和观察者进行操作的方法:

user> (def the-world (ref "hello"))
#'user/the-world
user> (def history-of-the-world (atom [@the-world]))
#'user/history-of-the-world
user> history-of-the-world
#<Atom@6ef167bb: ["hello"]>
user> (add-watch the-world :historian
                 (fn [key world-ref old-state new-state]
                   (if (not= old-state new-state)
                     (swap! history-of-the-world conj new-state))))
#<Ref@47a2101a: "hello">
user> (do
        (dosync (ref-set the-world "better"))
        @the-world)
"better"      
user> (let [exclamator (fn [x] (str x  "!"))]
        (dosync
          (alter the-world exclamator)
          (alter the-world exclamator)
          (alter the-world exclamator))
        @the-world)
"better!!!"
user> @history-of-the-world
["hello" "better" "better!!!"]

这样对原子也起作用吗?
Yazz.com 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.