Sets

Along with maps, Clojure also sports a built-in set data type. The literal syntax for a set borrows the braces from maps but adds a # to the front:

 (​def​ genres #{:sci-fi :romance :mystery})
 
 (​def​ authors #{​"Dickens"​ ​"Austen"​ ​"King"​})

Like their mathematical namesakes, Clojure sets are all about membership: a value either is or is not a member of a set. Since a value can only be in a set once, if you repeat a value in a set literal, you’ll get an error. Thus, this:

 #{​"Dickens"​ ​"Austen"​ ​"Dickens"​}

is one "Dickens" too many:

 IllegalArgumentException Duplicate key​:​ Dickens...

Like maps, sets have their own ideas about the order of their elements. The set that you wrote as #{:sci-fi :romance :mystery} is liable to come ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.