Skip to content

Instantly share code, notes, and snippets.

@JohnnyJayJay
Last active March 8, 2022 22:33
Show Gist options
  • Save JohnnyJayJay/1316abc65adb6b5c06b7de7aa49c3ff3 to your computer and use it in GitHub Desktop.
Save JohnnyJayJay/1316abc65adb6b5c06b7de7aa49c3ff3 to your computer and use it in GitHub Desktop.
A Clojure function for atoms that I'm currently missing
(defn bigswap!
"`swap!` into an atom *and* return a custom value produced in the atomic function.
`atom` is the atom.
`f` is a function of two arguments: the first is a function `atom-set` that 'sets' the atom to the given value.
The second is the current value in the atom.
In essence, `bigswap!` returns the value of `f` while setting the value of the atom to the value set by `atom-set`, if applicable."
[atom f]
(let [return-val (volatile! nil)]
(swap!
atom
(fn [a]
(let [res (volatile! a)
atom-set (partial vreset! res)
ret (f atom-set a)]
(vreset! return-val ret)
@res)))
@return-val))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment