Alternate version of swap! also returning swapped out value

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

    Atoms are un-coordinated so it seems likely that any attempt to do this outside of the swapping function it's self will likely fail. You could write a function that you call instead of swap! which constructs a function that saves the existing value before applying the real function, and then pass this constructed function to swap!.

    user> (def foo (atom  []))
    #'user/foo
    user> (defn save-n-swap! [a f & args] 
             (swap! a (fn [old-val] 
                        (let [new-val (apply f (cons old-val args))] 
                           (println "swapped out: " old-val "\n" "swapped in: " new-val) 
                           new-val)))) 
    #'user/save-n-swap!
    user> (save-n-swap! foo conj 4) 
    swapped out:  [] 
     swapped in:  [4]
    [4] 
    user> (save-n-swap! foo conj 4) 
    swapped out:  [4]
     swapped in:  [4 4]
    [4 4] 
    

    This example prints it, It would also make sense to push them to a changelog stored in another atom

提交回复
热议问题