user3245240
user3245240

Reputation: 255

Maintaining State with def ref in Clojure

I have the following function:

(defn best-move [tracked-moves]
  (def all-scores (ref tracked-moves))
    @all-scores)

Its being called by a recursive function. I want to be able to keep passing in tracked-moves, and for them to all exist within @all-scores. The way it is written right now, @all-scores will only hold onto the last tracked-moves that it is given. How can I get it to hold onto all of the data that it receives every time the best-move function is called? And to not just return the last of all the data it receives?

Upvotes: 0

Views: 114

Answers (1)

Jeremy
Jeremy

Reputation: 22415

The problem is that you're using def incorrectly. Any use of def (and defn) will create a namespace-level var. It doesn't matter where you call def. As you've pointed out, you're continuously redefining all-scores. The short answer is to pull your definition of all-scores to the top level, so you're not constantly invoking it. Then, update the ref as described in the documentation. If you're not using transactions, and don't need to manage multiple refs, you might want to use atoms instead.

Upvotes: 2

Related Questions