Wednesday, September 09, 2020

#100DaysOfClojure (Day [10] Sets)

A Set is a collection with unique elements. They are like mathematical sets, unordered and unique. They are used for checking whether a collection contains an element or removing an arbitrary element. You will notice they can contain any type including functions.


You create a Set as follows

#{1 "Hello" :anytype 22/7}
=> #{1 "Hello" 22/7 :anytype}

You can add an element to a Set as follows

(conj #{1 "Hello" :anytype 22/7} 0x0A)
=> #{1 "Hello" 22/7 :anytype 10}

You can remove an element from a Set as follows

(disj #{1 "Hello" 22/7 :anytype 10} 0x0A)
=> #{1 "Hello" 22/7 :anytype}

You can check containment in a Set as follows

(contains? #{1 "Hello" 22/7 :anytype 10} 22/7)
=> true

(contains? #{1 "Hello" 22/7 :anytype 10} :wrontype)
=> false

You can combine 2 Sets as follows

(into #{1 "Hello" 22/7 :anytype} #{0x0B "World" 1/3})
=> #{1/3 "World" 1 "Hello" 22/7 11 :anytype}

You can also do Set functions like union, difference and intersections. These functions exist in the Clojure.set namespace and has to be used as such.

You can do unions of Sets as follows

(clojure.set/union #{1 "Hello" 22/7 :anytype} #{0x0B "World" 1/3})
=> #{1/3 "World" 1 "Hello" 22/7 11 :anytype}

You can do a difference of Sets as follows

(clojure.set/difference #{1 "Hello" 22/7 :anytype} #{0x01 "Hello" 1/3})
=> #{22/7 :anytype}

And finally you can use the intersection function on Sets as follows

(clojure.set/intersection #{1 "Hello" 22/7 :anytype} #{0x01 "Hello" 1/3})
=> #{1 "Hello"}

Tomorrow I will look at some of the flow functions in Clojure

(println “Bye 4 Now!") 

No comments: