\documentclass[a4paper, fleqn, 10pt]{report}
\usepackage[utf8]{inputenc}
\usepackage{t1enc}
\usepackage[table, usenames,dvipsnames,svgnames]{xcolor}
\usepackage[pdftex]{graphicx}
\usepackage{booktabs}
\usepackage{setspace}
\onehalfspacing
\usepackage{fullpage}
\usepackage{enumerate}
\usepackage{multicol}
\usepackage{tikz}
\usepackage{amsmath, amsthm, amssymb}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{multirow}

\usepackage{newtxtext}
\usepackage[libertine]{newtxmath}
%\usepackage{fourier}

\theoremstyle{definition}
\newtheorem{prb}{Problem}[chapter]
\newenvironment{prb*}[1]
  {\renewcommand\theprb{\thechapter.\arabic{prb}\rlap{$^{#1}$}}\prb}
  {\endprb}

\newcommand{\R}{\mathbf{R}}
\newcommand{\N}{\mathbf{N}}
\newcommand{\Z}{\mathbf{Z}}
\newcommand{\Q}{\mathbf{Q}}
\newcommand{\C}{\mathbf{C}}
\renewcommand{\P}{\mathbf{P}}

\renewcommand{\labelitemi}{$\blacktriangleright$}
\renewcommand{\tan}{\mathrm{tg}}

\newcommand{\mc}[1]{{\color{Blue}\tt #1}}
\newcommand{\mck}[1]{{\tt#1}}

\DeclareMathOperator{\ch}{cosh}

\frenchspacing

\title{Introduction to Matlab Programming}
\author{Problems \\[2em] Budapest University of Technology and Economics}
\date{2014}

\begin{document}
\maketitle
\chapter{Arrays and Graphics}
\section{Exercises}
\begin{prb*}{1}
Use the documentation to look up the functions: \mc{atan} and \mc{atan2}.
Illustrate the similarity and difference between them.
\end{prb*}

\begin{prb*}{1}
What are the results of the following expressions and why:
\[\frac{1}{0},\: \frac{0}{0},\: \frac{0}{\infty},\: \frac{\infty}{0},\: \frac{\infty}{\infty},\: \infty + \infty,\: \infty - \infty,\: 0\cdot\infty, \: 1^\infty, 0^0,\: 0^\infty,\: \infty^0,\: \infty^\infty.\]
\end{prb*}

\begin{prb*}{1}
Let $x:=3$ and $y:=7,$ using variables $x$ and $y$ find the value of the following expressions:
\begin{multicols}{3}
\begin{enumerate}[a)]
 \item $\dfrac{x^2-y^2}{x^3y}$
 \item $x^y-y^x$
 \item $\sin(\pi(x+y)) - \sqrt{y-x}$
 \item $\log_x(y)$
 \item $e^x + e^{-x} - 2\ch(x)$
 \item $\sqrt[x]{y}$
\end{enumerate}
\end{multicols}
\end{prb*}

\begin{prb*}{1}
Write a program, that converts from kilometers to miles by reading an input (number) from the user.
\end{prb*}

\begin{prb*}{1}
Explain the results of the following expressions:
\[\mc{uint8}(5-17), \quad [\text{'M'},\: 65,\: 84,\: 76,\: 65,\: 66], \quad \mc{int8}(1-2^{10}), \quad 1+0.1\times\mc{eps}\: \text{ opposed to }\: 1+100\times\mc{eps}.\]
\end{prb*}

\begin{prb*}{2}
Make the following lists using only the colon operator (\mc{:}), \mc{linspace} and arithmetics:
\begin{multicols}{2}
\begin{enumerate}[a)]
 \item $[0, 2, 4, 6, \dots, 20]$
 \item $[11, 9, \dots, -9, -11]$
 \item $[0.001, 0.01, \dots, 1000, 10000]$
 \item $[1, 2, 4, 8, \dots, 1024]$
 \item $[\underbrace{1,-1,1,-1,\dots, 1,-1}_{20}]$
 \item the list obtained by dividing the unit interval $[0, 1]$ to 5 equal parts (boundary points included)
 \item the list obtained by dividing the interval $[0, 2\pi)$ to 7 equal parts ($0$ included, $2\pi$ excluded)
\end{enumerate}
\end{multicols}
\end{prb*}

\begin{prb*}{1}
Run the following command and explain the result:
\[\mathrm{\mc{char}}(\mathrm{\mc{cumsum}}([117,\:-2,\:-14,\:13,\:-50,\:45,\:-12,\:8,\:3,\:-62,\:53,\:12,\:-2])).\]
Can you do your own version?
\end{prb*}

\begin{prb*}{2}
Make a list $X$ of 20 random integers: $-10\le X_k\le 30$ with uniform distribution.
Now, select the following entries of this list:
\begin{multicols}{2}
\begin{enumerate}[a)]
 \item negative entries
 \item entries greater than or equal to $7$
 \item entries greater than $-5$ and less than or equal to $12$
 \item odd entries
 \item entries divisible by 3 or 7
 \item entries dividing 360
\end{enumerate}
\end{multicols}
\end{prb*}

\begin{prb*}{2}
Define the following functions using anonymus functions:
\begin{multicols}{2}
\begin{enumerate}[a)]
 \item $\mathrm{sum\_n}(n) := 1 + 2 + \dots + n$
 \item $\mathrm{sum\_square}(n):= 1^2 + 2^2 + \dots + n^2$
 \item $\mathrm{fact}(n) := n!$
 \item $\mathrm{binom}(n,k) := \binom{n}{k}$
 \item $\mathrm{ln2}(n) := 1 - \frac{1}{2} + \frac{1}{3} - \frac{1}{4} + \dots + \frac{(-1)^{n+1}}{n}$
 \item $\mathrm{sol\_quad}(a, b) := [\frac{-a-\sqrt{a^2-4b}}{2}, \frac{-a+\sqrt{a^2-4b}}{2}]$
 \item $\mathrm{cum\_avr}([x_1, x_2, \dots, x_n]) := [x_1, \frac{x_1 + x_2}{2}, \dots, \frac{x_1 + x_2 + \dots + x_n}{n}]$
 \item $\mathrm{first}([x_1, x_2, \dots, x_n]) := x_1$
 \item $\mathrm{rest}([x_1, x_2, \dots, x_n]) := [x_2, x_3, \dots, x_n]$
 \item $\mathrm{take}([x_1, x_2, \dots, x_n], m) := [x_1, x_2, \dots, x_m]$
 \item $\mathrm{drop}([x_1, x_2, \dots, x_n], m) := [x_{m+1}, x_{m+2}, \dots, x_n]$
\end{enumerate}
\end{multicols}
\end{prb*}

\begin{prb*}{2}
Make the following matrices using only the colon operator (\mc{:}), \mc{diag}, \mc{zeros},
\mc{ones}, \mc{eye}, \mc{repmat}, \mc{reshape}, \mc{cat}, \mc{flipdim}, \mc{padarray} and arithmetics:
\begin{multicols}{3}
\begin{enumerate}[a)]
\item $\displaystyle
\begin{bmatrix}
0 & 1 & 0 & 1 & 0 & 1\\
1 & 0 & 1 & 0 & 1 & 0\\
0 & 1 & 0 & 1 & 0 & 1\\
1 & 0 & 1 & 0 & 1 & 0
\end{bmatrix}
$
\item $\displaystyle
\begin{bmatrix}
2 & 5 & 0 & 0 & 0 & 0\\
7 & 2 & 5 & 0 & 0 & 0\\
0 & 7 & 2 & 5 & 0 & 0\\
0 & 0 & 7 & 2 & 5 & 0\\
0 & 0 & 0 & 7 & 2 & 5\\
0 & 0 & 0 & 0 & 7 & 2
\end{bmatrix}
$

\item $\displaystyle
\begin{bmatrix}
1 & 1 & 1 & 1\\
2 & 2 & 2 & 2\\
3 & 3 & 3 & 3\\
4 & 4 & 4 & 4
\end{bmatrix}
$

\item $\displaystyle
\begin{bmatrix}
1 & 4 & 7 & 10\\
0 & 0 & 0 & 0\\
2 & 5 & 8 & 11\\
0 & 0 & 0 & 0\\
3 & 6 & 9 & 12\\
0 & 0 & 0 & 0
\end{bmatrix}
$

\item $\displaystyle
\begin{bmatrix}
0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 1 & 1 & 1 & 0 & 0\\
0 & 0 & 1 & 1 & 1 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0
\end{bmatrix}
$

\item $\displaystyle
\begin{bmatrix}
0 & 0 & 0 & 3 & 3 & 1 & 1\\
0 & 0 & 0 & 3 & 3 & 1 & 1\\
2 & 2 & 2 & 3 & 3 & 1 & 1\\
2 & 2 & 2 & 3 & 3 & 5 & 5\\
0 & 0 & 0 & 3 & 3 & 5 & 5\\
0 & 0 & 0 & 3 & 3 & 5 & 5
\end{bmatrix}
$
\end{enumerate}
\end{multicols}
\end{prb*}

\begin{prb*}{1}
Make a $10\times10$ multiplication table. Could you do it in modulo $11$ residue class?
\end{prb*}

\begin{prb*}{2}
Make a $5\times6$ matrix $X$ of random integers $0\le X_{ij}\le 50,$
then determine the
\begin{multicols}{3}
\begin{enumerate}[a)]
 \item maximum of each column,
 \item minimum of each row,
 \item sum of the rows,
 \item sum of the even columns,
 \item sum of the first and last columns,
 \item even entries,
 \item number of zeros,
 \item largest entry,
 \item three smallest entries.
\end{enumerate}
\end{multicols}
\end{prb*}

\begin{prb*}{3}
Consider Table \ref{tab:experiment} containing experiment data on 30 subjects.
Make a random test table, and determine the:
\begin{multicols}{2}
\begin{enumerate}[a)]
 \item IDs of all female,
 \item ID of the youngest male,
 \item IDs of those scored $\ge0.5,$
 \item mean and standard deviation of the scores
 \item mean age of those scored $\le 0.2,$
 \item gender ratio,
 \item IDs of females past 35,
 \item mean scores of males younger than 37,
 \item gender ratio of those scored $\ge 0.7,$
 \item IDs of females scored $\le 0.3$ or younger than $40.$
\end{enumerate}
\end{multicols}
\begin{table}[ht!]
\centering
\begin{tabular}{cccc}
\toprule
 ID & Gender (1--M, 2--F) & Age (20--50) & Score (0--1)\\
 \midrule
 1  & 2 & 32 & 0.68\\
 2  & 2 & 28 & 0.78\\
 3  & 1 & 47 & 0.98\\
 4  & 2 & 45 & 0.43\\
 \vdots & \vdots & \vdots & \vdots\\[0.5em]
 30  & 1 & 22 & 0.73\\
 \bottomrule
\end{tabular}
\caption{Example of the experiment data}\label{tab:experiment}
\end{table}
\end{prb*}

\begin{prb*}{3}
Given a round table with 10 seats.
Let $0$ and $1$ denote the empty and occupied seats, respectively.
The seats are randomly taken, that is we have a list of random 0's and 1's.
Count the number of (non-empty) neighbours within distance of 2 for all seats.
How about if the table wasn't round?
\end{prb*}

\begin{prb*}{3}
Plot the following functions in one figure, but in three -- vertically arranged -- seperate axes:
 \[ \frac{\sin(x)}{x},\: -10\le x\le 10, \qquad \sin\left(\frac{1}{x}\right),\: -10\le x\le 10, \qquad x^2e^{-x}\cos(5x),\: 0\le x\le 10.\]
\end{prb*}

\begin{prb*}{1}
Simulate a hundred rolls with two dice, and plot the histogram of the result.
\end{prb*}

\begin{prb*}{1}
 Plot the pie chart of the age data in Table \ref{tab:experiment} for the age groups: 20--30--40--50,
 highlight the most numerous group.
\end{prb*}

\begin{prb*}{1}
 Make 5 figures arranged in an X pattern.
 Make sure that your solution works with any screen resolution.
\end{prb*}

\begin{prb*}{2}
 Draw the following pictures using graphics primitives.
 \begin{figure}[ht!]
\centering
\includegraphics[height=4cm]{stop}\hspace{4cm}
\includegraphics[height=4cm]{owl}
\end{figure}
\end{prb*}

\begin{prb*}{2}
Design your own clock showing the time given by a triplet \mck{[h, m, s]}.
\end{prb*}

\newpage
\section{Projects}
\subsection*{Random Walk in 2D$^{10}$}
Consider a particle sitting at the origin.
Every step the particle makes one of the moves: left, right, up or down
randomly with equal probability.
Plot the particle's trajectory for a few hundred steps as shown in Figure \ref{fig:rw}.

\begin{figure}[ht!]
\centering
\includegraphics[width=0.5\linewidth]{rwFig}
\caption{Trajectory of a random walk.}\label{fig:rw}
\end{figure}

\subsection*{Monte Carlo Simulation$^{20}$}
Consider the square having vertices $A(1,-1),\: B(1,1),\: C(-1,1),\: D(-1,-1)$ and -- inside this square -- the unit disk.
Choose $n$ random points $P(x,y)$ inside the square, i.e. $-1\le x,y \le 1.$
Let $N$ denote the number of points inside the disk, that is $x^2+y^2\le 1.$
Now, if $n$ is large enough, then
\[\frac{N}{n} \approx \frac{A_{\text{disk}}}{A_{\text{square}}} = \frac{\pi}{4}.\]
Write a program that simulates the above process.
Display the unit disk and the points, also plot the relative frequency: $\frac{N}{n}$ for
all $n=1,2,\dots$ as shown in Figure \ref{fig:mc}.

\begin{figure}[ht!]
\centering
\includegraphics[width=0.48\linewidth]{mcFig1}
\includegraphics[width=0.48\linewidth]{mcFig2}
\caption{Results of the simulation.}\label{fig:mc}
\end{figure}

\subsection*{Convay's Game of Life$^{30}$}
This game is played on an $n\times n$ grid of 1's and 0's,
where 1 and 0 represent living and dead cells, respectively.
It is clear that every cell has exactly 8 neighbours,
except along the border.
However, we can view these border cells, as if they had 8 neighbours,
considering the cells outside the border dead.
The population of cells advances to a new generation by
applying the following rules for every cell (from Wikipedia):
\begin{itemize}
 \item Any live cell with fewer than two live neighbours dies, as if caused by under-population.
 \item Any live cell with two or three live neighbours lives on to the next generation.
 \item Any live cell with more than three live neighbours dies, as if by overcrowding.
 \item Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
\end{itemize}

Write a program that for a given table, computes the next generation.
For example:
\[
\begin{bmatrix}
 0 & 1 & 1 & 0\\
 1 & 1 & 0 & 1\\
 0 & 1 & 1 & 1\\
 1 & 0 & 1 & 1
\end{bmatrix}
\quad \longrightarrow
\quad
\begin{bmatrix}
 1 & 1 & 1 & 0\\
 1 & 0 & 0 & 1\\
 0 & 0 & 0 & 0\\
 0 & 0 & 0 & 1
\end{bmatrix}
\]
Look up the \mc{image} object in the documentation, and
use it to display the original and new generation in separate figures.

\subsection*{PageRank$^{30}$}
This algorithm was first used by Google to order search results.
According to Google:
\begin{quote}
PageRank works by counting the number and quality of links to a page to determine a rough estimate of how important the website is.
The underlying assumption is that more important websites are likely to receive more links from other websites.
\end{quote}
From this perspective the internet consists of webpages and links between them (see Figure \ref{fig:graph}).
\begin{figure}[ht!]
 \centering
 \includegraphics[width=0.5\textwidth]{graph}
 \caption{An example graph with $n=4$ edges.}\label{fig:graph}
\end{figure}
The graph in Figure~\ref{fig:graph} is represented as two arrays: vertecies ($V$) and edges ($E$)
in the following way:
\[V=
\begin{bmatrix}
1 & 2 & 3 & 4
\end{bmatrix},
\quad
E=\begin{bmatrix}
1 & 1 & 3 & 3 & 4\\
2 & 3 & 1 & 2 & 2
\end{bmatrix}.
\]
Denote the number of vertices by $n,$ which is $n=4$ in our example.
Now we construct the adjacency matrix $A$ of the graph, that is we have $A_{ij}=1$
if and only if the graph has the edge $i\to j,$ otherwise $A_{ij}=0.$
It could be that, some of the rows have only zero entries, which are quite problematic, therefore
we need to substitute every such row with a row full of ones to get a new matrix $B.$
This means, that if we have webpages that don't link to anywere, than we assume
instead they link to everywhere.
For the example graph, they look like this:
\[
A =
\begin{bmatrix}
0 & 1 & 1 & 0\\
0 & 0 & 0 & 0\\
1 & 1 & 0 & 0\\
0 & 1 & 0 & 0
\end{bmatrix}
\qquad\longrightarrow
\qquad
B =
\begin{bmatrix}
0 & 1 & 1 & 0\\
1 & 1 & 1 & 1\\
1 & 1 & 0 & 0\\
0 & 1 & 0 & 0
\end{bmatrix}.
\]
The next step is to make sure that every row sums up to one, thus we need to normalize the rows of $B$
by which we obtain the matrix $M$ with entries
\[M_{ij} := \frac{B_{ij}}{\sum_{k=1}^n B_{ik}} = \frac{B_{ij}}{B_{i1} + B_{i2} + \dots + B_{in}}.\]
Continuing the example, we have:
\[
M =
\begin{bmatrix}
0 & \frac{1}{2} & \frac{1}{2} & 0\\
\frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4}\\
\frac{1}{2} & \frac{1}{2} & 0 & 0\\
0 & 1 & 0 & 0
\end{bmatrix}.
\]
In order to regularize the problem, we need to perturb the matrix $M$ with the matrix $S,$
that is \[P:=\alpha M + (1-\alpha)S,\]
where  $S_{ij} := 1/n.$
Following Google's recommendation we set $\alpha := 0.8.$ The example becomes:
\[P = \frac{4}{5}\begin{bmatrix}
0 & \frac{1}{2} & \frac{1}{2} & 0\\
\frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4}\\
\frac{1}{2} & \frac{1}{2} & 0 & 0\\
0 & 1 & 0 & 0
\end{bmatrix} + \frac{1}{5}
\begin{bmatrix}
\frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4}\\
\frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4}\\
\frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4}\\
\frac{1}{4} & \frac{1}{4} & \frac{1}{4} & \frac{1}{4}
\end{bmatrix}=
\frac{1}{20}
\begin{bmatrix}
1 & 9 & 9 & 1\\
5 & 5 & 5 & 5\\
9 & 9 & 1 & 1\\
1 & 17 & 1 & 1
\end{bmatrix}
\]
Now, in the last step we need to solve the linear equation $P^\top x=x$ for the unkown vector $x.$
This $x$ vector will contain the ranking scores for each webpage.
The equation $P^\top x=x$ is equivalent to the homogeneous equation $(P^\top-I)x=0,$
where $I$ is the $n\times n$ identity matrix.
Due to the earlier regularization, we can be sure there is only one
$x$ vector satisfying this equation\footnote{It is clear that both $x$ and let's say $1.34\cdot x$
imply the same ranking.
So actually, there are infinitely many solutions for $P^\top x = x,$
but they only differ in a scalar factor, thus implying the same ranking.}.
Finally, normalize the result, so that the ranking scores sum up to 1:
\[r := \frac{x}{\sum_{i=1}^n x_i}.\]
The ranking scores for the example: $r = [0.223,\: 0.426,\: 0.223,\: 0.128],$
so the ranking is $R = [2,\: 3,\: 1,\: 4].$

