Tuesday, May 13, 2014

Clojure Koans Answers and Explanations - 4 - Sets

After the 3rd Clojure Koans post, this one is for 4th set of Clojure Koans - the one on sets.Unroll your sleeves, this one is a small post.

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;1
(= #{} (set __))
; #{} creates an empty set
; here is another way to do the same thing
(= #{} (set nil))
; do remember to check the type of a set, it is
; user=> (type #{})
; clojure.lang.PersistentHashSet


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;2
(= __ (count #{1 2 3}))
; predictable by now, right?
(= 3 (count #{1 2 3}))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;3
(= __ (set '(1 1 2 2 3 3 4 4 5 5)))
; a set tries to mirror the set in math
; so, this holds out 
(= (set '(1 2 3 4 5)) (set '(1 1 2 2 3 3 4 4 5 5)))
; and so does
(= #{1 2 3 4 5} (set '(1 1 2 2 3 3 4 4 5 5)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;4
(= __ (clojure.set/union #{1 2 3 4} #{2 3 5}))
; as is obvious this asks for invoking union of 2 sets
(= #{1 2 3 4 5} (clojure.set/union #{1 2 3 4} #{2 3 5}))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;5
(= __ (clojure.set/intersection #{1 2 3 4} #{2 3 5}))
; this one is intersection
(= #{2 3} (clojure.set/intersection #{1 2 3 4} #{2 3 5}))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;6
(= __ (clojure.set/difference #{1 2 3 4 5} #{2 3 5})))
; a diff of 2 sets is the first set minus the elements
; of 2nd set
(= #{ 1 4} (clojure.set/difference #{1 2 3 4 5} #{2 3 5}))
  


No comments:

Post a Comment