Aaron Bell
Aaron Bell

Reputation: 862

Can you see previous values for an atom in Clojure?

"Clojure metaphysics construes identity as something we humans impose on a succession of unchanging values produced by a process over time".

Imposed identity on a sequence of states

(Higginsworth, October 2015)

If this is true, if identity surronds all these states, then I should be able to do something like this.

user=> (def wow (atom 1))
#'user/wow
user=> (swap! wow (fn [cur] "You say 'Hello'."))
"You say 'Hello'."
user=> (swap! wow (fn [cur] "I say 'Goodbye'."))
"I say 'Goodbye'."
user=> (swap! wow (fn [cur] "Hello, hello!"))
"Hello, hello!"

; Can I do this?
user=> (get-old-atom-state wow 0)
1
(get-old-atom-state wow 1)
"You say 'Hello'"

Is this so? Or does Clojure actually GC the old values if not used?

Upvotes: 1

Views: 262

Answers (2)

erdos
erdos

Reputation: 3538

The JVM does garbage collect the old and not referenced values of an atom.

However, you can set up a listener to the changes of the atom values and store the old values manually to another atom.

user=> (def wow (atom 1))
#'user/wow

user=> (def wow-history (atom ()))
#'user/wow-history

user=> (add-watch wow :hist
          (fn [_ _ old _] (swap! wow-history conj old)))

Mutate the atom:

user=> (swap! wow (fn [cur] "You say 'Hello'."))
"You say 'Hello'."

user=> (swap! wow (fn [cur] "I say 'Goodbye'."))
"I say 'Goodbye'."

user=> (swap! wow (fn [cur] "Hello, hello!"))
"Hello, hello!"

Now lets check the values in the history:

user=> @wow-history
("I say 'Goodbye'." "You say 'Hello'." 1)

Do not forget to clean up the wow-history atom when you do not need the old values to prevent memory leaks.

user=> (reset! wow-history ())
()

Upvotes: 2

amalloy
amalloy

Reputation: 91887

If this is true, if identity surronds all these states, then I should be able to do something like this.

I don't really see any justification for this "should", philosophically. "Aaron Bell" is an identity that encompasses many states you have been in in the past, but I can't interact with, or even observe, any of those past states. The only way I would know about any of them is if somebody had observed them and written down those observations in some immutable object that I can refer to.

Clojure's identities behave the same way: you can take a snapshot at any time, and after you do, you can look at that snapshot whenever you want. But states nobody looked at are lost forever.

Upvotes: 5

Related Questions