Write a program that for a given $V$ and $E$ computes the ranking.
Use randomly generated test graphs to test your program.
Make sure that the test graph is a simple (directed) graph, i.e. it does not contain
loops or multiple edges.

\chapter{Data Types, Functions and Flow Control}
\section{Exercises}
\begin{prb*}{3}
Create a structure array named {\tt subject} with the following fields: {\tt .name}, {\tt.age}, {\tt.weight}, {\tt.height}
using data from Table~\ref{tab:sub}, and determine the
\begin{multicols}{2}
 \begin{enumerate}[a)]
  \item average age
  \item mean and standard deviation of the weights
  \item names of the 3 oldest subjects
  \item names of those who are younger than $25$
  \item average age of those who are taller than 160\,cm, and not heavier than 60\,kg
  \item names of those who have height above average
 \end{enumerate}
\end{multicols}
\begin{table}[ht!]
 \centering
 \begin{tabular}{lccc}
  \toprule
  \multicolumn{4}{c}{Subject}\\
  \midrule
  Name & Age & Weight & Height\\
  \midrule
  Judy Garcia  	  & 23 & 59 & 167\\
  Robert Baker 	  & 22 & 66 & 180\\
  Laura Ross 	  & 28 & 70 & 171\\
  Kimberly Price  & 21 & 45 & 162\\
  Nancy Thompson  & 27 & 90 & 165\\
  Tina Clark 	  & 28 & 77 & 191\\
  \bottomrule
 \end{tabular}
 \caption{Data for creating the structure {\tt subject}.}\label{tab:sub}
\end{table}
\end{prb*}

\begin{prb*}{5}
 Write a script that you can use to manage the structure {\tt subject}.
 At the start it should be checked (\mc{exist}) whether there is a variable in the Work Space called {\tt subject}
 or not, in the latter case it should be checked if there is a file {\tt subject.m}, and then loaded (\mc{load}) into the Work Space.
 If neither the variable nor the file exist; an empty structure should be initialized.
 Create a menu for your program with the following items:
 \begin{description}
  \item[New] Create new entry in {\tt subject}. The program should ask for the subject's name, age, weight and height.
  \item[View] Print out the name of every subject.
  \item[Exit] Before quitting, the program should ask whether to save the changes or not, and act accordingly (\mc{save}).
 \end{description}
\end{prb*}

\begin{prb*}{5}
Write a function that, for a given subject,
calculates the body mass index.
Specifically, write a function named \mc{get\_bmi} with one input and three (optional) outputs:
\begin{description}
 \item[\mc{get\_bmi}\mck{(s)}] prints out the name and textual classification of the subject {\tt s},
 \item[\mck{bmi = }\mc{get\_bmi}\mck{(s)}] gives the body mass index of subject {\tt s},
 \item[\mck{[bmi, bmi\_class] = }\mc{get\_bmi}\mck{(s)}] gives the body mass index and numeric classification.
\end{description}

\begin{table}[ht!]
 \centering
 \begin{tabular}{clc}
  \toprule
  & \multicolumn{2}{c}{Classification}\\
  \cmidrule(r){2-3}
  BMI [$\mathrm{kg}/\mathrm{m}^2$] & Text & Number \\
  \midrule
  --15 	 & very severely underweight 	& $-3$\\
  15--16 & severely underweight 	& $-2$\\
  16--18.5 & underweight 		& $-1$\\
  \midrule
  18.5--25 & normal 			& $0$\\
  \midrule
  25--30   & overweight			& $1$\\
  30--35   & moderately obese 		& $2$\\
  35--   & severely obese 		& $3$\\
  \bottomrule
 \end{tabular}\label{tab:BMI}
 \caption{BMI classification}
\end{table}
\end{prb*}

\begin{prb*}{2}
Using the following cells
\begin{center}
\mck{ranks =  \{2,3,4,5,6,7,8,10,J,Q,K,A\}},\quad \mck{suits =  \{Clubs,Diamonds,Hearts,Spades\}}
\end{center}
create the standard 52-card deck as a cell containing all pairs: \mck{\{\{'2','Clubs'\}, \{'3','Clubs'\},\dots\}}.
\end{prb*}

\begin{prb*}{2}
Determine how many different ways the number $1729$ can be decomposed to a sum of two cubes of positive integers, i.e. integers $a,b>0$ satisfying $a^3 + b^3 = 1729.$
Use trial and error for all integers $1\le a\le b\le 12.$
\end{prb*}

\begin{prb*}{2}
Using trial and error, determine the Pythagorean triples: $a^2 + b^2 = c^2$ for all $1\le a\le b\le c\le 100$.
\end{prb*}

\begin{prb*}{5}
Let $M$ a natural number, and consider the (finite) sequence $u(M)=\begin{bmatrix}u_0 & u_1 & \dots & u_n\end{bmatrix}^\top$
generated by a given function $f\colon \N\to \N$ in the following way:
\[u(M) = \begin{bmatrix}
          M& f(M)&\ f(f(M)) & f^3(M) & \dots & f^n(M)
         \end{bmatrix}\quad \text{or equivalently} \quad u_0:=M,\ u_{k+1} = f(u_k),\]
where
\[f(n) = \begin{cases}
            n/2, & \text{if }n \text{ is even,}\\
            3n+1 & \text{if }n \text{ is odd,}
           \end{cases}
\]
The famous Collatz conjecture states that starting from any natural number $M$ the sequence $u(M)$ will eventually
reach $1.$
Assuming the conjecture is true, let $n$ the smallest number such that $f^n(M) = 1,$
so that the last element in the list $u(M)$ is $u_n=1.$
The number of steps taken to reach 1 is called stopping time $T(M)$.
For example:
\[u(17)=[17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], \quad T(17) = 12.\]
Write a function named \mck{u = }\mc{collatz}\mck{(M)}.
Plot $(M,\max u(M)).$ Plot the histogram of the stopping time $T(M)$ for $2\le M \le 500.$
\end{prb*}

