Learn clojure in Y minutes - Sets

The following is from Learn clojure in Y minutes.

The hashtag with brackets indicates a persistent hash set.

> (class #{1 2 3})
    clojure.lang.PersistentHashSet

set - gets the set of values in a collection

> (set [1 2 3 1 2 3 3 2 2 1 3])
    #{1 2 3}

conj - adds a member to a set

> (conj #{1 2 3} 4)
    #{1 2 3 4}

disj - removes a member from a set

> (disj #{1 2 3} 1)
    {2 3}

To test for existence of an item in a set, use the set as a function.

> (#{1 2 3} 1)
    1
    
    > (#{1 2 3} 4)
    nil

There are plenty more functions in the clojure.sets namespace.

Published January 08, 2015