set
,java.util.Set
,std::set
, std::unordered_set
Note: mathematical sets (data types like std::set
) are “immutable”
(Some references write this as \(A \subset B\))
{n/d for n in [-1,0,1] for d in [1,2,3]}
{–1.0, –0.5, –0.333, 0.0, 0.333, 0.5, 1.0}
.Sets can contain other sets!
We will soon encounter classes of languages (sets of sets of strings).
The power set of a set \(S\) is the set of all subsets of \(S\).
What is the cardinality of \(\powerset(S)\)?
Corresponding programming data types:
list/tuple
,java.util.List
,std::vector
{(a, b) for a in A for b in B}
set(itertools.product(A, B))
What is the cardinality of \(A^2\)?
C
function signature “bool f(int a);
” corresponds to a function \(f: \Z \to \{0, 1\}\).abs
: take the absolute value of an integer
Type signature? \(\texttt{abs}: \Z \to \Z\) or \(\texttt{abs}: \Z \to \N\)
Definition: \[ \text{for all } x \in \Z, \quad \texttt{abs}(x) = \begin{cases} x & \text{if } x \ge 0 \\ -x & \text{otherwise} \end{cases} \]
Corresponding C
code:
int abs(int x) { return x >= 0 ? x : -x; }
add
: add two integers together
Type signature? \(\texttt{add}: \Z \times \Z \to \Z\)
Definition: \[ \text{for all } x, y \in \Z, \quad \texttt{add}(x, y) = x + y \]
Corresponding C
code:
int add(int x, int y) { return x + y; }
Rather than a rule or formula, a function can be defined by a (potentially infinite) table of inputs and outputs.
Example: \[ f: \{0, 1, 2, 3, 4\} \to \{0, 1, 2, 3, 4\} \]
defined by:
\(n\) | \(f(n)\) |
---|---|
0 | 1 |
1 | 2 |
2 | 3 |
3 | 4 |
4 | 0 |
(incrementing modulo 5)
Example: \(\text{even}: \Z \to \{ \text{true}, \text{false} \}\) defined by \[ \text{even}(n) = \begin{cases} \text{true} & \text{if } n \text{ is even} \\ \text{false} & \text{otherwise} \end{cases} \]
Any predicate is identified by the subset of inputs that make it true
(e.g., even is identified by the set of even integers).
Relation: a predicate with domain \(A^2 = A \times A\);
equivalently, a subset of \(A^2\)
Negation/NOT
\[ \begin{array}{c|c} x & \neg x \\ \hline 0 & 1 \\ 1 & 0 \end{array} \]
Conjunction/AND
\[ \begin{array}{cc|c} x & y & x \land y \\ \hline 0 & 0 & 0 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 1 & 1 \end{array} \]
Disjunction/OR
\[ \begin{array}{cc|c} x & y & x \lor y \\ \hline 0 & 0 & 0 \\ 0 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 1 \end{array} \]
Exclusive or/XOR \[ \begin{array}{cc|c} x & y & x \oplus y \\ \hline 0 & 0 & 0 \\ 0 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 0 \end{array} \]
Implication
\[ \begin{array}{cc|c} x & y & x \implies y \\ \hline 0 & 0 & 1 \\ 0 & 1 & 1 \\ 1 & 0 & 0 \\ 1 & 1 & 1 \end{array} \]
(“If x then y” or “x implies y”)
Equivalent to \(\neg x \lor y\).
Equality/IFF
\[ \begin{array}{cc|c} x & y & x \iff y \\ \hline 0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0 \\ 1 & 1 & 1 \end{array} \]
“x if and only if y”
Equivalent to \((x \land y) \lor (\neg x \land \neg y)\).