\begin{prb*}{4}
Implement the quicksort algorithm as a function \mck{v = }\mc{quicksort}\mck{(u)}, where
$u,\,v$ are lists, and $v$ is the sorted version of $u.$
\begin{quote}
The quicksort algorithm (from Wikipedia):
\begin{enumerate}
 \item Pick an element, called a pivot, from the array.
 \item Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
 \item Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.
\end{enumerate}

\end{quote}

\end{prb*}

\section{Projects}
\subsection*{Simple Game$^{30}$}
In this game the computer thinks of a number $ 1\le n\le 100$, then you have to guess that number.
Each time you guess, the computer tells you whether your guess is too small or too large.
As soon as you guess the correct number the game is over.
Every time the game is played the time (score) that was needed to find the number should be recorded.

To store information about the players and their scores use the structure \mck{game} with fields:
\begin{description}
 \item[\mck{.player}] A structure array with fields:
  \begin{description}
  \item[\mck{.name}] A string, the name of the player.
  \item[\mck{.time}] A vector containing the player's scores. Should be an empty vector, if no game has been played yet.
 \end{description}
 \item[\mck{.cp}] An integer representing the current player, such that \mck{game.player(game.cp)} refers to the
		  structure corresponding to the current player.
\end{description}
Make sure, that the variable \mck{game} exists in the Work Space by
loading a previously saved one, or -- if the file does not exist then -- initializing one (with at least one player).

Create a menu for the game with the following items:
\begin{description}
\item[Start]
    Starts the game by calling the function \mc{start\_game}.
    Write a function named \mck{game\_new =}\mc{ start\_game}\mck{(game)}, so that -- after finishing the game --
    it appends the time (needed to succed) to the current player's time vector; and returns with the updated structure \mck{game\_new}.
\item[Change Player]
    Change the current player by calling the function \mc{change\_player}.
    Write a function named \mck{game\_new = }\mc{change\_player}\mck{(game)} that
    lists all players, from which the user can choose one; and returns with the structure \mck{game\_new}
    where the current player (\mck{game.cp}) has been updated -- in accordance with the user's choice.
\item[New Player]
    Add a new player by calling the function \mc{new\_player}. Write a function named \mck{game\_new = }\mc{new\_player}\mck{(game)} that adds a new entry to the structure array \mck{game.player} by asking the player's name,
    and returning with the updated structure \mck{game\_new}.
    The new player's  time vector should be empty. When a new player is added, make sure that the the current player is set to the new player.
\item[View Ranking]
    List the top 5 players and their scores by calling the function \mc{view\_ranking}.
\item[Quit]
    Quit the program. Save the variable \mck{game} using \mc{save}.
\end{description}
Make sure that besides the menu the current player's name is also displayed.

\subsection*{Euler Solver$^{30}$}
Differential equations play a central role in modeling dynamical systems, such as the weather,
the chemical processes in a cell or the motion of a commet.
Henceforth, we only consider deterministic continuous models that can be described by
an explicit, first order ordinary differential equation in the form:
\begin{equation}
\dot x(t) = f(t,x(t)),\quad x(t_0) = x_0,\label{eq:ode}
\end{equation}
for some interval $t\in [t_0, t_N],$
where $x\colon \R\to\R^n$ the state variable, and $f\colon\R\times\R^n\to\R^n$ is the model.
In general, we can only calculate the approximate solution of \eqref{eq:ode} in discrete points $t_1,t_2,\dots,t_N.$
The solution at these points are approximated $x(t_n)\approx x_n$ by using the forward Euler method:
\[t_{n+1} = t_n + h, \quad x_{n+1} = x_n + h f(t_n, x_n), \qquad n=0,1,\dots,N-1\]
where $h$ is the step size, a fixed small positive number.

Write a function named \mck{sol = }\mc{euler\_solve}\mck{(ivp)}
where the input \mck{ivp} is a structure defining the initial value problem \eqref{eq:ode},
having the following fields:
\begin{description}
 \item[\mck{.model}] is a function handle for the function $f\colon \R\times\R^n\to\R^n,$
 \item[\mck{.initial\_value}] is the initial vector $x_0\in\R^n,$
 \item[\mck{.interval}] is an array \mck{[t0, tN]}, where $t_0$ and $t_N$ are the initial and final time, respectively.
 \item[\mck{.step\_size}] is the step size $h,$ if it's empty use $h:=|t_N-t_0|\cdot 10^{-3}.$
\end{description}
The output \mck{sol} is a structure with fields \mck{.t} which contains the time vector $[t_0,t_0+h,\dots,t_0+Nh],$
and \mck{.x} which contains the approximation of the solutions $x_1(t),\,x_2(t),\dots,x_n(t)$ in its rows.

Test your solver by writing scripts for the following problems:
\begin{enumerate}[a)]
\item Solve the logistic equation: $\dot x = x(1-x)$ for the initial values $x(0):=x_0\in\{0,0.25,0.5,\dots,2\},$
      and plot the solutions (see Figure \ref{fig:logistic}).
\item Solve the equation $\ddot u + 2\xi\dot u + u = 0$ of a damped oscillator -- with the initial value
$u(0) := 1,\: \dot u(0) := 0$ -- for the damping parameters $\xi =0.2,0.3,\dots,1.4,$
      and plot the solutions (see Figure \ref{fig:damped}).\\
      {\it \small Hint: to write the oscillator in the form of \eqref{eq:ode} set $x=(x_1\ \ x_2)^\top:=(u\ \ \dot u)^\top.$}
      \begin{figure}[ht!]
	\centering
	\begin{subfigure}[b]{0.48\textwidth}
	  \includegraphics[width=\textwidth]{logistic}
	  \caption{Logistic equation for different initial values.}
	  \label{fig:logistic}
	\end{subfigure}
	\begin{subfigure}[b]{0.48\textwidth}
	 \includegraphics[width=\textwidth]{damped}
	 \caption{Damped oscillator for different dampings.}
	  \label{fig:damped}
	\end{subfigure}
	\caption{Solutions of the logistic equation and the damped oscillator.}
      \end{figure}

\item Solve the Lorenz system:
	\begin{equation}
	    \dot u = 10(v-u),\qquad
	    \dot v = u(28-w)-v,\qquad
	    \dot w = uv - \frac{8}{3}z,\label{eq:lorenz}
	\end{equation}
	\begin{figure}[ht!]
	\centering
	 \includegraphics[width=0.8\textwidth]{lorenz}
	 \caption{A trajectory and its projections of the Lorenz System.}\label{fig:lorenz}
	\end{figure}

      for the initial value $x(0) = (u(0)\ v(0)\ w(0))^\top := (1\ 1\ 1)^\top,$
      and plot the  trajectory $t\mapsto (u(t), v(t), w(t))$ in three dimensions using \mc{plot3} (see Figure~\ref{fig:lorenz}).
      Show the following projections of the trajectory as well: $t\mapsto (30, v(t), w(t)),\: t\mapsto (u(t), 30, w(t)),\: t\mapsto (u(t), v(t), 0).$
\end{enumerate}

\subsection*{Cellular Automaton$^{30}$}
Let $x_1=[x_{1,1},x_{1,2},\dots,x_{1,m}]$ a list of zeros and ones representing the state of the automaton.
At each step the state of automaton evolves by a set of rules.
For a given rule $r$ the state is updated by
\[x_{i+1,k} = f_r(x_{i,k-1}, x_{i,k}, x_{i,k+1}),\quad k=1,2,\dots,m\]
with the assumption $x_{i,0} = x_{i,m+1} = 0$ for all $i=1,2,\dots,n.$
\begin{table}[ht!]\centering
 \begin{tabular}{ccccccccccccc}
 \toprule
      &     &     &  &\multicolumn{8}{c}{rules} \\
      \cmidrule{5-13}
  $a$ & $b$ & $c$ &  & 0 & 1 & 2 & 3 & 4 &\dots & 30 &\dots  & 255 \\
  \midrule
%  & & & & \multicolumn{5}{c}{$f_r(u_{k-1},u_k,u_{k+1})$} \\
  0 & 0 & 0 & $d_0(r)$ & 0 & 1 & 0 & 1 & 0 & \dots & 0 &\dots & 1\\
  0 & 0 & 1 & $d_1(r)$ & 0 & 0 & 1 & 1 & 0 & \dots & 1 &\dots & 1\\
  0 & 1 & 0 & $d_2(r)$ & 0 & 0 & 0 & 0 & 1 & \dots & 1 &\dots & 1\\
  0 & 1 & 1 & $d_3(r)$ & 0 & 0 & 0 & 0 & 0 & \dots & 1 &\dots & 1\\
  1 & 0 & 0 & $d_4(r)$ & 0 & 0 & 0 & 0 & 0 & \dots & 1 &\dots & 1\\
  1 & 0 & 1 & $d_5(r)$ & 0 & 0 & 0 & 0 & 0 & \dots & 0 &\dots & 1\\
  1 & 1 & 0 & $d_6(r)$ & 0 & 0 & 0 & 0 & 0 & \dots & 0 &\dots & 1\\
  1 & 1 & 1 & $d_7(r)$ & 0 & 0 & 0 & 0 & 0 & \dots & 0 &\dots & 1\\
  \bottomrule
 \end{tabular}
\caption{All possible rules. Columns $0,1,2,\dots$ contain the digits of the corresponding rule in base 2.}\label{tab:rules}
\end{table}
Any rule $r=0,1,2,\dots,255$ in base 2 has at most 8 digits, and can be written as
\[r = d_0(r) + 2 d_1(r) + 2^2d_2(r) + \dots + 2^7d_7(r), \qquad d_i(r)\in\{0,1\},\quad i=0,2,\dots,7.\]
The map $f_r$ is defined as $f_r(a,b,c) = d_i(r),$ where $i=2^2a + 2b + c.$
For instance, consider $r = 30 = 2^1 + 2^2 + 2^3 + 2^4,$ so $d_0(30) = 0,\: d_1(30) = 1,\: d_2(30) = 1,$ etc.
Therefore $f_{30}(0,0,0)=d_0(30) = 0,\: f_{30}(0,0,1)=d_1(30) = 1,\: f_{30}(0,1,0)=d_2(30) = 1,$ etc., for summary see Table~\ref{tab:rules}.
\begin{figure}[ht!]
\centering
  \includegraphics[width=0.7\textwidth]{rule30}
  \caption{Rule 30, generated using \mc{cellular\_automaton}\mck{(30,\,[50,\,100],\,50)}.}\label{fig:automaton}
\end{figure}

The evolution of an initial state $x_1=[x_{1,1},x_{1,2},\dots,x_{1,m}]$ for $n$ steps is collected in the matrix
\[X = \begin{bmatrix}
       x_1\\
       x_2\\
       \vdots\\
       x_n
      \end{bmatrix} =
     \begin{bmatrix}
       x_{1,1} & x_{1,2} & \dots & x_{1,m}\\
       x_{2,1} & x_{2,2} & \dots & x_{2,m}\\
       \vdots & \vdots & \ddots & \vdots\\
       x_{n,1} & x_{n,2} & \dots & x_{n,m}
      \end{bmatrix}.
      \]
Write a function named \mc{cellular\_automaton} considering the following specification:
\begin{description}
  \item[\mc{cellular\_automaton}\mck{(r, [n,\,m])}] shows the evolution of the initial state $x_1$  as an image by the rule $r$ for $n$ steps, where the initial state is $x_{1,1}=1,$ $x_{1,i}=0$ for all $i=2,\dots,m.$
  \item[\mc{cellular\_automaton}\mck{(r, n)}] is the same as before except $m=n.$
  \item[\mc{cellular\_automaton}\mck{(r, [n,\, m], [i1,\,i2\,\dots,\,ik])}] is the same as before except the initial state is defined by $x_{1,i}=1$ for all $i\in\{i_1,i_2,\dots,i_k\}$ and $x_{1,i}=0$ otherwise. See an example in Figure \ref{fig:automaton}.
  \item[\mck{X = }\mc{cellular\_automaton}\mck{(r, \dots)}] instead of plotting, it returns with a matrix $X$ containing the states of the automaton as its rows.
\end{description}

\subsection*{Iterated Function System$^{30}$}
Given a polygon $S$ in the plane represented by its $m$ vertices $u_{i}=(x_i\ y_i)^\top,$ and a set of of affine contraction maps:
\[S =  \begin{bmatrix}
	    u_{1}\\
	    u_{2}\\
	    \vdots\\
	    u_{m}
        \end{bmatrix},\qquad F_i(u):=A_i u + b_i, \quad A_i\in\R^{2\times 2},\,b_i\in\R^2, \quad i=1,2,\dots,n.\]
