typestar

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

  1. spring-list is a set literal, and disj and conj derive autumn-list from it.
  2. (spring-list "wren") calls the set as a function, answering with the value or with nil.
  3. set/union, set/intersection, and set/difference combine the two lists three ways.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Collections, step 6 of 27 in Language basics.

← Previous Next →