Skip to content

Latest commit

 

History

History
62 lines (45 loc) · 1.83 KB

adding-and-removing.asciidoc

File metadata and controls

62 lines (45 loc) · 1.83 KB

Adding and removing items

Problem

You want to obtain a new set with items added or removed.

Solution

The conj function supports sets, just as it does lists, vectors and maps. Use it to add an item or items to a set: just pass it the set and any number of items to add.

(conj #{:a :b :c} :d)
;; -> #{:a :b :c :d}

(conj #{:a :b :c} :d :e)
;; -> #{:a :b :c :d :e}

To remove one or more items, use the disj function, which is specific to sets. It takes a set and one or more keys to remove.

(disj #{:a :b :c} :b)
;; -> #{:a :c}

(disj #{:a :b :c} :b :c)
;; -> #{:a}
Discussion

Since sets are unordered, there is no concept of "where" items are added or removed; either a set contains an item, or it doesn’t.

Note that both conj and disj return a set of the same concrete type as the original. A hash set will remain a hash set, a sorted set will remain a sorted set.

Also worth noting is that these operations are simply no-ops if the set already does or does not contain the item being added or removed. conj returns the same set if it already contains the item, just as disj does if the specified item was already absent.

If you’re adding or removing large numbers of items from sets, you should also consider using the dedicated set manipulation functions from the clojure.set namespace, particularly clojure.set/union ,which can be used to add the items of multiple set together, and clojure.set/difference, which can be used to obtain a set of items not contained in another set. These are typically a far more natural expression of set operations than many calls to conj or disj, or invoking them with large numbers of arguments.

See also
  • Adding items to lists (xref)

  • Adding items to vectors (xref)

  • Using set manipulation functions (xref)