Last Updated: February 25, 2016
·
990
· sativaware

Working with sets in Clojure

To jump in with an example, lets model part of a chat application using Clojure's sets.

Lets say, in our Chat app, that there is a list of people who are online.

If we take a look - our Chat app currently has three people online:

#{"Jane" "Joe" "Janice"}

If we wanted to add Peter, who just came online, we could do the following:

(conj #{"Jane" "Joe" "Janice"} "Peter")
;; => #{"Joe" "Peter" "Jane" "Janice"}

The conj function returns a new collection with "peter" added.

If, in the meantime, Joe went offline we could do this:


(disj  #{"Joe" "Peter" "Jane" "Janice"} "Joe")
;; => #{"Peter" "Jane" "Janice"}

The disj function returns a new set that does not contain "Joe".

Say you wanted to see how many people where online, you could do the following:

(count #{"Peter" "Jane" "Janice"})
;; => 3

You could double check to make sure that Joe is, in fact, offline:


(contains? #{"Peter" "Jane" "Janice"} "Joe")
;; => false

Likewise you could check that Janice is still, indeed, online:


(contains? #{"Peter" "Jane" "Janice"} "Janice")
;; => true

Grab the gist here, stick it in your REPL and play.