Sets, Relations & Functions

The vocabulary of discrete maths — sets and set operations, power sets and Cartesian products, relations and their properties, equivalence relations and partial orders, functions (injective, surjective, bijective), cardinality and countability, with connections to databases, types and hashing.

Beginner 6 min readLesson 2 of 9

Sets, relations and functions are the vocabulary of computer science. Databases are relations, types are sets, hash functions are functions, dependency graphs are relations, and countability arguments show some problems can't be solved by any program.

Sets

A set is an unordered collection of distinct elements: A={1,2,3}A = \{1, 2, 3\}. Order and duplicates don't matter: {3,1,1,2}={1,2,3}\{3, 1, 1, 2\} = \{1, 2, 3\}.

NotationMeaning
x∈Ax \in Ax is an element of A
A⊆BA \subseteq BEvery element of A is in B (subset)
∅\emptysetThe empty set
∣A∣\lvert A \rvertCardinality (number of elements)
{x∈Z∣x>0}\{x \in \mathbb{Z} \mid x > 0\}Set-builder notation: positive integers
N,Z,Q,R\mathbb{N}, \mathbb{Z}, \mathbb{Q}, \mathbb{R}Naturals, integers, rationals, reals

Set operations

OperationNotationElementsPythonSQL
UnionA∪BA \cup BIn A or Ba | bUNION
IntersectionA∩BA \cap BIn botha & bINTERSECT / inner join
DifferenceA∖BA \setminus BIn A but not Ba - bEXCEPT
Symmetric differenceA△BA \triangle BIn exactly onea ^ b—
ComplementA‾\overline{A}Not in A (within a universe U)—NOT IN
Python
followers_of_a = {"asha", "ben", "chen", "dev"}
followers_of_b = {"chen", "dev", "eli"}
print(followers_of_a & followers_of_b)   # mutual followers: {'chen', 'dev'}
print(followers_of_a - followers_of_b)   # only A's: {'asha', 'ben'}

De Morgan's laws for sets mirror those of logic (Logic and proofs): A∪B‾=A‾∩B‾\overline{A \cup B} = \overline{A} \cap \overline{B}.

Inclusion–exclusion: ∣A∪B∣=∣A∣+∣B∣−∣A∩B∣\lvert A \cup B \rvert = \lvert A \rvert + \lvert B \rvert - \lvert A \cap B \rvert (Combinatorics).

Power sets and Cartesian products

  • The power set P(A)\mathcal{P}(A) is the set of all subsets. If ∣A∣=n\lvert A \rvert = n, then ∣P(A)∣=2n\lvert \mathcal{P}(A) \rvert = 2^n — each element is in or out. This is why brute-forcing subsets is exponential (Backtracking), and why subsets map to n-bit masks (Bit manipulation).
  • The Cartesian product A×B={(a,b)∣a∈A,b∈B}A \times B = \{(a, b) \mid a \in A, b \in B\} — all ordered pairs. ∣A×B∣=∣A∣⋅∣B∣\lvert A \times B \rvert = \lvert A \rvert \cdot \lvert B \rvert. A SQL CROSS JOIN is a Cartesian product; a struct/record type is a product of its field types.

Relations

A (binary) relation R from A to B is a subset of A×BA \times B — a set of pairs that are "related". Write a R ba \,R\, b when (a,b)∈R(a, b) \in R.

Examples: "is less than" on integers; "follows" on users; "is a prerequisite of" on courses; a database table enrolments(student, course) is a relation — the relational model is named after this (Relational model). Relations on a single set are directed graphs (Graph theory).

Properties of relations on a set A

PropertyDefinitionExampleCounterexample
Reflexivea R a for all a≤, =<
Symmetrica R b ⇒ b R a"is a sibling of", "is friends with""follows"
Antisymmetrica R b and b R a ⇒ a = b≤, ⊆, "divides" (on positive integers)"is friends with"
Transitivea R b and b R c ⇒ a R c<, "is an ancestor of""is a parent of"

The transitive closure adds all pairs reachable through chains: from "is a parent of" you get "is an ancestor of"; from "depends on" you get "depends on, directly or indirectly" — computed by graph search or Floyd–Warshall (Shortest paths), or recursive SQL CTEs.

Equivalence relations

Reflexive + symmetric + transitive. An equivalence relation partitions the set into disjoint equivalence classes:

  • "Has the same remainder mod 3" partitions integers into {…, 0, 3, 6, …}, {…, 1, 4, …} and {…, 2, 5, …}.
  • "Is connected to" partitions a network's nodes into connected components — exactly what union–find maintains (Union-find).
  • "Are anagrams" groups words by their sorted letters — a common interview pattern using a hash map keyed by the class representative.

Partial orders

Reflexive + antisymmetric + transitive. Elements may be incomparable:

  • ⊆ on sets ({1} and {2} are incomparable).
  • "Must happen before" on tasks — dependencies, build steps, course prerequisites. A topological sort extends a partial order to a total order (Topological sort).
  • Happens-before in distributed systems; vector clocks form a partial order (Clocks and ordering).

A total order additionally makes every pair comparable (≤ on numbers) — what sorting requires. Comparators in code must define a consistent (strict weak) order or sorting breaks.

Functions

A function f:A→Bf: A \to B assigns exactly one output in B (the codomain) to each input in A (the domain). The set of outputs actually produced is the range (image).

KindDefinitionPictureExample
Injective (one-to-one)Different inputs → different outputsNo collisionsUser ID → email (if unique)
Surjective (onto)Every element of B is hitCodomain fully coveredStudent → grade, if every grade is awarded
BijectiveBothPerfect pairing; has an inverseEncryption under a fixed key; a permutation
  • Hash functions map a huge domain to a small codomain, so they cannot be injective — collisions are guaranteed by the pigeonhole principle (Combinatorics); good ones spread inputs evenly (Hash tables).
  • Composition (g∘f)(x)=g(f(x))(g \circ f)(x) = g(f(x)) — function pipelines, middleware, compose in functional programming.
  • Pure functions in programming match the mathematical notion: same input, same output, no side effects.

Cardinality and countability

Two sets have the same cardinality if there's a bijection between them. This extends "size" to infinite sets — with surprises:

  • Countably infinite: can be listed as a sequence (bijection with ℕ). The integers (0, 1, −1, 2, −2, …), the rationals, all finite strings over an alphabet, and all programs are countable.
  • Uncountable: no such listing exists. The real numbers, and the set of all subsets of ℕ (equivalently, all functions ℕ → {0, 1}).

Cantor's diagonal argument proves the reals are uncountable: given any supposed list of all reals in (0, 1), construct a number whose n-th digit differs from the n-th digit of the n-th number. It's not in the list — contradiction.

The punchline for computer science: there are countably many programs but uncountably many problems (functions from inputs to yes/no). So most problems have no program that solves them. The halting problem is a concrete example, proved with the same diagonal trick (Turing machines and computability).

Key takeaways
  • Sets support union, intersection, difference and complement — mirrored by Python sets and SQL.
  • The power set of an n-element set has 2ⁿ elements; Cartesian products form tuples (cross joins, record types).
  • Relations are sets of pairs (database tables, graphs); key properties are reflexive, symmetric, antisymmetric, transitive.
  • Equivalence relations partition sets into classes (union–find, grouping); partial orders model dependencies (topological sort).
  • Functions are injective, surjective or bijective; hash functions must collide by pigeonhole.
  • Countable vs uncountable: programs are countable, problems are not — so most problems are unsolvable.