Sets & membership in Clojure
Compares two birding lists using set literals and clojure.set.
(require '[clojure.set :as set])
;; a set literal keeps one copy of each value
(def spring-list #{"heron" "kite" "wren" "swift"})
;; conj adds and disj removes; both return new sets
(def autumn-list (disj (conj spring-list "brant") "swift"))
;; a set is a function that answers with the value or with nil
(println (spring-list "wren") (spring-list "puffin"))
;; union gathers every bird, intersection keeps the overlap
(println (sort (set/union spring-list autumn-list)))
(println (sort (set/intersection spring-list autumn-list)))
;; difference keeps what the first set has and the second does not
(println (set/difference spring-list autumn-list))
How it works
spring-listis a set literal, anddisjandconjderiveautumn-listfrom it.(spring-list "wren")calls the set as a function, answering with the value or with nil.set/union,set/intersection, andset/differencecombine the two lists three ways.
Keywords and builtins used here
conjdefdisjprintlnrequiresort
The run, in numbers
- Lines
- 17
- Characters to type
- 654
- Tokens
- 79
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 63 seconds.
Step 3 of 3 in Collections, step 6 of 27 in Language basics.