Accediendo a la historia de un `ref` en Clojure


9

La documentación para referencia muestra una opción: max-history y establece que "las referencias acumulan el historial dinámicamente según sea necesario para hacer frente a las demandas de lectura". Puedo ver que hay historial en REPL, pero no veo cómo encontrar valores anteriores de una referencia:

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

Presumiblemente el mundo ha tenido los valores "hola", "mejor" y "mejor !!!". ¿Cómo accedo a ese historial?

Si no es posible acceder a ese historial, ¿hay algún tipo de datos que mantenga un historial de sus valores que pueda consultarse después? ¿O es por eso que se creó la base de datos datomic?

Respuestas:


7

Creo que: min-history y: max-history solo se refieren al historial de una referencia durante una transacción.

Sin embargo, aquí hay una manera de hacerlo con un átomo y un observador:

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!!!"]

¿Funcionará igual con los átomos también?
Yazz.com
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.