When we are working with sets in Clojure we can use some useful functions from the clojure.set namespace. In a previous post we learned how we can get the difference of several sets. To get the union of several input sets we use the union function of the clojure.set namespace. The function returns a new set that is the union of unique elements from the input sets. A nil value is ignored by the union function.

In the following example code we use union:

(ns mrhaki.set.union
  (:require [clojure.set :as set]
            [clojure.test :refer [is]]))

;; union return a set with elements that contains the unique
;; elements of the input sets.
(is (= #{"Java" "Clojure" "Groovy" "Kotlin"}
      (set/union #{"Java" "Clojure" "Groovy"} #{"Kotlin" "Groovy" "Clojure"})))

;; We can use multiple input sets.
(is (= #{"Java" "Clojure" "Groovy" "Kotlin"}
       (set/union #{"Java" "Clojure" "Groovy"}
                  #{"Groovy" "Clojure"}
                  #{"Kotlin"})))

;; A nil input is ignored.
(is (= #{"Clojure" "Groovy" "Kotlin"}
       (set/union #{"Groovy" "Clojure"} nil #{"Kotlin"})))

Written with Clojure 1.10.1.

shadow-left