One can apply $F_i$ to the polygon $S$ and get an other polygon $F_i(S)$ by applying $F_i$
to every vertices of the polygon in the following way:
\[F_i(S) =
	    \begin{bmatrix}
	      F_i(u_{1})\\
	      F_i(u_{2})\\
	      \vdots\\
	      F_i(u_{m})\\
	    \end{bmatrix}=
	    \begin{bmatrix}
	      A_iu_{1}+b_i\\
	      A_iu_{2}+b_i\\
	      \vdots\\
	      A_iu_{m}+b_i\\
	    \end{bmatrix}.
\]
Generate new polygons recursively by
\[X_{k+1} = \begin{bmatrix}
             F_1(X_k) & F_2(X_k) & \dots\ & F_n(X_k)
            \end{bmatrix}
, \qquad X_0 = S,\]
where $X_k$ is a matrix containing polygons as its columns, and $F_i(X_k)$ means that $F_i$
applied column-wise, that is applied to every polygon contained in $X_k.$

For example, when the polygons are triangles $m=3$, and we have two transformations $F_1,\,F_2$ so that $n=2.$
\[
X_0 =\begin{bmatrix}
      u_{1}\\
      u_{2}\\
      u_{3}
     \end{bmatrix},\quad
X_1 =\begin{bmatrix}
      F_1(X_0) & F_2(X_0)
     \end{bmatrix},\quad
\]
\[
X_2 =\begin{bmatrix}
      F_1(X_1) & F_2(X_1))
     \end{bmatrix}=
     \begin{bmatrix}
      F_1(F_1(X_0)) & F_1(F_2(X_0)) & F_2(F_1(X_0)) & F_2(F_2(X_0))
     \end{bmatrix}.
\]

Write a function named \mc{ifs} considering the following specification:
\begin{description}
 \item[\mc{ifs}\mck{(ifs\_data)}] shows the polygons determined by the input (see below the input specification).
 \item[\mck{X = }\mc{ifs}\mck{(ifs\_data)}] instead of plotting it gives the matrix $X_k.$
 \item[\mc{ifs}\mck{(ifs\_data, 'Color', [1,0,0], \dots)}] excepts extra arguments as an option for \mc{patch} object.
\end{description}

The input structure \mck{ifs\_data} has the following fields:
\begin{description}
 \item[\mck{.initial\_shape}] a vector representing the initial polygon $S.$
 \item[\mck{.transformation}] a cell containing the matrices $A_i,\ i=1,2\dots,n$
 \item[\mck{.dilation}] a cell containing the dilations $b_i,\ i=1,2\dots,n$
 \item[\mck{.step}] is an integer $N,$ then the iteration goes $N$ steps, thus calculating $X_N.$
		    Note that the size of $X_N$ is $2m\times n^N.$
\end{description}

Test your function by writing a script for the following problems:
\begin{enumerate}[a)]
 \item Show the 6th approximation of the Sierpinski triangle:
 \[A_1 = A_2 = A_3 = \begin{bmatrix}
          1/2 & 0\\
          0   & 1/2
         \end{bmatrix},\quad
         b_1 = \begin{bmatrix}
          0 \\
          0
         \end{bmatrix},\quad
         b_2 = \begin{bmatrix}
          1/2 \\
          0
         \end{bmatrix},\quad
         b_3 = \begin{bmatrix}
          1/4 \\
          \sqrt{3}/4
         \end{bmatrix},
\]
starting from the equilateral triangle: $S=\begin{bmatrix}0 & 0 & 1 & 0 & 1/2 & \sqrt{3}/2\end{bmatrix}^\top.$
The Figure \ref{fig:ifs}. shows the first three approximation of the Sierpinski triangle.
Try out what happens when you start from the square: $S=\begin{bmatrix}0 & 0 & 1 & 0 & 1 & 1 & 0 & 1\end{bmatrix}^\top.$
\begin{figure}[ht!]
\centering
  \includegraphics[width=0.3\textwidth]{ifs1}
  \includegraphics[width=0.3\textwidth]{ifs2}
  \includegraphics[width=0.3\textwidth]{ifs3}
  \caption{Approximations of the the Sierpinski triangle: $X_0,\,X_1,\,X_2$.}\label{fig:ifs}
\end{figure}
\item Show the 4th approximation of the Sierpinski carpet:
 \[A_1 =  \dots = A_8 = \begin{bmatrix}
          1/3 & 0\\
          0   & 1/3
         \end{bmatrix}\]
\[       b_1 = \begin{bmatrix}
          0 \\
          0
         \end{bmatrix},\
         b_2 = \begin{bmatrix}
          1 \\
          0
         \end{bmatrix},\
         b_3 = \begin{bmatrix}
          2 \\
          0
         \end{bmatrix},\
         b_4 = \begin{bmatrix}
          0 \\
          1
         \end{bmatrix},\
         b_5 = \begin{bmatrix}
          2 \\
          1
         \end{bmatrix},\
         b_6 = \begin{bmatrix}
          0 \\
          2
         \end{bmatrix},\
         b_7 = \begin{bmatrix}
          1 \\
          2
         \end{bmatrix},\
         b_8 = \begin{bmatrix}
          2 \\
          2
         \end{bmatrix},
\]
starting from the square: $S=\begin{bmatrix}0 & 0 & 3 & 0 & 3 & 3 & 0 & 3\end{bmatrix}^\top.$
\begin{figure}[ht!]
\centering
  \includegraphics[width=0.3\textwidth]{carpet1}
  \includegraphics[width=0.3\textwidth]{carpet2}
  \includegraphics[width=0.3\textwidth]{carpet3}
  \caption{Approximations of the Sierpinski triangle: $X_0,\,X_1,\,X_2$.}\label{fig:ifs}
\end{figure}
\item Show the 9th approximation of the Dragon curve:
\[
A_1 = \frac{1}{\sqrt{2}}\begin{bmatrix}
          \cos(\pi/4) & \sin(\pi/4)\\
          -\sin(\pi/4) & \cos(\pi/4)
         \end{bmatrix},\quad
A_2 = \frac{1}{\sqrt{2}}\begin{bmatrix}
          \cos(5\pi/4) & -\sin(5\pi/4)\\
          \sin(5\pi/4) & \cos(5\pi/4)
         \end{bmatrix}
\]
\[       b_1 = \begin{bmatrix}
          0 \\
          0
         \end{bmatrix},\
         b_2 = \begin{bmatrix}
          1 \\
          0
         \end{bmatrix}
\]
in blue (see Figure \ref{fig:dragon}.), starting from the initial polygon $S= \begin{bmatrix}0 & -0.05 & 1 & -0.05 & 1 & 0.05 & 0 & 0.05\end{bmatrix}^\top.$
\begin{figure}[ht!]
\centering
  \includegraphics[width=0.3\textwidth]{dragon1}
  \includegraphics[width=0.3\textwidth]{dragon2}
  \includegraphics[width=0.3\textwidth]{dragon3}
  \caption{Approximations of the dragon curve: $X_0,\ X_1,\ X_2$.}\label{fig:dragon}
\end{figure}
\end{enumerate}

\end{document}

\[S_1 = \begin{bmatrix}
	    F_1(u_{1,1}) & F_2(u_1) & \dots & F_n(u_1)\\
	    F_1(u_{2,1}) & F_2(u_2) & \dots & F_n(u_2)\\
	    \vdots\\
	    F_1(u_{m,1}) & F_2(u_m) & \dots & F_n(u_m)\\
        \end{bmatrix}
\]


% Format: LaTeX
\documentstyle{report}

\setlength{\parskip}{\baselineskip}
\setlength{\parindent}{0pt}

\begin{document}

\chapter{Unsolved Problems}

\section{Odd Perfect Numbers}

A number is said to be {\em perfect\/} if it
is the sum of its divisors.  For example, $6$ is
perfect because \(1+2+3 = 6\), and $1$, $2$, and $3$
are the only numbers that divide evenly into $6$
(apart from 6 itself).

It has been shown that all even perfect numbers
have the form \[2^{p-1}(2^{p}-1)\] where $p$
and \(2^{p}-1\) are both prime.

The existence of {\em odd\/} perfect numbers is
an open question.
\end{document}


\section{Update PAULI-ISO-QMDD after Clifford unitary}

Roughly: two parts. 1: Update rule for general matrices and general (Pauli group) isomorphism QMDD. 2: Update rule for Clifford gates on Pauli isomorphism QMDDs representing stabilizer states.

\subsection{General update rule}

(We assume that the data structures for vectors and matrices have been described in earlier sections.)

1. Produce $\ket{\psi}:=A\ket{\phi}$, namely  $A\ket{phi_0}$ en $A\ket{phi_1}$. Here $A$

2. Check whether the node $\ket{\psi}$ is already in the database.

3. Otherwise, check whether $\ket{\psi}$ is $\mathcal{G}$-isomorphic to a node already in the database. If so, reroute the edges of $\ket{\psi}$ to that node, and delete all newly orphaned nodes.

(Bonus algorithm: Compute expectation values: $\bra{\psi} H \ket{\psi}$. Find a place to put this.)

TODO: Sketch of algorithm on A4.

\subsection{Special update rule}

\subsubsection{Applying a CNOT gate}

1. Update rule for CNOT

2. Try to prune the isomorphism into a single global phase

\subsubsection{Applying a Single-qubit Clifford gate}

1. Expression for Hadamard gate, Phase gate

2. Finding a new isomorphism (work in progress)

(The remainder of this text is old)

Here, we explain briefly why updating Pauli-ISO-QMDDs after a Clifford is nontrivial in the general case.
Below, an algorithm that performs the task is presented

\subsection{Why the Clifford update is nontrivial}

Stabilizer states in Pauli-iso-qmdd has multiple flavours:

\begin{itemize}
\item Z-flavour: read the QMDD as 'in the computational basis'
\item Graph-State-flavour: use Z-flavour but only use Pauli strings containing I and Z (at this point, this flavour precisely contains all graph states), while keeping a list of single-qubit Cliffords that will be applied to the graph state.
\item Pauli-flavour: for each qubit, keep a flag that indicates whether it is stored in the X,Y or Z-basis
\end{itemize}

Performing a single-qubit Clifford in Z-flavour requires an algorithm to update a subpart of the tree with $(\unit + \beta P) / \sqrt{2}$ where $P$ is a Pauli string and $\beta \in \{\pm 1, \pm i\}$.
This follows from a local basis transform, which for example for Z to X-basis follows from the identity
\[
    \ket{0} \otimes \ket{\phi} + \ket{1} \otimes P\ket{\phi}
    =
    \ket{+} \otimes \frac{\unit + P}{\sqrt{2}} \ket{\phi} + \ket{-} \otimes \frac{\unit - P}{\sqrt{2}}\ket{\phi}
.
\]
CNOTs, on the other hard, are straightforward in Z-flavour.

For Pauli-flavour, the story is reversed: for the same reason, CNOTs are hard but single-qubit Cliffords are trivial.

[For more explanation, see the presentation \url{miscellaneous/2020_05_19_treeform_clifford_update_difficulty.pdf}]

\subsection{An algorithm for the Clifford update}

Here, we sketch how to update a stabilizer state in treeform after application of a single-qubit Clifford or a CNOT.
We use the Z-flavour of treeform, i.e. a stabilizer state on $n$ qubit is recursively defined as $\ket{\phi} = \ket{a} \otimes \ket{\psi}$ or $\ket{\phi} = (\ket{0} \otimes \ket{\psi} + \alpha \ket{1}\otimes \otimes P \ket{\psi}) / \sqrt{2}$, where $a \in \{0, 1, \pm 1, \pm i\}$ and $\alpha \in \{\pm 1, \pm i\}$ and $\ket{\psi}$ is an $n-1$ qubit stabilizer state (or equals $1$ in case $n=1$).

First note that if the most significant qubit is not involved in the application of a Clifford $C$, then in both the knife- and fork cases, it can easily be seen that the Clifford 'propogates' down the tree with little overhead until it meets the first qubit it acts upon:

knife: $C\ket{a} \otimes \ket{\psi} = \ket{a} \otimes \left( C\ket{\psi}\right)$

fork:
$
C \left( \ket{0} \otimes \ket{\psi} + \alpha \ket{1} \otimes Q\ket{\psi}\right)
=
\ket{0} \otimes C\ket{\psi} + \alpha \ket{1} \otimes \left(CQC^{\dagger}\right) \left(C\ket{\psi}\right)
$

\subsubsection{Updating stabilizer state in Treeform after a CNOT}

Denote the stabilizer state by $\ket{\phi}$

\textbf{Claim: updating after a CNOT can be done in time $\mathcal{O}(n^2)$, where $n$ is the number of qubits of $\ket{\phi}$.}

We distinguish two cases.

