data abstraction
Summary
Pairs
js
const x = pair(1, 2);
Box and pointer diagrams
Concept
Primitive form of data abstraction using pairs to store 2 values
Second value can be used to store another pair, into a chain of pairs
First value can also be a pair, to form a tree of pairs
js
const p = pair(a, b) // -> [a, b]
head(p) // -> a
tail(p) // -> b
Further abstracted to lists, trees(cs) and arrays
Equality vs Identity
=== -> Equal by identity
equal() -> Equal by value
js
const a = pair(1, 2);
const b = a;
const c = pair(1, 2);
a === b; // -> true
a === c; // -> false
equal(a, b); // -> true
equal(a, c); // -> true
Extra
Tikz template for box and pointer diagrams
latex
\usepackage{tikz}
\usetikzlibrary{positioning,arrows.meta}
% definitions for box and pointer diagrams
\def\boxsize{6mm}
\tikzset{cell/.style={inner sep=0pt,minimum size=\boxsize, node distance=2em and 3.5em}}
\newcommand\ptr[2]%
{
\draw[arrows={-Latex}] (#1.center)--(#2);
}
\newcommand\pnull[1]%
{
\draw (#1.south west)--(#1.north east);
}
\newcommand\pair[4][]%
{
\node[draw,cell,#1] (#2) {#3};
\node[draw,cell,anchor=west] (#2tail) at (#2.east) {#4};
}
\begin{document}
\begin{tikzpicture}
% draw diagram here
\node (start) {list};
\pair[right=of start]{p1}{10}{}
\pair[right=of p1]{p2}{}{}
\pair[below=of p2]{p3}{40}{}
\ptr{p1tail}{p2}
\ptr{p2}{p3}
\ptr{p2tail}{p3}
\draw[arrows={-Latex}] (start.east)--(p1);
\pnull{p3tail}
\end{tikzpicture}
\end{document}