Alternate version of swap! also returning swapped out value

后端 未结 5 791
栀梦
栀梦 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:21

    Clojure's swap! is just a spinning compare-and-set. You can define an alternate version that returns whatever you like:

    (defn alternate-swap [atom f & args]
      (loop []
        (let [old @atom
              new (apply f old args)]
          (if (compare-and-set! atom old new)
            [old new]  ; return value
            (recur)))))
    

提交回复
热议问题