If $\ket{\phi}$ is a `knife', i.e. $\ket{\phi} = \ket{a} \otimes \ket{\psi}$ for some $a \in \{0, 1, \pm 1, \pm i\}$ and $\ket{\psi}$ is an $(n-1)$-qubit stabilizer state, then the update is straightforward: if $a\in \{0, 1\}$, then the post-CNOT state is a knife and becomes a fork otherwise.
For example, if $\ket{\phi} = \ket{+}\otimes\ket{\psi}$, then $CNOT\ket{\phi} = \ket{0} \ket{\psi} + \ket{1} \otimes X \ket{\psi}$.
(Note we could still ``reduce'' the tree [in the sense of reducing a decision diagram], which we treat below]

If $\ket{\phi}$ is a `fork', i.e. $\ket{\phi} = \ket{0} \otimes \ket{\psi} + \alpha \ket{1}\otimes \otimes P \ket{\psi}$ (omitting normalization), then $CNOT\ket{\phi} = \ket{0} \otimes \ket{\psi} + \alpha \ket{1} \otimes XP \ket{\psi}$.

The only remaining question is: can we reduce this tree?
That is, are the post-CNOT states which are a fork, really a fork or can they also be written as knife?

We claim that this can be done in time $\mathcal{O}(n^2)$ by distinguishing the modulus of the expectation value of the fork-operator (i.e. the Pauli-string $Q$ in $\ket{0} \otimes \ket{\psi} + \alpha \ket{1} \otimes Q\ket{\psi}$) with $\ket{\phi}$ to equal 1, or to be less.
To be precise: if $|\bra{\phi} Q \ket{\phi}| = 1$, then $Q\ket{\phi} = \bra{\phi} Q\ket{\phi} \ket{\phi}$ and thus the fork can be reduced to $\left(\ket{0} + \alpha \bra{\phi} Q\ket{\phi} \ket{1} \right) \otimes \ket{\psi}$, and otherwise it remains as it is.

We now claim that $\bra{\phi} Q \ket{\phi}$ can be determined in time $\mathcal{O}(n^2)$ by recursing over the $n$ qubits, and each step takes at most time $\mathcal{O}(n)$.
The knife case is straightforward: $\bra{\phi} A \ket{\phi} = \bra{\phi} A_0 \ket{\phi} \cdot \bra{\phi} A_r \ket{\phi}$, and the lefmost expectation value is computed in constant time.

[TODO: IDEA: below, we assume that $A$ is a general string. Can we exploit the fact that we know its structure (i..e $X \cdot P$ where $P$ is a known string)?]

The fork case is a bit more involved (omitting adjoint signs since Pauli strings are self-adjoint):
\begin{eqnarray}
\bra{\phi} A \ket{\phi}
    &=&
\bra{0} A_0 \ket{0} \otimes \bra{\psi} A_r \ket{\psi}
+
\\
    &&
\bra{1} A_0 Q_0 \ket{0} \otimes \bra{\psi} A_r Q_r \ket{\psi}
+
\\
    &&
\bra{1} Q_0 A_0 \ket{0} \otimes \bra{\psi} Q_r A_r \ket{\psi}
+
\\
    &&
\bra{1} Q_0 A_0 Q_0 \ket{1} \otimes \bra{\psi} Q_r A_r Q_r \ket{\psi}
\end{eqnarray}

Note by the fact that $Q$ and $A$ are Pauli strings, either the first and last terms or the second and third terms are zero (because Pauli strings either commute or anticommute).
The remaining terms only differ by a $\pm 1$ factor.
Which is the case, can be determined by computing whether the string commute or anticommute, which can be done in time $\mathcal{O}(n)$ since the strings are of length $n$.
What remains is to compute $\bra{\psi} Q_r A_r \ket{\psi}$ or $\bra{\psi} A_r \ket{\psi}$ (depending on which terms survive), which is done in the recursive step.

\subsubsection{Updating Treeform after a single-qubit Clifford}

