Sets






cycognito



clojure logo

Sets

☕ When is a set a better fit than a list or a vector?

Sets - creation

To create a set from a sequence, you use set:

(set '(1 "hello" [1 2]))

In a set, there are no duplicates

(set [1 1 "hello" "hello" [1 2] '(1 2)])

☕ Why [1 2] and (1 2) are considered as duplicates?

You can also create a set with the set literal #{} But then, duplicates are forbidden!

#{1 2 3 1}

Sets - functions

It’s efficient to check if an element belongs to a set

(contains? #{1 2 3} 2)

Checking belonging is the most natural operation on a set. Set behaves as a function

(#{1 2 3} 2)

Making a sequence concrete

(into #{}) converts a sequence into a set

(into #{} (range 5))

(into []) converts a sequence into a vector

(into [] (range 5))

(into ()) converts a sequence into a list

(into [] (range 5))