Clojure idiomatic get-and-set function

Is there a more idiomatic / readable way to write get-and-set functions in Clojure than:

(def the-ref (ref {}))

(defn get-and-set [new-value]
  (dosync
    (let [old-value @the-ref]
     (do
       (ref-set the-ref new-value)
       old-value))))
+3
source share
1 answer

for simple cases, I tend to see that this operation is used directly, and not wrapped in a function:

hello.core> (dosync (some-work @the-ref) (ref-set the-ref 5))
5

In this case, it is usually used as the wrapper you are looking for. within This is important because dosync blends well with other transactions and makes transaction boundaries visible. If you are in a position where the wrapper function can fully encapsulate all ref references, refs might not be the best tool. dosyncdosync

A typical use of links may look in the following ways:

(dosync (some-work @the-ref @the-other-ref) (ref-set the-ref @the-other-ref))

, , ref, ref, . , , .

+2

All Articles