Updating a stabilizer state in treeform $\ket{\phi}$ after a single-qubit Clifford for a knife-case is straightforward and uses the fact that the set $\{\ket{0}, \ket{1}, \ket{\pm}, \ket{\pm i}$ is closed under single-qubit Cliffords.

For a fork, the algorithm requires slightly different operations for each Clifford, but for each, the underlying principle is the same and is again based on the fact that they map the set of single-qubit stabilizer states to itself.

As an example, we treat the application of $H$ to the first qubit of the state $\ket{0} \otimes \ket{\psi} + \alpha \ket{1} \otimes P \ket{\psi}$, which equals
\[
\ket{+} \otimes \ket{\psi} + \alpha \ket{-} \otimes P \ket{\psi}
\]
and can be rewritten as
\[
    \ket{0} \otimes (\unit + \alpha P) \ket{\psi} + \ket{1} \otimes (\unit - \alpha P) \ket{\psi}
    .
\]

Now we need two things:

- a pauli string $A$ that maps $\unit + \alpha P$ to $\unit - \alpha P$. Any string that anitcommutes with $P$ will do [TODO NEEDS CHECKING!] and can be found in time $\mathcal{O}(n)$.

- rewriting $(\unit + \alpha P) \ket{\psi}$ in treeform. This is more involved and can be done recursively on the size of $\ket{\psi}$. At each level, it is required to check whether $P$ and the fork-operator of that level commute or anticommute (in a similar fashion to the `reduction of the tree' in the CNOT-application explained above) and thus requires a total runtime of $\mathcal{O}(n^2)$.


\chapter{Problem Formulation}

Given a string of text, typically a phrase, we are interested in detecting and correcting misspelling errors in the
typed phrase. This project aims to implement an Error Model, capable of offering corrected candidates to a single
misspelled word, and a Hidden Markov Model, capable of finding the most likely sequence of candidates for each word in
a sentence.

The two models work sequentially in a pipeline, but are not strictly dependant on each other, as the Error Model
acts as a local corrector, and the HMM acts as a maximiser of the probability of the sequences of candidates.

\section{Design Choices}

We have chosen to implement this solution using the English language for various reasons. First of all, the great
majority of material in literature deals with this problem in the English language. Moreover it is a somewhat simpler
language compared to Italian, for example, since it doesn't use special characters, such as accents, and it doesn't
have as many verb tenses and special forms.

Furthermore, we chose not to consider all punctuation and special character symbols, but only letters and sometimes
numbers.

We assume that a typed word only depends on the previous one for ease of implementation. This assumption allows us to
model the problem as a first order HMM.
If we know the probability of a word given its predecessor, the frequency of each word, and the probability to
type word $x$ when word $y$ is intended, we have all the necessary ingredients to use Hidden Markov Models.

We also assume that, in our artificial perturbation of words, the number of errors in a word follows a binomial
distribution depending on the length of the word.

\section{Software}
We have developed the project using the \textbf{Python} programming language, taking advantage of various open-source
libraries: \textbf{edlib} to compute the sequence of edit operations to transform a word in another one,
\textbf{networkx} to represent the trellis graph produced by Viterbi's algorithm, \textbf{pandas} to store the
evaluation results, \textbf{matplotlib} and \textbf{graphviz} to visualize the trellis graph.

We also created a graphical user interface that provides real-time local spell checking and on-demand visualisation of
the trellis graph. This part is implemented as a native macOS application written in \textbf{Swift} that interacts with
our Python code using Swift's official Python interoperation.

\begin{figure}[H]
	\centering
	\includegraphics[width=10cm]{ui-candidates.png}
	\caption{Screenshot of the user interface for real-time spell checking}
	\label{fig:noisychannel}
\end{figure}


\documentclass{report}

\usepackage[a4paper, margin=2cm]{geometry}
\usepackage{textgreek}
\usepackage{mathpartir}
\usepackage{mathtools}
\usepackage{amssymb}

\allowdisplaybreaks[1]
\newtagform{nowidth}{\llap\bgroup(}{)\egroup}

\newcommand{\theLang}{myml}
\newcommand{\code}{\mathtt}
\newcommand{\backtick}{{}^{\backprime}}
\newcommand{\ruleTag}[1]{\label{#1}\tag{\textsc{#1}}}
\DeclareMathOperator{\domain}{dom}
\DeclareMathOperator{\union}{union}
\DeclareMathOperator{\find}{find}
\DeclareMathOperator{\describeContextScheme}{descCtxScm}
\DeclareMathOperator{\describeScheme}{descScm}
\DeclareMathOperator{\describeType}{descType}
\DeclareMathOperator{\describeRow}{descRow}
\DeclareMathOperator{\describePresence}{descPre}
\DeclareMathOperator{\describePresenceWithType}{descPT}
\DeclareMathOperator{\instantiate}{inst}
\DeclareMathOperator{\instantiateType}{instType}
\DeclareMathOperator{\instantiateRow}{instRow}
\DeclareMathOperator{\instantiatePresence}{instPre}
\DeclareMathOperator{\generalizeValue}{genVal}
\DeclareMathOperator{\generalize}{gen}
\DeclareMathOperator{\freeVariable}{fv}
\DeclareMathOperator{\freeVariableWithKind}{fvKind}
\DeclareMathOperator{\dangerousVariable}{dv}
\DeclareMathOperator{\dangerousVariableRecordRow}{dvRcdRow}
\DeclareMathOperator{\dangerousVariableRecordPresence}{dvRcdPre}
\DeclareMathOperator{\dangerousVariableVariantRow}{dvVariantRow}
\DeclareMathOperator{\dangerousVariableVariantPresence}{dvVariantPre}
\DeclareMathOperator{\unify}{unify}
\DeclareMathOperator{\unifyRow}{unifyRow}
\DeclareMathOperator{\unifyPresence}{unifyPre}
\DeclareMathOperator{\unifyPresenceWithType}{unifyPT}
\newcommand{\newVariable}{newvar}
\newcommand{\newVariables}{newvars}
\newcommand{\entails}{\vdash}
\newcommand{\typingRelation}[5]{#1, #2 \entails #3 \;:\; #4 ,\; #5}
\newcommand{\composite}{\circ}
\newcommand{\definedAs}{\stackrel{def}{=}}
\newcommand{\sequencing}{;\;}

\title{The Definition of \theLang}
\author{Lin Yinfeng}

\begin{document}

\maketitle

\tableofcontents

\chapter{\theLang{} the Calculus}

\section{Syntax}

\subsection{Term}

\begin{align*}
\code{t} \Coloneqq \quad & & \text{term} \\
& \code{\lambda\ x.\ t} & \text{abstraction} \\
| \quad & \code{t\ t} & \text{application} \\
| \quad & \code{x} & \text{variable} \\
| \quad & \code{let\ x = t\ in\ t} & \text{let-in} \\
| \quad & \code{\{\ \}} & \text{empty record} \\
| \quad & \code{extend(l)} & \text{record extend} \\
| \quad & \code{update(l)} & \text{record update} \\
| \quad & \code{access(l)} & \text{record access} \\
| \quad & \code{[\ ]} & \text{empty match} \\
| \quad & \code{extend(\backtick l)} & \text{match extend} \\
| \quad & \code{update(\backtick l)} & \text{match update} \\
| \quad & \code{\backtick l} & \text{variant creation} \\
| \quad & \code{ref} & \text{reference} \\
| \quad & \code{!} & \text{dereference} \\
| \quad & \code{\coloneqq} & \text{assignment} \\
| \quad & \code{l} & \text{location} \\
| \quad & \code{new} & \text{new}
\end{align*}

\subsection{Derived Form}

\begin{align*}
\lambda\ \_ .\ \code{t} \definedAs & \lambda\ \code{x}.\ \code{t} \quad \text{where \(\code{x} \not\in \freeVariable(\code{t})\)} \\
\code{t}_1\sequencing\code{t}_2 \definedAs & (\lambda\ \_ .\ \code{t}_2)\ \code{t}_1
\end{align*}

\subsection{Value}

\begin{align*}
\code{v} \Coloneqq \quad & & \text{value} \\
& \code{\lambda\ x.\ t} & \text{abstraction} \\
| \quad & \code{rv} & \text{record value} \\
| \quad & \code{mv} & \text{match value} \\
| \quad & \code{\backtick l\ v} & \text{variant} \\
| \quad & \code{extend(l)} & \text{record extend 1} \\
| \quad & \code{extend(l)\ v} & \text{record extend 2} \\
| \quad & \code{update(l)} & \text{record update 1} \\
| \quad & \code{update(l)\ v} & \text{record update 2} \\
| \quad & \code{access(l)} & \text{record access} \\
| \quad & \code{extend(\backtick l)} & \text{match extend 1} \\
| \quad & \code{extend(\backtick l)\ v} & \text{match extend 2} \\
| \quad & \code{update(\backtick l)} & \text{match update 1} \\
| \quad & \code{update(\backtick l)\ v} & \text{match update 2} \\
| \quad & \code{\backtick l} & \text{variant creation} \\
| \quad & \code{ref} & \text{reference} \\
| \quad & \code{!} & \text{dereference} \\
| \quad & \code{\coloneqq} & \text{assignment 1} \\
| \quad & \code{\coloneqq\ v} & \text{assignment 2} \\
| \quad & \code{l} & \text{location}
\end{align*}

\begin{align*}
\code{rv} \Coloneqq \quad & & \text{record value} \\
& \code{\{\ \}} & \text{empty record} \\
| \quad & \code{extend(l)\ v\ rv} & \text{record extend}
\end{align*}

\begin{align*}
\code{mv} \Coloneqq \quad & & \text{match value} \\
& \code{[\ ]} & \text{empty match} \\
| \quad & \code{extend(\backtick l)\ v\ mv} & \text{match extend}
\end{align*}

\subsection{Type}

\begin{align*}
\code{T, MT} \Coloneqq \quad & & \text{monomorphic type} \\
& \code{X} & \text{type variable} \\
& \code{MT \rightarrow MT} & \text{arrow} \\
& \code{\{\ R\ \}} & \text{record} \\
& \code{[\ R\ ]} & \text{variant} \\
& \code{\mu X.\ MT} & \text{recursive} \\
& \code{Ref\ MT} & \text{reference}
\end{align*}

\begin{align*}
\code{R} \Coloneqq \quad & & \text{row} \\
& \code{\cdot} & \text{empty row} \\
& \code{X} & \text{row variable} \\
& \code{l : P, R} & \text{presence} \\
& \code{\mu X.\ R} & \text{recursive}
\end{align*}

\begin{align*}
\code{P} \Coloneqq \quad & & \text{presence} \\
& \code{Absent} & \text{absent} \\
& \code{Present\ MT} & \text{present} \\
& \code{X} & \text{variable} \\
& \code{X\ MT} & \text{variable with type}
\end{align*}

\begin{align*}
\code{PT} \Coloneqq \quad & & \text{presence with type} \\
& \code{PTAbsent} & \text{absent} \\
& \code{PTPresent} & \text{present} \\
& \code{X} & \text{variable}
\end{align*}

\begin{align*}
\code{PT} \Coloneqq\quad & & \text{polymorphic type} \\
& \code{MT} & \text{monomorphic type} \\
& \code{\forall\ X :: K.\ PT} & \text{universal qualified}
\end{align*}

\subsection{Kind}

\begin{align*}
\code{K} \Coloneqq \quad & & \text{kind} \\
& \code{*} & \text{proper} \\
& \code{Presence} & \text{presence} \\
& \code{Row} & \text{row} \\
& \code{K \Rightarrow K} & \text{arrow}
\end{align*}

\subsection{Typing Context}

\begin{align*}
\Gamma \Coloneqq \quad & & \text{typing context} \\
& \code{\emptyset} & \text{empty} \\
& \code{\Gamma, \code{x}:\code{PT}} & \text{binding}
\end{align*}

\section{Evaluation}

Evaluation of \theLang{} is defined in small step operational semantic. The relation \(\code{t}\mid\mu \longrightarrow \code{t}\mid\mu\) is the smallest relation satisfying all instances of the following rules.

\usetagform{nowidth}
\begin{gather}
\inferrule
{}
{(\lambda\ \code{x}.\ \code{t}_{12})\ \code{v}_2\mid\mu \longrightarrow [\code{x}\mapsto\code{v}_2]\code{t}_{12} \mid\mu}
\ruleTag{E-AppAbs}
\\
\inferrule
{\code{t}_1\mid\mu \longrightarrow \code{t}'_1\mid\mu'}
{\code{t}_1\ \code{t}_2\mid\mu \longrightarrow \code{t}'_1\ \code{t}_2\mid\mu'}
\ruleTag{E-App1}
\\
\inferrule
{\code{t}_2\mid\mu \longrightarrow \code{t}'_2\mid\mu'}
{\code{v}_1\ \code{t}_2\mid\mu \longrightarrow \code{v}_1\ \code{t}'_2\mid\mu'}
\ruleTag{E-App2}
\\
\inferrule
{}
{\code{let}\ \code{x} = \code{v}_1\ \code{in}\ \code{t}_2\mid\mu \longrightarrow [\code{x}\mapsto\code{v}_1]\code{t}_2\mid\mu}
\ruleTag{E-LetV}
\\
\inferrule
{\code{t}_1\mid\mu \longrightarrow \code{t}'_1\mid\mu'}
{\code{let}\ \code{x} = \code{t}_1\ \code{in}\ \code{t}_2\mid\mu \longrightarrow \code{let}\ \code{x} = \code{t}'_1\ \code{in}\ \code{t}_2\mid\mu'}
\ruleTag{E-Let}
\\
\inferrule
{}
{(\code{extend}(\backtick \code{l}_1)\ \code{v}_1\ \code{mv}_1)\ (\backtick \code{l}_2\ \code{v}_2)\mid\mu\longrightarrow
\code{mv}_1\ (\backtick \code{l}_2\ \code{v}_2)\mid\mu}
\ruleTag{E-Match1}
\\
\inferrule
{}
{(\code{extend}(\backtick \code{l})\ \code{v}_1\ \code{mv}_1)\ (\backtick \code{l}\ \code{v}_2)\mid\mu\longrightarrow
\code{v}_1\ \code{v}_2\mid\mu}
\ruleTag{E-Match2}
\\
\inferrule
{}
{\code{update}(\backtick \code{l}_1)\ \code{v}_1\ (\code{extend}(\backtick \code{l}_2)\ \code{v}_2\ \code{mv}_2)\mid\mu\longrightarrow \\\\
\code{extend}(\backtick \code{l}_2)\ \code{v}_2\ (\code{update}(\backtick \code{l}_1)\ \code{v}_1\ \code{mv}_2)\mid\mu}
\ruleTag{E-MatUpdate1}
\\
\inferrule
{}
{\code{update}(\backtick \code{l})\ \code{v}_1\ (\code{extend}(\backtick \code{l})\ \code{v}_2\ \code{mv}_2)\mid\mu\longrightarrow
(\code{extend}(\backtick \code{l})\ \code{v}_1\ \code{mv}_2)\mid\mu}
\ruleTag{E-MatUpdate2}
\\
\inferrule
{}
{\code{access}(\code{l}_1)\ (\code{extend}(\code{l}_2)\ \code{v}_2\ \code{mv}_2)\mid\mu\longrightarrow
\code{access}(\code{l}_1)\ \code{mv}_2\mid\mu}
\ruleTag{E-RcdAccess1}
\\
\inferrule
{}
{\code{access}(\code{l})\ (\code{extend}(\code{l})\ \code{v}_2\ \code{mv}_2)\mid\mu\longrightarrow
\code{v}_2\mid\mu}
\ruleTag{E-RcdAccess2}
\\
\inferrule
{}
{\code{update}(\code{l}_1)\ \code{v}_1\ (\code{extend}(\code{l}_2)\ \code{v}_2\ \code{mv}_2)\mid\mu\longrightarrow \\\\
\code{extend}(\code{l}_2)\ \code{v}_2\ (\code{update}(\code{l}_1)\ \code{v}_1\ \code{mv}_2)\mid\mu}
\ruleTag{E-RcdUpdate1}
\\
\inferrule
{}
{\code{update}(\code{l})\ \code{v}_1\ (\code{extend}(\code{l})\ \code{v}_2\ \code{mv}_2)\mid\mu\longrightarrow
(\code{extend}(\code{l})\ \code{v}_1\ \code{mv}_2)\mid\mu}
\ruleTag{E-RcdUpdate2}
\\
\inferrule
{\code{l}\notin\domain(\mu)}
{\code{ref}\ \code{v}\mid\mu\longrightarrow\code{l}\mid(\mu, \code{l}\mapsto\code{v})}
\ruleTag{E-Ref}
\\
\inferrule
{\mu(\code{l}) = \code{v}}
{\code{!}\ \code{l}\mid\mu\longrightarrow v\mid\mu}
\ruleTag{E-Deref}
\\
\inferrule
{\code{l}\in\domain(\mu)}
{\code{l}\coloneqq\code{v}\mid\mu\longrightarrow \code{unit}\mid[\code{l}\mapsto\code{v}]\mu}
\ruleTag{E-Assign}
\end{gather}

\section{Substitution}

A substitution \([\code{x}\mapsto\code{t}]\) is a mapping from term or type variables to terms or types. Apply substition \([\code{x}\mapsto\code{t}_1]\) to \(\code{t}_3\), is written \([\code{x}\mapsto\code{t}_1]\code{t}_2 = \code{t}_3\), which replace all occurrence of variable \(\code{x}\) in \(\code{t}_2\) to \(\code{t}_1\). Free variables in \(\code{t}_1\) should not be bound in \(\code{t}_3\). Use \textalpha-conversion to prevent free variables in \(\code{t}_1\) being bound.

\section{Typing}

\subsection{Equivalence Relation}

Maintain an equivalence relation \(E\) with Union-Find algorithm.

Every equivalence class has a descriptor, which is an element in the equivalence class.

The operation \(\find(E, e) = e'\) return the descriptor of the element \(e\) in the equivalence relation \(E\).

The operation \(\union(E, a, b) = E'\) equate the equivalence class of element \(a\) and \(b\), make the descriptor of the equivalence class of element \(b\) as the descriptor of the unioned equivalence class. Return the new equivalence relation \(E'\).

\subsection{Type Description from Equivalence Relation}

Equivalence relation of type, row and presence forms tree representations of monomorphic type.

operation \(\describeType(E, V, \code{T})\) to convert a monomorphic type \(\code{T}\) into a complete type by continuous replacing variables with its descriptor in equivalence relation \(E\).\(V\) is a set of variable, variable in the set will not be converted.

\(\describeRow(E, V, \code{R})\), \(\describePresence(E, V, \code{P})\), \(\describePresenceWithType(E, V, \code{PT})\) do the same thing as \(\describeType\) for other kind of types.

\(\describeScheme(E, V, \code{PT})\) only convert non qualified variables.

\begin{gather}
\inferrule
{\describeScheme(E, V \cup \{\code{X}\}, \code{PT}) = \code{PT}'}
{\describeScheme(E, V, \forall\ \code{X} :: \code{K} .\ \code{PT}) = \forall\ \code{X} :: \code{K} .\ \code{PT}'}
\ruleTag{DescScm-PT}
\\
\inferrule
{}
{\describeScheme(E, V, \code{MT}) = \describeType(E, V, \code{MT})}
\ruleTag{DescScm-MT}
\end{gather}

\begin{gather}
\inferrule
{\code{X} \in V}
{\describeType(E, V, \code{X}) = \code{X}}
\ruleTag{DescType-Var1}
\\
\inferrule
{\code{X} \not\in V \and
 \find(E, \code{X}) = \code{X}}
{\describeType(E, V, \code{X}) = \code{X}}
\ruleTag{DescType-Var2}
\\
\inferrule
{\code{X} \not\in V \and
 \find(E, \code{X}) = \code{MT} \and
 \code{MT} \not= \code{X} \\\\
 \describeType(E, V \cup \{\code{X}\}, \code{MT}) = \code{MT}' \and
 \code{X} \not\in \freeVariable(\code{MT}')}
{\describeType(E, V, \code{X}) = \code{MT}'}
\ruleTag{DescType-Var3}
\\
\inferrule
{\code{X} \not\in V \and
 \find(E, \code{X}) = \code{MT} \and
 \code{MT} \not= \code{X} \\\\
 \describeType(E, V \cup \{\code{X}\}, \code{MT}) = \code{MT}' \and
 \code{X} \in \freeVariable(\code{MT}')}
{\describeType(E, V, \code{X}) = \mu\code{X}.\code{MT}'}
\ruleTag{DescType-VarRec}
\\
\inferrule
{\describeType(E, V, \code{MT}_1) = \code{MT}'_1 \\\\
 \describeType(E, V, \code{MT}_2) = \code{MT}'_2}
{\describeType(E, V, \code{MT}_1\rightarrow\code{MT}_2) = \code{MT}'_1\rightarrow\code{MT}'_2}
\ruleTag{DescType-Arr}
\\
\inferrule
{\describeRow(E, V, \code{R}) = \code{R}'}
{\describeType(E, V, \{\ \code{R}\ \}) = \{\ \code{R}'\ \}}
\ruleTag{DescType-Rcd}
\\
\inferrule
{\describeRow(E, V, \code{R}) = \code{R}'}
{\describeType(E, V, [\ \code{R}\ ]) = [\ \code{R}'\ ]}
\ruleTag{DescType-Variant}
\\
\inferrule
{\describeType(E, V, \code{MT}) = \code{MT}'}
{\describeType(E, V, \code{Ref}\ \code{MT}) = \code{Ref}\ \code{MT}'}
\ruleTag{DescType-Ref}
\\
\inferrule
{\describeType(E, V \cup \{\code{X}\}, \code{MT}) = \code{MT}'}
{\describeType(E, V, \mu\code{X}.\code{MT}) = \mu\code{X}.\code{MT}'}
\ruleTag{DescType-Rec}
\end{gather}

\begin{gather}
\inferrule
{}
{\describeRow(E, V, \cdot) = \cdot}
\ruleTag{DescRow-Empty}
\\
\inferrule
{\code{X} \in V}
{\describeRow(E, V, \code{X}) = \code{X}}
\ruleTag{DescRow-Var1}
\\
\inferrule
{\code{X} \not\in V \and
 \find(E, \code{X}) = \code{X}}
{\describeRow(E, V, \code{X}) = \code{X}}
\ruleTag{DescRow-Var2}
\\
\inferrule
{\code{X} \not\in V \and
 \find(E, \code{X}) = \code{R} \and
 \code{R} \not= \code{X} \\\\
 \describeRow(E, V \cup \{\code{X}\}, \code{R}) = \code{R}' \and
 \code{X} \not\in \freeVariable(\code{R}')}
{\describeRow(E, V, \code{X}) = \code{R}'}
\ruleTag{DescRow-Var3}
\\
\inferrule
{\code{X} \not\in V \and
 \find(E, \code{X}) = \code{R} \and
 \code{R} \not= \code{X} \\\\
 \describeRow(E, V \cup \{\code{X}\}, \code{R}) = \code{R}' \and
 \code{X} \in \freeVariable(\code{R}')}
{\describeRow(E, V, \code{X}) = \mu\code{X}.\code{R}'}
\ruleTag{DescRow-VarRec}
\\
\inferrule
{\describePresence(E, V, \code{P}) = \code{P}' \and
 \describeRow(E, \code{R}) = \code{R}'}
{\describeRow(E, V, (\code{l}:\code{P},\code{R})) = \code{l}:\code{P}',\code{R}'}
\ruleTag{DescRow-Pre}
\\
\inferrule
{\describeRow(E, V \cup \{\code{X}\}, \code{R}) = \code{R}'}
{\describeRow(E, V, \mu\code{X}.\code{R}) = \mu\code{X}.\code{R}'}
\ruleTag{DescRow-Rec}
\end{gather}

\begin{gather}
\inferrule
{}
{\describePresence(E, V, \code{Absent}) = \code{Absent}}
\ruleTag{DescPre-Abs}
\\
\inferrule
{\describeType(E, V, \code{MT}) = \code{MT}'}
{\describePresence(E, V, \code{Present}\ \code{MT}) = \code{Present}\ \code{MT}'}
\ruleTag{DescPre-Pre}
\\
\inferrule
{\find(E, \code{X}) = \code{X}}
{\describePresence(E, V, \code{X}) = \code{X}}
\ruleTag{DescPre-Var1}
\\
\inferrule
{\find(E, \code{X}) = \code{P} \and
 \code{MT} \not= \code{X} \and
 \describePresence(E, V, \code{P}) = \code{P}'}
{\describePresence(E, V, \code{X}) = \code{P}'}
\ruleTag{DescPre-Var2}
\\
\inferrule
{\describePresenceWithType(E, V, \code{X}) = \code{X} \\\\
 \describeType(E, V, \code{MT}) = \code{MT}'}
{\describePresence(E, V, \code{X}\ \code{MT}) = \code{X}\ \code{MT}')}
\ruleTag{DescPre-PTVar1}
\\
\inferrule
{\describePresenceWithType(E, V, \code{X}) = \code{PTAbsent}}
{\describePresence(E, V, \code{X}\ \code{MT}) = \code{Absent}}
\ruleTag{DescPre-PTVar2}
\\
\inferrule
{\describePresenceWithType(E, V, \code{X}) = \code{PTPresent} \\\\
 \describeType(E, V, \code{MT}) = \code{MT}'}
{\describePresence(E, V, \code{X}\ \code{MT}) = \code{Present}\ \code{MT}'}
\ruleTag{DescPre-PTVar3}
\end{gather}

\begin{gather}
\inferrule
{}
{\describePresenceWithType(E, V, \code{PTAbsent}) = \code{PTAbsent}}
\ruleTag{DescPT-Abs}
\\
\inferrule
{}
{\describePresenceWithType(E, V, \code{PTPREsent}) = \code{PTPREsent}}
\ruleTag{DescPT-Pre}
\\
\inferrule
{\find(E, \code{X}) = \code{X}}
{\describePresenceWithType(E, V, \code{X}) = \code{X}}
\ruleTag{DescPT-Var1}
\\
\inferrule
{\find(E, \code{X}) = \code{PT} \and
 \code{PT} \not= \code{X}}
{\describePresenceWithType(E, V, \code{X}) = \describePresenceWithType(E, V, \code{PT})}
\ruleTag{DescPT-Var2}
\end{gather}

\begin{gather}
\inferrule
{}
{\describeContextScheme(E, V, \code{\emptyset}) = \code{\emptyset}}
\ruleTag{DescCtxScm-Empty}
\\
\inferrule
{}
{\describeContextScheme(E, V, (\code{x}:\code{PT}, \Gamma)) = \code{x}:\describeScheme(E, V, \code{PT}), \Gamma}
\ruleTag{DescCtxScm-Bind}
\end{gather}

\subsection{Instantiation}

Instantiation first replace every qualified type variable with fresh variables, then encode the type as a tree in equivalence relation.

\begin{gather}
\inferrule
{\instantiate(E, \code{PT}) = E', \code{PT'}}
{\instantiate(E, \code{\forall\ X.\ PT}) = E' , [\code{X}\mapsto\newVariable]\code{PT'}}
\ruleTag{Inst-PT}
\\
\instantiate(E, \code{MT}) = \instantiateType(E, \code{MT})
\ruleTag{Inst-MT}
\end{gather}

\begin{gather}
\inferrule
{}
{\instantiateType(E, \code{X}) = E , \code{X}}
\ruleTag{InstType-Var}
\\
\inferrule
{\instantiateType(E, \code{T}_1) = E_1, \code{T}'_1 \and
\instantiateType(E_1, \code{T}_2) = E_2, \code{T}'_2}
{\instantiateType(E, \code{T}_1\rightarrow\code{T}_2) = E_2, \code{T}'_1\rightarrow\code{T}'_2}
\ruleTag{InstType-Arr}
\\
\inferrule
{\instantiateRow(E, \code{R}) = E', \code{R}'}
{\instantiateType(E, \{\ \code{R}\ \}) = E', \{\ \code{R}'\ \}}
\ruleTag{InstType-Rcd}
\\
\inferrule
{\instantiateRow(E, \code{R}) = E', \code{R}'}
{\instantiateType(E, [\ \code{R}\ ]) = E', [\ \code{R}'\ ]}
\ruleTag{InstType-Variant}
\\
\inferrule
{\instantiateType(E, \code{MT}) = E', \code{MT}' \and
 \union(E', \code{X}, \code{MT}') = E''}
{\instantiateType(E, \mu \code{X}.\code{MT}) = E'', \code{X}}
\ruleTag{InstType-Rec}
\\
\inferrule
{\instantiateType(E, \code{MT}) = E', \code{MT}'}
{\instantiateType(E, \code{Ref}\ \code{MT}) = E', \code{Ref}\ \code{MT}'}
\ruleTag{InstType-Ref}
\end{gather}

\begin{gather}
\inferrule
{}
{\instantiateRow(E, \cdot) = E, \cdot}
\ruleTag{InstRow-Empty}
\\
\inferrule
{}
{\instantiateRow(E, \code{X}) = E, \code{X}}
\ruleTag{InstRow-Var}
\\
\inferrule
{\instantiatePresence(E, \code{P}) = E', \code{P}' \and
 \instantiateRow(E', \code{R}) = E'', \code{R}'}
{\instantiateRow(E, (\code{l}:\code{P}, \code{R})) = E'', (\code{l}:\code{P}', \code{R}')}
\ruleTag{InstRow-Pre}
\\
\inferrule
{\instantiateRow(E, \code{R}) = E', \code{R}' \and
 \union(E', \code{X}, \code{R}') = E''}
{\instantiateRow(E, \mu\code{X}.\code{R}) = E'', \code{X}}
\ruleTag{InstRow-Rec}
\end{gather}

\begin{gather}
\inferrule
{}
{\instantiatePresence(E, \code{Absent}) = E, \code{Absent}}
\ruleTag{InstPre-Abs}
\\
\inferrule
{\instantiateType(E, \code{MT}) = E', \code{MT}'}
{\instantiatePresence(E, \code{Present}\ \code{MT}) = E', \code{Present}\ \code{MT}'}
\ruleTag{InstPre-Pre}
\\
\inferrule
{}
{\instantiatePresence(E, \code{X}) = E, \code{X}}
\ruleTag{InstPre-Var}
\\
\inferrule
{\instantiateType(E, \code{MT}) = E', \code{MT}'}
{\instantiatePresence(E, \code{X}\ \code{MT}) = E', \code{X}\ \code{MT}'}
\ruleTag{InstPre-VarWithType}
\end{gather}

\subsection{Generalization}

\begin{equation}
\begin{split}
\generalizeValue(\Gamma, E, \code{MT}) & = \forall\ \overline{\freeVariable(\code{MT}') \setminus \freeVariable(\Gamma')}.\ \code{MT}' \\
\Gamma' & = \describeContextScheme(\Gamma) \\
\code{MT}' & = \describeType(E, \emptyset, \code{MT})
\end{split}
\ruleTag{Gen-Value}
\end{equation}

\begin{equation}
\begin{split}
\generalize(\Gamma, E, \code{MT}) & = \forall\ \overline{\freeVariable(\code{MT}') \setminus \freeVariable(\Gamma') \setminus \dangerousVariable(\code{MT}')}.\ \code{MT}' \\
\Gamma' & = \describeContextScheme(\Gamma) \\
\code{MT}' & = \describeType(E, \emptyset, \code{MT})
\end{split}
\ruleTag{Gen-NonValue}
\end{equation}

\subsubsection{Dangerous Variable}

Working in progress.

\subsubsection{Replace Covariant Only Present}

Working in progress.

\subsection{Typing Relation}

\begin{gather}
\inferrule
{\code{X}:\code{PT} \in \Gamma \and
 \instantiate(\code{PT}) = \code{MT}}
{\typingRelation{\Gamma}{E}{\code{X}}{\code{MT}}{E}}
\ruleTag{T-Var}
\\
\inferrule
{\typingRelation{\Gamma}{E}{\code{t}_1}{\code{MT}_1}{E_1} \and
 \typingRelation{\Gamma}{E_1}{\code{t}_2}{\code{MT}_2}{E_2} \\\\
 \code{X} = \newVariable \and
 \unify(E_2, \code{MT}_1, \code{MT}_2\rightarrow\code{X}) = E_3}
{\typingRelation{\Gamma}{E}{\code{t}_1\ \code{t}_2}{\code{X}}{E_3}}
\ruleTag{T-App}
\\
\inferrule
{\code{X} = \newVariable \and
 \typingRelation{(\Gamma, \code{x}:\code{X})}{E}{\code{t}}{\code{MT}}{E'}}
{\typingRelation{\Gamma}{E}{\lambda\ \code{x}.\ \code{t}}{\code{X}\rightarrow\code{MT}}{E'}}
\ruleTag{T-Abs}
\\
\inferrule
{\typingRelation{\Gamma}{E}{\code{t}_1}{\code{MT}_1}{E_1} \and
 \generalize(\Gamma, E_1, \code{MT}_1) = \code{PT}_1 \\\\
 \typingRelation{(\Gamma, \code{x}:\code{PT}_1)}{E_1}{\code{t}_2}{\code{MT}_2}{E_2}}
{\typingRelation{\Gamma}{E}{\code{let}\ \code{x} = \code{t}_1\ \code{in}\ \code{t}_2}{\code{MT}_2}{E_2}}
\ruleTag{T-Let}
\\
\inferrule
{\typingRelation{\Gamma}{E}{\code{t}_1}{\code{MT}_1}{E_1} \and
 \generalizeValue(\Gamma, E_1, \code{MT}_1) = \code{PT}_1 \\\\
 \typingRelation{(\Gamma, \code{x}:\code{PT}_1)}{E_1}{\code{t}_2}{\code{MT}_2}{E_2}}
{\typingRelation{\Gamma}{E}{\code{let}\ \code{x} = \code{v}_1\ \code{in}\ \code{t}_2}{\code{MT}_2}{E_2}}
\ruleTag{T-LetVal}
\end{gather}

\begin{gather}
\inferrule
{}
{\typingRelation{\Gamma}{E}{\{\ \}}{\{\ \cdot\ \}}{E}}
\ruleTag{T-EmptyRcd}
\\
\inferrule
{\code{P}, \code{R}, \code{PT}, \code{MT} = \newVariables}
{\typingRelation{\Gamma}{E}{\code{extend(l)}}
 {\code{MT}\rightarrow\{\ \code{l}:\code{P}, \code{R}\ \}\rightarrow\{\ \code{l}:\code{PT}\ \code{MT}, \code{R}\ \}}
 {E}}
\ruleTag{T-RcdExtend}
\\
\inferrule
{\code{R}, \code{PT}, \code{MT}_1, \code{MT}_2 = \newVariables}
{\typingRelation{\Gamma}{E}{\code{update(l)}}
 {\code{MT}_1\rightarrow\{\ \code{l}:\code{Present}\ \code{MT}_2, \code{R}\ \}\rightarrow\{\ \code{l}:\code{PT}\ \code{MT}_1, \code{R}\ \}}
 {E}}
\ruleTag{T-RcdUpdate}
\\
\inferrule
{\code{R}, \code{MT} = \newVariables}
{\typingRelation{\Gamma}{E}{\code{access(l)}}
 {\{\ \code{l}:\code{Present}\ \code{MT}, \code{R}\ \}\rightarrow\code{MT}}
 {E}}
\ruleTag{T-RcdAccess}
\\
\inferrule
{\code{MT} = \newVariable}
{\typingRelation{\Gamma}{E}{[\ ]}{[\ \cdot\ ]\rightarrow\code{MT}}{E}}
\ruleTag{T-EmptyMatch}
\\
\inferrule
{\code{MT}_1, \code{MT}_2, \code{R}, \code{P}, \code{PT} = \newVariables \\\\
 \code{MT} = (\code{MT}_1\rightarrow\code{MT}_2)\rightarrow([\ \code{\backtick l}:\code{P}, \code{R}\ ]\rightarrow\code{MT}_2)\rightarrow[\ \code{\backtick l}:\code{PT}\ \code{MT}_1, \code{R}\ ]\rightarrow\code{MT}_2}
{\typingRelation{\Gamma}{E}{\code{extend(\backtick l)}}{\code{MT}}{E}}
\ruleTag{T-MatchExtend}
\\
\inferrule
{\code{MT}_1, \code{MT}_2, \code{MT}_3, \code{R}, \code{P}, \code{PT} = \newVariables \\\\
 \code{MT} = (\code{MT}_1\rightarrow\code{MT}_3)\rightarrow([\ \code{\backtick l}:\code{Present}\ \code{MT}_2, \code{R}\ ] \rightarrow\code{MT}_3) \\\\
 \rightarrow[\ \code{\backtick l}:\code{PT}\ \code{MT}_1, \code{R}\ ]\rightarrow\code{MT}_3}
{\typingRelation{\Gamma}{E}{\code{extend(\backtick l)}}{\code{MT}}{E}}
\ruleTag{T-MatchUpdate}
\\
\inferrule
{\code{MT}, \code{R} = \newVariable}
{\typingRelation{\Gamma}{E}{\code{\backtick l}}{\code{MT}\rightarrow[\ \code{\backtick l}:\code{Present}\ \code{MT}, \code{R}\ ]}{E}}
\ruleTag{T-Variant}
\\
\inferrule
{\code{MT} = \newVariable}
{\typingRelation{\Gamma}{E}{\code{ref}}{\code{MT}\rightarrow\code{Ref}\ \code{MT}}{E}}
\ruleTag{T-Ref}
\\
\inferrule
{\code{MT} = \newVariable}
{\typingRelation{\Gamma}{E}{\code{!}}{\code{Ref}\ \code{MT}\rightarrow\code{MT}}{E}}
\ruleTag{T-Deref}
\\
\inferrule
{\code{MT} = \newVariable}
{\typingRelation{\Gamma}{E}{\code{:=}}{\code{Ref}\ \code{MT}\rightarrow\code{MT}\rightarrow\{\ \cdot\ \}}{E}}
\ruleTag{T-Assign}
\\
\inferrule
{\code{MT} = \newVariable}
{\typingRelation{\Gamma}{E}{\code{new}}{(\code{Ref} \code{MT}\rightarrow\code{MT})\rightarrow\code{MT}}{E}}
\ruleTag{T-New}
\end{gather}

\subsection{Unification}

\begin{align*}
\unify(E, \code{MT}_1, \code{MT}_2) = \;
& \text{let}\ \code{S} = \find(E, \code{MT}_1)\ \text{in} \\
& \text{let}\ \code{T} = \find(E, \code{MT}_2)\ \text{in} \\
& \text{if}\ \code{S} = \code{T} \\
& \quad \text{then}\ E \\
& \text{else}\ \text{if}\ \code{S} = \code{X} \\
& \quad \text{then}\ \union(E, \code{X}, \code{T}) \\
& \text{else}\ \text{if}\ \code{T} = \code{X} \\
& \quad \text{then}\ \union(E, \code{X}, \code{S}) \\
& \text{else} \\
& \quad \text{let}\ E' = \union(E, \code{S}, \code{T})\ \text{in} \\
& \quad \text{if}\ \code{S} = \code{S}_{1}\rightarrow\code{S}_{2}\ \text{and}\ \code{T} = \code{T}_{1}\rightarrow\code{T}_{2} \\
& \quad \quad \text{then}\ \text{let}\ E'' = \unify(E', \code{S}_{1}, \code{T}_{1})\ \text{in}\ \unify(E'', \code{S}_{2}, \code{T}_{2}) \\
& \quad \text{else}\ \text{if}\ \code{S} = \{\ \code{R}_1\ \}\ \text{and}\ \code{T} = \{\ \code{R}_2\ \} \\
& \quad \quad \text{then}\ \unifyRow(E', \code{R}_1, \code{R}_2) \\
& \quad \text{else}\ \text{if}\ \code{S} = [\ \code{R}_1\ ]\ \text{and}\ \code{T} = [\ \code{R}_2\ ] \\
& \quad \quad \text{then}\ \unifyRow(E', \code{R}_1, \code{R}_2) \\
& \quad \text{else}\ \text{if}\ \code{S} = \code{Ref}\ \code{S}'\ \text{and}\ \code{T} = \code{Ref}\ \code{T}' \\
& \quad \quad\text{then}\ \unify(E', \code{S}', \code{T}') \\
& \quad \text{else} \\
& \quad \quad \text{fail}
\end{align*}

\begin{align*}
\unify(E, \code{R}_1, \code{R}_2) = \;
& \text{let}\ \code{R}'_1 = \find(E, \code{R}_1)\ \text{in} \\
& \text{let}\ \code{R}'_2 = \find(E, \code{R}_2)\ \text{in} \\
& \text{if}\ \code{R}'_1 = \code{R}'_2 \\
& \quad \text{then}\ E \\
& \text{else}\ \text{if}\ \code{R}'_1 = \code{X} \\
& \quad \text{then}\ \union(E, \code{X}, \code{R}'_2) \\
& \text{else}\ \text{if}\ \code{R}'_2 = \code{X} \\
& \quad \text{then}\ \union(E, \code{X}, \code{R}'_1) \\
& \text{else}\ \text{if}\ \code{R}'_1 = \cdot\ \text{and}\ \code{R}'_2 = \code{l}:\code{P},\code{R}''_2 \\
& \quad \text{then}\ \text{let}\ E' = \unifyPresence(E, \code{P}, \code{Absent})\ \text{in}\ \unifyRow(E', \code{R}''_2, \cdot) \\
& \text{else}\ \text{if}\ \code{R}'_1 = \code{l}:\code{P},\code{R}''_1\ \text{and}\ \code{R}'_2 = \cdot \\
& \quad \text{then}\ \text{let}\ E' = \unifyPresence(E, \code{P}, \code{Absent})\ \text{in}\ \unifyRow(E', \code{R}''_1, \cdot) \\
& \text{else}\ \text{if}\ \code{R}'_1 = \code{l}:\code{P}_1,\code{R}''_1\ \text{and}\ \code{R}'_2 = \code{l}:\code{P}_2,\code{R}''_2 \\
& \quad \text{then}\ \text{let}\ E' = \unifyPresence(E, \code{P}_1, \code{P}_2)\ \text{in}\ \unifyRow(E', \code{R}''_1, \code{R}''_2) \\
& \text{else}\ \text{if}\ \code{R}'_1 = \code{l}_1:\code{P}_1,\code{R}''_1\ \text{and}\ \code{R}'_2 = \code{l}_2:\code{P}_2,\code{R}''_2 \\
& \quad \text{then}\ \text{let}\ \code{R}_3 = \newVariable\ \code{in} \\
& \qquad \text{let}\ E' = \unifyRow(E, \code{R}''_1, (\code{l}_2:\code{P}_2,\code{R}_3))\ \text{in}\ \unifyRow(E', \code{R}''_2, (\code{l}_1:\code{P}_1,\code{R}_3)) \\
& \text{else} \\
& \quad \text{fail}
\end{align*}

\begin{align*}
\unifyPresence(E, \code{P}_1, \code{P}_2) = \;
& \text{let}\ \code{P}'_1 = \find(E, \code{P}_1)\ \text{in} \\
& \text{let}\ \code{P}'_2 = \find(E, \code{P}_2)\ \text{in} \\
& \text{if}\ \code{P}'_1 = \code{P}'_2 \\
& \quad \text{then}\ E \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{X}\ \text{then} \\
& \quad \text{then}\ \union(E, \code{X}, \code{P}'_2) \\
& \text{else}\ \text{if}\ \code{P}'_2 = \code{X}\ \text{then} \\
& \quad \text{then}\ \union(E, \code{X}, \code{P}'_1) \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{Present}\ \code{MT}_1\ \text{and}\ \code{P}'_2 = \code{Present}\ \code{MT}_2\ \text{then} \\
& \quad \text{then}\ \unify(E, \code{MT}_1, \code{MT}_2) \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{X}_1\ \code{MT}_1\ \text{and}\ \code{P}'_2 = \code{Absent}\ \text{then} \\
& \quad \text{then}\ \unifyPresenceWithType(E, \code{X}_1, \code{PTAbsent}) \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{Absent}\ \text{and}\ \code{P}'_2 = \code{X}_2\ \code{MT}_2\ \text{then} \\
& \quad \text{then}\ \unifyPresenceWithType(E, \code{X}_2, \code{PTAbsent}) \\
& \quad \text{then}\ \unify(E, \code{MT}_1, \code{MT}_2) \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{X}_1\ \code{MT}_1\ \text{and}\ \code{P}'_2 = \code{Present}\ \code{MT}_2\ \text{then} \\
& \quad \text{then}\ \text{let}\ E' = \unifyPresenceWithType(E, \code{X}_1, \code{PTPresent})\ \text{in}\ \unify(E', \code{MT}_1, \code{MT}_2) \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{Present}\ \code{MT}_1\ \text{and}\ \code{P}'_2 = \code{X}_2\ \code{MT}_2\ \text{then} \\
& \quad \text{then}\ \text{let}\ E' = \unifyPresenceWithType(E, \code{X}_2, \code{PTPresent})\ \text{in}\ \unify(E', \code{MT}_1, \code{MT}_2) \\
& \text{else}\ \text{if}\ \code{P}'_1 = \code{X}_1\ \code{MT}_1\ \text{and}\ \code{P}'_2 = \code{X}_2\ \code{MT}_2\ \text{then} \\
& \quad \text{then}\ \text{let}\ E' = \unifyPresenceWithType(E, \code{X}_1, \code{X}_2)\ \text{in}\ \unify(E', \code{MT}_1, \code{MT}_2) \\
& \text{else} \\
& \quad \text{fail}
\end{align*}

\begin{align*}
\unifyPresenceWithType(E, \code{PT}_1, \code{PT}_2) = \;
& \text{let}\ \code{PT}'_1 = \find(E, \code{PT}_1)\ \text{in} \\
& \text{let}\ \code{PT}'_2 = \find(E, \code{PT}_2)\ \text{in} \\
& \text{if}\ \code{PT}'_1 = \code{PT}'_2 \\
& \quad \text{then}\ E \\
& \text{else}\ \text{if}\ \code{PT}'_1 = \code{X}\ \text{then} \\
& \quad \text{then}\ \union(E, \code{X}, \code{PT}'_2) \\
& \text{else}\ \text{if}\ \code{PT}'_2 = \code{X}\ \text{then} \\
& \quad \text{then}\ \union(E, \code{X}, \code{PT}'_1) \\
& \text{else} \\
& \quad \text{fail}
\end{align*}

\chapter{\theLang{} the Language}

Working in progress.

\end{document}