Alternate version of swap! also returning swapped out value

后端 未结 5 780
栀梦
栀梦 2021-01-20 03:33

I talked about this a bit on IRC\'s #clojure channel today but would like to go more in detail here. Basically, in order to better understand atoms, swap!

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 04:32

    You could use a macro like:

    (defmacro swap!-> [atom & args]
      `(let [old-val# (atom nil)
             new-val# (swap! ~atom #(do
                                      (swap! old-val# (constantly %))
                                      (-> % ~args)))]
         {:old @old-val# :new new-val#}))
    
    (def data (atom {}))
    
    (swap!-> data assoc :a 3001)
    => {:new {:a 3001} :old {}}
    

提交回复
热议问题