Chuyển đến nội dung

Bài 12 · Data Structures

Sets in Clojure: Membership, Union and Intersection

Use Clojure sets for unique values and fast membership tests: literals, conj and disj, sets as predicate functions, union, intersection, difference, subset checks, sorted-set and uses.

A set is a collection of unique values with no particular order. Sets answer one question very quickly: "is this thing in the collection?". They also support the classic set operations: union, intersection and difference. In Clojure, sets are immutable like every other core collection, and a set is also a function, which makes it a handy predicate.

Creating sets

CLOJURE
#{:red :green :blue}
(hash-set 1 2 3)
(set [1 2 2 3 3 3])     ; #{1 3 2}   duplicates disappear
(set "hello")           ; #{\e \h \l \o}
(sorted-set 3 1 2)      ; #{1 2 3}   kept in order
(into #{} [:a :b])

A set literal with a duplicate element, such as #{1 1}, is an error. The printed order of a normal set is unspecified. Use sorted-set if you need ordering.

Membership and size

CLOJURE
(def colors #{:red :green :blue})

(contains? colors :red)     ; true
(contains? colors :pink)    ; false
(colors :red)               ; :red     a set is a function
(colors :pink)              ; nil
(count colors)              ; 3
(empty? #{})                ; true

Because (colors :red) returns the element itself (or nil), a set works well wherever a predicate is expected:

CLOJURE
(filter colors [:red :pink :blue :cyan])   ; (:red :blue)
(remove #{:a :b} [:a :c :b :d])            ; (:c :d)
(some #{:x} [:a :x :b])                    ; :x

A set used as a predicate returns the stored element, so if you store nil or false in a set, (s false) gives a falsey value even though the element is present. When that matters, use contains?.

Adding and removing

CLOJURE
(conj colors :yellow)     ; adds an element (no effect if already present)
(conj colors :red)        ; same set
(disj colors :red)        ; removes an element
(into colors [:pink :cyan])
colors                    ; unchanged

conj adds, disj removes ("disjoin"). assoc and dissoc are for maps, not sets.

JS Stand-in: sets with JavaScript Set

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Set algebra with clojure.set

Set operations live in the clojure.set namespace:

CLOJURE
(require '[clojure.set :as set])

(def a #{1 2 3 4})
(def b #{3 4 5 6})

(set/union a b)          ; #{1 2 3 4 5 6}
(set/intersection a b)   ; #{3 4}
(set/difference a b)     ; #{1 2}
(set/difference b a)     ; #{5 6}
(set/subset? #{1 2} a)   ; true
(set/superset? a #{1})   ; true

difference is not symmetric: it keeps what the first set has that the second does not. The symmetric difference can be written as (set/difference (set/union a b) (set/intersection a b)).

clojure.set also provides relational operations for sets of maps, which behave like simple database tables:

CLOJURE
(def users #{{:id 1 :name "Ada"} {:id 2 :name "Grace"}})

(set/select #(> (:id %) 1) users)    ; #{{:id 2, :name "Grace"}}
(set/project users [:name])          ; #{{:name "Ada"} {:name "Grace"}}
(set/rename users {:name :full-name})
(set/index users [:id])              ; a map from {:id n} to matching sets

set/join combines two sets of maps on common keys, like an SQL join.

Typical uses

  • Removing duplicates: (set coll) or (distinct coll). The distinct function keeps the original order; set does not.
  • Fast lookups: build a set once, test membership many times ((contains? allowed-roles role)).
  • Tags and flags: {:tags #{:urgent :billing}} with (conj tags :new).
  • Visited nodes in a graph search.
  • Validation: (every? allowed-chars input) where allowed-chars is a set of characters.
CLOJURE
(def vowels #{\a \e \i \o \u})
(count (filter vowels "functional programming"))   ; 7
JS Stand-in: finding common and missing items

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "missing" line is (set/difference need have) in Clojure.

Equality and nesting

Sets compare by value, and the order is irrelevant: (= #{1 2 3} #{3 2 1}) is true. Sets can contain any value that has a stable equality, including vectors and maps, so #{[1 2] [2 1]} has two elements. Because collections are values, sets of maps work correctly; this is one thing Java's mutable collections cannot do safely.

Choosing a collection

Vector Ordered, indexed.
Map Key to value lookup.
Set Unique items, fast contains?.
List Code and front-first stacks.

Need "is it in there?" Use a set.

1 / 2

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does (set [1 2 2 3 3 3]) produce?

    set converts a collection to a set and removes duplicates.
  2. 2. Which function removes an element from a set?

    disj removes an element from a set; dissoc is for maps.
  3. 3. What does (filter #{:a :b} [:a :c :b :d]) return?

    The set acts as a predicate: it returns the element for members and nil for non-members.
  4. 4. What is (clojure.set/difference #{1 2 3} #{3 4})?

    difference keeps items of the first set that are not in the second.

Summary

  • Sets hold unique values; build them with #{}, set or hash-set, and use sorted-set for order.
  • contains? or calling the set tests membership; conj adds and disj removes.
  • clojure.set provides union, intersection, difference, subset?, plus relational operations on sets of maps.
  • A set is a convenient predicate for filter, remove and some.

Next: Immutability and Persistent Data

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.