Best way to toggle an entry in a set

It made a major impression on me when I first saw a toggle function on a boolean in a mapatom that just used (swap! _ update :key not). Having seen that, Is there a cleaner way to do a similar toggle in a regular Set? Here’s what I’ve come up with, not noticing any useful helpers in the core docs on set:

(defn set-toggle
  "Add or remove item `i` from set `S`"
  [S i]
  (let [f (if (S i) disj conj)]
    (f S i)))

I am not aware of any function like this built into Clojure. disj and conj are built in, of course, and are enough to build this nice little function you have written.

One minor comment on generality: If you want this to work for sets that can contain nil or false, I would recommend changing the call (S i) to (contains? S i) instead.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.