Skip to content

Instantly share code, notes, and snippets.

@bnyeggen
Created March 12, 2012 15:22
Show Gist options
  • Save bnyeggen/2022610 to your computer and use it in GitHub Desktop.
Save bnyeggen/2022610 to your computer and use it in GitHub Desktop.
Switch values of two refs/atoms/agents
(defn switch-refs
"Must be called in transaction"
[a b]
(let [av @a bv @b
setter (fn [_ v] v)]
(commute a setter bv)
(commute b setter av)))
(defn switch!
"Blocks on both sequentially, nontransactional"
[a b]
(let [av @a bv @b
setter (fn [_ v] v)]
(swap! a setter bv)
(swap! b setter av)))
(defn switch-agents
"Updates can happen in either order, and will be set to current value of a
and b, not val at actual execution (=> should probably call after an await)"
[a b]
(let [av @a bv @b
setter (fn [_ v] v)]
(send a setter bv)
(send b setter av)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment