\section*{Introduction}

In this part, we present a development  for the \coq{} proof assistant, after the work of Kirby and Paris. This formalization contains the following main parts:

\begin{itemize}
\item Representation in \coq{} of hydras and hydra battles.
\item A proof that every battle is finite and won by Hercules. This proof is based on a \emph{variant} which maps any hydra to an ordinal strictly less than $\epsilon_0$ and is strictly decreasing along any battle.

\item Using a combinatorial toolkit designed by J.~Ketonen and R.~Solovay~\cite{KS81}, we prove that, for any ordinal $\mu<\epsilon_0$, there exists no such variant mapping any hydra to an ordinal strictly less than $\mu$. Thus, the complexity of $\epsilon_0$ is really needed in the previous proof.

\item We prove a relation between the length of a ``classic''  kind of  battles \footnote{This class is also called \emph{standard} in this document (text and proofs). The \emph{replication factor} of the hydra is exactly $i$ at the $i$-th round of the battle (see Sect~\vref{sect:replication-def}).}
and the Wainer-Hardy hierarchy of ``rapidly growing functions'' $H_\alpha$~\cite{Wainer1970}. The considered class of battles, which we call \emph{standard},  is the most considered one in the scientific  literature (including popularization).
\end{itemize}

Simply put, this document tries to combine the scientific interest of two articles~\cite{KP82, KS81} and a book~\cite{schutte} with the playful activity of truly proving theorems.
We hope  that such a work, besides exploring a nice piece of discrete mathematics,
will show how \coq{} and its standard library are well fitted to help us to understand some non-trivial mathematical developments, and also to experiment the constructive parts of  the proof through functional programming.

 We also hope to provide a little clarification on infinity (both potential and actual) through the notions of function, computation, limit,
 type and proof.

%\section{Remarks}

\subsection*{Difference from Kirby and Paris's work}
In~\cite{KP82}, Kirby and Paris show  that there is no proof of termination of all hydra battles in Peano Arithmetic (PA).
Since we are used to writing proofs in higher order logic, the restriction to PA was quite unnatural for us. So we chose to prove another statement without any reference to PA, by considering a class of proofs indexed by ordinal numbers up to $\epsilon_0$.

\subsection*{State of the development}
The \coq{} scripts herein are in constant development since our contribution~\cite{CantorContrib} on  notations for the ordinals $\epsilon_0$ and $\Gamma_0$.
We added new material: axiomatic definitions of countable ordinals after Schütte~\cite{schutte}, combinatorial aspects of $\epsilon_0$, after Ketonen and Solovay~\cite{KS81} and Kirby and Paris~\cite{KP82}, recent \coq{} technology: type classes, equations, etc.

We are now working in order to make clumsy proofs more readable, simplify definitions, and ``factorize'' proofs as much as possible.
Many possible improvements are suggested as ``todo''s or ``projects'' in this text.

\section*{Future work (projects)}
\index{hydras}{Projects}

This document and the proof scripts are far from being complete.

First, there must be a lot of typos to correct, references and index items to add. Many proofs are too complex and should be simplified, etc.

The following extensions are planned, but help is needed:

\begin{itemize}
\item Semi automatic tactics for proving inequalities $\alpha < \beta$, even when $\alpha$ and $\beta$ are not closed terms.
\item Extension to $\Gamma_0$ (in Veblen normal form)
\item More lemmas about hierarchies of rapidly growing functions, and their relationship
    with primitive recursive functions and provability in Peano arithmetic
(following~\cite{KS81, KP82}).
\item From \coq's point of view, this development could be used as an illustration of the evolution of the software, every time new libraries and sets of tactics could help to simplify the proofs.
\end{itemize}

\subsection*{Main references}

In our development, we adapt the definitions and prove many theorems which
we found in the following articles.
\begin{itemize}
\item ``Accessible independence results for Peano arithmetic''  by Laurie Kirby and Jeff Paris~\cite{KP82}
\item ''Rapidly growing Ramsey Functions'' by Jussi Ketonen and Robert Solovay~\cite{KS81}
\item ``The Termite and the Tower'', by Will Sladek~\cite{Sladek07thetermite}
\item Chapter V of ``Proof Theory'' by Kurt Schütte~\cite{schutte}
\end{itemize}

\chapter{Hydras and hydra games}

\label{sec:orgheadline91}
\label{chapter:hydras}

This chapter is dedicated to the representation of hydras and rules of the hydra game in \coq's specification language:~\gallina.

Technically, a \emph{hydra} is just a finite ordered tree, each node of which
has any number of sons. Contrary to the computer science tradition, we display the hydras
with the heads up and the foot (i.e., the root of the tree) down.
Fig.~\ref{fig:Hy} represents such  a hydra, which will be referred to as \texttt{Hy} in our examples (please look at the
module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html}{Hydra.Hydra\_Examples}).
\emph{For a less formal description of hydras, please see
\url{https://www.smbc-comics.com/comic/hydra}.}

\begin{figure}[h]
\centering
\begin{tikzpicture}[very thick, scale=0.6]

\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (2,4) {$\bullet$};
\node (N3) at (2,6) {$\bullet$};
\node (H0) at (0,2) {$\Smiley[2][vertfluo]$};
\node (H1) at (0,8) {$\Smiley[2][vertfluo]$};
\node (H2) at (4,8) {$\Smiley[2][vertfluo]$};
\node (H4) at (4,2) {$\Smiley[2][vertfluo]$};
\node (H5) at (4,4) {$\Smiley[2][vertfluo]$};
\draw (foot) -- (N1)[very thick] ;
\draw (N1) -- (N2);
\draw (N2) -- (N3);
\draw (N3) to [bend left= 10]  (H1) ;
\draw (N3) to [bend right= 16] (H2);
\draw (foot) to [bend left= 10]  (H0) ;
\draw (foot) to [bend right = 10] (H4) ;
\draw (N1) to [bend right= 16] (H5);
\end{tikzpicture}
\caption{The hydra \texttt{Hy} \label{fig:Hy}}
\end{figure}

We use a specific vocabulary for talking about hydras. Table~\ref{tab:hyd2tree} shows the correspondence between our terminology and the usual vocabulary for trees in computer science.

\begin{figure}[h]
  \centering
  \begin{tabular}{ll}
Hydras & Finite rooted trees\\
\hline
foot & root\\
head & leaf\\
node & node\\
segment  & (directed) edge \\
sub-hydra & subtree\\
daughter & immediate subtree\\
\end{tabular}
  \caption{Translation from hydras to trees}
  \label{tab:hyd2tree}
\end{figure}

The hydra \texttt{Hy} has a \emph{foot} (below), five \emph{heads}, and eight \emph{segments}.
We leave it to the reader to define various parameters such as the height, the size, the highest arity (number of sons of a node) of a hydra. In our example, these parameters have the respective values $4$, $9$ and $3$.

\subsection{The rules of the game}

\label{sec:orgheadline44}
\label{sect:replication-def}

A \emph{hydra battle} is a fight between Hercules and the Hydra.
More formally, a  battle is a sequence of \emph{rounds}.
At each round:
\begin{itemize}
\item If the hydra is composed of just one head, the battle is finished
and  Hercules is the winner.
\item Otherwise, Hercules chops off \emph{one} head of the hydra,

\begin{itemize}
\item If the head is at distance 1 from the foot, the head is just lost by the hydra, with no more reaction.
\item Otherwise, let us denote by \(r\) the node that was at distance \(2\) from
the removed head in the direction of the foot,  and consider the  sub-hydra \(h'\) of \(h\), whose  root is \(r\) \footnote{$h'$ will be called ``the wounded part of the hydra'' in the subsequent text. In Figures~\vref{fig:Hy2} and ~\vref{fig:Hy4}, this sub-hydra  is displayed in red.}. Let $n$ be some natural number.
Then $h'$ is replaced by  $n+1$ of copies of \(h'\) which share the same root $r$.
 The \emph{replication factor} $n$ may be different (and generally is)   at each round of the fight.
It may be chosen by the hydra, according to its strategy, or imposed by some
particular rule. In many presentations of hydra battles, this number is increased by $1$ at each round. In the following presentation, we will also consider battles where the hydra is free to choose its ~replication factor at each round of the battle\footnote{Let us recall that, if the chopped-off head was at distance 1 from the foot, the replication factor is meaningless.}.
\end{itemize}
\end{itemize}

Note that the description given in~\cite{KP82} of the replication process in hydra battles is also  semi-formal.

\label{original-rules}

\begin{quote}
  ``From the node that used to be attached to the head which was just chopped off, traverse one
segment towards the root until the next node is reached. From this node sprout $n$ replicas of
that part of the hydra (after decapitation) which is ``above'' the segment just traversed, i.e., those
nodes and segments from which, in order to reach the root, this segment would have to be
traversed. If the head just chopped off had the root of its nodes, no new head is grown. ''
\end{quote}

Moreover, we note that this description is in \emph{imperative} terms. In order to formally study the properties of hydra battles, we prefer to use a mathematical vocabulary, i.e., graphs, relations, functions, etc.
Thus, the replication process will be represented as a binary relation on a data type \texttt{Hydra},
linking the state of the hydra \emph{before} and \emph{after} the transformation.
A battle will thus be represented as a sequence of terms of type \texttt{Hydra}, respecting the rules of the game.

\subsection{Example}
Let us start a battle between Hercules and the hydra \texttt{Hy} of Fig.~\ref{fig:Hy}.

At the first round, Hercules chooses to chop off the rightmost head of \texttt{Hy}.
Since this head is near the floor, the hydra simply loses this head. Let us call
 \texttt{Hy'} the resulting state of the hydra, represented in Fig.~\vref{fig:Hy-prime}.

Next, assume Hercules chooses to chop off one of the two highest heads of \texttt{Hy'}, for instance the rightmost one. Fig.~\vref{fig:Hy2} represents the broken segment in dashed lines, and the part that will be replicated in red. Assume also that the hydra decides to add 4 copies of the red part\footnote{In other words, the replication factor at this round is equal to $4$.}. We obtain a new state \texttt{Hy''} depicted in Fig.~\ref{fig:Hy3}.

\begin{figure}[h]
\centering
\begin{tikzpicture}[very thick, scale=0.6]

\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (2,4) {$\bullet$};
\node (N3) at (2,6) {$\bullet$};
\node (H0) at (0,2) {$\Smiley[2][vertfluo]$};
\node (H1) at (0,8) {$\Smiley[2][vertfluo]$};
\node (H2) at (4,8) {$\Smiley[2][vertfluo]$};
\node (H5) at (4,4) {$\Smiley[2][vertfluo]$};
%\node (H4) at (6,0) {$\Xey[2][lightgray]$};
\draw (foot) -- (N1)[very thick] ;
\draw (N1) -- (N2);
\draw (N2) -- (N3) ;
\draw (N3) to [bend left= 10]  (H1) ;
\draw (N3) to [bend right= 16] (H2);
\draw (foot) to [bend left= 10]  (H0) ;
\draw (N1) to [bend right= 16] (H5);
\end{tikzpicture}

\caption{\texttt{Hy'}: the state  of \texttt{Hy} after one round \label{fig:Hy-prime}}
\end{figure}

\begin{figure}[hp]
\centering
\begin{tikzpicture}[very thick, scale=0.5]

\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (2,4)  {{\color{lightred}$\bullet$}};
\node (N3) at (2,6) {{\color{lightred}$\bullet$}};
\node (H0) at (0,2) {$\Smiley[2][vertfluo]$};
\node (H1) at (0,8) {$\Sey[2][lightred]$};
%\node (H2) at (5,0) {$\Xey[2][lightgray]$};
\node (H5) at (4,4) {$\Smiley[2][vertfluo]$};
\node (ex) at (5,8) {};
\draw (foot) -- (N1)[very thick] ;
\draw (N1) -- (N2);
\draw  (N2) -- (N3)[draw=lightred];
\draw (N3) to   [bend left= 10](H1) [draw=lightred];
\draw [dashed] (N3) to [bend left= 10](ex);
\draw (foot) to [bend left= 10]  (H0) ;
\draw (N1) to [bend right= 16] (H5);
\end{tikzpicture}
\caption{A second beheading}
\label{fig:Hy2}
\end{figure}

\begin{figure}[hp]
\centering
\begin{tikzpicture}[very thick, scale=0.6]

\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (2,4) {$\bullet$};
\node (N3) at (2,6) {{\color{lightred}$\bullet$}};
\node (H1) at (0,8) {$\Smiley[2][vertfluo]$};
\node (H11) at (2,8) {$\Smiley[2][vertfluo]$};
\node (H12) at (4,8) {$\Smiley[2][vertfluo]$};
\node (H13) at (6,8) {$\Smiley[2][vertfluo]$};
\node (H14) at (8,8) {$\Smiley[2][vertfluo]$};

\node (N3) at (1,6) {$\bullet$};
\node (N31) at (2,6) {$\bullet$};
\node (N32) at (3,6) {$\bullet$};
\node (N33) at (4,6) {$\bullet$};
\node (N34) at (5,6) {$\bullet$};

\node (H0) at (0,2) {$\Smiley[2][vertfluo]$};
\node (H5) at (4,4) {$\Smiley[2][vertfluo]$};
\draw (foot) -- (N1)[very thick] ;
\draw (N1) -- (N2);
\draw (N2) -- (N3);
\draw (N2) -- (N31);
\draw (N2) -- (N32);
\draw (N2) -- (N33);
\draw (N2) -- (N34);
\draw (N3) to   [bend left= 10](H1) ;
\draw (N31) to   [bend left= 10](H11) ;
\draw (N32) to   [bend left= 10](H12) ;
\draw (N33) to   [bend left= 10](H13) ;
\draw (N34) to   [bend left= 10](H14) ;
\draw (foot) to [bend left= 10]  (H0) ;
\draw (N1) to [bend left= 10]  (H5) ;
\end{tikzpicture}
\caption{\texttt{Hy''}: the state of \texttt{Hy} after two rounds \label{fig:Hy3}}
\end{figure}

Figs.~\ref{fig:Hy4} and~\vref{fig:Hy5} represent a possible third round of the battle, with a replication factor equal to $2$. Let us call \texttt{Hy'''} the state of the hydra after that third round.

\begin{figure}[hp]
\centering
\begin{tikzpicture}[very thick, scale=0.6]

\node (foot) at (2,0)  {{\color{lightred}$\bullet$}};
\node (N1) at (2,2) {{\color{lightred}$\bullet$}};
\node (N2) at (2,4) {{\color{lightred}$\bullet$}};
\node (N3) at (2,6) {{\color{lightred}$\bullet$}};
\node (exN4) at (4,4) {};
\node (H1) at (0,8) {$\Sey[2][lightred]$};
\node (H11) at (2,8) {$\Sey[2][lightred]$};
\node (H12) at (4,8) {$\Sey[2][lightred]$};
\node (H13) at (6,8) {$\Sey[2][lightred]$};
\node (H14) at (8,8) {$\Sey[2][lightred]$};

\node (N3) at (1,6) {{\color{lightred}$\bullet$}};
\node (N31) at (2,6) {{\color{lightred}$\bullet$}};
\node (N32) at (3,6) {{\color{lightred}$\bullet$}};
\node (N33) at (4,6) {{\color{lightred}$\bullet$}};
\node (N34) at (5,6) {{\color{lightred}$\bullet$}};

\node (H0) at (0,2) {$\Smiley[2][vertfluo]$};
%\node (H5) at (4,0) {$\Xey[2][lightgray]$};
\draw (foot) -- (N1)[very thick,draw=lightred] ;
\draw (N1) -- (N2)[draw=lightred];
\draw (N2) -- (N3)[draw=lightred];
\draw (N2) -- (N31)[draw=lightred];
\draw (N2) -- (N32)[draw=lightred];
\draw (N2) -- (N33)[draw=lightred];
\draw (N2) -- (N34)[draw=lightred];
\draw (N3) to   [bend left= 10](H1) [draw=lightred];
\draw (N31) to   [bend left= 10](H11) [draw=lightred];
\draw (N32) to   [bend left= 10](H12) [draw=lightred];
\draw (N33) to   [bend left= 10](H13) [draw=lightred];
\draw (N34) to   [bend left= 10](H14) [draw=lightred];
\draw (foot) to [bend left= 10]  (H0) ;
\draw [dashed] (N1) to  [bend left= 10](exN4);
\end{tikzpicture}
\caption{A third beheading (wounded part in red) \label{fig:Hy4}}
\end{figure}

\begin{figure}[hp]
\centering
\begin{tikzpicture}[very thick, scale=0.4]

\node (foot) at (10,0) {$\bullet$};

\node (N1) at (2,2) {$\bullet$};
\node (N2) at (2,4) {$\bullet$};
\node (N3) at (2,6) {{\color{lightred}$\bullet$}};
\node (H1) at (0,8) {$\Smiley[1][vertfluo]$};
\node (H11) at (2,8) {$\Smiley[1][vertfluo]$};
\node (H12) at (4,8) {$\Smiley[1][vertfluo]$};
\node (H13) at (6,8) {$\Smiley[1][vertfluo]$};
\node (H14) at (8,8) {$\Smiley[1][vertfluo]$};

\node (N3) at (1,6) {$\bullet$};
\node (N31) at (2,6) {$\bullet$};
\node (N32) at (3,6) {$\bullet$};
\node (N33) at (4,6) {$\bullet$};
\node (N34) at (5,6) {$\bullet$};

\node (H0) at (-3,3) {$\Smiley[1][vertfluo]$};

\draw (foot) to [bend left=10] (N1)[very thick] ;
\draw (N1) -- (N2);
\draw (N2) -- (N3);
\draw (N2) -- (N31);
\draw (N2) -- (N32);
\draw (N2) -- (N33);
\draw (N2) -- (N34);
\draw (N3) to   [bend left= 10](H1) ;
\draw (N31) to   [bend left= 10](H11) ;
\draw (N32) to   [bend left= 10](H12) ;
\draw (N33) to   [bend left= 10](H13) ;
\draw (N34) to   [bend left= 10](H14) ;
\draw (foot) to [bend left = 15]  (H0) ;

% second copy
\node (N01) at (12,2) {$\bullet$};
\node (N02) at (12,4) {$\bullet$};
\node (N03) at (12,6) {{\color{lightred}$\bullet$}};
\node (H001) at (10,8) {$\Smiley[1][vertfluo]$};
\node (H0011) at (12,8) {$\Smiley[1][vertfluo]$};
\node (H0012) at (14,8) {$\Smiley[1][vertfluo]$};
\node (H0013) at (16,8) {$\Smiley[1][vertfluo]$};
\node (H0014) at (18,8) {$\Smiley[1][vertfluo]$};

\node (N03) at (11,6) {$\bullet$};
\node (N031) at (12,6) {$\bullet$};
\node (N032) at (13,6) {$\bullet$};
\node (N033) at (14,6) {$\bullet$};
\node (N034) at (15,6) {$\bullet$};

\draw (foot) -- (N01)[very thick] ;
\draw (N01) -- (N02);
\draw (N02) -- (N03);
\draw (N02) -- (N031);
\draw (N02) -- (N032);
\draw (N02) -- (N033);
\draw (N02) -- (N034);
\draw (N03) to   [bend left= 10](H001) ;
\draw (N031) to   [bend left= 10](H0011) ;
\draw (N032) to   [bend left= 10](H0012) ;
\draw (N033) to   [bend left= 10](H0013) ;
\draw (N034) to   [bend left= 10](H0014) ;

% third copy
\node (N001) at (22,2) {$\bullet$};
\node (N002) at (22,4) {$\bullet$};
\node (N003) at (22,6) {{\color{lightred}$\bullet$}};
\node (H001) at (20,8) {$\Smiley[1][vertfluo]$};
\node (H0011) at (22,8) {$\Smiley[1][vertfluo]$};
\node (H0012) at (24,8) {$\Smiley[1][vertfluo]$};
\node (H0013) at (26,8) {$\Smiley[1][vertfluo]$};
\node (H0014) at (28,8) {$\Smiley[1][vertfluo]$};

\node (N003) at (21,6) {$\bullet$};
\node (N0031) at (22,6) {$\bullet$};
\node (N0032) at (23,6) {$\bullet$};
\node (N0033) at (24,6) {$\bullet$};
\node (N0034) at (25,6) {$\bullet$};

\draw (foot) -- (N001)[very thick] ;
\draw (N001) -- (N002);
\draw (N002) -- (N003);
\draw (N002) -- (N0031);
\draw (N002) -- (N0032);
\draw (N002) -- (N0033);
\draw (N002) -- (N0034);
\draw (N003) to   [bend left= 10](H001) ;
\draw (N0031) to   [bend left= 10](H0011) ;
\draw (N0032) to   [bend left= 10](H0012) ;
\draw (N0033) to   [bend left= 10](H0013) ;
\draw (N0034) to   [bend left= 10](H0014) ;
\end{tikzpicture}
\caption{The configuration \texttt{Hy'''} of \texttt{Hy} \label{fig:Hy5}}
\end{figure}
\FloatBarrier

We leave it to the reader  to guess the following  rounds of the battle \dots
 % Please keep in mind that, in this
% the hydra is free to chose any number of replications at each time, whereas
% Hercules chops only one head per round.

% Let us precise that, in this game, Hercules wins if the hydra is eventually reduced
% to a single head.
% We know from~\cite{KP82} that, whichever the initial configuration of the
% hydra, and the strategies of both players, Hercules eventually wins. The
% aforementionned paper shows also that there do not exist any \emph{simple} proof of this result.

\section{Hydras and their representation in \emph{Coq}}
\label{sec:orgheadline48}

\index{hydras}{Library Hydra!Types!Hydra}
\index{hydras}{Library Hydra!Types!Hydrae}

In order to describe trees where each node can have an arbitrary (but finite) number of sons, it is usual to define a type where each node carries a \emph{forest}, \emph{i.e} a list of trees
(see for instance Chapter 14, pages 400-406 of \cite{BC04}).

For this purpose, we define two mutual \emph{ad-hoc}  inductive types, where \texttt{Hydra} is the main type, and \texttt{Hydrae} is a helper for describing finite sequences of hydra.
\label{types:Hydra}
\label{types:Hydrae}

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#Hydra}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/HydraDef}

%\index{To do}
\index{hydras}{Projects}

\begin{project}
Look for an existing library on trees with nodes of arbitrary arity, in order to replace  this ad-hoc type with something more generic.
\end{project}

\index{hydras}{Projects}

\begin{project}

 Another very similar representation could use the \texttt{list} type family instead of the specific
type \texttt{Hydrae}:

\input{movies/snippets/Hydra_Definitions/HydraAlt}

Using this representation, re-define all the constructions of this chapter.
You will probably have to use patterns described for instance in~\cite{BC04} or the archives of the Coq-club~\cite{Coq}.

\end{project}

\index{hydras}{Projects}

\begin{project}
The type \texttt{Hydra} above describes hydras as \emph{plane trees}, i.e., as drawn on a sheet of paper or computer screen. Thus, hydras are \emph{oriented},
and it is appropriate to consider a \emph{leftmost} or \emph{rightmost} head of
the beast. It could be interesting to consider another representation, in which
every non-leaf node has a \emph{multi-set} -- not an ordered list -- of daughters.
\end{project}

\subsubsection{Abbreviations}

We provide several notations for hydra patterns  which occur often in our developments.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#head}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/headsEtc}

For instance, the hydra \texttt{Hy}  of Figure~\vref{fig:Hy} is defined in \emph{Gallina} as follows:

\vspace{4mm}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html\#Hy}{Hydra.Hydra\_Examples}}

\input{movies/snippets/Hydra_Examples/Hy}

Hydras quite frequently contain  multiple adjacent  copies of the same subtree. The following functions
will help us to describe and reason about replications in hydra battles.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#hcons_mult}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/hconsMult}

\vspace{4mm}

For instance, the hydra \texttt{Hy''} of Fig~\vref{fig:Hy3}  can be defined in \coq{} as follows:

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html}{Hydra.Hydra\_Examples}}

\input{movies/snippets/Hydra_Examples/HySecond}

\subsubsection{Recursive functions on type \texttt{Hydra}}
\label{sec:orgheadline41}
\label{sec:hsize-def}

In order to  define a recursive function over the type \texttt{Hydra}, one has to consider the three constructors
\texttt{node}, \texttt{hnil} and \texttt{hcons} of the mutually inductive types \texttt{Hydra} and \texttt{Hydrae}.
Let us define for instance the function which  computes the number of nodes of any hydra:

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/hsize}

\input{movies/snippets/Hydra_Examples/HySize}

Likewise, the \emph{height} (maximum distance between the foot and a head)
is defined by mutual recursion:

\input{movies/snippets/Hydra_Definitions/height}

\input{movies/snippets/Hydra_Examples/HyHeight}

\index{hydras}{Exercises}

\begin{exercise}
Define a function \texttt{max\_degree: Hydra $\arrow$ nat} which  returns the highest degree of a node in any hydra. For instance, the evaluation of the term \texttt{(max\_degree Hy)} should return $3$.
\end{exercise}

\subsection{Induction principles for hydras}
\label{sec:orgheadline42}

In this section, we show how induction principles are used to prove properties on the type
\texttt{Hydra}. Let us consider for instance the following statement:
\begin{quote}
  `` The height of any hydra is strictly less than its size. ''
\end{quote}

\subsubsection{A failed attempt}

One may try to use the default tactic of proof by induction, which corresponds to an application of the automatically  generated  induction principle for  type \texttt{Hydra}:

\input{movies/snippets/Hydra_Examples/HydraInd}

Let us start a simple proof by induction.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html}{Hydra.Hydra\_Examples}}

\input{movies/snippets/Hydra_Examples/BadInductiona}

We might be tempted to do an induction on the sequence \texttt{s}:

\input{movies/snippets/Hydra_Examples/BadInductionb}

The first subgoal is trivial.

\input{movies/snippets/Hydra_Examples/BadInductionc}

Let us look at the second subgoal of the induction.

\input{movies/snippets/Hydra_Examples/BadInductiond}

We notice that this subgoal does not contain any hypothesis
on the height and size of the hydra \texttt{h}. So, it looks hard to prove the conclusion. Let's stop.

\input{movies/snippets/Hydra_Examples/BadInductione}

\subsubsection{A Principle of mutual induction}
In order to get an appropriate induction scheme for the types
\texttt{Hydra} and \texttt{Hydrae}, we can use  \coq{}'s  command \texttt{Scheme}.

\index{coq}{Mutually inductive types}
\index{coq}{Commands!Scheme}

\input{movies/snippets/Hydra_Definitions/HydraRect2}

\input{movies/snippets/Hydra_Examples/HydraRect2Check}

\subsubsection{A Correct proof}

Let us now use \texttt{Hydra\_rect2} for proving that the height of any hydra is strictly less than its size.
Using this scheme requires an auxiliary predicate, called \texttt{P0} in \texttt{Hydra\_rect2}'s statement.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/hForall}

\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html}{Hydra.Hydra\_Examples}}
\input{movies/snippets/Hydra_Examples/heightLtSizea}

The first subgoal is easily solvable, using some arithmetic.
The second and third ones are
almost trivial. We let the reader look at the source.
\input{movies/snippets/Hydra_Examples/heightLtSizez}

\index{hydras}{Exercises}

\begin{exercise}
It happens very often that, in the proof of  a proposition of the form
(\texttt{$\forall\,$ h:Hydra, $P$ h}), the predicate \texttt{P0}
is  (\texttt{h\_forall $P$}).  Design a tactic for induction on hydras that frees the user from binding explicitly \texttt{P0},  and solves trivial subgoals. Apply it for writing  a shorter proof of \texttt{height\_lt\_size}.
\end{exercise}

\section{Relational description of hydra battles}

In this section, we represent the rules of hydra battles as a binary relation associated with
a \emph{round}, i.e., an interaction composed of the two following actions:
\begin{enumerate}
\item Hercules chops off one head of the hydra.
\item Then, the  hydra replicates the wounded part (if the head is at distance $\geq 2$ from the foot).
\end{enumerate}
The relation associated with each round of the battle is parameterized  by the \emph{expected} replication  factor (irrelevant if the chopped head is at distance 1 from the foot,
but present for consistency's sake).

In our description,  we will apply the following naming convention: if $h$ represents the configuration of the hydra before a round, then the configuration of $h$ after this round will be called $h'$.
 Thus, we are going to define a proposition  (\texttt{round\_n $n\;h\;h'$})  whose intended meaning will be `` the hydra $h$  is transformed into $h'$  in a single round of a battle, with the expected replication factor $n$ ''.

Since the replication of parts of the hydra depends on the distance of the chopped head from  the foot, we  decompose our description into two main  cases, under the form of a bunch of [mutually] inductive predicates over the types \texttt{Hydra} and \texttt{Hydrae}.

The mutually exclusive cases we consider are the following:
\begin{itemize}
\item \textbf{R1}: The chopped off head was at distance 1 from the foot.
\item \textbf{R2}: The chopped off head was at a distance greater than or equal to  $2$ from the foot.
\end{itemize}

\subsection{Chopping off a head at distance 1 from the foot (relation  R1)}

If Hercules chops off a head near the floor, there is no replication at all. We use an auxiliary
predicate \texttt{S0}, associated with the removing of one head from a sequence of hydras.

\vspace{4pt}\emph{From Module\href{../theories/html/hydras.Hydra.Hydra_Definitions.html}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/S0Def}
\input{movies/snippets/Hydra_Definitions/R1Def}

\subsubsection{Example}
\label{sec:orgheadline45}

Let us represent in \coq{}   the transformation of the hydra of Fig.~\vref{fig:Hy} into
the configuration represented in Fig.~\ref{fig:Hy-prime}.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html}{Hydra.Hydra\_Examples}}

\input{movies/snippets/Hydra_Examples/Hy1}

\subsection{Chopping off a head at distance \texorpdfstring{$\geq 2$}{>= 2} from the foot (relation R2) }

Let us now consider beheadings  where the chopped-off head is at distance greater than or equal to $2$ from the foot. All the following relations are parameterized by the replication factor  $n$.

 Let $s$ be a sequence of hydras.
The proposition (\texttt{S1 n s s'}) holds if $s'$ is obtained by replacing some element $h$ of $s$ by
$n+1$ copies of $h'$, where  the proposition (\texttt{R1 h h'}) holds, in other words, $h'$ is just $h$, without the chopped-off  head. \texttt{S1} is an inductive relation with two constructors that allow us to choose the position in $s'$ of the wounded sub-hydra $h$.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#S1}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/S1Def}

The rest of the definition is composed of two mutually inductive relations on hydras and sequences of hydras. The first constructor of \texttt{R2} describes the case where the chopped head is exactly at height $2$. The others constructors allow us to consider beheadings at height strictly greater than $2$.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#R2}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/R2Def}

\subsubsection{Example}
Let us prove the transformation of \texttt{Hy'} into \texttt{Hy''} (see Fig.~\vref{fig:Hy3}). We use an experimental set of tactics for specifying the place where the
interaction between Hercules and the hydra holds.

\vspace{4pt}\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Examples.html}{Hydra.Hydra\_Examples}}.

\input{movies/snippets/Hydra_Examples/R2Example}

The reader is encouraged to look at all the successive subgoals of this example.
\emph{Please consider also exercise~\vref{exo:interactive-battle}.}

\subsection{Binary relation associated with a round}

We combine the two cases above into a single relation.
First,  we define the  relation \texttt{(round\_n n h h')} where \texttt{n} is the expected number of  replications (irrelevant in the case of an \texttt{R1}-transformation).

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#round_n}{Hydra.Hydra\_Definitions}}

\index{hydras}{Library Hydra!Predicates!round\_n}

\input{movies/snippets/Hydra_Definitions/roundNDef}

By abstraction over \texttt{n}, we define a \emph{round} (small step) of a battle:

\index{hydras}{Library Hydra!Predicates!round}
\label{sect:infix-round}

\input{movies/snippets/Hydra_Definitions/roundDef}

\index{hydras}{Projects}

\begin{project}
Give a direct translation of Kirby and Paris's description of hydra battles (quoted on page~\pageref{original-rules}) and prove that our relational description is consistent with theirs.
\end{project}

\subsection{Rounds and battles}

Using library \href{https://coq.inria.fr/distrib/current/stdlib/Coq.Relations.Relation_Operators.html}{Relations.Relation\_Operators}, we define \texttt{round\_plus},  the transitive closure of \texttt{round}, and \texttt{round\_star},  the reflexive and transitive closure of \texttt{round}.

\label{sect:infix-rounds}

\input{movies/snippets/Hydra_Definitions/roundPlus}

\index{hydras}{Exercises}

\begin{exercise}
  Prove that if \texttt{$h$ -+-> $h'$}, then
  the height of $h'$ is less or equal than the height of $h$.

\end{exercise}

\begin{remark}
\label{remark:transitive-closure}
\coq's library \href{https://coq.inria.fr/distrib/current/stdlib/Coq.Relations.Relation_Operators.html}{Coq.Relations.Relation\_Operators}
contains three logically equivalent definitions of the transitive closure of a binary relation. This equivalence is proved in
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Relations.Operators_Properties.html}{Coq.Relations.Operators\_Properties} .

Why three definitions for a single mathematical concept?
Each definition generates an associated induction principle.
 According to the form of statement one would like to prove, there is a ``best choice'':

\begin{itemize}
\item For proving $\forall y, x\,R^+\,y \;\arrow\; P\,y$, prefer
\texttt{clos\_trans\_n1}
\item For proving $\forall x,\,x\,R^+\,y \;\arrow\; P\,x$, prefer \texttt{clos\_trans\_1n}
\item For proving $\forall x\,y, \,x\,R^+\,y \;\arrow\;P\,x\,y$,
prefer \texttt{clos\_trans},
\end{itemize}
But there is no ``wrong choice'' at all: the equivalence lemmas in \linebreak
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Relations.Operators_Properties.html}{Coq.Relations.Operators\_Properties}
 allow the user
to convert any one of the three closures into another one before applying the corresponding elimination tactic.
The same remark also holds for reflexive and transitive closures.
\end{remark}

\index{hydras}{Exercises}

\begin{exercise}
Define a restriction of \coqsimple{round},  where Hercules always chops off
the leftmost among the lowest heads.

Prove that, if $h$ is not a simple head, then there exists a unique $h'$ such that \texttt{h}  is transformed into \texttt{ h'} in one round, according to this restriction.

\end{exercise}

\index{hydras}{Exercises}

\begin{exercise}[Interactive battles]
\label{exo:interactive-battle}
Given a hydra \texttt{h}, the specification of a hydra battle for \texttt{h} is the type
\Verb@{h':Hydra | h -*-> h'}@. In order to avoid long sequences of \texttt{split}, \texttt{left}, and
\texttt{right}, design a set of dedicated tactics for the interactive building of a battle.
Your tactics will have the following functionalities:
\begin{itemize}
\item  Chose to stop a battle, or continue
\item Chose an expected number of replications
\item Navigate in a hydra, looking for a head to chop off.
\end{itemize}

Use your tactics for simulating a small part of a hydra battle, for instance the rounds which lead from
\texttt{Hy} to \texttt{Hy'''}  (Fig.~\vref{fig:Hy5}).

\textbf{Hints:}
\begin{itemize}

\item Please keep in mind that the last  configuration of your interactively built battle is known only at the end of the battle. Thus, you will have to create and solve subgoals with existential variables. For that purpose, the tactic \texttt{eexists}, applied to the
goal \Verb@{h':Hydra | h -*-> h'}@ generates the subgoal \Verb|h -*-> ?h'|.
\item You may use Gérard Huet's \emph{zipper} data structure~\cite{zipper} for writing tactics associated with Hercules's  interactive search for a head to chop off.
\end{itemize}

\end{exercise}

\subsection{Classes of battles}
\label{sect:battle-classes}

In some presentations of hydra battles, e.g.~\cite{KP82, bauer2008}, the transformation associated with the $i$-th round may depend on $i$. For instance, in these articles, the replication factor at the $i$-th round is equal to $i$. In other examples, one can allow the hydra to apply any replication factor at any time. In order to be the most general as possible, we define the type of predicates which relate the state of the hydra before and after the $i$-th round of a battle.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html}{Hydra.Hydra\_Definitions}}
\label{types:Battle}
\index{hydras}{Library Hydra!Type classes!Battle}

\input{movies/snippets/Hydra_Definitions/BattleDef}

The most general class of battles is \texttt{free}, which allows the hydra to chose any replication factor at every step:

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#free}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/freeDef}

We chose to call \emph{standard}\footnote{This appellation is ours. If there is a better one, we will change it.} the kind of battles which appear  most often in the literature and correspond to an arithmetic progression of the replication factor : $0,1,2,3, \dots$

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#standard}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/standardDef}

\subsection{Big steps}

Let $B$ be any instance of class \texttt{Battle}. It is easy to define inductively the relation between the $i$-th and the $j$-th steps of a battle of type $B$.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#fight}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/battleRelDef}

The following property allows us to build battles by composition of smaller ones.

%% TODO display subgoals when fixed

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Lemmas.html}{Hydra.Hydra\_Lemmas}}

\noindent
\input{movies/snippets/Hydra_Lemmas/battleTrans}

% \begin{remark}
%  The class \texttt{free} is strongly related with the transitive closure  \texttt{round\_plus}, as expressed by the following lemmas.

% \vspace{4pt}
% \emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Lemmas.html}{Hydra.Hydra\_Lemmas}}

%  \begin{Coqsrc}
%  Lemma battle_free_equiv1 : forall i j h h',
%              battle free i h j h' ->   h -+-> h'.

%  Lemma battle_free_equiv2 : forall h h',
%      h -+-> h' ->
%     forall i, exists j,  battle free i h j h'.
%  \end{Coqsrc}

% \end{remark}

\section{A long battle}
\label{sect:big-battle}

In this section we consider a simple example of battle, starting with a small hydra,
shown on figure~\vref{fig:hinit}, with a simple strategy for both players:

\begin{itemize}
\item At each round, Hercules chops off the rightmost head of the hydra.
\item The battle is {standard}: at the round number $i$, the expected replication is $i$.
\end{itemize}

\begin{figure}[h]
  \centering
  \begin{tikzpicture}[thick, scale=0.30]
 \node (foot) at (6,0) {$\bullet$};
\node (n1) at  (3,3) {$\bullet$};
\node (h1) at  (1,6) {$\Smiley[1][green]$};
\node (h2) at  (3,6) {$\Smiley[1][green]$};
\node (h3) at  (6,6) {$\Smiley[1][green]$};
\node (h4) at  (6,6) {$\Smiley[1][green]$};
\node (h5) at  (6,3) {$\Smiley[1][green]$};
\node (h6) at  (9,3) {$\Smiley[1][green]$};
\draw (foot) -- (n1);
\draw (n1) to   [bend left=20] (h1);
\draw (n1) to   (h2);
\draw (n1) to   [bend right=20] (h3);
\draw (foot) -- (h5);
\draw (foot) to  [bend right=20] (h6);
\end{tikzpicture}

  \caption{The hydra \texttt{hinit}}
  \label{fig:hinit}
\end{figure}

\emph{From Module~\href{../theories/html/hydras.Hydra.BigBattle.html}{Hydra.BigBattle}}

\input{movies/snippets/BigBattle/hinitDef}

The lemma we would like to prove is ``The considered battle lasts exactly $N$ rounds'',
with $N$ being a natural number we gave to guess.

But the  battle is so long that no \emph{test} can give us any estimation of its length, and we do need the expressive power of logic to compute this length. However, in order to  guess this length, we made some experiments, computing with \gallina{}, \coq{}'s  functional programming language.
Thus, we can consider this development as a collaboration of proof with computation.
In the following lines, we show how we found experimentally the value of the number $N$.
The complete proof is in file \url{../theories/html/hydras.Hydra.BigBattle.html}.

\subsection{The beginning of hostilities}
During the two first rounds, our hydra loses its two rightmost heads.  Figure~\vref{fig:hinit-plus2} shows the state of the hydra   just before the third round.

\begin{figure}[h]
  \centering
  \begin{tikzpicture}[thick, scale=0.30]
 \node (foot) at (3,0) {$\bullet$};
\node (n1) at  (3,3) {$\bullet$};
\node (h1) at  (1,6) {$\Smiley[1][green]$};
\node (h2) at  (3,6) {$\Smiley[1][green]$};
\node (h3) at  (6,6) {$\Smiley[1][green]$};
\node (h4) at  (6,6) {$\Smiley[1][green]$};
\draw (foot) -- (n1);
\draw (n1) to   [bend left=20] (h1);
\draw (n1) to   (h2);
\draw (n1) to   [bend right=20] (h3);
\end{tikzpicture}

  \caption{The hydra (\texttt{hyd1 h3})}
  \label{fig:hinit-plus2}
\end{figure}

The following lemma  is a formal description of these first rounds, in terms of the
\texttt{battle} predicate.

\input{movies/snippets/BigBattle/L02}

\subsection{Looking for regularities}

A first study with pencil and paper suggested us that, after three rounds, the hydra always looks like in figure~\vref{fig:hinit-plusn} (with a variable number of
subtrees of height 1 or 0).
Thus, we introduce a few handy abbreviations.

\input{movies/snippets/BigBattle/Notations}

For instance, the hydra shown in  Fig~\ref{fig:hinit-plusn} is  (\texttt{hyd 3 4 2}). The hydra (\texttt{hyd 0 0 0})  is the ``final'' hydra of any terminating battle, {i.e.},
a tree whith exactly one node and no edge.

\begin{figure}[h]
  \centering
  \begin{tikzpicture}[thick, scale=0.30]
 \node (foot) at (15,0) {$\bullet$};
\node (a) at  (3,4) {$\bullet$};
\node (b) at  (6,4) {$\bullet$};
\node (c) at  (9,4) {$\bullet$};
\node (d) at  (13,4) {$\bullet$};
\node (e) at  (16,4) {$\bullet$};
\node (f) at  (19,4) {$\bullet$};
\node (g) at  (22,4) {$\bullet$};
\node (h) at  (25,4) {$\Smiley[1][green]$};
\node (i) at  (28,4) {$\Smiley[1][green]$};
\node (aa) at  (2.5,8) {$\Smiley[1][green]$};
\node (ab) at  (3.5,8) {$\Smiley[1][green]$};
\node (ba) at  (5.5,8) {$\Smiley[1][green]$};
\node (bb) at  (6.5,8) {$\Smiley[1][green]$};
\node (ca) at  (8.5,8) {$\Smiley[1][green]$};
\node (cb) at  (9.5,8) {$\Smiley[1][green]$};
\node (da) at  (13,8) {$\Smiley[1][green]$};
\node (ea) at  (16,8) {$\Smiley[1][green]$};
\node (fa) at  (19,8) {$\Smiley[1][green]$};
\node (ga) at  (22,8) {$\Smiley[1][green]$};
\draw (foot) -- (a);
\draw (foot) -- (b);
\draw (foot) -- (c);
\draw (foot) -- (d);
\draw (foot) -- (e);
\draw (foot) -- (f);
\draw (foot) -- (g);
\draw (foot) -- (h);
\draw (foot) -- (i);
\draw (a) -- (aa);
\draw (a) -- (ab);
\draw (b) -- (ba);
\draw (b) -- (bb);
\draw (c) -- (ca);
\draw (c) -- (cb);
\draw (d) -- (da);
\draw (e) -- (ea);
\draw (f) -- (fa);
\draw (g) -- (ga);
\end{tikzpicture}

  \caption{The hydra (\texttt{hyd 3 4 2})}
  \label{fig:hinit-plusn}
\end{figure}

With these notations, we get a formal description of the first three rounds.

\input{movies/snippets/BigBattle/L23L03}

\subsection{Testing  \dots}
In order to study \emph{experimentally} the different  configurations of the  battle, we will use a simple data type for representing the states as tuples composed of
the round number, and the respective number of daughters  \texttt{h2}, \texttt{h1}, and heads
of the current hydra.

\input{movies/snippets/BigBattle/stateDef}

The following function returns the next configuration of the game.
Note that this function is defined only for making experiments and is not  ``certified''.  Formal proofs about our battle only start with the lemma
\texttt{step\_battle}, page~\pageref{lemma:step-battle}.

\input{movies/snippets/BigBattle/nextDef}

We can make bigger steps through iterations of \texttt{next}.
The functional \texttt{iterate}, similar to Standard Library's \texttt{Nat.iter},
is defined and studied in~\href{../theories/html/hydras.Prelude.Iterates.html\#iterate}{Prelude.Iterates}.
\index{hydras}{Library Prelude!iterate}

\label{Functions:iterate}

\input{movies/snippets/Iterates/iterateDef}

The following function computes the state of the battle at the $n$-th round.

\input{movies/snippets/BigBattle/testDefTests}

The battle we are studying looks to be awfully long. Let us concentrate our
tests on some particular events : the states where $\texttt{nh}=0$.
From the value of \texttt{test 5},  it is obvious that at the 10-th round, the counter \texttt{nh} is equal to zero.

\input{movies/snippets/BigBattle/smartTest}

Thus, $(1 + 11)$ rounds later, the \texttt{n1} field is equal to $2$, and
\texttt{nh}   to $0$.

\input{movies/snippets/BigBattle/smartTestb}

Next round, we decrement \texttt{n2} and set \texttt{n1} to $95$.

\input{movies/snippets/BigBattle/smartTestc}

We now have some intuition of the sequence.
It looks like the next ``\texttt{nh}=0'' event will happen at the $192=2(95+1)$-th round, then at the $2(192+1)$-th round, etc.

\input{movies/snippets/BigBattle/doubleS}

\subsection{Proving \dots}
We are now able to reason about the sequence of transitions defined by our hydra battle. Instead of using the data-type \texttt{state} we study the relationship
between different configurations of the battle.

Let us define a binary relation associated with every round of the battle.
In the following definition \texttt{i} is associated with the round number (or date, if we consider a discrete time), and \texttt{a}, \texttt{b}, \texttt{c} respectively associated with the number of \texttt{h2}, \texttt{h1} and heads connected to the hydra's foot.

\input{movies/snippets/BigBattle/oneStep}

The relation between \texttt{one\_step} and the rules of hydra battles is asserted by the following lemma.

\label{lemma:step-battle}

\input{movies/snippets/BigBattle/stepBattle}

\vspace{4pt}

Next, we define ``big steps'' as the transitive closure of \texttt{one\_step},
and reachability (from the initial configuration of figure~\ref{fig:hinit} at time $0$).

\input{movies/snippets/BigBattle/steps}

The following lemma establishes a relation between \texttt{steps} and the predicate \texttt{battle}.

\input{movies/snippets/BigBattle/stepsBattle}

\vspace{4pt}

Thus, any result about \texttt{steps} will be applicable to standard battles.
Using the predicate \texttt{steps},  our study of the length of the considered battle
can  be decomposed into three parts:

\begin{enumerate}
\item  Characterization of regularities of some events
\item Study of the beginning of the battle
\item Computing the exact length of the battle.
\end{enumerate}

First, we prove that, if at round $i$ the hydra is equal to
(\texttt{hyd a (S b) 0}), then it will be equal to (\texttt{hyd a b 0}) at the $2(i+1)$-th round.

\vspace{4pt}

\input{movies/snippets/BigBattle/LS}

From now on, the lemma \texttt{reachable\_S} allows us to watch larger and larger steps of
the battle.

\input{movies/snippets/BigBattle/L4}

\input{movies/snippets/BigBattle/L10To95}

\subsection{Giant steps}

We are now able to make bigger steps in the simulation of the battle.
First, we iterate the lemma \texttt{reachable\_S}.

\vspace{4pt}

\input{movies/snippets/BigBattle/Bigstep}

\vspace{4pt}

Applying lemmas \texttt{BigStep} and \texttt{L95} we make a first jump.

\vspace{4pt}

\input{movies/snippets/BigBattle/MDef}

Figure~\ref{fig:HM}  represents the hydra at the $M$-th round.
At the $(M+1)$-th round, it will look like in fig~\ref{fig:HM-plus1}.

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.5]
\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (3,4) {$\Smiley[2][green]$};
\node (N3) at (1,4) {$\Smiley[2][green]$};
\draw (foot) -- (N1);
\draw (N1) to [bend right =15] (N2);
\draw (N1) to  [bend left=15](N3);
\end{tikzpicture}
\caption{\label{fig:HM}}
The state of the hydra after $M$ rounds.
% The hydra \texttt{h} of the proof that \(\omega^2\) is too small for proving Hercules' victory

\end{figure}

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.5]
\node (foot) at (10,0) {$\bullet$};
\node (N1) at (0,5) {$\bullet$};
\node (N12) at (0,8) {$\Smiley[2][green]$};
\node (N2) at (2,5) {$\bullet$};
\node (N22) at (2,8) {$\Smiley[2][green]$};
\node (N3) at (4,5) {$\bullet$};
\node (N32) at (4,8) {$\Smiley[2][green]$};
\node (N4) at (6,5) {$\bullet$};
\node (N42) at (6,8) {$\Smiley[2][green]$};

\node (Ndots) at (12,8) {\Huge $\dots$};
\node (Ndots2) at (12,5) {\Huge $\dots$};

\node (N8) at (18,5) {$\bullet$};
\node (N82) at (18,8) {$\Smiley[2][green]$};
\node (N9) at (20,5) {$\bullet$};
\node (N92) at (20,8) {$\Smiley[2][green]$};

\draw (foot) -- (N1);
\draw (foot) -- (N2);
\draw (foot) -- (N3);
\draw (foot) -- (N4);
\draw (foot) -- (N8);
\draw (foot) -- (N9);
\draw (N1) to  (N12);
\draw (N2) to  (N22);
\draw (N3) to  (N32);
\draw (N4) to  (N42);
\draw (N8) to  (N82);
\draw (N9) to  (N92);
\end{tikzpicture}
\caption{\label{fig:HM-plus1}}
The state of the hydra after $M+1$ rounds (with $M+1$ heads).

\end{figure}

\input{movies/snippets/BigBattle/L295S}

\vspace{4pt}

Then, applying once more the lemma \texttt{BigStep}, we get the exact time when
Hercules wins!

\vspace{4pt}

\input{movies/snippets/BigBattle/NDef}

\vspace{4pt}

We are now able to prove formally that the considered battle is
composed of $N$ steps.

\vspace{4pt}

\input{movies/snippets/BigBattle/Done}

\subsection{A minoration lemma}

Now, we would like to get an intuition of  how big the number $N$ is.
For that purpose, we use a minoration of the function \texttt{doubleS} by the
function (\texttt{fun n => 2 * n}).

\vspace{4pt}

\input{movies/snippets/Exp2/exp2Def}

\vspace{4pt}

Using a few facts (proven in
\href{../theories/html/hydras.Hydra.BigBattle.html}{hydras.Hydra.BigBattle}),we get several  minorations.

\input{movies/snippets/BigBattle/minorationLemmas}

\vspace{4pt}

The number $N$ is greater than or  equal to $2^{2^{95}\times 95}.$ If we wrote $N$ in base $10$, $N$ would require at least $10^{30}$ digits!

\section{Generic properties}

The example we just studied shows that the termination of any battle may take a very long time. If we want to study hydra battles in general, we have to consider
any hydra and any strategy, both for Hercules and the hydra itself. So, we first  give some definitions, generally borrowed from transition systems vocabulary (see~\cite{tel_2000} for instance).

\subsection{Liveliness}

Let $B$ be an instance of \texttt{Battle}. We say that $B$ is \emph{alive} if
for any configuration $(i,h)$, where $h$ is not a head, there exists a further step in class $B$.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#Alive}{Hydra.Hydra\_Definitions}}

\input{movies/snippets/Hydra_Definitions/AliveDef}

The theorems \texttt{Alive\_free} and \texttt{Alive\_standard} of the module
\href{../theories/html/hydras.Hydra.Hydra_Theorems.html}{Hydra.Hydra\_Theorems} show that the classes \texttt{free} and \texttt{standard} satisfy this property.

\input{movies/snippets/Hydra_Theorems/AliveThms}

Both theorems are proved with the help of the  following strongly specified function:

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Lemmas.html\#next_round_dec}{Hydra.Hydra\_Lemmas}}

\input{movies/snippets/Hydra_Lemmas/nextRoundDec}

\subsection{Termination}

The termination of \emph{any}  battle is naturally expressed by the predicate \texttt{well\_founded} defined in the module \href{https://coq.inria.fr/distrib/current/stdlib/Coq.Init.Wf.html}{Coq.Init.Wf}
 of the Standard Library.

\index{hydras}{Library Hydra!Predicates!Termination}

\input{movies/snippets/Hydra_Definitions/TerminationDef}

Let $B$ be an instance of class \texttt{Battle}. A \emph{variant} for $B$ consists
in a well-founded relation $<$  on some type \texttt{A}, and a function
(also called a \emph{measure}) \texttt{m:Hydra->A} such that for any successive steps $(i,h)$ and $(1+i,h')$  of a battle in $B$, the inequality $m(h')<m(h)$ holds.

\vspace{4pt}
\noindent

\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Definitions.html\#Hvariant}{Hydra.Hydra\_Definitions}}

\label{sect:hvariant-def}

\index{hydras}{Library Hydra!Type classes!Hvariant}

\input{movies/snippets/Hydra_Definitions/HvariantDef}

\index{hydras}{Exercises}

\begin{exercise}
 Prove that, if there exists some  instance of (\texttt{Hvariant Lt wf\_Lt $B$ $m$}), then there exists no infinite battle in  $B$.
\end{exercise}

\subsection{A  small proof of impossibility}
\index{coq}{Proofs of impossibility}

\label{omega-case}

When one wants to prove a termination theorem with the help of a variant,
one has to consider first a well-founded set $(A,<)$, then a strictly decreasing measure on this set.  The following two lemmas show that if  the order structure $(A,<)$ is too simple, it is useless to look for a convenient measure, which simply no exists. Such kind of result is useful, because it saves you time and effort.

The best known well-founded order is the natural order on the set $\mathbb{N}$ of natural numbers (the type \texttt{nat} of Standard library). It would be interesting to look for some measure $m:\texttt{nat}\arrow\texttt{nat}$ and prove it is a variant.

Unfortunately, we can prove that
\emph{no} instance of class (\texttt{WfVariant round Peano.lt $m$}) can be built, where
$m$ is \emph{any} function of type \texttt{Hydra $\arrow$ nat}.

Let us present the main steps of that proof, the script of which  is in the module ~\href{../theories/html/hydras.Hydra.Omega_Small.html}{Hydra/Omega\_Small.v} \footnote{ The name of this file means ``the ordinal $\omega$ is too small for proving the termination of [free] hydra battles ''. In effect, the elements of $\omega$, considered as a set, are just the natural numbers (see next chapter for more details)}.

%\subsubsection{Preliminaries}

Let us assume there exists some variant $m$ from \texttt{Hydra} into \texttt{nat} for proving
    the  termination of all hydra battles.

\input{movies/snippets/Omega_Small/omegaSmalla}

We define an injection $\iota$ from the type \texttt{nat} into \texttt{Hydra}.
For any natural number $i$, $\iota(i)$ is the hydra composed of a foot and
$i+1$ heads at height $1$. For instance, Fig.~\ref{fig:flower} represents the hydra $\iota(3)$.

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.5]
\node (foot) at (4,0) {$\bullet$};
\node (N1) at (2,2) {$\Smiley[2][green]$};
\node (N2) at (4,2) {$\Smiley[2][green]$};
\node (N3) at (6,2) {$\Smiley[2][green]$};
\node (N4) at (8,2) {$\Smiley[2][green]$};
\draw (foot) to [bend left =25] (N1);
\draw (foot) to [bend left =15] (N2);
\draw (foot) to [bend right =15] (N3);
\draw (foot) to [bend right =25] (N4);
\end{tikzpicture}
\caption{\label{fig:flower}
The hydra $\iota(3)$}
\end{figure}

\input{movies/snippets/Omega_Small/iotaDef}

Let us consider now some hydra \texttt{big\_h} out of the range of the injection $\iota$ (see Fig.~\vref{fig:h-omega-omega}).

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.5]
\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (2,4) {$\Smiley[2][green]$};
\draw (foot) -- (N1);
\draw (N1) to  (N2);
\end{tikzpicture}
\caption{\label{fig:h-omega-omega}}
 The hydra \texttt{big\_h}.
\end{figure}

\input{movies/snippets/Omega_Small/bigHDef}

 Using the functions $m$ and $\iota$, we define a second hydra \texttt{small\_h}, and show
 there is a one-round battle that transforms \texttt{big\_h} into \texttt{small\_h}. Please note that,
due to the hypothesis \texttt{Hvar}, we are interested in the termination of \emph{free} battles.
There is no problem to consider a round with (\texttt{m big\_h}) as the replication factor.

\input{movies/snippets/Omega_Small/smallHDef}

But, by hypothesis, $m$ is a variant. Hence, we infer the following inequality.

\vspace{4pt}

\input{movies/snippets/Omega_Small/mLt}

In order to get a contradiction, it suffices to  prove the inequality
$m(\texttt{big\_h}) \leq m(\texttt{small\_h})$ i.e.,  $m(\texttt{big\_h}\leq m(\iota (m(\texttt{big\_h})))$.

\input{movies/snippets/Omega_Small/mGea}

Intuitively, it means that, from any hydra of the form (\texttt{iota $i$}), the battle will
take (at least) $i$ rounds. Thus the associated measure cannot be less than $i$.
Technically, we prove this lemma by Peano induction on $i$.

\begin{itemize}
\item The base case $i=0$ is trivial
\item Otherwise, let $i$ be any natural number and assume  the inequality
  $i \leq m(\iota(i))$.
  \begin{enumerate}
  \item  But the hydra $\iota(S(i))$ can be transformed in one round into
    $\iota(i)$ (by losing its rightmost head, for instance)
  \item Since $m$ is a variant, we have $m(\iota(i)) < m(\iota(S(i)))$,
    hence  $i< m(\iota(S(i)))$, which implies  $S(i)\leq  m(\iota(S(i)))$.
  \end{enumerate}
\end{itemize}

We are now ready to complete our impossibility proof.

\vspace{4pt}

\inputsnippets{Omega_Small/mGeb, omega_Small/mGez,
  Omega_Small/omegaSmallz}

\index{hydras}{Exercises}

\begin{exercise}
Prove that there exists no variant $m$ from \texttt{Hydra} into \texttt{nat} for proving
    the  termination of all \emph{standard} battles.
\end{exercise}

\subsubsection{Conclusion}

In order to build a variant for proving the termination of all hydra battles, we need to consider order structures more complex than the usual order on type \texttt{nat}.
The notion of \emph{ordinal number} provides a catalogue of well-founded order types.
For a reasonably large bunch of ordinal numbers, \emph{ordinal notations} are data-types which allow the \coq{} user to define functions, to compute and prove some properties, for instance by reflection.

The next chapter is dedicated to a generic formalization of ordinal notations, and chapter~\ref{chap:T1} to a proof of termination of all hydra battles with the help of an ordinal notation for the interval $[0,\epsilon_0)$\,\footnote{We use the mathematical notation $[a,b)$ for the interval $\{x|a\leq x < b\}$.}.
\index{maths}{Notations!Interval}

%--------------------------------------------------------------

\chapter{Introduction to ordinal numbers and ordinal notations}

The proof of termination of all hydra battles presented in~\cite{KP82} is based
on \emph{ordinal numbers}.
From a mathematical point of view, an ordinal is a representative of an equivalence class for isomorphisms of  totally ordered well-founded sets.

For the computer scientist, ordinals are tools for proving the totality of a given recursive function, or termination of a transition system. \emph{Ordinal arithmetic}
provides a set of functions whose properties, like \emph{monotony}, allow to define \emph{variants}, \emph{i.e.} strictly decreasing measures used in proofs of termination.

\vspace{4pt}

Let us have a look at Figure~\ref{fig:ordinal-sequence}. It presents a few items of a  sequence of ordinal numbers, which extends the sequence of natural numbers.

\begin{figure}[h]
  \centering
\fbox{\Large
  \begin{minipage}{1.0\linewidth}
  \begin{align*}
     &\textcolor{blue}{0},\,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,\ldots\\
&\textcolor{red}{\omega},\,\omega+1,\omega+2,\omega+3,\ldots\\
&\textcolor{red}{\omega\times 2},\,\omega\times 2+1,\ldots, \textcolor{red}{\omega\times 3},\,\omega\times 3+1,\ldots, \textcolor{red}{\omega\times 4},\ldots\\
&\textcolor{red}{\omega^2},\ldots, \textcolor{red}{\omega^2\times 42},\ldots,\textcolor{red}{\omega^3},\ldots, \textcolor{red}{\omega^4},\omega^4+1,\ldots\\
&\textcolor{red}{\omega^\omega},\ldots, \textcolor{red}{\omega^\omega+\omega^7\times 8},\ldots,\textcolor{red}{\omega^\omega\times 2},\omega^\omega\times 2+1, \ldots\\
&\textcolor{red}{\omega^{\omega^\omega}},\ldots, \textcolor{red}{\omega^{\omega^\omega}+\omega^\omega\times 42+ \omega^{55}+\omega}, \ldots, \textcolor{red}{\omega^{\omega^{\omega+1}}}, \omega^{\omega^{\omega+1}}+1,\dots\\
& \textcolor{red}{\epsilon_0 (= \omega^{\epsilon_0)}}, \epsilon_0+1, \epsilon_0+2, \epsilon_0+3, \ldots\\
& \textcolor{red}{\epsilon_1}, \ldots, \textcolor{red}{\epsilon_2}, \ldots, \textcolor{red}{\epsilon_\omega},\ldots \\
& \textcolor{red}{\Gamma_0}, \Gamma_0+1, \Gamma_0+2, \Gamma_0+3,\ldots, \textcolor{red}{\Gamma_0+\omega}, \ldots\\
&\ldots
  \end{align*}
  \end{minipage}}

  \caption{A short overview of the sequence of ordinal numbers}
  \label{fig:ordinal-sequence}
\end{figure}

Let us comment some features of this figure:

\begin{itemize}
\item The ordinals are listed in a strictly increasing order.
\item Dots : ``$\ldots$'' stand for  infinite sequences of ordinals, not shown for lack of space. For instance, the ordinal $42$ is not shown in the first line, but it exists, somewhere between $17$ and $\omega$.
\item Each ordinal printed in black is the immediate successor of another ordinal. We call it a \emph{successor} ordinal. For instance, $12$ is the successor of $11$, and $\omega^4+1$ the successor of $\omega^4$.
\item Ordinals (displayed in red)  that  follow immediately dots are called \emph{limit ordinals}. With respect to the order induced by this sequence, any limit ordinal $\alpha$ is the least upper bound of  the set $\mathbb{O}_\alpha$ of all ordinals strictly less than $\alpha$.
\item
For instance $\omega$ is the least upper bound of the set of all finite ordinals (in the first line). It is also the first limit ordinal, and the first infinite ordinal, in the sense that
the set $\mathbb{O}_\omega$ is infinite.
\item The ordinal $\epsilon_0$ is the first number which is equal to its own exponential of base $\omega$. It plays an important role in proof theory, and is particularly studied in chapters~\ref{chap:T1} to \ref{chap:alpha-large}.
\item Any ordinal is  either the ordinal \textcolor{blue}{$0$},
a successor ordinal, or a \textcolor{red}{limit ordinal}.
\end{itemize}

\section{The mathematical point of view}

\subsection{Well-ordered sets}
Let us start with some definitions.
A  \emph{well-ordered set} is a set provided with a binary relation $<$ which has the following properties.
\begin{description}
\item[irreflexivity] : $\forall x\in A, x\not< x$
\item[transitivity] : $\forall x\,y\,z\in A, x<y \Rightarrow y<z \Rightarrow x<z$
\item[trichotomy]: $\forall x\,y\in A, x<y \vee x = y \vee y < x$
\item[well foundedness]: $<$ is well-founded (every element of $A$ is accessible)\footnote{In classical mathematics, we would say that there is no infinite sequence $a_1>a_2> \dots a_n> a_{n+1}\dots$ in $A$. In contrast, \coq's standard library contains
an inductive definition of a predicate \texttt{Acc} which allows us to write
constructive proofs of accessibility (See \href{https://coq.inria.fr/distrib/current/stdlib/Coq.Init.Wf.html}{Coq.Init.Wf}).}.
\end{description}

The best known examples of well-ordered sets are the set $\mathbb{N}$ of natural numbers (with the usual order $<$), as well as any finite segment $[0,i)=\{j\in\mathbb{N}\,|\,j<i\}$.
The disjoint union of two copies of $\mathbb{N}$, \emph{i.e.} the set $\{0,1\}\times\mathbb{N}$ is also well-ordered,
with respect to the order below:

\begin{align*}
(i,j) < (i,k) & \;\textit{\textbf{if} }\; j < k\\
(0,k) < (1,l) & \;\textit{\textbf{for\,any}}\;k \;\textit{\textbf{and}} \; l
\end{align*}

\subsection{Ordinal numbers}

\index{maths}{Ordinal numbers}

Let $(A,<_A)$ and $(B,<_B)$ two well-ordered sets. $A$ and $B$ are said to have \emph{the same order type} if
there exists a strictly monotonous bijection $b$ from $A$ to $B$, \emph{i.e.} which verifies the proposition
$\forall x\,y\in A,\, x <_A y \Rightarrow b(x) <_B  b(y)$.

Having the same order type is an equivalence relation between well-ordered sets. Ordinal numbers (in short: \emph{ordinals})  are descriptions (\emph{names}) of the equivalence classes.
For instance, the order type of $(\mathbb{N},<)$ is associated with the ordinal called  $\omega$, and the order we considered on
the disjoint union of $\mathbb{N}$ and itself is named $\omega+\omega$.

In a set-theoretic framework, one can consider any ordinal $\alpha$ as a well-ordered set, whose  elements are just the ordinals strictly less than $\alpha$, \emph{i.e.} the \emph{segment} $\mathbb{O}_\alpha=[0, \alpha)$. So, one can speak about \emph{finite}, \emph{infinite}, \emph{countable}, etc., ordinals. Nevertheless, since we work within type theory,
we do not identify ordinals as sets of ordinals, but consider the correspondence between ordinals and sets of ordinals as the function that maps $\alpha$ to $\mathbb{O}_\alpha$.
For instance $\mathbb{O}_\omega=\mathbb{N}$, and $\mathbb{O}_7=\{0,1,2,3,4,5,6\}$.

We cannot cite all the literature published on ordinals since Cantor's book
\cite{cantorbook}, and
leave it to the reader to explore the bibliography.

\section{Ordinal numbers in Coq}

Two kinds of representation of ordinals are defined in our development.

\begin{itemize}
\item A ``mathematical'' representation of the set of countable ordinal numbers, after Kurt Schütte~\cite{schutte}. This representation uses several (hopefully harmless) axioms. We use it as a reference for proving the correctness of ordinal notations.
\item A family of \emph{ordinal notations} (also called \emph{[ordinal] notation systems}), \emph{i.e.} data types used to represent segments $[0,\mu)$, where $\mu$ is some countable ordinal. Each ordinal notation is defined inside the Calculus of Inductive Constructions (without axioms). Many functions are defined, allowing proofs by computation. Note that proofs of
correctness of a given ordinal notation with respect to Schütte's model obviously use axioms.
Please execute the \texttt{Print Assumptions} command in case of doubt.
\end{itemize}

% \section{Countable ordinals}

% Chapter~\ref{chap:schutte} of this document presents an adaptation to \coq{} of an axiomatization in classical logic of the set of countable ordinals by K. Schütte~\cite{schutte}.
% That formalization is quite complex, technical and unshamedly non-constructive,  so we put its description  in the last chapter of this document.

% Please note that Schütte considers the (uncountable) set $\mathbb{O}$ of all countable ordinals. This set is well ordered (which is one of Schütte's axioms), and associates to any ordinal $\alpha$ the segment $\mathbb{O}_\alpha$ of all ordinals strictly less than $\alpha$.

% In our adaptation to \coq{}, we declare a type \texttt{Ord}, a binary relation \texttt{lt} (with infix notation \texttt{"\_<\_"}, and assume Schütte's axiom. In Chapter~\ref{chap:schutte},
% we derive some interesting properties of countable ordinals from these axioms.

It is interesting to compare proofs of a given property (for instance the associativity of addition) both in the computational framework of some ordinal notation, and in the axiomatic model of Schütte.

\section{Ordinal Notations}

Fortunately, the ordinals we need for  studying hydra battles are much simpler than Schütte's, and can be represented as quite simple data types in \gallina.

Let $\alpha$ be some (countable) ordinal;
in \coq{} terms, we call \emph{ordinal notation for $\alpha$} a structure composed
of:
\begin{itemize}
\item A data type $A$ for representing all ordinals strictly below $\alpha$,
\item A well founded order $<$ on $A$,
\item A correct function for comparing two ordinals. Note  that the reflexive closure of $<$ is thus a \emph{total order}.
\end{itemize}

Such a structure can be proved correct relatively to a bigger ordinal notation or
to Schütte's model.

\subsection{A class for ordinal notations}

From the \coq{} user's point of view, an ordinal notation is
a structure allowing to compare two ordinals by computation, and proving by well-founded induction.

\subsubsection{The \texttt{Comparable class}}

The following class, contributed by Jérémy Damour and Théo Zimmermann, allows us to apply generic lemmas and tactics
about decidable strict orders.
The correctness of the comparison function is expressed through Stdlib's type
\texttt{Datatypes.CompareSpec}.

\begin{Coqsrc}
Inductive CompareSpec (Peq Plt Pgt : Prop) : comparison -> Prop :=
    CompEq : Peq -> CompareSpec Peq Plt Pgt Eq
  | CompLt : Plt -> CompareSpec Peq Plt Pgt Lt
  | CompGt : Pgt -> CompareSpec Peq Plt Pgt Gt.
\end{Coqsrc}

\emph{From Module~\href{../theories/html/hydras.Prelude/mparable.html\#Hvariant}{Prelude.Comparable}}

\label{sect:comparable-def}

\input{movies/snippets/Comparable/ComparableDef}

\subsubsection{The \texttt{ON} class}

The following class definition, parameterized with a type $A$, a binary relation \texttt{lt} on $A$, specifies that \texttt{lt} is a well-founded strict order, provided with a correct comparison function.

\vspace{4pt}
\noindent\emph{From
Library~\href{../theories/html/hydras.OrdinalNotations.ON_Generic.html}{OrdinalNotations.ON\_Generic}}

\label{types:ON}
\index{hydras}{Library OrdinalNotations!Type classes!ON}

\input{movies/snippets/ON_Generic/ONDef}

We give  also a few handy definitions and lemmas for any ordinal notation.

\label{sect:on-lt-notation}
\label{sect:on-le-notation}
\label{sect:measure-ON}
\label{sect:bigO-ON}

\inputsnippets{ON_Generic/ONDefsa, ON_Generic/ONDefsb}

\begin{remark}
The infix notations \texttt{o<} and \texttt{o<=} are defined in order to make apparent the distinction between the various notation scopes that may co-exist in a same statement. So the infix \texttt{<} and \texttt{<=} are reserved to the natural numbers. In the mathematical formulas, however, we still use $<$ and $\leq$ for comparing ordinals.
\end{remark}

% \subsection{Ordinal notations and  termination measures}
% \label{sect:measure-ON}

% The following lemma (together with the type class mechnism) allows us to define termination measures over any ordinal notation. It is just an application of  the libraries \texttt{Coq.Wellfounded.Inverse\_Image}
% and  \texttt{Coq.Wellfounded.Inclusion}.

% \begin{Coqsrc}
% Definition measure_lt {A:Type}{lt: relation A}
%             {compare : A -> A -> comparison}
%             {on : ON lt compare}
%             {B : Type} (m : B -> A) : relation B :=
%              fun x y => on_lt (m x) (m y).

% Lemma wf_measure  {A:Type}(lt: relation A)
%             {compare : A -> A -> comparison}
%             {on : ON lt compare}
%             {B : Type}
%             (m : B -> A):  well_founded (measure_lt m).
% \end{Coqsrc}

% A simple example of application is given in Sect.~\vref{sect:merge-example}.

\section{Example: the ordinal \texorpdfstring{$\omega$}{omega}}

The simplest example of ordinal notation is built over the type \texttt{nat} of \coq's standard library. We just have to apply already proven lemmas about Peano numbers.

\vspace{4pt}
\noindent\emph{From Library~\href{../theories/html/hydras.OrdinalNotations.ON_Omega.html}{OrdinalNotations.ON\_Omega}}

\inputsnippets{ON_Omega/OmegaDefa, ON_Omega/OmegaDefb}

\section{Sum of  two ordinal notations}

Let \texttt{NA} and \texttt{NB} be two ordinal notations, on the respective types \texttt{A} and \texttt{B}.

 We consider a new strict order
on the disjoint sum of the associated types, by putting all elements of \texttt{A} before the elements of \texttt{B} (thanks to Standard Library's relation operator \texttt{le\_AsB}).

\vspace{4pt}
\noindent
\emph{From Library~\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Relations.Relation_Operators.html}{Relations.Relation\_Operators}}.

\begin{Coqanswer}
Inductive
le_AsB (A B : Type) (leA : A -> A -> Prop) (leB : B -> B -> Prop)
  : A + B -> A + B -> Prop :=
| le_aa : forall x y : A, leA x y -> le_AsB A B leA leB (inl x) (inl y)
| le_ab : forall (x : A) (y : B), le_AsB A B leA leB (inl x) (inr y)
| le_bb : forall x y : B, leB x y -> le_AsB A B leA leB (inr x) (inr y)
\end{Coqanswer}

\pagebreak

\vspace{4pt}
\noindent\emph{From Library~\href{../theories/html/hydras.OrdinalNotations.ON_plus.html}{OrdinalNotations.ON\_plus}}

\input{movies/snippets/ON_plus/Defs}

In order to build an instance of \texttt{Comparable}, we have to define a correct comparison function.

\inputsnippets{ON_plus/compareDef,
  ON_plus/compareCorrect, ON_plus/plusComp}

The Lemma \texttt{Wellfounded.Disjoint\_Union.wf\_disjoint\_sum} of Standard Library
helps us to prove that our order \texttt{lt} is well-founded, thenwe can build an instance of \texttt{ON}:

\inputsnippets{ON_plus/ltWf, ON_plus/OnPlus}

\subsection{The ordinal \texorpdfstring{$\omega+\omega$}{omega + omega}}

The ordinal $\omega+\omega$ (also known as $\omega\times 2$) may be represented as the concatenation
of two copies of $\omega$ (Figure~\ref{fig:omega-plus-omega}).
It is also represented by the two first lines of Figure~\ref{fig:ordinal-sequence}.

\begin{figure}[h]
   \centering
   \begin{tikzpicture}[very thick, scale=0.5]
\begin{scope}[color=blue]
\node(A0) at (2,0)[label=below:$0$]{$\bullet$};
\node(A1) at (3,0)[label=below:$1$]{$\bullet$};
\node(A2) at (4,0)[label=below:$2$]{$\bullet$};
\node (Adots) at (6,0) {$\ldots$};
\node(An) at (8,0)[label=below:$n$]{$\bullet$};
\node(A2) at (10,0)[label=below:$n+1$]{$\bullet$};
\node (Adots1) at (12,0) {$\ldots$};
\end{scope}
\begin{scope}[color=red]
\node(B0) at (14,0)[label=below:$0$,label=above:\textcolor{red}{$\omega$}]{$\bullet$};
\node(B1) at (16,0)[label=below:$1$, label=above:$\omega+1$]{$\bullet$};
\node(B2) at (18,0)[label=below:$2$,label=above:$\omega+2$]{$\bullet$};
\node (Bdots) at (20,0) {$\ldots$};
\node (Bn) at (22,0) [label=below:$p$, label=above:$\omega+p$]{$\bullet$};
\node (Bdots2) at (24,0) {$\ldots$};
\end{scope}
\end{tikzpicture}
   \caption{\textcolor{blue}{$\omega+{\color{red}\omega}$}}
   \label{fig:omega-plus-omega}
 \end{figure}

We can define this notation in \coq{} as an instance of \texttt{ON\_plus}.

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Omega_plus_omega.html}{OrdinalNotations.ON\_Omega\_plus\_omega}}

\input{movies/snippets/ON_Omega_plus_omega/OmegaPlusOmegaDef}

\vspace{4pt}

We can now define abbreviations. For instance, the finite ordinals are represented by terms built with  the constructor \texttt{inl}, and the first infinite ordinal $\omega$ by the term \texttt{(inr 0)}.

\vspace{4pt}

\input{movies/snippets/ON_Omega_plus_omega/finiteOmega}

\vspace{4pt}

\input{movies/snippets/ON_Omega_plus_omega/ltOmega}

% \label{warning:coercions}
% \index{Coq!Coercions}
% \begin{remark}
% Beware of coercions and notation scopes!
% Let us consider the following goal:

% \begin{Coqsrc}
%  Goal (6 o< 8).
%  auto with arith.
% \end{Coqsrc}

% \begin{Coqanswer}
% 1 subgoal (ID 9)

%   ============================
%   6 o< 8
% \end{Coqanswer}

% Please keep in mind that the current notation scope interprets the infix \texttt{``<''} as the predicate \texttt{Omega\_plus\_omega.lt} and not \texttt{Nat.lt}. More,  the coercion mechanism converts the terms \texttt{6:nat} [resp. \texttt{8:nat} ]
% into \texttt{inl 6} [resp. \texttt{inl 8}].  So, the initial goal is correctly interpreted by \coq{}, but not as an inequality between two natural numbers.

% \begin{Coqsrc}
% Set Printing All.
% \end{Coqsrc}

% \begin{Coqanswer}
% 1 subgoal (ID 337)

%   ============================
%   @on_lt nat Peano.lt Nat.compare Omega (S (S (S (S (S (S O))))))
%     (S (S (S (S (S (S (S (S O))))))))
% \end{Coqanswer}

% Anyway, the initial goal is provable, using \texttt{le\_AsB}'s first constructor.

% \begin{Coqsrc}
%   constructor; auto with arith.
% Qed.
% \end{Coqsrc}

% \end{remark}
%

\section{Limits and successors}

Let us look again at our implementation of $\omega+\omega$. We can classify its elements into three categories:

\begin{itemize}
\item The least ordinal, \texttt{(inl 0)}, also known as  \texttt{(fin 0)}.
\item The first infinite ordinal $\omega$.
\item The remaining ordinals, either of the form \texttt{(inl (S $i$))} or \texttt{(inr (S $i$))} (in black on Figure~\ref{fig:ordinal-sequence}), called \emph{successor ordinals}.
\end{itemize}

\subsection{Definitions}
It would be interesting to specify at the most generic level, what is a zero, a successor or a limit ordinal. Let $<$ be a strict order on a type $A$.

\begin{itemize}
\item A \emph{least} element is a minorant (in the large sense) of the full set  on $A$,
\item $y$ is a \emph{successor} of $x$ if $x<y$ and there is no element between $x$ and $y$. We will also say that $x$ is a \emph{predecessor} of $y$.
\item $x$ is a \emph{limit} if $x$ is not a least element, and for any $y$ such that $yo<x$,
 there exists some $z$ such that $y<z<x$.
\end{itemize}

The following definitions are in Library \href{../theories/html/hydras.Prelude.MoreOrders.html}{Prelude.MoreOrders}.

\input{movies/snippets/MoreOrders/Defs}

\index{hydras}{Exercises}
\begin{exercise}
Prove, that, in any ordinal notation system, every ordinal has at most one predecessor, and at most one successor.

\emph{You may start this exercise with the file
\href{https://github.com/coq-community/hydra-battles/blob/master/exercises/ordinals/predSuccUnicity.v}{exercises/ordinals/predSuccUnicity.v}.}

\end{exercise}

\index{hydras}{Exercises}
\begin{exercise}
Prove, that, in any ordinal notation system, if $\beta$ is a successor of $\alpha$,
then for any $\gamma$, $\gamma<\beta$ implies
$\gamma\leq\alpha$.

\emph{You may start this exercise with the file
\href{https://github.com/coq-community/hydra-battles/blob/master/exercises/ordinals/lt_succ_le.v}{exercises/ordinals/lt\_succ\_le.v}.}
\end{exercise}

\subsection{Limits and successors in \texorpdfstring{$\omega+\omega$}{omega+omega}}

Using the definitions above, we can prove the following lemma:

\vspace{4pt}

\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Omega_plus_omega.html}{OrdinalNotations.ON\_Omega\_plus\_omega}}

\input{movies/snippets/ON_Omega_plus_omega/limitIff}

\vspace{4pt}

Regarding successors, let us define the following function and prove its correctness:

\input{movies/snippets/ON_Omega_plus_omega/succDef}

\input{movies/snippets/ON_Omega_plus_omega/succCorrect}

\vspace{4pt}

We can also check whether an ordinal is a successor by a simple computation:

\input{movies/snippets/ON_Omega_plus_omega/succb}

\vspace{4pt}

Finally, the nature of any ordinal is decidable (inside this notation system) :

\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Omega_plus_omega.html}{OrdinalNotations.ON\_Omega\_plus\_omega}}

\input{movies/snippets/ON_Omega_plus_omega/ZeroLimitSuccDec}

\section{Product of ordinal notations}

Let \texttt{NA} and \texttt{NB} be two ordinal notations, on the respective  ordered types \texttt{A} and \texttt{B}. The product of \texttt{NA} and \texttt{NB} is considered as the concatenation of $B$ copies of $A$, ordered by the lexicographic order on $B\times A$.

In \coq{}, we build an instance of class \texttt{ON} through a sequence of steps as for the sum of ordinal notations.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_mult.html}{OrdinalNotations.ON\_mult}}

\inputsnippets{ON_mult/Defs}
\inputsnippets{ON_mult/multComp,  ON_mult/ONMult}
\inputsnippets{ON_mult/endDefs}

\section{The ordinal \texorpdfstring{$\omega^2$}{omega2}}

The ordinal $\omega^2$ (also called $\phi_0(2)$, see Chap.~\ref{chap:schutte}), is an instance of the multiplication presented in the preceding section.

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Omega2.html}{OrdinalNotations.ON\_Omega2}}

\inputsnippets{ON_Omega2/Omega2Def, ON_Omega2/Defs}

\subsection{Arithmetic of \texorpdfstring{$\omega^2$}{omega^2}}

\subsubsection{Successor}

The successor of any ordinal is defined by a simple pattern-matching.

\input{movies/snippets/ON_Omega2/succ}

This function is proved to be correct w.r.t. the \texttt{Successor} predicate.

\input{movies/snippets/ON_Omega2/succOK}

\input{movies/snippets/ON_Omega2/succLemmas}

\subsubsection{Addition}

We can define on \texttt{Omega2} an addition which extends the addition on \texttt{nat}. Please note that this operation is not commutative:

\inputsnippets{ON_Omega2/plusDef, ON_Omega2/plusExamples}

\subsubsection{Multiplication}

The restriction of ordinal multiplication to the segment $[0,\omega^2)$ is not a total function.
For instance $\omega\times\omega= \omega^2$ is outside the set of represented values.
Nevertheless, we can define two operations mixing natural numbers and ordinals.

\input{movies/snippets/ON_Omega2/multFinDef}
\input{movies/snippets/ON_Omega2/multFinExamples}

Multiplication with a finite ordinal and addition are related through the following lemma:

\inputsnippets{ON_Omega2/uniqueDecompositiona,
  ON_Omega2/uniqueDecompositionb,
  ON_Omega2/uniqueDecompositionz}

\subsection{A proof of termination using \texorpdfstring{$\omega^2$}{omega^2}}
\label{sect:merge-example}.

Using the lemma of Sect.~\vref{sect:measure-ON}, we can define easily a total function which merges two lists (example contributed by Pascal Manoury).

\index{coq}{Commands!Function}

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Omega2.html}{OrdinalNotations.ON\_Omega2}}

\input{movies/snippets/ON_Omega2/Merge}

\subsection{Yet another  proof of impossibility}
\label{omega2-case}

In Sect.~\vref{omega-case}, we proved that there exists no variant from \texttt{Hydra} to \texttt{(nat,$<$)}
(\emph{i.e.} the ordinal $\omega$) for proving the termination of all hydra battles.
We  prove now that  the ordinal $\omega^2$ is also insufficient for this purpose.

The proof we are going to comment has exactly the same structure as in Section~\ref{omega-case}.
 Nevertheless, the proof of technical  lemmas is a little more complex, due to
 the structure of the lexicographic order on $\mathbb{N}\times\mathbb{N}$.
Consider for instance that there exists an infinite number of ordinals  between
$\omega$ and $\omega\times 2$.

The detailed  proof script is in the file
\href{https://github.com/coq-community/hydra-battles/blob/master/theories/ordinals/Hydra/Omega2_Small.v}{theories/ordinals/Hydra/Omega2\_Small.v}.

\subsubsection{Preliminaries}
Let us assume there is a variant from \texttt{Hydra} into $\omega^2$  for proving the   termination of all hydra battles.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Omega2_Small.html}{Hydra.Omega2\_Small}}

\input{movies/snippets/Omega2_Small/Impossibility}
\input{movies/snippets/Omega2_Small/Impossibilitya}

We  follow the same pattern as in Sect.~\ref{omega-case}.
First, we define an injection $\iota$ from type \texttt{t} into \texttt{Hydra}, by
 associating to  each ordinal $\omega\times i+ j = (i,j)$ the hydra with $i$ branches of length $2$ and
$j$ branches of length $1$.

%% revenir ici

\vspace{4pt}
\emph{From Module ~\href{../theories/html/hydras.Hydra.Omega2_Small.html\#iota}{Hydra.Omega2\_Small}}

\input{movies/snippets/Omega2_Small/Impossibilityc}

For instance, Figure~\vref{fig:essai2} shows the hydra associated to the ordinal
$(3,5)$, a.k.a. $\omega\times 3 + 5$.

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.4]
\node (foot) at (6,0) {$\bullet$};
\node (N1) at (1,3) {$\bullet$};
\node (N2) at (3,3) {$\bullet$};
\node (N3) at (5,3) {$\bullet$};
\node (N4) at (8,3) {$\Smiley[2][green]$};
\node (N5) at (11,3) {$\Smiley[2][green]$};
\node (N6) at (14,3) {$\Smiley[2][green]$};
\node (N7) at (17,3){$\Smiley[2][green]$};
\node (N8) at (20,3){$\Smiley[2][green]$};
\node  (N9) at (0,5) {$\Smiley[2][green]$};
\node (N10) at (2,5) {$\Smiley[2][green]$};
\node (N11) at (4,5) {$\Smiley[2][green]$};
\draw (foot) to [bend left=10] (N1);
\draw (foot) -- (N2);
\draw (foot) -- (N3);
\draw (foot) -- (N4);
\draw (foot) -- (N5);
\draw (foot) -- (N6);
\draw (foot) to [bend right=10] (N7);
\draw (foot) to [bend right=15] (N8);
\draw (N1) to [bend left=10] (N9);
\draw (N2) -- (N10);
\draw (N3) -- (N11);
\end{tikzpicture}
\caption{\label{fig:essai2}
The hydra $\iota(\omega\times 3+5)$}
\end{figure}

Like in Sect.~\ref{omega-case}, we build a hydra out of the range of \texttt{iota} (represented in Fig.~\vref{fig:h-omega2-small}).

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.5]
\node (foot) at (2,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (3,4) {$\Smiley[2][green]$};
\node (N3) at (1,4) {$\Smiley[2][green]$};
\draw (foot) -- (N1);
\draw (N1) to [bend right =15] (N2);
\draw (N1) to  [bend left=15](N3);
\end{tikzpicture}
\caption{\label{fig:h-omega2-small}}
 The hydra \texttt{big\_h}.
\end{figure}

\input{movies/snippets/Omega2_Small/Impossibilityb}

 In a second step, we build a ``smaller'' hydra\footnote{With respect to the measure $m$.}.

\input{movies/snippets/Omega2_Small/Impossibilityd}

\vspace{4pt}

Like in Sect.~\ref{omega-case}, we prove the double inequality \texttt{m big\_h o<= m small\_h o< m big\_h}, which is impossible.

\subsubsection{Proof of the inequality \texttt{m small\_h o< m big\_h}}

In order to prove the inequality  \texttt{m\_lt: m small\_h o< m big\_h}, it suffices to
build a battle transforming \texttt{big\_h} into \texttt{small\_h}.

First we prove that \texttt{small\_h} is reachable from \texttt{big\_h} in one or two steps. Let us decompose \texttt{m big\_h} as $(i,j)$.
If $j=0$, then one round suffices to transform \texttt{big\_h} into $\iota(i,j)$.
If $j>0$, then a first round transforms \texttt{big\_h} into $\iota(i+1,0)$ and a second round into $\iota(i,j)$. So, we have the following result.

\input{movies/snippets/Omega2_Small/bigToSmall}

Since $m$ is a variant, we infer the following inequality:

\input{movies/snippets/Omega2_Small/mLt}

\subsubsection{Proof of the inequality \texttt{m big\_h o<= m small\_h} }

The proof of the inequality \texttt{m big\_h o<= m small\_h} is quite more complex than in Sect~\ref{omega-case}.  If we consider any ordinal $\alpha=(i,j)$, where $i>0$, there exists an infinite number of
ordinals strictly less than $\alpha$, and there exists an infinite number of battles that start from
$\iota(\alpha)$. Indeed, at any configuration $\iota(k,0)$, where $k>0$, the hydra can freely choose any replication number. Intuitively, the measure of such a hydra must be large enough for taking into account
all the possible battles issued from that hydra.
Let us now give more technical details.

The first steps of our proof prepare a well-founded induction on $\omega^2$.

\input{movies/snippets/Omega2_Small/mGe}

Then a case analysis on $i$ and $j$ allows us to
consider three cases :

\begin{itemize}
\item $i=j=0$: the inequality is trivial.
\item $i=1+l, j=0$ ($(i,j)$ is a limit ordinal): By the induction hypothesis \texttt{IHij},
  $(l,k)\leq m(\iota(l,k))$ for any $k$. But (by the rules of the hydra game), $\iota(i,0)$ is transformed into any $\iota(l,k)$ in one round. Thus $m(\iota(l,k)) < m(\iota(i,0))$ for any $k$.
  Therefore, $(l,k) <  m(\iota(i,0))$ for any $k$, thus
  $(i,0) \leq m(\iota(i,0))$.
 \item $j= l+1$  ($(i,j)$ is a successor).  a similar, but simpler case: we apply the induction hypothesis to the pair $(i,l)$.
 \end{itemize}

 Please look at the proof script for more details.

 \input{movies/snippets/Omega2_Small/mGeb}

\subsubsection{End of the proof}
From \texttt{m\_ge}, we get \texttt{m big\_h o<= m small\_h = m (iota (m big\_h)) }.
Since $<$ is a strict order (irreflexive  and transitive), this inequality is incompatible with the strict inequality  \texttt{m small\_h o< m big\_h} (lemma \texttt{m\_lt}).

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Omega2_Small.html\#Impossible}{Hydra.Omega2\_Small}}

  \input{movies/snippets/Omega2_Small/Impossible}

\index{hydras}{Exercises}

\begin{exercise}
Prove that there exists no variant $m$ from \texttt{Hydra} into $\omega^2$ for proving
    the  termination of all \emph{standard} battles.
\end{exercise}

\begin{remark}
In Chapter~\ref{ks-chapter}, we  prove a generalization of the impossibility lemmas of
Sect.~\ref{omega-case} and this section, with the same proof structure, but with much more
complex technical details.
 \end{remark}

% \index{Exercises}
% \begin{exercise}

% \label{sec:orgheadline63}
% Write \emph{direct} proofs ({i.e.},  without applying the result and tools of Chap.~\ref{ks-chapter}) that the following data structures  are too simple for defining a variant for any hydra battle.

% \begin{itemize}
% \item  $\omega^n$ : the set of all $n$-uples of natural numbers, ordered  by
%   lexicographic ordering
% \item  $\omega^\omega$: the set of all decreasing sequences (with respect to $\le$)  of natural numbers, ordered by lexicographic ordering on lists.

% For instance, the following inequality holds:
% \[\langle 4,3,3,3,3,3,3,2,2,2 \rangle\,<\,\langle 4,4,2 \rangle\]
% \end{itemize}

% \end{exercise}

\section{A notation for finite ordinals}

Let $n$ be some natural number. The segment associated with $n$ is the interval
$[0,n)\,=\,\{0,1,\dots,n-1\}$.
One may represent the ordinal $n$ by a sigma type.

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Finite.html}{OrdinalNotations.ON\_Finite}}

\label{def: Finite-ord-type}

\input{movies/snippets/ON_Finite/Defs}

For instance, let us build two elements of the segment $[0, 7)$, \emph{i.e.} two
inhabitants of   type (\texttt{t 7}), and prove a simple  inequality (see Fig.~\ref{fig:O7}).

\begin{figure}[h]
\centering
\begin{tikzpicture}[very thick, scale=0.6]

\node (N0) at (0,0) {$\bullet$};
\node (i0) at (0,1) {$0$};
\node (N1) at (2,0) {$\bullet$};
\node (i1) at (2,1) {$1$};
\node (N2) at (4,0) {$\bullet$};
\node (i2) at (4,1) {$2$};
\node (N3) at (6,0) {$\bullet$};
\node (i3) at (6,1) {$3$};
\node (N4) at (8,0) {$\bullet$};
\node (i4) at (8,1) {$4$};
\node (N5) at (10,0) {$\bullet$};
\node (i5) at (10,1) {$5$};
\node (N6) at (12,0) {$\bullet$};
\node (i6) at (12,1) {$6$};
\node(alpha1) at (4,-1) {$\alpha_1$};
\node(alpha2) at (10,-1) {$\beta_1$};
\end{tikzpicture}

\caption{The segment $\mathbb{O}_7$\label{fig:O7}}
\end{figure}

\index{coq}{Commands!Program}

\input{movies/snippets/ON_Finite/Example1}

Note that the type (\texttt{t 0}) is empty, and that, for any natural number
 $n$, $n$ does not belong to (\texttt{t $n$}).

 \input{movies/snippets/ON_Finite/t0Empty}

\begin{Coqsrc}
Program Definition bad : t 10 := 10.
Next Obligation.
\end{Coqsrc}

\begin{Coqanswer}
1 subgoal (ID 118)

  ============================
  10 <? 10
\end{Coqanswer}

\begin{Coqsrc}
  compute.
Abort.
\end{Coqsrc}

%\input{movies/snippets/ON_Finite/bad}

In order to build an instance of \texttt{ON}, we define a comparison function,  and prove its correctiness.

\vspace{4pt}

\input{movies/snippets/ON_Finite/compareDef}

\begin{remark}
 The proof of \texttt{compare\_correct} uses a well-known pattern of \coq{}.
Let us consider  the following subgoal.

\begin{Coqanswer}
 1 subgoal (ID 110)

  n, x0 : nat
  i, i0 : x0 <? S n
  ============================
  exist (fun i1 : nat => i1 <=? n) x0 i =
  exist (fun i1 : nat => i1 <=? n) x0 i0
\end{Coqanswer}

Applying the tactic \texttt{f\_equal} generates a simpler subgoal.

\begin{Coqanswer}
1 subgoal (ID 112)

  n, x0 : nat
  i, i0 : x0 <? S n
  ============================
  i = i0
\end{Coqanswer}

We have now to prove that there exists at most one  proof of (\texttt{Nat.ltb x0 (S n)}). This is not obvious, but  a consequence of the following lemma of library
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Logic.Eqdep_dec.html}{Coq.Logic.Eqdep\_dec}.

\index{Coq}{Unicity of equality proofs}
\label{sect:eq-proof-unicity}

\begin{Coqanswer}
eq_proofs_unicity_on :
forall (A : Type) (x : A),
(forall y : A, x = y \/ x <> y) ->
forall (y : A) (p1 p2 : x = y), p1 = p2
\end{Coqanswer}

Thus unicity of proofs of \texttt{Nat.ltb x0 (S n)}  comes from the decidability of
equality on type \texttt{bool}.
This is why we used the boolean function \texttt{Nat.ltb} instead of the inductive predicate \texttt{Nat.lt} in the definition of type \texttt{t $n$} (see page~\pageref{def: Finite-ord-type}).
For more information about this pattern, please look at the numerous mailing lists and
FAQs on \coq{}).

\end{remark}

Please note  that attempting to compare a term  of type (\texttt{t $n$}) with a term of
type (\texttt{t $p$})  leads to an error if $n$ and $p$ are not convertible.

\input{movies/snippets/ON_Finite/Example2}

Applying lemmas of the libraries \texttt{Coq.Wellfounded.Inverse\_Image}, \linebreak
 \texttt{Coq.Wellfounded.Inclusion}, and \texttt{Coq.Arith.Wf\_nat}, we prove that our
relation \texttt{lt} is well founded.

\input{movies/snippets/ON_Finite/ltWf}

Now we can build our instance of \texttt{OrdinalNotation}.

\input{movies/snippets/ON_Finite/ONInstance}

\begin{remark}
It is important to keep in mind  that the integer $n$ is not an ``element'' of \texttt{FinOrd $n$}. In set-theoretic presentations of ordinals, the set associated with the ordinal $n$ is $\{0,1,\dots,n-1\}$.
In our formalization, the interpretation of an ordinal as a set is realized by the function \texttt{bigO} (see Section\vref{sect:bigO-ON}).
\end{remark}

\begin{remark}
 There is no interesting arithmetic on finite ordinals, since functions like successor, addition, etc.,  cannot be represented in \coq{} as \emph{total} functions.
\end{remark}

\begin{remark}
Finite ordinals are also formalized in MathComp~\cite{MCB}.  See also Adam Chlipala's \emph{CPDT}~\cite{chlipalacpdt2011} for a thorough study of the use of dependent types.
\end{remark}

%%%

\section{Comparing two ordinal notations}

It is sometimes useful to compare two ordinal notations with respect to expressive power
(the segment of ordinals  they represent).

The following class specifies a strict inclusion of segments. The notation \texttt{OA} describes a segment $[0,\alpha)$, and \texttt{OB} is a larger segment (which contains a notation for $\alpha$, whilst $\alpha$ is not represented in \texttt{OA}). We require also  that the comparison functions of the two notation systems are compatible.

\begin{figure}[h]
   \centering
   \begin{tikzpicture}[very thick, scale=0.6]
\begin{scope}[color=blue]
\node (A) at (0,0) {$A$};
\node(A0) at (2,0)[label=below:$0$]{$\bullet$};
\node(A1) at (3,0)[label=below:$1$]{$\bullet$};
\node(A2) at (4,0)[label=below:$2$]{$\bullet$};
\node (Adots) at (6,0) {$\ldots$};
\end{scope}
\begin{scope}[color=red]
\node (B) at (0,2) {$B$};
\node(B0) at (2,2)[label=above:$0$]{$\bullet$};
\node(B1) at (3,2)[label=above:$1$]{$\bullet$};
\node(B2) at (4,2)[label=above:$2$]{$\bullet$};
\node (Bdots) at (6,2) {$\ldots$};
\node (b) at (8,2) [label=above:$\omega$]{$\bullet$};
\node (bsucc) at (9,2) [label=above:$\omega+1$]{$\bullet$};
\node (Bdots2) at (10,2) {$\ldots$};
\end{scope}
\begin{scope}[color=red!50!blue]
\draw [->,thin] (A0) -- node [auto] {$\iota$} (B0);
\draw [->,thin] (A1) -- node [auto] {$\iota$} (B1);
\draw [->,thin] (A2) -- node [auto] {$\iota$} (B2);
\draw [->,thin] (Adots) -- node [auto] {$\iota$} (Bdots);
\end{scope}
\end{tikzpicture}
   \caption{\textcolor{blue}{$A$} is a sub-segment  of \textcolor{red}{$B$}}
   \label{fig:subsegment}
 \end{figure}

If \texttt{OB} is presumed to be correct, then we may consider that \texttt{OA} ``inherits'' its correctness from the bigger notation system \texttt{OB}.

\label{types:SubON}
\index{hydras}{Library OrdinalNotations!Type classes!SubON}

following definition
(in ~\href{../theories/html/hydras.OrdinalNotations.ON_Generic.html}{ON\_Generic}).

\input{movies/snippets/ON_Generic/SubONDef}

For instance, we prove that \texttt{Omega} is a sub-notation of
\texttt{Omega\_plus\_Omega} (with $\omega$ as the first ``new'' ordinal, and \texttt{fin} as the injection).

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Omega_plus_omega.html}{OrdinalNotations.ON\_Omega\_plus\_omega}}

\input{movies/snippets/ON_Omega_plus_omega/Incl}

We can also show that, if $i<j$, then the segment $[0,i)$ is a ``sub-segment'' of
$[0,j)$. Since the terms  ($t\;i$) and ($t\;j$) are not convertible, we consider a ``cast''
function $\iota$ from ($t\;i$) into ($t\;j$), and prove that this function is  a monotonous bijection  from ($t\;i$) to
the segment $[0,i)$ of ($t\;j$).

\index{coq}{Commands!Program}

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.OrdinalNotations.ON_Finite.html}{OrdinalNotations.ON\_Finite}}

\input{movies/snippets/ON_Finite/InclIJ}
\input{movies/snippets/ON_Finite/InclIJa}
\input{movies/snippets/ON_Finite/InclIJb}
\input{movies/snippets/ON_Finite/InclIJc}
\input{movies/snippets/ON_Finite/InclIJd}

\index{hydras}{Exercises}
\begin{exercise}
Prove that \texttt{Omega\_plus\_Omega} cannot be a sub-notation of \texttt{Omega}.
\end{exercise}

\index{hydras}{Projects}
\begin{project}
Adapt the definition of \texttt{Hvariant} (Sect.~\ref{sect:hvariant-def}) in order to
have an ordinal notation as argument. Prove that if $O_A$ is a sub-notation of $O_B$, then any variant defined on  $O_A$ can be automatically transformed into
a variant on $O_B$.
\end{project}

\section{Comparing an ordinal notation with Schütte's model}

Finally, it may be interesting to compare an ordinal notation with the more theoretical model from Schütte (well, at least with our formalization of that model). This would be a relative proof of correctness of the considered  ordinal  notation.

The following class specifies that a notation \texttt{OA} describes a segment $[0,\alpha)$,
where $\alpha$ is a countable ordinal \emph{à la}  Schütte.

\label{types:ON-for}
\index{hydras}{Library OrdinalNotations!Type classes!ON\_correct}

\input{movies/snippets/ON_Generic/ONCorrect}

For instance, the following theorem tells that \texttt{Epsilon0}, our notation system for the segment $[0,\epsilon0)$ is a correct implementation of the theoretically defined  ordinal $\epsilon_0$
(see chapter~\ref{chap:schutte} for more details).

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.Schutte.Correctness_E0.html}{Schutte.Correctness\_E0}}

\input{movies/snippets/Correctness_E0/Epsilon0Correct}

\index{hydras}{Projects}

\begin{project}
  When you have read Chapter~\ref{chap:schutte}, prove that the sum of two ordinal notations \texttt{ON\_plus} implements the addition of ordinals.
\end{project}

\section{Isomorphism of ordinal notations}

In some cases we want to show that two notation systems describe the same segment (for instance $[0,3+\omega)$ and $[0,\omega)$\;). For this purpose, one may prove that the two notation systems are order-isomorphic.

\index{hydras}{Library OrdinalNotations!Type classes!ON\_Iso}

\label{types:ON-iso}

\input{movies/snippets/ON_Generic/ONIso}

\index{hydras}{Exercises}

\begin{exercise}
\label{exo:i-plus-omega}
Let $i$ be some natural number. Prove that the notation systems
\texttt{Omega} and (\texttt{ON\_plus (OrdFin $i$) Omega}) are isomorphic.

{\it \textbf{Note:} This property reflects the equality $i+\omega=\omega$, that we prove also in larger notation systems, as well as in Schütte's model.}
This exercise is partially solved for $i=3$ (in ~\href{../theories/html/hydras.OrdinalNotations.Example_3PlusOmega.html}{OrdinalNotations.Example\_3PlusOmega}).

\end{exercise}

\index{hydras}{Projects}
\label{exo:ON-mult}
\begin{project}
% Define in \coq{} the product of two ordinal notations $N_A$ and $N_B$.
% If $A$ [resp. $B$] is the underlying type of $N_A$ [resp. $N_B$], the
% product \texttt{ON\_mult $N_A$ $N_B$} is implemented over the cartesian product $B\times A$ (with the lexicographic ordering).

This exercise is about the non-commutativity of the multiplication of ordinals, reflected in ordinal notations.

For instance, the
elements of the product (\texttt{ON\_mult Omega (FinOrd 3)}) are ordered as follows.
\[(0,0),(0,1),(0,2),(0,3),(0,4),\dots,{\color{red}(1,0),} (1,1),(1,2),\dots, {\color{red}(2,0)},(2,1),(2,2),\dots\]

Note that the elements of  (\texttt{ON\_mult (FinOrd 3) Omega}) are differently ordered (without limit ordinals):
\[(0,0),(1,0),(2,0),(0,1),(1,1),(2,1),(0,2),(1,2),(2,2),(0,3),\dots\]

Prove formally  that \texttt{ON\_mult (FinOrd $i$) Omega} is isomorphic to
\texttt{Omega}  whilst
\texttt{Omega}  is a sub-notation of \texttt{ON\_mult Omega (FinOrd $i$)},
for any strictly positive $i$.

\textbf{Note:} Like Exercise~\ref{exo:i-plus-omega}, this project corresponds to the [in]equalities $i+\omega=\omega<\omega+i$, for any natural number $i$.
\end{project}

\index{hydras}{Projects}
\begin{project}
Consider two isomorphic ordinal notations \texttt{OA} and \texttt{OB}.
Prove that, if \texttt{OA} [resp. \texttt{OB}] is a correct implementation
of $\alpha$ [resp. $\beta$], then $\alpha=\beta$.
\end{project}

\index{hydras}{Projects}
\begin{project}
\label{project:succ-limit-dec}
Add to the class \texttt{ON} the requirement that for any $\alpha$ it is decidable whether $\alpha$ is $0$, a successor or a limit ordinal.

\textbf{Hint:}   Beware of the instances associated with sum and product of notations!
  You may consider additional fields
to make the sum and product of notations ``compositional''.

\end{project}

\index{hydras}{Projects}
\begin{project}
\label{project:on-setoid}
Reconsider the  class \texttt{ON}, with an equivalence instead of Leibniz equality.
\end{project}

%%%% ICI ICI

\section{Other ordinal notations}
%%% TODO : Fix the multiplication function in branch FixOmegaOmega

% \index{hydras}{Projects}

% \begin{project}
% The directory \texttt{theories/OmegaOmega} contains an ad-hoc formalization of $\omega^\omega$, contributed by Pascal Manoury. Every ordinal $\alpha$ is represented by a list $l$ whose elements are the coefficients of $\omega$ in  the Cantor normal form of $\alpha$ (in reverse order). For instance, the ordinal
% $\omega^{8}\times 5 + \omega^{6}\times 8 + \omega^2\times 10 + \omega + 7$ is represented by the list \texttt{[5;0;8;0;0.0;10,1,7]}.

%  Develop this representation and compare it with the other ordinal notations.

% \end{project}

\index{hydras}{Projects}

\begin{project}
Let $N_A$ be a notation system for ordinals strictly less than $\alpha$,
with the strict order $(A,<_A)$. Please build the notation system
\texttt{ON\_Expl $N_A$}, on the type of multisets of elements of $A$
(or, if preferred, the type of non-increasing finite sequences on $A$,
provided with the lexicographic ordering on lists).

For instance, let us take $N_A=\texttt{Omega}$, and take $\alpha=\langle 4,4,2,1,0\rangle$,
 $\beta=\langle 4,3,3,3,3,3,2\rangle$, and $\gamma=\langle 5\rangle$. Then $\beta<\alpha<\gamma$.

In contrast the list $\langle5,6,3,3\rangle$ is not non-increasing (\emph{i.e.} sorted w.r.t. $\geq$), so it is not to be considered.

Note that if the notation $N_A$ implements the ordinal
$\alpha$,  the new notation $\omega^{N_A}$ must implement the ordinal $\phi_0(\alpha)$, a.k.a. $\omega^\alpha$ (see chapter~\ref{chap:schutte})

\end{project}

\begin{remark}
 The set of ordinal terms in Cantor normal form (see Chap.~\ref{chap:T1}) and
in Veblen normal form (see
\href{../theories/html/hydras.Gamma0.Gamma0.html}{Gamma0.Gamma0}) are shown to be ordinal notation systems, but there is a lot of work to be done in order to unify ad-hoc  definitions and proofs which were written before the definition of the \texttt{ON} type class.
\end{remark}

%------------------------------------------------------------------------

\chapter[A proof of termination, using epsilon0]{A proof of termination, using ordinals below \texorpdfstring{$\epsilon_0$}{Epsilon0}}

\label{cnf-math-def}
\label{chap:T1}

In this chapter, we adapt to \coq{} the well-known~\cite{KP82}  proof that Hercules eventually wins every battle, whichever the strategy  of each player.
In other words, we present  a formal and self contained proof of termination  of all [free] hydra battles.
First, we take from Manolios and Vroon~\cite{Manolios2005} a representation of the ordinal $\epsilon_0$ as terms in Cantor normal form. Then, we define a variant for hydra battles as a measure that maps any hydra to some ordinal strictly less than $\epsilon_0$.

\section{The ordinal \texorpdfstring{\(\epsilon_0\)}{epsilon0}}
\label{sec:epsilon0-intro}

\subsection{Cantor normal form}
\index{maths}{Cantor normal form}

The ordinal \(\epsilon_0\) is the least ordinal number that satisfies
the equation \(\alpha = \omega^\alpha\), where \(\omega\) is
the least infinite ordinal. Thus, we can consider \(\epsilon_0\) as an
\emph{infinite} \(\omega\)-tower.
Nevertheless,
any ordinal strictly less that \(\epsilon_0\)
can be finitely represented by a unique  \emph{Cantor normal form},
that is, an expression  which is either  the ordinal \(0\) or
a sum  \(\omega^{\alpha_1} \times n_1 + \omega^{\alpha_2} \times n_2 +
  \dots + \omega^{\alpha_p} \times n_p\) where all the \(\alpha_i\)
are ordinals in Cantor  normal form, \(\alpha_1 > \alpha_2 > \alpha_p\),
and all the \(n_i\) are positive integers.

An example of Cantor normal form is displayed in Fig \ref{fig:cnf-example}:
Note that  any ordinal of
the form \(\omega^0 \times i + 0\) is just written \(i\).

\begin{figure}[htb]
\centering
\begin{tikzpicture}[scale=2, every node/.style={transform shape}]
\node[color=blue]{$\omega^{(\omega^\omega\,+\, \omega^2 \times 8 \,+\, \omega)}+ \omega^\omega + \omega^4+ 6$};
\end{tikzpicture}
\caption{\label{fig:cnf-example}
An ordinal in Cantor normal form}
\end{figure}

In the rest of this section, we define an inductive type for representing in \texttt{Coq}
all the ordinals strictly  less than  \(\epsilon_0\), then extend some arithmetic operations
to this type, and finally prove that our representation fits well with
the expected mathematical properties: the order we define is a well order,
and the decomposition into Cantor normal form  is consistent
with the implementation of the arithmetic operations of exponentiation of base \(\omega\)
and addition.

\paragraph*{Remark}
\label{sec:orgheadline65}
Unless explicitly mentioned, the term ``ordinal" will be used instead of
``ordinal strictly less than \(\epsilon_0\)" (except in Chapter~\ref{chap:schutte} where it stands for ``countable ordinal'').

\subsection{A data type for  ordinals in Cantor normal form}
\label{sec:orgheadline72}
\label{sec:T1-inductive-def}

% Our user contribution~\cite{CantorContrib} represents
% the set of ordinals strictly less than $\epsilon_0$ in Cantor normal form as in~\cite{Manolios2005}, and also the set
% of ordinals strictly  less than $\Gamma_0$ in Veblen normal form.

    Let us define an inductive type whose
constructors are respectively associated
with the ways to build Cantor normal forms:

\begin{itemize}
\item the ordinal \(0\)
\item the construction \((\alpha,\, n,\,\beta)  \mapsto \omega^\alpha \times (n + 1)+ \beta \quad (n\in\mathbb{N})\)
\end{itemize}

\vspace{4pt}
\noindent\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#T1}{Epsilon0.T1}}

\label{types:T1}
%\index{Constants!zero:T1}
\index{hydras}{Library Epsilon0!Types!T1}

\input{movies/snippets/T1/T1Def}

\paragraph{Remark}
The name \texttt{T1} we gave to this data-type  is proper to this development and refers
to a hierarchy of ordinal notations. For instance, in Library \href{../theories/html/hydras.Gamma0.T2.html}{Gamma0.T2},  the following type is used to represent ordinals strictly less than \(\Gamma_0\),  in Veblen normal form (see also~\cite{schutte}).
\noindent

\input{movies/snippets/T2/T2Def}

\subsubsection{Example}

\label{alpha0-def}
For instance, the ordinal  $\omega^\omega+\omega^3\times 5+2$ is represented by the following term:

\input{movies/snippets/T1/alpha0}

\begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.5, level 1/.style={sibling distance=6cm},
level 2/.style={sibling distance=35mm},
level 3/.style={sibling distance=17mm}]
\node  {ocons}
  child {  node {ocons}
            child { node {ocons} child {node {zero}} child {node{0}} child{node{zero}}}
         child {node {0}}
         child {node {zero}}}
    child {node {0}}
   child {node {ocons}
 child { node {ocons} child {node {zero}} child {node{2}} child{node{zero}}}
  child {node {4}}
         child {node {ocons} child {node {zero}} child {node{1}} child{node{zero}}}};

\end{tikzpicture}

\caption{The tree-like representation of the ordinal $\omega^\omega+\omega^3\times 5 +2$\label{fig:cnf-tree}}

\end{figure}

\paragraph{Remark}
For simplicity's sake, we chose to forbid  expressions of the form $\omega^\alpha\times 0 + \beta$. Thus, the construction (\texttt{ocons $\alpha$ $n$ $\beta$}) is intended to represent the
ordinal $\omega^\alpha\times(n+1)+\beta$ and not $\omega^\alpha\times n+\beta$.
In a future version, we should replace  the type \texttt{nat} with \texttt{positive} in \texttt{T1}'s
definition. But this replacement would take a lot of time \dots{}

\subsection{Abbreviations}

Some abbreviations may help to write more concisely complex ordinal terms.

\subsubsection{Finite ordinals}
\label{sec:orgheadline67}

For representing finite ordinals, \emph{i.e.} natural numbers, we first introduce a notation for terms of the form $n+1$, then define a coercion from type \texttt{nat} into \texttt{T1}.
\label{sect:notation-FS}

\label{sect:notation-F}

\input{movies/snippets/T1/finiteOrds}

% \index{Coq!Coercions}
% \index{Functions!Coercions@Coercions (from nat to ordinal types)}
% \begin{remark}
% Please refer to the remark~\pageref{warning:coercions} about the use of coercions.
% % The use of coercions like \texttt{fin} allow us to be close to the mathematical tradition where natural numbers are ordinals too.
% % Nevertheless, it may happen that a goal like \texttt{3 < 5} could be
% % interpreted as \texttt{(lt (fin 3) (fin 5))},  depending on the current notation scope.
% % When this misinterpretation happens, tactics like \texttt{auto with arith}, \texttt{lia} do not work!
% % Thus, it is useful to write \texttt{(3 < 5)\%nat}  an inequality between two natural numbers.
% \end{remark}

\subsubsection{The ordinal \(\omega\)}
\label{sec:orgheadline68}

  Since \(\omega\)'s Cantor normal form is
i.e. \(\omega^{\omega^0}\times 1+ 0\), we can define the following abbreviation:

\label{sect:omega-notation2}

\input{movies/snippets/T1/omegaDef}

Note that \texttt{omega} is not an identifier, thus any tactic like \texttt{unfold omega} would fail.

\subsubsection{The ordinal \(\omega^\alpha\), a.k.a. \(\phi_0(\alpha)\)}
\label{sect:notation-phi0}
We provide also a notation for ordinals of the form $\omega^\alpha$.

\index{hydras}{Library Epsilon0!Notations!phi0@phi0 (exponential of base omega)}

\input{movies/snippets/T1/phi0Def}

\index{maths}{Additive principal ordinals}

\begin{remark}
\label{sec:orgheadline69}
The name \(\phi_0\)
   comes from ordinal numbers theory. In~\cite{schutte}, Schütte defines
$\phi_0$  as the ordering (\emph{i.e.} enumerating) function of the set  of \emph{additive principal ordinals} \emph{i.e.} strictly positive ordinals $\alpha$ that verify $\forall \beta<\alpha, \beta+\alpha=\alpha$. For Schütte,  $\omega^\alpha$ is just a notation for $\phi_0(\alpha)$.  See also Chapter~\ref{chap:schutte} of this document.
\end{remark}

\subsubsection{The hierarchy of \(\omega\)-towers:}
\label{sec:orgheadline71}

The ordinal $\epsilon_0$, although not represented by a finite term in Cantor normal form, is approximated by the sequence of $\omega$-towers (see also Sect~\vref{sect:epsilon0-as-limit} ).

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html}{Epsilon0.T1}}

\input{movies/snippets/T1/towerDef}

For instance, Figure~\ref{fig:tower7} represents  the ordinal returned by the
 evaluation of the term \texttt{omega\_tower 7}.

\begin{figure}[htb]
\centering
\begin{tikzpicture}[scale=2, every node/.style={transform shape}]
\node[color=blue]{$\omega^{{{\omega}^{{{\omega}}^{{{\omega}}^{{\omega^{{\omega}^{\omega}}}}}}}}$};
\end{tikzpicture}
\caption{\label{fig:tower7}
The $\omega$-tower of height 7}
\end{figure}

\subsection{Pretty-printing ordinals in Cantor normal form}
\label{sect:ppT1}
\index{hydras}{Library Epsilon0!Types!ppT1}

Let us consider again the ordinal $\alpha_0$ defined in section~\vref{alpha0-def}
If we ask \coq{} to print its  normal form, we get a hardly readable term of type \texttt{T1}.

\input{movies/snippets/T1/alpha0Compute}

The following data type defines an abstract syntax for more readable ordinals terms in Cantor normal form:

\label{types:ppT1}
\index{hydras}{Library Epsilon0!Functions!pp@ pp (pretty printing terms in Cantor normal form)}

\input{movies/snippets/T1/ppT1Def}

The function \texttt{pp: T1 -> ppT1} converts any closed term of type \texttt{T1} into a human-readable expression. For instance, let us convert the term \texttt{alpha\_0}.

\input{movies/snippets/T1/ppAlpha0}

\index{hydras}{Projects}
\begin{project}
Design  (in \ocaml?) a set of tools for systematically pretty printing ordinal terms in Cantor normal form.
\end{project}

\subsection{Comparison between ordinal terms}
\label{sec:orgheadline73}

% Our formalisation of Cantor Normal Form will take two steps:
% 1 Definition of a strict order \texttt{o<} on the type \texttt{T1},
% 2 Using \texttt{o<} for characterizing terms in normal form.

In order to compare two terms of type \texttt{T1}, we define a recursive function \texttt{compare} that maps two ordinal tems $\alpha$ and $\beta$ to a value of type \texttt{comparison}. This type is defined in \coq's standard library
\texttt{Init.Datatypes} and
contains three constructors:  \texttt{Lt} (less than), \texttt{Eq} (equal), and
\texttt{Gt} (greater than).

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#compare}{Epsilon0.T1}}

\input{movies/snippets/T1/compareDef}

\label{Predicates:lt-T1}
Please note that this definition of \texttt{lt} makes it easy to write proofs by computation, as shown by the following examples.

\vspace{4pt}

\input{movies/snippets/T1/ltExamples}

%%% TODO : link to Comparable and StrictOrder classes

Links between the function \texttt{compare} and the relations
\texttt{lt} and \texttt{eq} are established through the following lemmas (~\vref{sect:comparable-def}).
\vspace{4pt}

\input{movies/snippets/T1/Instances}

% \vspace{4pt}
% \emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#compare_refl}{Epsilon0.T1}}

% \begin{Coqsrc}
% Lemma compare_refl : forall alpha, compare alpha alpha =  Eq.
% \end{Coqsrc}

% \begin{Coqsrc}
% Lemma compare_reflect : forall alpha beta,
%     match compare alpha beta with
%     |   Lt => lt alpha  beta
%     |   Eq => alpha = beta
%     |   Gt => lt beta  alpha
%     end.
% \end{Coqsrc}

% We prove also that the relation \texttt{lt} is a strict total order.

% \vspace{4pt}
% \emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#lt_irrefl}{Epsilon0.T1}}

% \begin{Coqsrc}
% Theorem lt_irrefl (alpha: T1):  ~ lt alpha alpha.

% Theorem lt_trans (alpha beta gamma : T1) :
%   lt alpha  beta -> lt beta gamma -> lt alpha gamma.

% Definition lt_eq_lt_dec  :
%    forall alpha beta : T1,
%           {lt alpha  beta} + {alpha = beta} + {lt beta alpha}.
% \end{Coqsrc}

% \vspace{4pt}

% Please note that the order \texttt{lt} is not reflected
% in the structure (size and/or height) of the terms of \texttt{T1}.

% \begin{Coqsrc}
% Example Ex0:
%   lt (ocons (phi0 (phi0 omega)) 2
%             (ocons (phi0 10) 33
%                    (ocons (phi0 9) 63 zero)))
%      (ocons  (phi0 (phi0 omega)) 2 (phi0 (phi0 11))).
% Proof.
%   reflexivity.
% Qed.
% \end{Coqsrc}

% Uncomment for testing
%\textbf{Todo: Fix subgoal display }
%\input{movies/snippets/T1/compareRev}

\subsubsection{A Predicate for Characterizing Normal Forms}
\label{sect:t1-nf}

\label{sec:orgheadline74}
\label{sec:orgheadline75}
Our data-type \texttt{T1} allows us to write expressions that
are not properly in Cantor normal form as specified in Section \ref{sec:epsilon0-intro}.
For instance, consider the following term of type  \texttt{T1}.

\input{movies/snippets/T1/badTerm}

This term would have been written \(\omega^1\times 2 + \omega^\omega \times 3\) in the usual mathematical notation. We note that the exponents of $\omega$ are not in the right (strictly decreasing) order.
Nevertheless, with the help of the order \texttt{lt} on \texttt{T1}, we are now able to characterize
the set of all well-formed ordinal terms:

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#nf_b}{Epsilon0.T1}}

\label{Predicates:nf-T1}

\input{movies/snippets/T1/nfDef}

\input{movies/snippets/T1/nfAlpha0}

\input{movies/snippets/T1/nfBadTerm}

\subsection{Making normality implicit}
  We would like to get rid of terms of type \texttt{T1} which are not in Cantor normal form.
A simple way to do this is to consider statements of the form
\texttt{forall alpha: T1, nf alpha -> $P$ alpha}, where $P$ is a predicate over type \texttt{T1}, like in the following lemma \footnote{Ordinal addition is formally defined a little later (page~\ref{sect:infix-plus-T1})}.

\input{movies/snippets/T1/plusIsZero}

\vspace{4pt}

But this style leads to clumsy statements, and generates too many subgoals in interactive proofs (although often solved with \texttt{auto} or \texttt{eauto}).

One may encapsulate conditions of the form \texttt{(nf $\alpha$)} in
the most used predicates. For instance, we introduce the restriction of \texttt{lt} to terms in normal form, and provide a handy notation for this restriction.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Prelude.Restriction.html}{hydras.Prelude.Restriction}}

\input{movies/snippets/Restriction/restrictionDef}

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#LT}{Epsilon0.T1}}

\input{movies/snippets/T1/LTDef}

\label{Predicates:LT-T1}

For instance, in the following lemma, the condition that $\alpha$ is in normal form is included in the condition $\alpha< 1$.

\input{movies/snippets/T1/LTOne}

\subsubsection{A sigma-type for \texorpdfstring{$\epsilon_0$}{epsilon0}}

As we noticed in Sect.~\ref{sect:t1-nf}, the type \texttt{T1} is not a correct ordinal notation, since it contains terms that are not in Cantor normal form. In certain contexts (for instance in Sections~\ref{sect:L-equations}, \ref{sect:hardy},
and \ref{sect:wainer}),  we need to define total recursive functions on well-formed ordinal terms less  than $\epsilon_0$, using the \texttt{Equations} plug-in~\cite{sozeau:hal-01671777}.
 In order to define a type whose inhabitants represent just ordinals, we build a type gathering a term of type \texttt{T1} and a proof that this term is in normal form.

\label{sect:E0-def}
\label{types:E0}
\index{hydras}{Library Epsilon0!Types!E0}

\emph{From Module~\href{../theories/html/hydras.Epsilon0.E0.html}{Epsilon0.E0}}

\input{movies/snippets/E0/E0Def}

Many constructs : types, predicates, functions, notations, etc., on type \texttt{T1} are adapted to \texttt{E0}.

First, we declare a notation scope for \texttt{E0}.

\input{movies/snippets/E0/E0Scope}

Then we redefine the predicates of comparison.

\label{Predicates:Lt-E0}

\input{movies/snippets/E0/LtLeDef}

Equality in \texttt{E0} is just Leibniz equality. Note that, since \texttt{nf} is
defined by a Boolean function, for  any term $\alpha:\texttt{T1}$, there exists at most one proof of \texttt{nf $\alpha$}, thus two ordinals of type \texttt{E0} are
equal if and only iff their projection to \texttt{T1} are equal (see also Sect.~\vref{sect:eq-proof-unicity}).

\vspace{4pt}

\index{coq}{Unicity of equality proofs}

\input{movies/snippets/E0/nfProofUnicity}

\vspace{4pt}

\input{movies/snippets/E0/E0EqIff}

\vspace{4pt}

In order to  upgrade constants and functions from type \texttt{T1} to \texttt{E0}, we have to prove that
the term they build is in normal form.
For instance, let us represent the ordinals $0$ and $\omega$   as instances of the class \texttt{E0}.

\vspace{4pt}

\label{sect:omega-T1}

\input{movies/snippets/E0/ZeroOmega}

%\index{Constants!zero:T1}

\subsection{Syntactic definition of limit and successor ordinals}

Pattern matching and structural recursion allow us to define boolean characterizations  of successor and limit ordinals.

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#succb}{Epsilon0.T1}}

\input{movies/snippets/T1/succbLimitb}

The correctness of these definitions with respect to the mathematical notions of
limit and successor ordinals is established through several lemmas. For instance,
Lemma \texttt{canonS\_limit\_lub}, page~\pageref{lemma:canonS-limit}, shows that
if $\alpha$ is (syntactically) a limit ordinal, then it is the least upper bound of
a strictly increasing sequence of ordinals.

\subsection{Arithmetic on \texorpdfstring{$\epsilon_0$}{epsilon0}}
\subsubsection{Successor}

\index{hydras}{Library Epsilon0!Functions!succ}

The successor of any ordinal $\alpha< \epsilon_0$ is defined by structural
recursion on its Cantor normal form.

\label{Functions:succ-T1}

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.T1.html\#succ}{Epsilon0.T1}}

\input{movies/snippets/T1/succDef}

The following lemma establishes the connection between the  function
\texttt{succ} and the Boolean predicate \texttt{succb}.

\vspace{4pt}

\input{movies/snippets/T1/succbIff}

\index{hydras}{Exercises}
 \begin{exercise}
Prove in \coq{} that for any ordinal $0< \alpha<\epsilon_0$, $\alpha$ is a limit if
and only if for all $\beta<\alpha$, the interval $[\beta,\alpha)$ is
infinite.

\emph{You may start this exercise with the file
     \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/Limit_Infinity.v}{exercises/ordinals/Limit\_Infinity.v}.}
 \end{exercise}

\subsubsection{Addition and multiplication}

Ordinal addition and multiplication are also defined by structural recursion over the type \texttt{T1}. Please note that they use the \texttt{compare} function on some subterms of their arguments.

\label{sect:infix-plus-T1}

\input{movies/snippets/T1/plusDef}

\input{movies/snippets/T1/multDef}

\subsubsection{Examples}

The following examples are instances of \emph{proofs by computation}. Please note that  addition and multiplication on \texttt{T1}
are not commutative. Moreover,  both operations fail to be strictly monotonous in their first argument.

\input{movies/snippets/T1/plusMultExamples}

\input{movies/snippets/T1/notMono}

The function \texttt{succ} is related with addition through the following lemma:

\input{movies/snippets/T1/succIsPlusOne}

\subsubsection{Arithmetic on type \texttt{E0}}

 We define an addition in type \texttt{E0}, since the sum of two terms in normal form is in normal form too.

\input{movies/snippets/T1/plusNf}

\input{movies/snippets/E0/plusE0}
\input{movies/snippets/E0/CheckPlus}

\begin{remark}
In all this development, two representations of ordinals co-exist: ordinal terms (type \texttt{T1}, notation scope \texttt{t1\_scope}, for reasoning on the tree-structure of Cantor normal forms), and ordinal terms \emph{known to be in normal form} (type \texttt{E0}, notation scope \texttt{E0\_scope}). Looking at the contexts displayed by \coq{} prevents you from any risk of confusion.
\end{remark}

%% To simplify !
\index{hydras}{Exercises}
\begin{exercise}
Prove that for any ordinal $\alpha:\texttt{E0}$,
$\omega\leq \alpha$ if and only if, for any natural number $i$,
$i+\alpha=\alpha$.

\emph{You may start this exercise with the file
    \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/ge_omega_iff.v}{exercises/ordinals/ge\_omega\_iff.v}.}
\end{exercise}

\section{Well-foundedness and transfinite induction}

\index{maths}{Transfinite induction}

\subsection{About  well-foundedness}
\label{sec:orgheadline82}
   In order to use \texttt{T1} for proving termination results,
we need to prove that  our order \texttt{<} is well-founded. Then we will get \emph{transfinite induction} for free.

The proof of well-foundedness of the strict order $<$ on Cantor normal forms is already
available in the Cantor contribution by Castéran and Contejean~\cite{CantorContrib}. That proof relies on a library on recursive path orderings written by
E. Contejean. We present here  a direct proof of the same result, which does not require any knowledge on r.p.o.s.

\index{hydras}{Exercises}

\begin{exercise}
Prove that the \emph{total} order \texttt{lt} on \texttt{T1} is not well-founded.
\textbf{Hint:}  You will have to build a counter-example with terms of type \texttt{T1}
which are not in Cantor normal form.

\emph{You may start this exercise with the file
    \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/T1_ltNotWf.v}{exercises/ordinals/T1\_ltNotWf.v}.}
\end{exercise}

\subsubsection{A first attempt}
\label{sec:orgheadline77}
\index{coq}{Well-founded induction}

It is natural to try to prove by structural induction over \texttt{T1}
that every term in normal form is accessible through \texttt{LT}.

Unfortunately, it won't work. Let us consider some well-formed term
 $\alpha=\texttt{ocons $\beta\;n\;\gamma$}$, and assume that \(\beta\) and \(\gamma\) are accessible
 through \texttt{LT}. For proving the accessibility of $\alpha$, we have to consider
any well formed term \(\delta\) such that \(\delta<\alpha\).
But nothing guarantees that \(\delta\)  is strictly  less than \(\beta\) nor \(\gamma\), and we cannot use the induction hypotheses on   \(\beta\) nor \(\gamma\).

\input{movies/snippets/T1/wfLTBada}

The problem comes from the hypothesis \texttt{Hdelta}. It does not prevent  \(\delta\) to be bigger that \(\beta\) or
\(\gamma\);
for instance \(\delta\) may be of the form
\texttt{ocons $\beta$ $p'$  $\gamma'$},
where    \(p' < n\).
Thus, the induction hypotheses \texttt{IHbeta} and \texttt{IHgamma}  are useless for finishing our proof.

\input{movies/snippets/T1/wfLTBadz}

\subsubsection{Using a stronger inductive predicate.}
\label{sec:orgheadline78}
  Instead of trying to prove directly that any ordinal term \(\alpha\) in normal form is accessible
through \texttt{LT}, we propose to show first that any well formed
term of the form \(\omega^\alpha\times(n+1)+\beta\) is accessible (which is a stronger result).

\input{movies/snippets/T1/AccStrongDef}

The following lemma is an application of the strict inequality
$\alpha < \omega ^\alpha$. If $\alpha$ is strongly accessible, then, by definition,
$\omega^\alpha$ is accessible, thus $\alpha$ is \emph{a fortiori} accessible.

\input{movies/snippets/T1/AccStrongStronger}

Thus, it remains to prove that every ordinal strictly less than $\epsilon_0$
is strongly accessible.

% \subsubsection{Structure of the proof of well-foundedness of \texttt{LT}}

\label{sec:orgheadline81}
\label{proof-wf-epsilon0}
\paragraph{A helper}
\label{sec:orgheadline79}

First, we prove that, for  any \texttt{LT}-accessible term $\alpha$, $\alpha$ is
strongly accessible too (\emph{i.e.} any well formed
term (\texttt{ocons $\alpha$ $n$ $\beta$})  is accessible).

The proof is structured as an induction on $\alpha'$s accessibility. Let us consider
any  accessible term $\alpha$.

\input{movies/snippets/T1/AccImpAccStrong}

Let \texttt{n:nat} and \texttt{beta:T1} such that (\texttt{ocons alpha n beta}) is in normal form.
We prove first that \texttt{beta} is accessible,  which allows us to prove by well-founded induction on \texttt{beta},
and natural induction on \texttt{n}, that (\texttt{ocons alpha n beta}) is accessible.
The proof, quite long, can be consulted in \href{../theories/html/hydras.Epsilon0.T1.html}{Epsilon0.T1}.

\paragraph{Accessibility of any well-formed ordinal term}
\label{sec:orgheadline80}

Our goal is still to prove accessibility of any well formed ordinal term.
Thanks to our previous lemmas, we are almost done (by a simple structural induction!).

\input{movies/snippets/T1/nfAcc}

\input{movies/snippets/T1/T1Wf}

\index{maths}{Transfinite induction}

\input{movies/snippets/T1/transfiniteRecursor}

The following tactic starts a proof by  transfinite induction on any ordinal \mathcolor{$\alpha<\epsilon_0$}.

\input{movies/snippets/T1/transfiniteInduction}

\begin{remark}
\label{remark:a3pat}
The alternate proof of well-foundedness using \'Evelyne Contejean's work on
    recursive path ordering~\cite{DershowitzRPO, a3pat} is available in the
    library \href{../theories/html/hydras.Epsilon0.Epsilon0rpo.html}{Epsilon0.Epsilon0rpo}.
 \end{remark}

\subsection{An ordinal notation for  \texorpdfstring{$\epsilon_0$}{epsilon0}}

We build an instance of \texttt{ON}, and prove its correction w.r.t. Schutte's model.

\emph{From Module~\href{../theories/html/hydras.Epsilon0.E0.html}{Epsilon0.E0}}

\input{movies/snippets/E0/InstanceEpsilon0}

\label{instance-epsilon0}

\emph{From Module~\href{../theories/html/hydras.Schutte.Correctness_E0.html}{Schutte.Correctness\_E0}}

\input{movies/snippets/Correctness_E0/injectDef}

\input{movies/snippets/Correctness_E0/Epsilon0Correct}

\index{hydras}{Projects}
\begin{project}
 \emph{This exercise is a continuation of Project~\vref{exo:ON-mult}.}
Use \texttt{ON\_mult} to define an ordinal notation \texttt{Omega2} for $\omega^2=\omega\times\omega$.

Prove that \texttt{Omega2} is a sub-notation of \texttt{Epsilon0}.

Define on \texttt{Omega2} an addition compatible with the addition on \texttt{Epsilon0}.

\textbf{Hint}. You may use the following definition (in
    \href{../theories/html/hydras.OrdinalNotations.ON_Generic.html}{OrdinalNotations.ON\_Generic}).

\input{movies/snippets/ON_Generic/SubONSameOp}

     \end{project}

    \index{hydras}{Projects}
    \begin{project}
    The class \texttt{ON} of ordinal notations has been defined long after this
    chapter, and is not used in the development of the type \texttt{E0} yet.
    A better integration of both notions should simplify the development on ordinals in Cantor normal form. This integration is planned for the future versions.

    \end{project}

    \section{A refinement of \texttt{E0} : an ordinal notation for \texorpdfstring{$\omega^\omega$}{omega\^omega}}

    In Module   \href{https://github.com/coq-community/hydra-battles/blob/master/theories/ordinals/OrdinalNotations/OmegaOmega.v}{theories/ordinals/OrdinalNotations/OmegaOmega.v},
    we represent ordinals below $\omega^\omega$ by list of pairs of natural numbers (with the same coefficient shift as in \texttt{T1}).
    For instance, the ordinal $\omega^4\times 10 + \omega^3 + \omega+ 5$ is represented by the list \texttt{(4,9)::(3,0)::(1,0)::(0,4)::nil}.

  The usual operations : \texttt{succ}, \texttt{+}, \texttt{*} are simple variants of the same operations in \texttt{T1}.

    We establish this representation as a \emph{refinement} of the data types we used to represent ordinals less than $\epsilon_0$. Thus, many properties like well-foundedness of $<$ and associativity of $+$,  of this ordinal notations have very short proofs.

%ici
    \section{A variant for hydra battles}

    In order to prove the termination of any hydra battle, we try to define a variant mapping hydras to ordinals strictly less than $\epsilon_0$.
    In order to make such a variant easy to define (for instance by a structural recursion), we introduce a variant of addition, which, contrary to
    $+$, is commutative and strictly monotonous in both of its arguments. This last property makes it possible to prove that our function is
    truly a variant for hydra battles (in Sect.~\vref{sect:variant-decr}).

    \subsection{Natural sum (a.k.a. Hessenberg's  sum)}
    \label{sec:orgheadline87}
    \label{hydra-variant}

    Natural sum (Hessenberg's  sum) is a commutative and monotonous version of
    addition. It is used as an auxiliary operation  for defining variants
    for hydra battles, where Hercules is allowed to chop off any  head of the hydra.

    In the literature, the natural sum of ordinals \(\alpha\) and \(\beta\)
    is often denoted by \(\alpha \# \beta\)  or  \(\alpha \oplus  \beta\).
    Thus we called \texttt{oplus} the associated \emph{Coq} function.

    \subsubsection{Definition of \texttt{oplus}}
    \label{sec:orgheadline84}
    %\index{Functions!oplus @ oplus (Hessenberg commutative sum)}

    The definition of \texttt{oplus} is recursive in both of its
    arguments and uses  the same pattern as for the \texttt{merge} function on lists of library
    \texttt{Coq.Sorting.Mergesort}.

    \begin{enumerate}
    \item Define a nested recursive function, using the \texttt{Fix}
        construct

    \item Build a principle of induction dedicated to \texttt{oplus}

    \item Establish equations associated to each case of the definition.
    \end{enumerate}

    \paragraph{Nested recursive definition}
    \label{sec:orgheadline83}

    The following definition is composed of
    \begin{itemize}
    \item A main function \texttt{oplus}, structurally recursive in its
    first argument \texttt{alpha}
    \item An auxiliary function \texttt{oplus\_aux} within the scope of \texttt{alpha},
    structurally recursive in its argument \texttt{beta};  \texttt{oplus\_aux beta}
       is supposed to compute  \texttt{oplus alpha beta}.
    \end{itemize}

    \vspace{4pt}
    \emph{From Module~\href{../theories/html/hydras.Epsilon0.Hessenberg.html\#oplus}{Epsilon0.Hessenberg}}

    \label{sect:infix-oplus}

    \input{movies/snippets/Hessenberg/oplusDef}

    The reader will note that each recursive call of the functions
    \texttt{oplus} and \texttt{oplus\_aux} satisfies \emph{Coq}'s constraint
    on recursive definitions. The function \texttt{oplus} is recursively called on a sub-term of its first argument,
    and \texttt{oplus\_aux} on a sub-term of its unique argument.
    Thus, \texttt{oplus}'s definition is accepted by \coq{} as a structurally recursive function.

    \subsubsection{Rewriting lemmas}
    \label{sec:orgheadline86}

    \emph{Coq}'s constraints on recursive definitions result in
    the quite  complex form of \texttt{oplus}'s definition.
    Proofs of properties of this function can be simpler if we
     derive a few  rewriting lemmas that will help to simplify
    expressions of the form (\texttt{oplus $\alpha$ $\beta$}).

    A first set of lemmas correspond to the various cases of \texttt{oplus}'s
    definition. They can be proved almost immediately.

    \input{movies/snippets/Hessenberg/oplusNeutral}

    % \subsubsection{A hand-made induction principle}
    % \label{sec:orgheadline85}

    % \index{Coq!Commands!Functional Scheme}

    % \emph{Coq} contains a command  \texttt{Functional Scheme} that
    % generates induction principles which correspond to recursive functions.
    % Unfortunately, the current version ( \texttt{8.11.0} ) doesn't work on \texttt{oplus},
    % probably because of the inner \texttt{Fix}.

    % \begin{Coqsrc}
    % Functional Scheme oplus_ind := Induction for oplus Sort Prop.
    % \end{Coqsrc}

    % \begin{Coqanswer}
    % Error: Anomaly "todo." Please report at http://coq.inria.fr/bugs/.
    % \end{Coqanswer}

    % Fortunately, it's a good exercise for a semi-experienced user, to write
    % her/him-self induction principles similar to the ones returned by
    % \texttt{Functional Scheme}.

    % \begin{itemize}
    % \item First, we choose to write a version for sort \texttt{Type}, since versions
    % for sorts \texttt{Prop} and \texttt{Set} can be easily derived from
    % the former one. According to \emph{Coq}'s naming politics, we will call our
    % principle \texttt{oplus\_rect}

    % \item The conclusion of \texttt{oplus\_rect} will be (\texttt{$P$ a b (oplus a b)}),
    % where $P$ is an arbitrary function of type
    % \texttt{T1 -> T1 -> T1 -> Type}

    % \item The premises of \texttt{oplus\_rect} will describe how to build an induction
    % on the graph of \texttt{oplus}.
    % \end{itemize}

    % We are now ready to state and prove \texttt{oplus\_rect}, and the reader
    % will note that the statement is longer than the proof script itself,
    % which is a standard proof by induction, simplification and case-analysis
    % that follows  \texttt{oplus}'s definition.

    % We associate also a tactic to the application of \texttt{oplus\_rect}.

    % \begin{Coqsrc}
    %  Lemma oplus_rect:
    %       forall P: T1 -> T1 -> T1 -> Type,
    %         (forall a:T1, P zero a a) ->
    %         (forall a: T1, P a zero a) ->
    %         (forall a1 n1 b1 a2 n2 b2 o,
    %            compare a1 a2 = Gt ->
    %            P b1 (ocons a2 n2 b2) o ->
    %            P (ocons a1 n1 b1) (ocons a2 n2 b2)
    %              (ocons a1 n1 o)) ->
    %         (forall a1 n1 b1 a2 n2 b2 o,
    %            compare a1 a2 = Lt ->
    %            P (ocons a1 n1 b1) b2 o ->
    %            P (ocons a1 n1 b1) (ocons a2 n2 b2)
    %            (ocons a2 n2 o)) ->
    %         (forall a1 n1 b1 a2 n2 b2 o,
    %            compare a1 a2 = Eq ->
    %            P b1 b2 o ->
    %           P (ocons a1 n1 b1) (ocons a2 n2 b2)
    %             (ocons a1 (S (n1 + n2)%nat) o)) ->
    %          forall a b, P a b (oplus a b).
    % Proof with auto.
    %    induction a.
    %    -    intro; simpl; destruct b;auto.
    %    -   induction b.
    %        + apply X0.
    %        + case_eq (compare a1 b1).
    %          * intro Comp; unfold oplus; rewrite Comp.
    %            cbn; apply X3 ...
    %          * intro Comp; cbn; rewrite Comp; apply X2...
    %          * intro Comp; cbn; rewrite Comp ...
    %  Defined.

    % Ltac oplus_induction a b:= pattern (oplus a b); apply oplus_rect.
    % \end{Coqsrc}

    % \index{Exercises}

    % \begin{exercise}
    % The induction principle \texttt{oplus\_rect} is still unused in our development.
    % Please build some nice examples of application.
    % \end{exercise}

    \index{hydras}{Projects}
    \begin{project}
    Compare \texttt{oplus}'s definition (with inner fixpoint) with other possibilities
    (\texttt{coq-equations}, \texttt{Function}, etc.).
    \end{project}
    \subsection{More theorems on Hessenberg's sum}

    We need to prove some properties of $\oplus$, particularly about
    its relation with the order $<$ on \texttt{T1}.

    \subsubsection{Commutativity, associativity}

    We prove  the commutativity of $\oplus$ in two steps.

    First, we prove by transfinite induction on $\alpha$ that the restriction of $\oplus$ to the
    interval $[0..\alpha)$ is commutative.

    \index{maths}{Transfinite induction}

    \input{movies/snippets/Hessenberg/oplusComm0}

    Then, we infer  $\oplus$'s commutativity for any pair of ordinals:
    Let $\alpha$ and $\beta$ be two ordinals strictly less than $\epsilon_0$. Both ordinals $\alpha$ and $\beta$ are
    strictly less than $\textrm{max}(\alpha,\beta)+1$.
        Thus, we have just to apply the lemma \coqsimple{oplus\_comm\_0}.

\input{movies/snippets/Hessenberg/oplusComm}

    Associativity of Hessenberg's sum is proved the same way.

    \input{movies/snippets/Hessenberg/oplusAssoc0}
    \input{movies/snippets/Hessenberg/oplusAssoc}

    \subsubsection{Monotonicity}

    At last, we prove that $\oplus$ is strictly monotonous in both of its arguments.

    \input{movies/snippets/Hessenberg/oplusMono}

      \index{hydras}{Projects}

    \begin{project}
    The library \texttt{Hessenberg} looks too long (proof scripts and compilation).
    Please try to make it simpler and more efficient!
    Thanks!
    \end{project}

    \subsection{A termination measure for hydra battles }

    \label{sec:hydra-measure}

    Let us define a measure from type \texttt{Hydra} into \texttt{T1}.

    \vspace{4pt}
    \emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Termination.html\#m}{Hydra.Hydra\_Termination}}

   \input{movies/snippets/Hydra_Termination/mDef}

    First, we prove that the measure $m(h)$  of any hydra $h$ is a well-formed ordinal term of type \texttt{T1}.

    \input{movies/snippets/Hydra_Termination/mNf}

    For proving the termination of all hydra battles, we have to prove that
    \texttt{m} is a variant. First, a few technical lemmas follow the decomposition of \texttt{round} into several relations. Then the lemma \texttt{round\_decr} gathers all the cases.

    \label{sect:variant-decr}

    \input{movies/snippets/Hydra_Termination/S0Decr}
    \input{movies/snippets/Hydra_Termination/R1Decr}
    \input{movies/snippets/Hydra_Termination/S1Decr}
    \input{movies/snippets/Hydra_Termination/R2Decr}
     \input{movies/snippets/Hydra_Termination/RoundDecr}

      Finally, we prove termination of all (free) battles.

    \label{thm:every-battle-terminates}

    \input{movies/snippets/Hydra_Termination/FinalThm}

    \section*{Conclusion}

    Let us recall three results we have proved so far.
    \begin{itemize}
    \item There exists a strictly decreasing variant which maps \texttt{Hydra} into
    the segment $[0,\epsilon_0)$ for proving the termination of any hydra battle
    \item There exists \emph{no} such variant from \texttt{Hydra} into
    $[0,\omega^2)$, \emph{a fortiori} into $[0,\omega)$.
    \end{itemize}

    So, a  natural question is `` Does there exist any strictly decreasing variant mapping
    type \texttt{Hydra} into some interval $[0,\alpha)$ (where $\alpha <\epsilon_0$) for proving the termination of all hydra battles''. The next chapter is dedicated to a formal proof that there exists no such $\alpha$, even if we consider a restriction to the set of ``standard'' battles.

    %\include{epsilon0}

    %\include{impossibility-proofs}

%-------------------------------------------------------------------

\chapter[The Ketonen-Solovay machinery]{Accessibility inside \texorpdfstring{$\epsilon_0$}{Epsilon0}: The Ketonen-Solovay Machinery\label{ks-chapter}}
\label{chap:ketonen}
\index{maths}{Ordinal numbers!Ketonen-Solovay machinery}

\section{Introduction}
The reader may think that our proof of termination in the previous  chapter requires a lot of mathematical tools and may be too  complex. So, the question is ``is there  any  simpler proof'' ?

In their article~\cite{KP82}, Kirby and Paris show that this result cannot be proved in Peano arithmetic. Their proof uses some knowledge about model theory and non-standard models of Peano arithmetic. In this chapter, we focus on a specific class of proofs of termination of hydra battles: construction of some variant mapping the type \texttt{Hydra} into a given initial  segment of ordinals. Our proof relies only on the Calculus of Inductive Constructions and is a natural complement of the results proven in the previous chapters.

\begin{itemize}
\item There is no variant mapping the type \texttt{Hydra} into the interval $[0,\omega^2)$ (section ~\vref{omega2-case}), and a fortiori
$[0,\omega)$ (section ~\vref{omega-case}).

\item There exists a variant which maps the type \texttt{Hydra} into the
interval $[0,\epsilon_0)$ (theorem \texttt{every\_battle\_terminates}, in section~\vref{thm:every-battle-terminates}).
\end{itemize}

Thus, a very natural question is the following one:
\begin{quote}
  `` Is there  any variant from
\texttt{Hydra} into some interval $[0,\mu)$, where $\mu<\epsilon_0$, for proving the termination of all hydra battles ?''
\end{quote}

We prove in \coq{} the following result:

\begin{quote}
There is no variant for proving the termination of all hydra battles
from \texttt{Hydra} into the interval $[0..\mu)$, where
$\mu< \epsilon_0$.
The same impossibility holds even if we consider only standard battles (with the successive replication factors $0,1,2,\dots,t,t+1,\dots$).
\end{quote}

Our proofs are  constructive and require no axioms: they are  closed terms of the CIC, and are mainly composed on function definitions and proofs of properties of these functions.
They  share much theoretical material with Kirby and Paris', although they do not use any knowledge about Peano arithmetic nor model  theory.  The combinatorial arguments we use and implement
come from
 an article by J.~Ketonen and R.~Solovay~\cite{KS81}, already  cited in the work
 by L.~Kirby and J.~Paris.% on the termination of Goodstein sequences and hydra battles~\cite{KP82}.
 Section $2$ of this article: ''A hierarchy of probably recursive functions'', contains a systematic study of \emph{canonical sequences}, which are closely related to
rounds of hydra battles.
Nevertheless, they have the same global structure as the simple proofs described in
sections~\vref{omega-case} and \vref{omega2-case}.
We invite the reader to compare the three proofs step by step, lemma by lemma.

\section{Canonical Sequences}
\label{ketonen-solovay-sect}
\index{maths}{Ordinal numbers!Canonical sequences}

Canonical sequences are functions that associate an ordinal $\canonseq{\alpha}{i}$ to every ordinal $\alpha<\epsilon_0$ and positive integer $i$. They satisfy several nice properties:

\index{maths}{Transfinite induction}
\begin{itemize}
\item If $\alpha\not=0$, then $\canonseq{\alpha}{i}<\alpha$. Thus canonical sequences can be used for proofs by transfinite induction or function definition by transfinite recursion
\item If $\lambda$ is a limit ordinal, then $\lambda$ is the least upper bound of the set
$\{\canonseq{\lambda}{i}\;|\,i\in\mathbb{N}_1\}$

\item If $\beta<\alpha<\epsilon_0$, then there is a ``path'' from $\alpha$ to $\beta$, \emph{i.e.} a
sequence $\alpha_0=\alpha, \alpha_1, \dots, \alpha_n=\beta$, where for every $k<n$, there exists some $i_k$ such that $\alpha_{k+1}=\canonseq{\alpha_k}{i_k}$
\item Canonical sequences correspond tightly to rounds of hydra battles: if $\alpha\not=0$,
then $\iota(\alpha)$ is transformed into $\iota(\canonseq{\alpha}{i+1})$ in one round with
the replication factor $i$ (Lemma \href{../theories/html/hydras.Hydra.O2H.html\#canonS_iota_i}{Hydra.O2H.canonS\_iota\_i}).
\item From the two previous properties, we infer that whenever $\beta<\alpha<\epsilon_0$, there exists a (free) battle from $\iota(\alpha)$ to $\iota(\beta)$.
\end{itemize}

\begin{remark}
  In~\cite{KS81}, canonical sequences are defined for any ordinal $\alpha <\epsilon_0$,
by stating that if $\alpha$ is a successor ordinal $\beta+1$,  the sequence associated with
$\alpha$ is simply the constant sequence whose terms are equal to $\beta$.
Likewise, the canonical sequence of $0$ maps any natural number to $0$.

This convention allows us to make total the function that maps any ordinal $\alpha$ and natural number $i$ to the ordinal $\canonseq{\alpha}{i}$.

\end{remark}

First, let us recall how canonical sequences are defined in~\cite{KS81}. For efficiency's sake, we decided not to implement directly K.\&S's definitions, but to define in \gallina{} simply typed structurally recursive functions which share the abstract properties which are used in the mathematical proofs\footnote{With a small difference: the $0$-th term of the canonical sequence is not the same in our development as in~\cite{KS81}.}.

\subsubsection{Mathematical definition of canonical sequences}

In~\cite{KS81} the definition of $\canonseq{\alpha}{i}$ is based on the following remark:
\begin{quote}
Any non-zero ordinal $\alpha$ can be decomposed in a unique way as the product
$\omega^\beta\times (\gamma+1)$.
\end{quote}

Thus the $\canonseq{\alpha}{i}$\,s are defined in terms of this decomposition:
\begin{definition}[Canonical sequences: mathematical definition]
\label{def:canonseq-math}

\end{definition}
\begin{mathframe}
  \begin{itemize}
\item Let $\lambda<\epsilon_0$ be a limit ordinal

\begin{itemize}
\item If $\lambda=\omega^{\alpha+1}\times (\beta+1)$, then
$\canonseq{\lambda}{i}= \omega^{\alpha+1}\times\beta +  \omega^\alpha \times i$
\item If $\lambda=\omega^{\gamma}\times (\beta+1)$, where $\gamma<\lambda$ is a limit ordinal, then
$\canonseq{\lambda}{i}=\omega^{\gamma}\times \beta + \omega^{\canonseq{\gamma}{i}}$
\end{itemize}

\item For successor ordinals, we have $\canonseq{\alpha+1}{i}= \alpha$

\item Finally, $\canonseq{0}{i}= \alpha$.
\end{itemize}
\end{mathframe}

\subsubsection{Canonical sequences in Coq}
\index{hydras}{Library Epsilon0!Functions!canon}
\index{hydras}{Library Epsilon0!Functions!canonS}

Our definition may look more complex than the mathematical one, but
uses plain structural recursion over the type \coqsimple{T1}. Thus, tactics like
\coqsimple{cbn}, \coqsimple{simpl}, \coqsimple{compute}, etc., are applicable.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Canon.html\#canon}{Epsilon0.Canon}}

\label{Functions:canonS}
\label{Functions:canon}

\input{movies/snippets/Canon/canonDef}

In the present state of this library, the following specializations of \texttt{canon} are still used in some proofs or lemma statements.

\input{movies/snippets/Canon/CanonS0}

For instance \coq's computing facilities allow us to verify the equalities\linebreak
\mathcolor{$\canonseq{\omega^\omega}{3} = \omega^3$} and
\mathcolor{$\canonseq{\omega^\omega*3}{42} = \omega^\omega*2 + \omega^{42}$}.

\input{movies/snippets/Canon/canonExamples}

% \index{hydras}{Projects}
% \begin{project}
% Many lemmas presented in this chapter were stated and proved before the introduction of
% the type class \texttt{ON} of ordinal notations, and in particular its  instance \texttt{Epsilon0}.
% Thus definitions and lemmas refer to the type \texttt{T1} of possibly not well-formed terms.
% This should be fixed in  a future version.
% \end{project}

\subsection{Basic properties of canonical sequences}

We did not  try to prove that our definition truly implements Ketonen and Solovay's  \cite{KS81}'s canonical sequences. The most important is that we were able to prove the
abstract properties  of canonical sequences that are really used in our proof. The complete proofs are in the module
~\href{../theories/html/hydras.Epsilon0.Canon.html}{Epsilon0.Canon}

For instance, the equality $\canonseq{\alpha+1}{i}=\alpha$  can be  proved by  structural induction on $\alpha$.

\input{movies/snippets/Canon/canonSucc}

\subsubsection{Canonical sequences and the order $<$}

\index{maths}{Transfinite induction}

We prove by transfinite induction over $\alpha$ that $\canonseq{\alpha}{i+1}$ is an ordinal strictly less than $\alpha$ (assuming $\alpha\not=0$). This property allows us to use the function \texttt{canonS} and its derivatives in function definitions by transfinite recursion.

\label{lemma:canonS_LT}

\input{movies/snippets/Canon/canonSLT}

\subsubsection{Limit ordinals are truly limits}
The following theorem states that any limit ordinal $\lambda<\epsilon_0$
is the limit of the sequence \showmath{\canonseq{\lambda}{i}\;(1\le i)}.

\vspace{4pt}

\emph{From Module~\href{../theories/html/hydras.Epsilon0.Canon.html\#canonS_limit_strong}{Epsilon0.Canon}}

\input{movies/snippets/Canon/canonSLimitStrong}

\label{lemma:canonS-limit}

Note the use of \coq's \texttt{sig} type in the theorem's statement, which
relates the boolean function \texttt{limitb} defined on the \texttt{T1} data-type with a constructive view of the limit of a sequence: for any $\beta<\lambda$, we can compute an item of the canonical sequence of $\lambda$ which is greater than $\beta$.
We can also state directly that $\lambda$ is a (strict) least upper bound of the elements of its canonical sequence.

\input{movies/snippets/Canon/canonSLimitLub}

\index{hydras}{Exercises}

\begin{exercise}\label{exo:simply-typed-canonseq}
Instead of using the \texttt{sig} type, define a simply typed function that, given two ordinals $\alpha$ and $\beta$, returns a natural number $i$ such that, if $\alpha$ is a limit ordinal and $\beta<\alpha$, then $\beta< \canonseq{\alpha}{i+1}$. Of course, you will have to prove the correctness of your function.

\textbf{Hint:} You may add to your function a third argument usually called \texttt{fuel} for allowing you to give a structurally
recursive function (\emph{cf} the post of Guillaume Melquiond on Coq-club (Dec 21, 2020)
\url{https://sympa.inria.fr/sympa/arc/coq-club/2020-12/msg00069.html}).
The type \texttt{fuel}, an alternative
to \texttt{nat} is available on \href{../theories/html/hydras.Prelude.Fuel.html}{Prelude.Fuel}).
\index{coq}{Giving fuel to a long computation}

\end{exercise}

\section{Accessibility inside \texorpdfstring{$\epsilon_0$}{epsilon0} : paths}
\index{maths}{Ordinal numbers!Accessibility inside epsilon0}
\label{sect:pathes-intro}

Let us consider a kind of accessibility problem inside $\epsilon_0$: given two ordinals $\alpha$ and $\beta$, where $\beta<\alpha<\epsilon_0$, find a \emph{path} consisting of a finite sequence $\gamma_0=\alpha,\dots,\gamma_l=\beta$,
where, for every $i<l$, $\gamma_i \not= 0$ \footnote{This condition allows us to ignore paths which end by a lot of useless $0$s.} and there exists some strictly positive integer $s_i$
such that $\gamma_{i+1}=\canonseq{\gamma}{s_i}$.

Let $s$ be the sequence $\langle s_0,s_1,\dots, s_{l-1} \rangle$. We describe the
existence of such a path with the notation $\alpha\xrightarrow [s]{}\beta$.

We say also that the considered path from $\alpha$ to $\beta$ \emph{starts at [index] $s_0$ and ends at $s_l$}.

For instance, we have $\omega*2 \xrightarrow[2,2,2,4,5]{}3$, through the
path $\langle\omega\times 2, \omega+2,\omega+1,\omega,4,3\rangle$.

\begin{remark}

Note that, given $\alpha$ and $\beta$, where $\beta < \alpha$, the sequence $s$ which leads from $\alpha$ to $\beta$ is not unique.

Indeed, if $\alpha$ is a limit ordinal, the first element of $s$ can be any integer $i$ such that $\beta<\canonseq{\alpha}{i}$, and if $\alpha$ is a successor ordinal,
then the sequence $s$ can start with any positive integer.

For instance, we have also
$\omega*2 \xrightarrow[3,4,5,6]{}\omega$.
Likewise,
$\omega*2 \xrightarrow[1,2,1,4]{} 0$ and
$\omega*2 \xrightarrow[3,3,3,3,3,3,3,3]{} 0$.
\end{remark}

\subsection{Formal definition}

\label{path-to-definition}

In \coq{}, the notion of path can be simply defined as an inductive predicate
parameterized by the destination $\beta$.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Paths.html}{Epsilon0.Paths}}

\index{hydras}{Library Epsilon0!Predicates!path\_to}
\label{sect:path-to-def}

\input{movies/snippets/Paths/transitionDefs}

\input{movies/snippets/Paths/pathDef}

\begin{remark}
In the present version of our library, we use a variant \texttt{path\_toS} of
\texttt{path\_to}, where the proposition
(\texttt{path\_toS $\beta$ $s$ $\alpha$}) is equivalent to
(\texttt{path\_to $\beta$ (List.map S $s$) $\alpha$}). This variant is scheduled to be deprecated.
\end{remark}

\index{hydras}{Exercises}

\begin{exercise}
Write a tactic for solving goals of the form (\texttt{path\_to $\beta$ $s$ $\alpha$})
where $\alpha$, $\beta$ and $s$ are closed terms.
You should solve automatically the following goals:

\begin{Coqsrc}
 path_to omega (2::2::2::nil) (omega * 2).

 path_to omega (3::4::5::6::nil) (omega * 2).

 path_to zero (interval 3 14) (omega * 2).

 path_to zero (repeat 3 8) (omega * 2).
\end{Coqsrc}

\end{exercise}

\subsection{Existence of a path}

\index{maths}{Transfinite induction}

By transfinite induction on $\alpha$, we prove that for any $\beta<\alpha$,
one can build a path from $\alpha$ to $\beta$ (in other terms, $\beta$ is accessible from $\alpha$).

\input{movies/snippets/Paths/LTPathTo}

\noindent
From the lemma \texttt{canonS\_LT}~\vref{lemma:canonS_LT}, we can convert any path into an inequality on ordinals (by induction on paths).

\input{movies/snippets/Paths/pathToLT}

\index{hydras}{Exercises}

\begin{exercise}[continuation of exercise~\vref{exo:simply-typed-canonseq}]
Define a simply typed function for computing a path from $\alpha$ to $\beta$.
\end{exercise}

\subsection{Paths and hydra battles}
\label{KS-o2h}

In order to apply our knowledge about  ordinal numbers less than $\epsilon_0$ to the study of hydra battles, we define an injection
from the interval $[0,\epsilon_0)$ into the type \texttt{Hydra}.

\vspace{4pt}

\emph{From Module~\href{../theories/html/hydras.Hydra.O2H.html}{Hydra.O2H}}

\input{movies/snippets/O2H/iotaDef}

For instance Fig.~\ref{fig:iota-example} shows the image by $\iota$ of the ordinal  \textcolor{black}{$\omega^{\omega+2}+\omega^\omega \times 2 + \omega + 1$}

  \begin{figure}[htb]
\centering
\begin{tikzpicture}[very thick, scale=0.3]
\node (foot) at (10,0) {$\bullet$};
\node (N1) at (2,2) {$\bullet$};
\node (N2) at (10,2) {$\bullet$};
\node (N22) at (7,2) {$\bullet$};
\node (N3) at (14,2) {$\bullet$};
\node (N4) at (18,2) {$\Smiley[2][green]$};
\node (N5) at (0,4) {$\bullet$};
\node (N6) at (2,5) {$\Smiley[2][green]$};
\node (N7) at (4,6) {$\Smiley[2][green]$};
\node (N88) at (7,4) {$\bullet$};
\node (N8) at (10,4) {$\bullet$};
\node (N9) at (14,6) {$\Smiley[2][green]$};
\node (N10) at (0,8) {$\Smiley[2][green]$};
\node (N11) at (10,7) {$\Smiley[2][green]$};
\node (N111) at (7,7) {$\Smiley[2][green]$};
\draw (foot) to [bend left=10] (N1);
\draw (foot) -- (N2);
\draw (foot) -- (N22);
\draw (foot) -- (N3);
\draw (foot) -- (N4);
\draw (N1) to  (N5);
\draw (N1) to   [bend left=10] (N6);
\draw (N1) to   [bend right=20] (N7);
\draw (N2) to  (N8);
\draw (N22) to  (N88);
\draw (N8) to  (N11);
\draw (N88) to  (N111);
\draw (N3) to  (N9);
\draw (N5) to  (N10);
\end{tikzpicture}
\caption{The hydra $\iota(\omega^{\omega+2}+\omega^\omega \times 2 + \omega + 1$) \label{fig:iota-example}}

\end{figure}

The following lemma (proved in ~\href{../theories/html/hydras.Hydra.O2H.html}{Hydra.O2H.v}) maps  canonical sequences to rounds of hydra battles.

\label{lemma:canonS-iota}

\input{movies/snippets/O2H/canonSIota}

The next step of our development extends this relationship to
the order $<$ on $[0,\epsilon_0)$ on one side, and hydra battles on the other side.

\input{movies/snippets/O2H/pathToRoundPlus}

As a corollary, we are now able to transform any inequality $\beta<\alpha<\epsilon_0$ into a (free) battle.

\input{movies/snippets/O2H/LTToRoundPlus}

\section{A  proof of impossibility}

We now have  the tools for proving that  there exists no variant bounded by some $\mu<\epsilon_0$ for proving the termination   of all battles. The proof we are going to show is a proof by contradiction. It  can
 be considered as a generalization of the
proofs described in  sections~\vref{omega-case} and \vref{omega2-case}.

In the module
\href{../theories/html/hydras.Hydra.Epsilon0_Needed_Generic.html}{Hydra.Epsilon0\_Needed\_Generic}, we assume there exists some variant $m$ bounded by some ordinal $\mu<\epsilon_0$. This part of the development is parameterized by some class $B$ of battles, which will be instantiated later to \texttt{free} or \texttt{standard}.

\input{movies/snippets/Hydra_Definitions/BoundedVariant}

Let us assume there exists such a variant:

\input{movies/snippets/Epsilon0_Needed_Generic/theContext}

\label{remark:m-decrease}
\begin{remark}
  The hypothesis \texttt{m\_decrease} is not provable  in general, but is satisfied by
the  \texttt{free} and \texttt{standard} kinds of battles. This trick allows to
``factorize'' our proofs  of impossibility.
\end{remark}

\index{maths}{Transfinite induction}

First, we prove that $m(\iota(\alpha))$ is always greater than or equal to $\alpha$, by  transfinite induction over $\alpha$.

\input{movies/snippets/Epsilon0_Needed_Generic/mGe0}

\begin{itemize}
\item If $\alpha=0$, the inequality trivially holds
\item If $\alpha$ is the successor of  some ordinal $\beta$, the inequality $\beta \leq m(\iota(\beta))$ holds (by induction hypothesis). But the hydra $\iota(\alpha)$ is transformed in one round into
$\iota(\beta)$, thus $m(\iota(\beta))<m(\iota(\alpha))$. Hence $\beta<m(\iota(\alpha))$, which implies $\alpha \leq m(\iota(\alpha))$
\item If $\alpha$ is a limit ordinal, then $\alpha$ is the least upper bound of the set
of all  the $\canonseq{\alpha}{i}$.  Thus, we have just to prove that $\canonseq{\alpha}{i}< m(\iota(\alpha))$ for any $i$.
\begin{itemize}
\item Let $i$ be some natural number.
By the induction hypothesis, we have $\canonseq{\alpha}{i} \leq m(\iota(\canonseq{\alpha}{i}))$. But the hydra $\iota(\alpha)$ is transformed into $\iota(\canonseq{\alpha}{i})$ in one round, thus $m(\iota(\canonseq{\alpha}{i})) < m(\iota(\alpha))$, by our hypothesis \texttt{m\_decrease}.
\end{itemize}
\end{itemize}

Please note that the impossibility proofs of
sections~\vref{omega-case} and \vref{omega2-case} contain a similar lemma, also called \texttt{m\_ge}.
We are now able to build a counter-example.

\input{movies/snippets/Epsilon0_Needed_Generic/mGeGeneric}

The (big) rest of the proof is dedicated to prove formally the converse inequality
\texttt{m small\_h t1< m big\_h}.

\subsection{The case of free battles}
\label{sec:free-battles-case}
Let us now consider that $B$ is instantiated to \texttt{free} (which means that we are considering proofs of termination of \emph{all} battles). The following lemmas are proved in Module~\href{../theories/html/hydras.Hydra.Epsilon0_Needed_Free.html}{Hydra.Epsilon0\_Needed\_Free}.
The case $B=\texttt{standard}$ is studied in section~\vref{std-case}.

\input{movies/snippets/Epsilon0_Needed_Free/theContext}

\begin{enumerate}
\item The following lemma is an application of \texttt{m\_ge\_generic}, since \texttt{free}
satisfies trivially the hypothesis \texttt{m\_decrease} (see page~\pageref{remark:m-decrease}).

\input{movies/snippets/Epsilon0_Needed_Free/mGe}

\item From the hypothesis \texttt{Hy}, we have \texttt{m big\_h t1< mu}
\item By Lemma \texttt{LT\_to\_round\_plus}, we get a (free) battle from
\texttt{big\_h = iota mu} to \texttt{small\_h = iota (m big\_h)}.

\input{movies/snippets/Epsilon0_Needed_Free/bigToSmall}

\item From the hypotheses on $m$, we infer:
\input{movies/snippets/Epsilon0_Needed_Free/mLt}

\item From lemmas \texttt{m\_ge} and \texttt{m\_lt}, and the irreflexivity of $<$, we get a contradiction.
\input{movies/snippets/Epsilon0_Needed_Free/ImpossibilityFree}

\end{enumerate}

We have now proved there exists no bounded variant for the class of free battles.

\input{movies/snippets/Epsilon0_Needed_Free/CheckDemo}

\section{The case of standard battles}
\label{sec:standard-intro}\label{std-case}
One may wonder if our theorem holds also in the framework of standard battles. Unfortunately, its proof relies on the lemma \texttt{LT\_to\_round\_plus} of
Module~\href{../theories/html/hydras.Hydra.O2H.html}{Hydra.O2H}.

\input{movies/snippets/O2H/LTToRoundPlus}

This lemma builds a battle out of any inequality $\beta<\alpha$.
It is a straightforward application of \texttt{LT\_path\_to} of
Module~\href{../theories/html/hydras.Epsilon0.Paths.html}{Epsilon0.Paths}:

\input{movies/snippets/Paths/LTPathTo}

The sequence $s$, used to build the sequence of replication factors of the battle, depends on
$\beta$, so we cannot be sure that the generated battle is a genuine standard battle.

The solution of this issue comes  once again from Ketonen and Solovay's article~\cite{KS81}. Instead of considering plain paths, i.e. sequences
$\alpha_0=\alpha,\alpha_1,\dots,\alpha_k=\beta$ where $\alpha_{j+1}$ is equal
to $\canonseq{\alpha_j}{i_j}$ where $i_j$ is \emph{any} natural number,
we consider various constraints on these sequences.
In particular, a path is called \emph{standard} if $i_{j+1} = i_j + 1$ for every $j<k$.
It  corresponds to a ``segment'' of some standard battles.
Please note that the vocabulary on paths is ours, but all the concepts come really from~\cite{KS81}.

In \coq{}, standard paths can be defined as follows.

\vspace{4pt}
\emph{From
Module~\href{../theories/html/hydras.Epsilon0.Paths.html}{Epsilon0.Paths}}

\input{movies/snippets/Paths/standardPathR}

In the mathematical text and figures, we shall use the notation
$\alpha \xrightarrow[i,j]{}\beta$ for the proposition
(\texttt{standard\_path $i$ $\alpha$ $j$ $\beta$}).
In~\cite{KS81} the notation is
$\alpha \xrightarrow[i]{*}\beta$
for
the proposition  $\exists j, i<j \wedge \alpha \xrightarrow[i,j]{} \beta$.

Our goal is now  to transform any inequality $\beta<\alpha<\epsilon_0$ into a standard path $\alpha \xrightarrow[i,j]{} \beta$ for some $i$ and $j$, then into a standard battle
from $\iota(\alpha+i)$ to $\iota(\beta)$.
Following~\cite{KS81}, we proceed in two stages:
\begin{enumerate}
\item we simulate plain (free) paths from $\alpha$ to $\beta$ with
paths made of steps $(\gamma,\canonseq{\gamma}{n})$, \emph{with the same $n$ all along the path}
\item we simulate any such path by a standard path.
\end{enumerate}

\subsection{Paths with a constant index}

First of all, paths with a constant index
enjoy nice properties. They are defined as paths where all the $i_j$ are equal to the same natural number $i$, for some $i>0$.

Like in~\cite{KS81}, we shall use the notation $\alpha \xrightarrow[i]{} \beta$ for denoting such a path, also called an $i$-path.

\input{movies/snippets/Paths/constPathDef}

% Paths with a given index can be effectively computed.
% Given $i$, $\alpha$ and $l$, the following function returns the ordinal $\beta$ such that there exists a path
% $\alpha \xrightarrow [i+1] {} \beta$ of length $l$.

% \begin{Coqsrc}
% Fixpoint const_funS (i:nat)(alpha : T1)(l:nat):  T1  :=
%   match l
%   with
%   | 0 => alpha
%   | S m => const_funS i (canonS i alpha) m
%   end.
% \end{Coqsrc}

% The following computations show  applications of \texttt{constS\_fun} to the
% ordinal $\omega^\omega$, with various values of $i$ and $l$.

% \begin{Coqsrc}
% Compute  (const_funS 2 (omega ^omega)  55).
% \end{Coqsrc}

% \begin{Coqanswer}
%   = zero
%      : T1
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute pp (const_funS 2 (omega ^omega) 15).
% \end{Coqsrc}

%   \begin{Coqanswer}
%  = (omega ^ 2 * 2)%pT1
%      : ppT1
%   \end{Coqanswer}

% \begin{Coqsrc}
% Compute pp (const_funS 4 (omega^omega)  100).
% \end{Coqsrc}

% \begin{Coqanswer}
% = (omega ^ 4 * 4 + omega ^ 3 * 4 + omega ^ 2 + omega * 4 + 4)%pT1
%      : ppT1
% \end{Coqanswer}

A most interesting property of $i$-paths is that we can ``upgrade'' their index, as stated by K.\&S.'s Corollary 12.

\index{maths}{Transfinite induction}

\emph{From
  Module~\href{../theories/html/hydras.Epsilon0.Paths.html}{Epsilon0.Paths}}

\input{movies/snippets/Paths/Cor12}

We  also use a version of \texttt{Cor12} with large inequalities.

\input{movies/snippets/Paths/Cor121}

\subsubsection{Sketch of proof of \texttt{Cor12}}
\index{maths}{Transfinite induction}

We prove this lemma by transfinite induction on $\alpha$.
Let us consider a path $\alpha \xrightarrow [i]{} \beta$ $(i>0)$. Its first step is
the pair $(\alpha,\canonseq{\alpha}{i})$, We have $\canonseq{\alpha}{i}<\alpha$ and
$\canonseq{\alpha}{i} \xrightarrow [i]{} \beta$.
Let $n$ be any natural number such that $n>i$.
By the induction hypothesis, there exists a path $\canonseq{\alpha}{n} \xrightarrow[i]{} \beta$.
\begin{itemize}
\item  If $\alpha$ is a successor ordinal $\gamma+1$, then $\canonseq{\alpha}{n} =
\canonseq{\alpha}{i}=\gamma$. Thus we have a path
$\alpha  \xrightarrow [n]{}  \gamma \xrightarrow [n]{} \beta$
\item If $\alpha$ is a limit ordinal, we apply the following theorem (numbered \texttt{2.4} in Ketonen and Solovay's article).

%   \begin{theorem}
% Let $\lambda$ be a limit ordinal, then for any pair of indices $0<i<j$, there is a path $\canonseq{\lambda}{j} \xrightarrow[1]{} \canonseq{\lambda}{i}$.
%   \end{theorem}

\input{movies/snippets/Paths/KSThm24}

 We build the following paths :

 \begin{enumerate}
 \item $\alpha \xrightarrow[n]{} \canonseq{\alpha}{n}$
 \item $\canonseq{\alpha}{n} \xrightarrow[1]{} \canonseq{\alpha}{i}$ (by \texttt{Theorem\_2\_4}),
\item $\canonseq{\alpha}{n} \xrightarrow[n]{} \canonseq{\alpha}{i}$ (applying the induction hypothesis to the preceding path);
\item $\canonseq{\alpha}{i} \xrightarrow[n]{} \beta$ (applying the induction hypothesis)\item $\alpha \xrightarrow[n]{} \beta$ (by composition of 1, 3, and 4).

 \end{enumerate}

\end{itemize}

\begin{remark}
 \texttt{Cor12} ``casts'' $i$-paths into $n$-paths for any $n>i$.
But the obtained $n$-path can be much longer than the original $i$-path.
The following exercise will give an idea of this increase.
\end{remark}

\index{hydras}{Exercises}
\begin{exercise}
  Prove that  the length of the $i+1$-path from
  $\omega^\omega$ to $\omega^i$ is $1 + (i+1)^{(i+1)}$, for any $i$. Note that the $i$-path from
  $\omega^\omega$ to $\omega^i$ is only one step long.
 \end{exercise}

Why is \texttt{Cor12} so useful?
Let us  consider two ordinals  $\beta<\alpha<\epsilon_0$. By induction on $\alpha$,
we decompose any inequality $\beta<\alpha$ into $\beta < \canonseq{\alpha}{i}< \alpha$, where $i$ is some integer. Applying corollary \texttt{Cor12'} we build a $n$-path from $\beta$ to $\alpha$,
where $n$ is the maximum of the indices $i$ met in the induction.

 Lemma 1, Section 2.6 of~\cite{KS81} is naturally expressed in terms of \coq's
\verb@sig@ construct.

\label{lemma:L-2_6-1}
\index{coq}{Sigma types}

\input{movies/snippets/Paths/Lemma261}

Intuitively, lemma   \texttt{Lemma2\_6\_1}  shows that if $\beta<\alpha<\epsilon_0$, then there exists  a battle from $\iota(\alpha)$ to $\iota(\beta)$ where the replication factor is constant, although large enough.

\subsection{Casting paths with a constant index into a standard path}

The article~\cite{KS81} contains
the following lemma, the proof of which is quite complex, which allows to simulate $i$-paths by $[i+1,j]$-paths, where $j$ is large enough.

\input{movies/snippets/Paths/constantToStandard}

\subsubsection{Sketch of proof of \texttt{constant\_to\_standard\_path}}

Our proof follows the proof by Ketonen and Solovay, including its organization as a sequence of lemma.  Since it is a non-trivial proof, we will comment its main steps below.

\subsubsection*{Preliminaries}

Please note that, given an ordinal $\alpha:\texttt{T1}$, and two natural numbers $i$ and $l$, there exists at most a standard path $\alpha \xrightarrow [i,i+l]{*} \beta$.
The following function computes $\beta$ from $\alpha$, $i$ and $l$.

\input{movies/snippets/Paths/standardGnaw}

\index{maths}{Transfinite induction}

By transfinite induction over  $\alpha$, we prove that the ordinal $0$ is reachable from any ordinal $\alpha<\epsilon_0$ by some standard path.

\input{movies/snippets/Paths/standardPathToZero}

\paragraph*{}
Now, let us consider two ordinals  $\beta<\alpha<\epsilon_0$.  Let $p$  be some $(n+1)$-path from $\alpha$ to $\beta$.

\input{movies/snippets/Paths/ConstantToStandardProof}

Applying \texttt{standard\_path\_to\_zero}, $0$ is reachable from $\alpha$ by some standard path  (see figure~\vref{fig:belle-preuve-1}).

\begin{figure}[h]
  \centering

\begin{tikzpicture}[very thick, scale=0.25]
\node (alpha) at (0,0) {$\alpha$};
    \node (beta) at (32, 0){$\beta$};

  \draw[->, very thick,blue] (alpha)-- node [below]{$n+1$} node [above] {$+$} (beta);

  \node (alpha1) at (5,5) {};
  \node (alpha2) at (13,5) {};
    \node (alpha3) at (20,5) {};
  \node (alphalast) at (35,5) {};
  \node (zero) at (45,0) {$0$};
  \draw [->, dashed,very thick,blue] (alpha)-- node [below, rotate=40]{$n+1$}  (alpha1);
  \draw [->, dashed,very thick,blue] (alpha1)-- node [below]{$n+2$}  (alpha2);
   \draw [->, dashed,very thick,blue] (alpha2)-- node [below]{$n+3$}  (alpha3);

  \node (dots) at (24,5) {$\dots$};
  \draw [->, dashed, very thick,blue] (alphalast)-- node [below, rotate=-26]{$n+p+1$}  (zero);

\end{tikzpicture}
\caption{A nice proof (1)}
  \label{fig:belle-preuve-1}
\end{figure}

\paragraph*{}

Since comparison on \texttt{T1} is decidable, one can compute the last step $\gamma$ of the standard path from $(\alpha,n+1)$  such that $\beta\leq \gamma$.
Let $l$ be the length of the path from $\alpha$ to $\gamma$.
This step of the proof is illustrated in figure~\vref{fig:belle-preuve-2}.

\begin{figure}[h]
  \centering

\begin{tikzpicture}[very thick, scale=0.25]
\node (alpha) at (0,0) {$\alpha$};
    \node (beta) at (32, 0){$\beta$};

  \node (alpha1) at (5,5) {};
  \node (alpha2) at (13,5) {};
  \node (dots) at (17,5) {$\ldots$};
    \node (alpha3) at (20,5) {};
    \node (gamma) at (24,0) {$\gamma$};
    \node (delta) at (38,0) {$\delta$};
    \draw [->, dashed,very thick,blue] (alpha)-- node [below,rotate=35]{$n+1$}  (alpha1);
  \draw [->, dashed,very thick,blue] (alpha1)-- node [below]{$n+2$}  (alpha2);
   \draw [->, dashed,very thick,blue] (alpha3)-- node [below,rotate = -48]{\tiny $n+l$}  (gamma);
   \draw  [->, dashed, blue] (gamma) to    [bend left=80] node [below]{$n+l+1$} (delta);
   \draw[->, very thick,blue] (alpha) to [bend right=34] node [below]{$n+1$} node [above] {$+$} (beta);
   \draw[thick] (alpha)--  (gamma);
   \draw[thick] (gamma)--  node [above] {$\geq$} (beta);
    \draw[thick] (beta)--  node [above] {$>$} (delta);
\end{tikzpicture}

\caption{A nice proof (2)}
  \label{fig:belle-preuve-2}
\end{figure}

\paragraph*{}

\begin{itemize}
\item If $\beta=\gamma$, its OK! We have got a standard path
from
$\alpha$ to $\beta$ with successive indices  $n+1, n+2, \dots, n+l+1$

\item Otherwise,  $\beta < \gamma$.  Let us consider  $\delta=\canonseq{\gamma}{n+l+1}$.
By applying several times lemma \texttt{Cor12},  one converts  every path of Fig~\ref{fig:belle-preuve-2} into
 a $n+l+1$-path  (see figure~\ref{fig:belle-preuve-3}).

But $\gamma$ is on the $n+l+1$-path from $\alpha$ to $\beta$.
As shown by figure~\vref{fig:fin-belle-preuve}, the ordinal $\delta$, reachable from
$\gamma$ in one single step,  must be greater than or equal to $\beta$, which contradicts our  hypothesis $\beta < \gamma$.

\begin{figure}[h]
  \centering

\begin{tikzpicture}[very thick, scale=0.25]
\node (alpha) at (0,0) {$\alpha$};
    \node (beta) at (32, 0){$\beta$};
    \node (alpha1) at (5,5) {};
  \node (alpha2) at (13,5) {};
  \node (dots) at (17,5) {$\ldots$};
    \node (alpha3) at (20,5) {};
    \node (gamma) at (24,0) {$\gamma$};
    \node (delta) at (38,0) {$\delta$};
     \draw [->, dashed,very thick,blue] (alpha)-- node [below, rotate = 40] {\tiny $n+l+1$}  node [above, rotate = 40]{\tiny $+$}  (alpha1);
  \draw [->, dashed,very thick,blue] (alpha1)-- node [below]{\tiny $n+l+1$} node [above]{\tiny $+$} (alpha2);
   \draw [->, dashed,very thick,blue] (alpha3)-- node [below, rotate = -48]{\tiny $n+l+1$} node [above, rotate = -36]{\tiny $+$}  (gamma);
   \draw  [->, dashed, blue] (gamma) to    [bend left=80] node [below]{\tiny $n+l+1$} node [above]{\color{red} $1$} (delta);
   \draw[->, very thick,blue] (alpha) to [bend right=34] node [below]{\small $n+l+1$} node [above] {\tiny $+$} (beta);
    \draw[thick] (gamma)--   node [above]{\color{red} $>$}(beta);
   \draw[thick] (alpha)--  (gamma);

    \draw[thick] (beta)--  node [above] {$>$} (delta);

\end{tikzpicture}

\caption{A nice proof (3)}
  \label{fig:belle-preuve-3}
\end{figure}

\begin{figure}[h]
  \centering
\begin{tikzpicture}[very thick, scale=0.25]
\node (alpha) at (0,0) {$\alpha$};
    \node (beta) at (32, 0){$\beta$};

  \node (alpha1) at (5,5) {};
  \node (alpha2) at (13,5) {};
  \node (dots) at (15,5) {$\ldots$};
    \node (alpha3) at (18,5) {};
    \node (gamma) at (24,0) {$\gamma$};
    \node (delta) at (42,0) {$\delta$};
    \draw [->, dashed,very thick,blue] (alpha)-- node [below, rotate = 40] {\tiny $n+l+1$}  node [above, rotate = 40]{\tiny $+$}  (alpha1);
  \draw [->, dashed,very thick,blue] (alpha1)-- node [below]{\tiny $n+l+1$} node [above]{\tiny $+$} (alpha2);
   \draw [->, dashed,very thick,blue] (alpha3)-- node [below, rotate = -36]{\tiny $n+l+1$} node [above, rotate = -36]{\tiny $+$}  (gamma);
   \draw  [->, dashed, blue] (gamma) to    [bend left=80] node [below]{\small $n+l+1$} node [above]{\color{red} $1$} (delta);
   \draw[->, very thick,blue] (alpha) to [bend right=34] node [below]{\small $n+l+1$} node [above] {\tiny $+$} (beta);
   \draw[thick] (alpha)--  (gamma);

    \draw[thick] (gamma)--  node [below]{\tiny $n+l+1$} node [above]{\color{red} $+$}(beta);
    \draw[thick] (beta)--  node [above] {$>$} (delta);

\end{tikzpicture}

\caption{A nice proof (4)}
  \label{fig:fin-belle-preuve}
\end{figure}

\end{itemize}
 The only possible case is  thus $\beta=\gamma$, so we have got a standard path  from $\alpha$ to $\beta$.

\input{movies/snippets/Paths/constantToStandard0}

Here is the full statement of the conversion from constant to standard paths.

\input{movies/snippets/Paths/constantToStandardPath}

Applying \texttt{Lemma2\_6\_1} and \texttt{constant\_to\_standard\_path}, we get the following corollary.

\input{movies/snippets/Paths/LTToStandardPath}

\subsection{Back to hydras}
\label{sec:standard-battles-cases}
We are now able to complete our proof that there exists no bounded variant for proving the termination of standard hydra battles. This proof can
be consulted in the module
\href{../theories/html/hydras.Hydra.Epsilon0_Needed_Std.html}{Hydra.Epsilon0\_Needed\_Std}.
Please note that it has the same global structure as in section\ref{sec:free-battles-case}
% ICI !
Applying the  lemmas  \texttt{Lemma2\_6\_1} of the module
\href{../theories/html/hydras.Epsilon0.Paths.html\#Lemma2_6_1}%
{Epsilon0.pathS}   and
\href{../theories/html/hydras.Epsilon0.Paths.html\#constant_to_standard_path}%
{\texttt{constant\_to\_standard\_path}},
we can convert any inequality $\beta<\alpha<\epsilon_0$ into a standard path from
$\alpha$ to  $\beta$, then into a fragment of a standard battle from
$\iota(\alpha)$ to $\iota(\beta)$, hence the inequality $m(\iota(\beta))<m(\iota(\alpha))$.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Hydra.Epsilon0_Needed_Std.html\#LT_to_standard_battle}{Hydra.Epsilon0\_Needed\_Std}}

\input{movies/snippets/Epsilon0_Needed_Std/LTToStandardBattle}

Next, please consider the following context:

\input{movies/snippets/Epsilon0_Needed_Std/theContext}

In the same way as for free battles, we import a large inequality
from
the module \href{../theories/html/hydras.Hydra.Epsilon0_Needed_Generic.html}{Epsilon0\_Needed\_Generic}.

\input{movies/snippets/Epsilon0_Needed_Std/mGe}

\paragraph*{} If remains to prove the following strict inequality, in order to have a contradiction.

\input{movies/snippets/Epsilon0_Needed_Std/mLt}

\paragraph*{Sketch of proof:} Let us recall that $\texttt{big\_h} = \iota(\mu)$
 and $\texttt{small\_h} = \iota (m (\texttt{big\_h}))$.

Since $m(\texttt{big\_h})< \mu$, there exists a standard path from $\mu$ to
$m(\texttt{big\_h})$, hence a   standard battle from $\iota(\mu)$  to
$\iota(m(\texttt{big\_h}))$,  i.e. from \texttt{big\_h} to \texttt{small\_h}.

Since $m$ is assumed to be a variant for standard battles, we get the inequality  $m(\texttt{small\_h}) < m(\texttt{big\_h})$.

\input{movies/snippets/Epsilon0_Needed_Std/endOfProof}

\subsection{Remarks}

We are grateful to
 J. Ketonen and R. Solovay  for the high quality of their explanations and proof details.
Our proof follows tightly the sequence of lemmas in their article, with a focus on
constructive aspects.
Roughly speaking, our implementation \emph{builds}, out of a hypothetical
  variant $m$, bounded by some ordinal $\mu<\epsilon_0$, a hydra \texttt{big\_h} which verifies the impossible inequality  $m(\texttt{big\_h})< m(\texttt{big\_h})$.

On may ask whether the preceding results are too restrictive, since they
refer to a particular data type \texttt{T1}.
In fact, our representation of ordinals strictly less than
 $\epsilon_0$ is faithful to their mathematical definition, at least
Kurt Schütte's~\cite{schutte}, as proved in Chapter~\vref{chap:schutte}.
(please see also the module
\href{../theories/html/hydras.Schutte.Correctness_E0.html}{hydras.Schutte.Correctness\_E0}).

Thus, we can infer that our theorems can be applied to any well order.

\index{hydras}{Projects}
\begin{project}
Study a possible modification of the definition of a variant  (for  standard battles).

\begin{itemize}
\item The variant is assumed to be strictly decreasing \emph{on configurations
reachable from some initial configuration where the replication factor is equal to $0$}
\item The variant may depend on the number of the current round.
\end{itemize}

In other words, its type should be \texttt{nat -> Hydra -> T1}, and it must
verify the inequality $m\, (S\,i)\, h' < m\,i\, h$ whenever the configuration
$(i,h)$ is reachable from some initial configuration $(0,h_0)$
and \texttt{h} is transformed into \texttt{h'} in the considered round.
Can we still prove the theorems of section~\ref{std-case} with this new definition?

\end{project}

%---------------------------------------------------------------------
\chapter{Large sets and rapidly growing functions}\label{chap:alpha-large}

\begin{remark}
Some notations (mainly names of fast-growing functions) of our development may differ slightly from the literature. Although this fact does not affect our proofs, we are preparing a future version where the names $F\_alpha$, $f\_alpha$, $H\_alpha$, etc., are fully consistent with the cited articles.

\end{remark}
%\section{Introduction}

In this chapter, we try to feel how long a standard battle can be.
To be precise, for any ordinal $\alpha<\epsilon_0$ and any positive integer $k$,
we give a minoration of the number of steps of a standard battle which
starts with the hydra $\iota(\alpha)$ and the replication factor $k$.

We express this number in terms of the Hardy hierarchy of fast-growing
functions~\cite{BW85, Wainer1970, KS81, Promel2013}.
 From the \coq{} user's point of view, such  functions are  very
attractive:  they are defined as functions  in \gallina{}, and we can apply them \emph{in theory}, but they are so complex that you will never be able to look at the result of the computation.
 Thus, our knowledge on these functions must rely on \emph{proofs}, not tests. In our development, we use often the rewriting rules generated by \coq's \texttt{Equations} plug-in.

\section{Definitions}

%\subsection{Definition}

\begin{definition}
Let $0<\alpha<\epsilon_0$ be any ordinal, and $s=\langle s_1, s_2, \dots, s_N\rangle$ a finite sequence of strictly positive natural numbers.

We say that $s$ is \emph{$\alpha$-large} if the sequence $\langle \alpha_0=\alpha,\dots,\alpha_{i+1}=\canonseq{\alpha_i}{i+1},\dots \rangle$ leads to $0$.
We say also that $s$ is \emph{minimally $\alpha$-large} (in short:
\emph{$\alpha$-mlarge}) if $s$ is $\alpha$-large
 and every strict prefix of $s$ leads to a non-zero ordinal (\emph{cf} Sect.~\vref{sect:path-to-def}).

\index{maths}{Ordinal numbers!Large sets}
\index{maths}{Ordinal numbers!Minimal large sets}

\end{definition}

\begin{remark}
  Ketonen and Solovay~\cite{KS81} consider  large finite \emph{sets} of natural numbers,  but they are mainly used as sequences. Thus, we chose to represent them explicitely as (sorted) lists.
\end{remark}

The following function ``gnaws'' an ordinal $\alpha$, following a sequence of indices (ignoring the $0$s).

\vspace{4pt}

\noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Paths.html\#gnaw}{Epsilon0.Paths}}

\input{movies/snippets/Paths/gnawDef}

\noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Large_SetsPaths.html\#gnaw}{Epsilon0.Large\_Sets}}

\input{movies/snippets/Large_Sets/largeDef}

Minimal large sequences can be directly defined in terms of the
predicate \texttt{path\_to} (\vref{sect:path-to-def}) which already prohibits paths containing non-final \texttt{zero}s.

\vspace{4pt}

\noindent
\emph{From Module~ \href{../theories/html/hydras.Epsilon0.Large_Sets.html\#mlarge}{Epsilon0.Large\_Sets}}

\index{hydras}{Library Epsilon0!Predicates!mlarge@mlarge (minimal large sequences)}

\input{movies/snippets/Large_Sets/largeDef}

Let us consider two integers $k$ and $l$, such that $0<k<l$. In order to check whether the interval $[k,l]$ is minimally large for $\alpha$, it is enough to
follow from $\alpha$ the path associated with the interval $[k,l)$ and verify that the last ordinal we obtain is equal to $1$.

\subsection{Example}

For instance the interval $[6,70]$ leads $\omega^2$ to $\omega\times 2 + 56$. Thus this interval is not $\omega^2$-mlarge.

\noindent
\emph{From Module~ \href{../theories/html/hydras.Epsilon0.Large_Sets_Examples.html\#mlarge}{Epsilon0.Large\_Sets\_Examples}}

\input{movies/snippets/Large_Sets_Examples/gnawEx1}

Let us try another computation.
\input{movies/snippets/Large_Sets_Examples/gnawEx2}

We may say that the interval $[6,700]$ is $\omega^2$-large, since it leads to $0$, but nothing assures us that the condition of minimality is satisfied.

The following lemma relates minimal largeness with the
function
\texttt{gnaw}.

\input{movies/snippets/Large_Sets/mlargeIff}

For instance, we can verify that the interval $[6,510]$ is $\omega^2$-mlarge.

\vspace{4pt}
 \noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Large_Sets_Examples.html}{Epsilon0.Large\_Sets\_Examples}}

\input{movies/snippets/Large_Sets_Examples/Ex1Lemma}

\section{Length of minimal large sequences}

Now, consider any natural number $k>0$ any ordinal $0<\alpha<\epsilon_0$.  We would like to compute
a number $l$ such that the interval $[k,l]$ is $\alpha$-mlarge. So,
the standard battle starting with $\iota(\alpha)$ and the replication factor $k$ will end after $(l-k+1)$ steps.

First, we notice that this  number $l$ exists, since the segment $[0,\epsilon_0)$ is well-founded and $\canonseq{\alpha}{i}<\alpha$ for any $i$ and $\alpha>0$.
Moreover, it is unique:

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Large_Sets.html}{Epsilon0.Large\_Sets}}

\input{movies/snippets/Large_Sets/mlargeUnicity}

Thus, we would like to define a function, parameterized by $\alpha$ which associates to any  strictly positive integer $k$ the number $l$ such that
the interval $[k,l]$ is $\alpha$-mlarge. It would be fine to write in \gallina{} a definition like this:

\begin{Coqbad}
Function L_ (alpha: E0) (i:nat) :  nat := ...
\end{Coqbad}

But we do not know how to fill the dots yet \dots{}   In the next section, we will
use \coq{} to reason  about the \emph{specification} of \texttt{L},
prove properties of any function which satisfies this specification.
In Sect.~\ref{sect:L-equations}, we use the \texttt{coq-equations} plug-in
to define a function \texttt{L\_}, and prove its correctness w.r.t. its specification.

\subsection{Formal specification}

Let $0<\alpha<\epsilon_0$ be an ordinal term. We consider any  function which  maps  any strictly positive integer $k$ to the number $l$, where
the interval $[k,l)$ is $\alpha$-mlarge.

\begin{remark}
In~\cite{KS81} Ketonen and Solovay consider the least natural number $l$ where the interval $[k,l]$ ($l$ included) is $\alpha$-large, and call $H_\alpha$ the function which maps $k$ to $l$. We chose to consider intervals $[l,k)$ instead of $[l,k]$
in order to simplify  some statements and proofs in composition lemmas associated with the ordinals of the form $\alpha\times i$ and
$\omega^\alpha\times i + \beta$.
Clearly, both approaches are related through the equality
$L_\alpha(k)=H_\alpha(k)+1$, for any non-null $\alpha$ and $k$.
\end{remark}

Our specification of the function \texttt{L} is as follows:

\emph{From Module~\href{../theories/html/hydras.Epsilon0.Large_Sets.html}{Epsilon0.Large\_Sets}}

\input{movies/snippets/Large_Sets/LSpecDef}

\begin{todo}
 Check if the functions $L_\alpha$ are the same as
\cite{KS81}' functions $f\_alpha$ (p. 297).
\end{todo}

Note that, for $\alpha\not=0$, the value of $f(0)$ is not specified.
Nevertheless, the restriction of $f$ to the set of strictly positive integers is unique (up to extensionality).

\input{movies/snippets/Large_Sets/LSpecUnicity}

\subsection{Abstract properties}

Let us now prove properties of any function $f$ (if any) which satisfies
\texttt{L\_spec}. We are looking for properties which could be used for writing \emph{equations} and prove the correctness of the function generated by the \texttt{coq-equations} plug-in. Moreover, they will give us some examples (for small values of $\alpha$).

Our exploration of the $L_\alpha$\,s  follows the usual scheme : transfinite induction, and proof-by-cases : zero, successors and limit ordinals.

\index{maths}{Transfinite induction}

\subsubsection{The  ordinal zero}
\label{sect:L-spec-zero}
The base case is directly a consequence of the specification.

\input{movies/snippets/Large_Sets/LZeroInv}

\subsubsection{Successor ordinals}
\label{sect:L-spec-succ}
Let $\beta$ be some ordinal, and assume the arithmetic function $f$ satisfies
the specification $(\texttt{L\_spec}\;\beta)$.  Let $k$ be any natural number.
Any path from $\texttt{succ}\,\beta$ to $0$ starting at $k+1$ can be decomposed into a first step from $\texttt{succ}\,\beta$ to $\beta$, then a path from
$\beta$ at $k+2$ to $0$.
By hypothesis the interval $[k+2, f(k+2)-1]$ is $\beta$-mlarge.
But the interval $[k+1, f(k+2)-1]$ is the concatenation of the singleton
$\{k+1\}$ and the interval $[k+2, f(k+2)-1]$.
So, the function $\lambda\,k.\,f(k+1)$ satisfies the specification $\texttt{L\_spec}\,\beta$.

Note that our decomposition of intervals works only if the intervals we consider are not empty. In order to ensure this property, we assume that $f\;k$ is always greater than $k$, which we note \texttt{S <<= f}, or \texttt{(fun\_le S f)}.

Useful abstract properties of arithmetic functions are
defined
in~\href{../theories/html/hydras.Prelude.Iterates.html\#fun_le}{Prelude.Iterates}.

\label{sect:abstract-arith-prop}

\input{movies/snippets/Iterates/funLeDef}

We prove also that the functions we consider are strictly monotonous. The section on successor ordinals has the following structure.

\emph{From Module~\href{../theories/html/hydras.Epsilon0.Large_Sets.html}{Epsilon0.Large\_Sets}}

\input{movies/snippets/Large_Sets/SectionSucc}

\subsubsection{Limit ordinals}
\label{sect:L-spec-lim}

Let $\lambda<\epsilon_0$ be any limit ordinal. In a similar way as for successors, we decompose any path from $\lambda$  into a first step to
$\canonseq{\lambda}{k}$, followed by a path to $0$. In the following section, we assume that there exists a correct function computing  $L_{\canonseq{\lambda}{k}}$ for any strictly positive $k$.

\input{movies/snippets/Large_Sets/SectionLim}

\subsection{First results}

Applying the previous lemmas on successors and limit ordinals,
we obtain a few  correct implementations of \texttt{(L\_spec $\alpha$)} for small values of $\alpha$.

\subsubsection{Finite ordinals}

By iterating the functional \texttt{L\_succ}, we get a realization of
\texttt{(L\_spec (fin $i$))} for any natural number $i$.

\input{movies/snippets/Large_Sets/LFinDef}
\vspace{-16pt}
\input{movies/snippets/Large_Sets/LFinOk}

\subsubsection{The first limit ordinal  \texorpdfstring{$\omega$}{omega}}

The lemmas \texttt{L\_fin\_ok} and \texttt{L\_lim\_ok}   allow us to get
by diagonalization a correct implementation for
\texttt{L\_spec omega}.

\input{movies/snippets/Large_Sets/LOmegaDef}
\vspace{-16pt}
\input{movies/snippets/Large_Sets/LOmegaOk}

\subsubsection{Towards  \texorpdfstring{$\omega^2$}{omega*omega}}

We would like to get exact formulas for the ordinal $\omega^2$, a.k.a.
$\phi_0(2)$. This ordinal is the limit of the sequence $\omega\times i\;(i \in \mathbb{N})$. Thus, we have to study ordinals of this form, then use
our lemma on limits.

The following lemma establishes a path from $\omega\times ( i+1)$ to
$\omega \times i$.

\input{movies/snippets/Large_Sets/pathToOmegaMult}

Let us consider a path from  $\omega\times(i+1)$ to $0$ starting at $k+1$.
A first ``big step'' will lead to $\omega\times i$ at $2(k+1)$. If $i>0$, the
next jump leads to $\omega\times(i-1)$ at $2(2(k+1))+1$, etc.

The following lemma expresses the length of the mlarge sequences associated with the finite multiples of $\omega$.

\input{movies/snippets/Large_Sets/omegaMultMlarge0}

\emph{From Module~ \href{../theories/html/hydras.Epsilon0.Large_Sets.html\#L_omega_mult}{Epsilon0.Large\_Sets}}

\input{movies/snippets/Large_Sets/LOmegaMultDef}

More generally, we prove the equality $L_{\omega\times i}(k)=2^i\times(k+1)-1$.

\input{movies/snippets/Large_Sets/LOmegaMultEqn}

Correctness of the function \texttt{L\_omega\_mult} is asserted through the following lemma.

\input{movies/snippets/Large_Sets/LOmegaMultOk}

By diagonalization, we obtain a simple formula for $L_{\omega^2}$.

\input{movies/snippets/Large_Sets/LOmegaSquare}
\input{movies/snippets/Large_Sets/LOmegaSquareEqn}
\input{movies/snippets/Large_Sets/LOmegaSquareOk}

%%%% ICI

\subsubsection{Going further}
Let us consider a last example, ``computing'' $L_{\omega^3}$.
Since the canonical sequence associated with this ordinal is composed of the
$\omega^2\times i\;(i\in\mathbb{N}_1)$, we have to study this sequence.

To this end, we prove a generic lemma, which expresses $L_{\omega^\alpha\times i}$ as an iterate of $L_{\omega^\alpha}$. Note that in this lemma, we assume that the function associated with $\alpha$ is strictly monotonous and
greater or equal than the successor function, and prove that $L_{\omega^\alpha\times i}$ satisfies  the same properties.

\input{movies/snippets/Large_Sets/phi0Mult}

Let us look now
at the ordinal $\omega^2\times i$, using \texttt{L\_phi0\_mult}.

\input{movies/snippets/Large_Sets/LOmegaSquareTimes}

We are now ready to get an exact formula for $L_{\omega^3}$, by diagonalization upon $L_{\omega^2\times i}$.

\input{movies/snippets/Large_Sets/LOmegaCube}

Thus, for instance, $L_{\omega^3}(3)=L_{\omega^2\times 4}(3)$.

\input{movies/snippets/Large_Sets/LOmegaCube3Eq}

This number is quite big. Using \texttt{Ocaml}'s \texttt{float} arithmetic,
we can under-approximate it by $2^{3.8\times10^{30}}\times 3.8\times{10^{30}}$.

\begin{Coqsrc}
# let exp2 x = 2.0 ** x;;

val exp2 : float -> float = <fun>
#   exp2 95.0 *. 97.0 -. 1.0;;
- : float = 3.84256588194182037e+30
# let n = exp2 95.0 ;;
# let p = n *. 97.0 -. 1.0;;
val p : float = 3.84256588194182037e+30

Estimation :
2 ** (3.84 e+30) * 3.84 e+30.
\end{Coqsrc}

\subsection{Using \texttt{Equations}}
\label{sect:L-equations}

Note that we did not define any function $L_\alpha$ \emph{for any $\alpha<\epsilon_0$} yet. We have got no more than a collection of proved realizations of $\texttt{L\_spec}\;\alpha$ for a few values of $\alpha$.

\index{coq}{Plug-ins!Equations}

Using the \texttt{coq-equations} plug-in by
M. Sozeau~\cite{sozeau:hal-01671777}, we will now define a function \texttt{L\_} which maps any ordinal  $\alpha<\epsilon_0$ to a proven realization of
$\texttt{L\_spec}\;\alpha$.
To this end, we represent ordinals as inhabitants of the type
\texttt{E0} of well-formed ordinal terms (see Sect~\vref{sect:E0-def}). So, we define a total function \texttt{L\_} of type
\texttt{E0 -> nat -> nat}, by transfinite recursion, considering the usual three cases : $\alpha=0$, $\alpha$ is a successor, $\alpha$ is a limit ordinal.

\subsubsection{Definition}

\vspace{4pt}
\noindent
\emph{From Module~\href{../theories/html/hydras.Epsilon0.L_alpha.html\#L_}{L\_alpha}).}

\label{Functions:L-alpha}
 \index{hydras}{Library Epsilon0!Functions!L\_@L\_ (final step of a minimal path}

\input{movies/snippets/L_alpha/LDef}

This definition results in a bunch of automatically generated lemmas. For instance:

\input{movies/snippets/L_alpha/AboutLEquation1}

In most cases, it may be useful to write human-readable  paraphrases of these statements.

\input{movies/snippets/L_alpha/Paraphrases}

Using these three lemmas as rewrite rules, we can prove more properties of the functions \texttt{L\_$\alpha$}.

\input{movies/snippets/L_alpha/LFiniteOmega}

By  well-founded induction on $\alpha$, we prove the following lemmas:

\input{movies/snippets/L_alpha/LGeS}

\input{movies/snippets/L_alpha/LCorrect}

Please note that the proof of \texttt{L\_correct} applies the lemmas proven in Sections~\ref{sect:L-spec-zero}, ~\ref{sect:L-spec-succ} and ~\ref{sect:L-spec-lim}.
Our previous study of \texttt{L\_spec} allowed us to pave the way for the definition by \texttt{Equations} and the correctness proof.

\subsubsection{Back to hydra battles}
\label{def:L-alpha}

Lemma \texttt{battle\_length\_std } of
Module~\href{../theories/html/hydras.Hydra.Battle_length.html}{Hydra.Battle\_length} relates the length of standard battles with the functions $L_\alpha$.

\input{movies/snippets/Battle_length/battleLengthStd}

\index{hydras}{Projects}
\begin{project}
Instead of considering standard paths and battles, consider ``constant'' paths and the corresponding battles. Please use \texttt{Equations} in order to define the function that computes the length of the $k$-path which leads  from $\alpha$ to $0$.
Prove a few  exact formulas and minoration lemmas.
\end{project}

\section{A variant of the Wainer-Hardy hierarchy}

\label{sect:hardy}

In order to give a feeling on  the complexity of the functions  $L_\alpha$s, we compare them with a better known family of functions, the  \emph{Wainer-Hardy hierarchy} of fast growing functions,
presented for instance in~\cite{Promel2013}.
\index{maths}{Rapidly growing functions!Hardy Hierarchy}

\begin{remark}
  Indeed, the functions presented in this section are a \emph{variant} of the Hardy hierarchy of functions. In the future versions of this development, we will correct the references to the literature. For the time being, we call our functions $H'_\alpha$ in order to underline the difference from ``classic'' Hardy functions.
\end{remark}

For each ordinal $\alpha$ below $\epsilon_0$, $H'_\alpha$ is
a total arithmetic function, defined  by  transfinite recursion on $\alpha$, according to three cases:

\index{maths}{Transfinite induction}

\begin{itemize}
\item If $\alpha=0$, then $H'_\alpha (k)= k$ for any natural number $k$.
\item If $\alpha=\textrm{succ}(\beta)$, then
$H'_\alpha(k)=H'_\beta(k+1)$ for any $k \in \mathbb{N}$
\item If $\alpha$ is a limit ordinal, then
$H'_\alpha(k) = H'_{(\canonseq{\alpha}{k+1})}(k)$ for any $k\in \mathbb{N}$.
\end{itemize}

\begin{remark}
 The ``classic'' definition of the Wainer-Hardy hierarchy differs in the third equation.

\begin{itemize}
\item If $\alpha=0$, then $H_\alpha (k)= k$ for any natural number $k$.
\item If $\alpha=\textrm{succ}(\beta)$, then
$H_\alpha(k)=H_\beta(k+1)$ for any $k \in \mathbb{N}$
\item If $\alpha$ is a limit ordinal, then
$H_\alpha(k) = H_{(\canonseq{\alpha}{k})}(k)$ for any $k\in \mathbb{N}$.
\end{itemize}

\end{remark}

\subsection{Definition in \texttt{Coq}}

We define a function \texttt{H'\_} of type \texttt{E0 -> nat -> nat} by transfinite induction over the type \texttt{E0} of the well formed ordinals below $\epsilon_0$.

\vspace{4pt}
\emph{From Module~\href{../theories/html/hydras.Epsilon0.Hprime.html\#H_}{Epsilon0.Hprime}}

\index{hydras}{Library Epsilon0!Functions!H\_@H\_ (Hardy hierarchy (variant))}
\index{coq}{Plug-ins!Equations}
\label{Functions:Hprime-alpha}

\input{movies/snippets/Hprime/HprimeDef}

\input{movies/snippets/Hprime/paraphrases}

\subsection{First  steps of the H' hierarchy}
Using rewrite rules from \texttt{H'\_eq1} to \texttt{H'\_succ\_eqn}, we can explore the functions $H'_\alpha$ for  small values of $\alpha$.

%ICI

\subsubsection{Finite ordinals}

By induction on $i$, we prove a simple expression of \texttt{H'\_ (Fin i)}, where
\texttt{Fin $i$}  is the $i$-th finite ordinal.

\input{movies/snippets/Hprime/HprimeFin}

\subsubsection{Multiples of \texorpdfstring{$\omega$}{omega}}

Since the canonical sequence of $\omega$ is composed of finite ordinals,
it is easy to get the formula associated with $H'_\omega$.

\input{movies/snippets/Hprime/HprimeOmega}

Before going further, we prove a useful rewriting lemma:

\input{movies/snippets/Hprime/HprimePlusFin}

Then, we get easily formulas for $H'_{\omega+i}$, and $H'_{\omega\times i}$ for any natural number $i$.

\input{movies/snippets/Hprime/HprimeExamples}

Crossing a new limit, we prove the following equality:
$$H'_{\omega^2} (k) = 2 ^ {k+1} \times (k+1) - 1$$.

\input{movies/snippets/Hprime/HprimeOmegaSqr}

\subsubsection{New limits}

Our next step would be to prove an exact formula for $H'_{\omega^\omega}(k)$.
Since the canonical sequence of $\omega^\omega$ is composed of all the
$\omega^i$, we first need to express $H'_{\omega^i}$ for any natural number $i$.

Let $i$ and $k$ be two natural numbers.
The ordinal $\canonseq{\omega^(i+1)}{k}$ is the product
$\omega^i \times k$, so we need also to consider ordinals of this form.

\begin{enumerate}
\item First,  we express $H'_{\omega^\alpha \times (i+2)}$ in terms of
$H'_{\omega^\alpha \times (i+1)}$.

\input{movies/snippets/Hprime/HprimeOmegaTerm1}

\item
Then, we prove by induction on $i$ that $H'_{\omega^\alpha \times (i+1)}$ is just the
$(i+1)$-th iterate of $H'_{\omega^\alpha}$.

\input{movies/snippets/Hprime/HprimeOmegaTerm}

\item In particular, we derive a formula for $H'_{\omega^{i+1}}$.

\input{movies/snippets/Hprime/HprimeSuccFun}
\input{movies/snippets/Hprime/HprimePhi0SI}

\item We get now a  formula for $H'_{\omega^3}$:

\input{movies/snippets/Hprime/HprimeOmegaCube}
\end{enumerate}

\subsubsection{A numerical example}

It looks hard to capture the complexity of this function by looking only at this
``exact'' formula.
Let us consider a simple example: the number $H'_{\omega^3}(3)$.

\input{movies/snippets/Hprime/HprimeOmegaCube3a}

Thus, the number $H_{\omega^3}(3)$ can be written as four nested applications of $f$.

\input{movies/snippets/Hprime/HprimeOmegaCube3b}

In order to make this statement more readable, we can introduce a local définition.

\input{movies/snippets/Hprime/HprimeOmegaCube3c}

This number looks quite big; let us compute an approximation with \texttt{Ocaml}:

\begin{Coqsrc}
# (2.0 ** 64.0 *. 64.0 -. 1.0);;
\end{Coqsrc}

\begin{Coqanswer}
- : float = 1.1805916207174113e+21
\end{Coqanswer}

\input{movies/snippets/Hprime/HprimeOmegaCube3d}

In a more classical writing, this number is displayed as follows:

{\Large
$$
H'_{\omega^3}(3) =  2 ^ {(2 ^ {N + 1} \, (N+1) )}   \,  (2 ^ {N+1} \, ( N +1) ) - 1
$$
}

We leave as an exercise to determine the best approximation as possible of
 the size of this number (for instance its number of digits).  For instance, if
we do not take into account the multiplications in the formula above,
we obtain that, in base $2$, the number $H'_{\omega^3}(3)$ has at least
$2^{10^{21}}$  digits. But it is still an under-approximation !

Now, we have got at last an exact formula for $H'_{\omega^\omega}$.

\input{movies/snippets/Hprime/HprimePhi0Omega}

Using extensionality of the functional \texttt{iterate}, we also get a closed formula.

\input{movies/snippets/Hprime/HprimePhi0OmegaClosed}

Note that this formula contains two occurrences of the functional \texttt{iterate}, the outer one is in fact a second-order iteration (on type \texttt{nat -> nat)}
and the inner one  first-order (on type \texttt{nat}).

\subsection{Abstract properties of
\texorpdfstring{$H'_\alpha$}{H'}}
~\label{sect:H-alpha-prop}

Since pure computation seems to be useless for dealing with expressions of the form $H'_\alpha(k)$, even for small values of $\alpha$ and $k$, we need to prove theorems for comparing $H'_\alpha(k)$ and $H'_\beta(l)$, in terms of comparison
between $\alpha$ and $\beta$ on the one hand, $k$ and $l$ on the other hand.

But beware of fake theorems! For instance, one could believe that $H'$ is monotonous in its first argument. The following proof shows this is false.

\input{movies/snippets/Hprime/HprimeNonMono1}

On the contrary, the functions of the $H'$ hierarchy have the following five properties~\cite{KS81}: for any $\alpha < \epsilon_0$,
\begin{itemize}
\item the function $H'_\alpha$ is strictly monotonous :
      For all $n,p \in\mathbb{N}, n < p \Rightarrow H'_\alpha(n)< H'_\alpha(p)$.
\item If $\alpha \not= 0$, then for every $n$, $n<H'_\alpha(n)$.
\item The function $H'_\alpha$ is pointwise less or equal than $H'_{\alpha+1}$

\item For any $n\geq 1$, $H'_\alpha(n)<H'_{\alpha+1}(n)$.
\emph{We say that $H'_{\alpha+1}$ dominates $H'_\alpha$ from $1$}.
\item For any $n$ and $\beta$, if $\alpha \xrightarrow[n]{} \beta$, then
$H'_\beta(n)\leq H'_\alpha(n)$.
\end{itemize}

\index{maths}{Abstract properties of arithmetic functions}
\index{hydras}{Abstract properties of arithmetic functions}

\index{maths}{Transfinite induction}

In \coq{}, we follow the  proof in~\cite{KS81}. This proof is mainly a single  proof by transfinite induction on $\alpha$ of the conjunction of the five properties.
For each $\alpha$, the three cases : $\alpha=0$, $\alpha$ is a limit, and
$\alpha$ is a successor are considered. Inside each case, the five sub-properties are proved sequentially, using the abstract properties defined in Sect~\vref{sect:abstract-arith-prop}

\input{movies/snippets/Hprime/PAP}

% By elimination, we get a catalogue of properties of the functions $L'_\alpha$:

% \begin{Coqsrc}
% Section Abstract_Properties.
%  Variable alpha : E0.

%  Theorem H'_alpha_mono : strict_mono (H'_ alpha).

%  Theorem H'_alpha_gt : alpha <> Zero ->
%         forall n, n < H'_ alpha n.

%  Theorem H'_alpha_Succ_le :
%         H'_ alpha <<= H'_ (Succ alpha).

%  Theorem H'_alpha_dom :
%     dominates_from 1 (H'_ (Succ alpha)) (H'_ alpha).

%  Theorem H'_restricted_mono_l :
%     forall beta n, Canon_plus n alpha beta ->
%                                  H'_ beta n <= H'_ alpha n.

%   Lemma H'_alpha_ge_id : id <<= H'_ alpha.

%   Lemma H'_alpha_mono_weak : forall k l, k <= l ->
%                                         H'_ alpha k <= H'_ alpha l.

% End Abstract_Properties.
% \end{Coqsrc}

Using a few lemmas \emph{à la} Ketonen-Solovay, we prove that
if $\alpha<\beta$, then $H'_\beta$ eventually dominates
$H'_\alpha$.
We let the reader look at its proof (Section \texttt{Proof\_of\_H'\_mono\_l} of \href{../theories/html/hydras.Epsilon0.Hprime.html\#H_}{Epsilon0.Hprime}).

\noindent
\input{movies/snippets/Hprime/HprimeDom}

\subsection{Comparison between \texttt{L\_} and \texttt{H'\_} }

By well-founded induction on $\alpha$, we prove a simple relation between $L_\alpha$ and $H'\_alpha$.

\emph{From Module~\href{../theories/html/hydras.Epsilon0.L_alpha.html\#H'_L_}{Epsilon0.L\_alpha}}

\input{movies/snippets/L_alpha/HprimeL}

\subsubsection{Back to hydras}

The following theorem relates the length of (standard) battles with the the $H'$ family of fast growing functions.

\vspace{4pt}

\noindent
\emph{From Module~\href{../theories/html/hydras.Hydra.Hydra_Theorems.html}{Hydra.Hydra\_Theorems}}

\input{movies/snippets/Hydra_Theorems/battleLengthStdHardy}

\section{A variant of the Wainer hierarchy (functions \texorpdfstring{$F_\alpha$}{F\_alpha})}
\label{sect:wainer}

\index{maths}{Rapidly growing functions!Wainer Hierarchy}

Ketonen and Solovay introduce in~\cite{KS81} a ``trivial'' variant of the Wainer hierarchy~\cite{BW85, Wainer1970} of fast growing functions, indexed by ordinals below $\epsilon_0$.

\label{F_equations}
\begin{itemize}
\item $F_0(i)=i+1$
\item $F_{\beta+1}(i)= (F_\beta)^{(i+1)}(i)$, where $f^{(i)}$ is the $i$-th iterate of $f$.
\item $F_\alpha(i) = F_{\canonseq{\alpha}{i}} (i)$ if $\alpha$ is a limit ordinal.
\end{itemize}

\begin{remark}
The difference with the ``classic'' Wainer hierarchy
$f\_\alpha\;(\alpha<\epsilon_0)$ lies in the second equation:
$f_{\beta+1}(i) = (f_\beta)^{(i)}(i)$ and not
$f_{\beta+1}(i) = (f_\beta)^{(i+1)}(i)$. A module about
the classic Wainer hierarchy is in preparation.
\end{remark}

A first attempt is to write a definition of $F_\alpha$ by equations, in the same way as for $H\_alpha$.  We use the functional \texttt{iterate} defined in
Module~\href{../theories/html/hydras.Prelude.Iterates.html\#iterate}{Prelude.Iterates}.

\index{hydras}{Library Prelude!iterate}

\input{movies/snippets/Iterates/iterateDef}

The following code comes from
 \href{../theories/html/hydras.Epsilon0.F_alpha.html}{Epsilon0.F\_alpha}.

 \index{coq}{Plug-ins!Equations}

 \input{movies/snippets/F_alpha/FailDemo}

We presume that this error comes from the recursive call of \texttt{F\_} inside
an application of \texttt{iterate}. The workaround we propose is to define first
the iteration of \texttt{F\_}  as an helper $F^*$, then to define the function $F$ as a ``iterating $F^*$ once''.

\texttt{Equations} accepts the following definition, relying on  lexicographic ordering on pairs $(\alpha,n)$.

\label{sect:F-equations}

\index{coq}{Plug-ins!Equations}
\label{Functions:F-alpha}
\index{maths}{Rapidly growing functions}
\index{hydras}{Library Epsilon0!Functions!F\_@F\_ (Wainer hierarchy)}

\input{movies/snippets/F_alpha/goodDef}

It is quite easy to prove that our function \texttt{F\_} satisfies the equations on page~\pageref{sect:F-equations}.
\index{hydras}{Library Prelude!iterate}

\input{movies/snippets/F_alpha/FEquations}

As for the Hardy functions, we can use these equalities as rewrite rules for
``computing'' some values of $F_\alpha(i)$, for small values of $\alpha$.

\input{movies/snippets/F_alpha/FirstValues}

Like in Sect~\ref{sect:H-alpha-prop}, we prove by induction the following properties (see~\cite{KS81}).

\input{movies/snippets/F_alpha/FalphaThms}

As a corollary, we prove the following proposition, p. 284 of~\cite{KS81}.
\begin{quote}
  If $\beta<\alpha$, $F_\alpha$ dominates $F_\beta$.
\end{quote}

\input{movies/snippets/F_alpha/FDomContext}
\input{movies/snippets/F_alpha/FDom}

\index{hydras}{Exercises}

\begin{exercise}
Prove the following property:

\begin{Coqsrc}
Lemma LF3 : dominates_from  2 (F_ 3) (fun  n => iterate exp2 n n).
\end{Coqsrc}

\emph{You may start this exercise with the file
\href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/F_3.v}{exercises/ordinals/F\_3.v}.}
\end{exercise}

\index{hydras}{Exercises}

\begin{exercise}
Prove that, for any $\alpha\geq 3$ and $n\geq 2$,
$F_\alpha(1+n)\geq 2^{F_\alpha(n)}$.

\emph{You may start this exercise with the file
    \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/F_3.v}{exercises/ordinals/F\_3.v}.}
\end{exercise}

%ici
\index{hydras}{Exercises}

\begin{exercise}
It is tempting to prove a simple property of monotony
of the function \texttt{F\_}.

\begin{quote}
   Let $\alpha\leq\beta<\epsilon_0$. For any $n\geq 2$,
$F_\alpha(n)\leq F_\beta(n)$.
\end{quote}
Prove or disprove this statement.

\emph{You may start this exercise with the file
    \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/is_F_monotonous.v}{exercises/ordinals/is\_F\_monotonous.v}.}
\end{exercise}

\index{hydras}{Exercises}
\begin{exercise}

Prove that for any $n\geq 2$, $\textrm{Ack}\,\,n\,n\leq  F_\omega(n)$, where \textrm{Ack} is the Ackermann function. Next, prove that $F_\alpha$ is not primitive recursive, for any $\alpha\geq\omega$  (please see Sect.~\vref{sect:ack-not-PR}).
On the other hand, please show that for any natural number $n$, the function $F_n$ is primitive recursive.
Thus $F\_alpha$ is primitive recursive if and only if $\alpha$ is finite.

\emph{You may start this exercise with the file
    \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/F_omega.v}{exercises/ordinals/F\_Omega.v}.
Properties of the Ackermann function are studied in
    \href{https://github.com/coq-community/hydra-battles/tree/master/theories/ordinals/MoreAck/Ack.v}{theories/ordinals/MoreAck/Ack.v} and
    \href{https://github.com/coq-community/hydra-battles/tree/master/theories/ordinals/MoreAck/AckNotPR.v}{theories/ordinals/MoreAck/AckNotPR.v}
.}
\end{exercise}

\section{Conclusion}

In Sect.~\vref{sect:battle-length-notPR}, we prove that the length of hydra-battles (for a given hydra, according to the initial replication factor) is not primitive recursive in general.
This proof uses properties of the Ackermann function, and the $H'_\alpha$, $F_\alpha$, $L_\alpha$ families of functions.

%%% TODO : Check the statement !
%
% \index{hydras}{Exercises}
% \begin{exercise}
% Let us quote a theorem from ~\cite{KS81} (page 297).

% \begin{quote}
% \begin{align*}
%   H'_{\omega^\alpha}(n+1) &\geq F_{\alpha}(n) \quad (n\geq 1, \alpha<\epsilon_0) \\
%  F_{\alpha}(n+1) &\geq H'_{\omega^\alpha}(n) \quad (n\geq 1, \alpha<\epsilon_0)
% \end{align*}
% Thus $H'_{\omega^\alpha}$ and $F_{\alpha}$ have essentially the same order of growth.

% \end{quote}

%  But, before trying to prove these facts, look at the definition of function $H$ in Ketonen and Solovay's paper ! Is it really the same as the definition we quote from Pr{\H o}mel's chapter~\cite{Promel2013},
% whereas \cite{KS81} define $H_\alpha(n)$ as ``the least integer $k$ such that $[n,k]$ is $\alpha$-large''. Thus, it may be useful to adapt the statement above.

% \end{exercise}

%  \subsection{Gnawing ordinals}

% \begin{definition}[After~\cite{KS81}]
%   Let $S$ be a finite set of positive integers, and $\alpha$ be an ordinal strictly less than $\epsilon_0$.  Let us denote by $s=s_1,s_2, \dots, s_N$ the sequence of
% the elements of $S$, enumerated in strictly increasing order.

% We consider the sequence of ordinals $\alpha_o=\alpha, \alpha_1=\canonseq{\alpha_0}{s_1},\dots,\alpha_{i+1}=\canonseq{\alpha_i}{s_{i+1}},\dots,
% \alpha_{N}=\canonseq{\alpha_{N-1}}{s_N}$.
% We denote by $\gnaw{s}{\alpha}$ the last ordinal of the sequence, \emph{i.e.}  $\alpha_N$.
% \end{definition}

% The following function computes $\gnaw{s}{\alpha}$ by recursion on $s$.
% \vspace{4pt}

% For instance, let us consider the ordinal $\omega^\omega$, and try some sequence of integers.

% \begin{Coqsrc}
% Compute pp (gnaw (omega ^ omega) (1::nil)).
% \end{Coqsrc}

% \begin{Coqanswer}
%   = omega%pT1 : ppT1
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute pp (gnaw (omega ^ omega) (1::2::nil)).
% \end{Coqsrc}

% \begin{Coqanswer}
% = P_fin 2
%      : ppT1
% \end{Coqanswer}

% Likewise, we can verify that $\gnaw{\omega^\omega}{\langle 1,2,3 \rangle}=1$
% and $\gnaw{\omega^\omega}{\langle 1,2,3,4 \rangle}=0$.

% \begin{Coqsrc}
% Example omega_omega_1_4 : gnaw (omega ^omega) (interval 1 4) = 0.
% Proof. trivial. Qed.

% Example omega_omega_1_3 : gnaw (omega ^omega) (interval 1 3) = 1.
% Proof. trivial. Qed.
% \end{Coqsrc}

% \begin{remark}
% \label{remark:gnaw-vs-battles}
% Let us consider an hydra battle, where Hercules always chops off the rightmost head of the hydra. Let $\alpha<\epsilon_0$ be an ordinal number, and
% $s=\langle i_1<i_2<\dots<i_N\rangle$ be  any finite sequence of positive integers.
% Then the battle initiated by the hydra $\iota(\alpha)$, with $s$ as the sequence of successive replication factors, leads to the hydra $\iota(\gnaw{s}{\alpha})$ as the final state.
% \end{remark}

% \subsection{Large sequences}

% \begin{remark}
% In their article~\cite{KS81}, Ketonen and Solovay use the appellation ``large set'' instead of ``large sequence'', but their definitions use an enumeration of the elements in increasing order. Thus, we shall use the term ``sequence'' when referring to our implementation in \coq{}, and ``set'' when referring to the statements of~\cite{KS81}.
% \end{remark}

% \begin{definition}[After\cite{KS81}]
% The sequence $s$ is said to be \emph{$\alpha$-large} if $\gnaw{\alpha}{s}=0$.
% \end{definition}

% \begin{Coqsrc}
% Definition largeb (alpha : T1) (s: list nat) :=
%   match gnaw alpha s with
%     | zero => true
%     | _ => false
%   end.

% Definition large (alpha : T1) (s : list nat) : Prop :=
%   largeb alpha s.
% \end{Coqsrc}

% For instance, the sequence $\langle 1,2,3,4 \rangle$ is $\omega^\omega$-large but not
% $\omega^{\omega+1}$-large, since $\gnaw{\omega^{\omega+1}}{\langle 1,2,3,4\rangle}$ is equal to $\omega \times 2 + 4$.

% %\omega^\omega+\omega^2\times 3 + \omega\times 4+ 5$.

% \begin{Coqsrc}
% Compute largeb (omega^omega) (interval 1 4).
% \end{Coqsrc}

% \begin{Coqanswer}
% = true : bool
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute largeb (omega^(omega+1)) (interval 1 4).
% \end{Coqsrc}

% \begin{Coqanswer}
% = false : bool
% \end{Coqanswer}

% \begin{remark}
% A sequence $s$ is $\alpha$-large if (still considering Hercules ``righmost-head'', tactic), it leads to Hercules' victory.
% \end{remark}

% \subsection{A little game}

% Let $\alpha<\epsilon_0$ be an ordinal, and $i$ a positive integer. We want to guess the least natural number  $j$  such that the interval $[i,i+j]$ is $\alpha$-large.
% Equivalently, we should have $\gnaw{\alpha}{[i, i+j-1]}=1$.

% The following functions takes three arguments: an ordinal $\alpha$, and two positive natural numbers  $i$ and $j$ (we assume, but not verify that $i$ and $j$ are strictly positive). It returns one of the three possible answers:

% \begin{itemize}
% \item \texttt{Ok} if $j$ is the smallest integer such that the interval $[i,i+j]$ is $\alpha$-large
% \item \texttt{Too\_far} if $[i,i+j]$ is  $\alpha$-large, but $j$ is not the smallest such positive integer
% \item \texttt{(Remaining $\beta$)} if $j$ is too small, and gnawing $\alpha$ with
%   $[i,i+j]$ is still equal to $\beta$, instead of $0$
% \end{itemize}

% \vspace{4pt}
% \noindent
% \emph{From Module~\href{../theories/html/hydras.Epsilon0.Large_Sets_Demo.html}{Ordinals.Epsilon0.Large\_Sets\_Demo}}

% \begin{Coqsrc}
% Inductive answer : Set := You_won | Too_far | Remaining (rest : ppT1).

% Definition large_set_check alpha i j :=
%   let beta := gnaw alpha (interval i (Nat.pred j))
%   in match beta with
%      | one => Ok
%      | zero => Too_far
%      |  _ => Remaining (pp (canonseq j beta))
%      end.
% \end{Coqsrc}

% \subsubsection{\texorpdfstring{$\omega$}{omega}-large intervals}

% For instance, let us consider the ordinal $\omega$ and start with $i=1$.

% \begin{Coqsrc}
% Compute large_set_check omega 1 2.
% \end{Coqsrc}

% \begin{Coqanswer}
%      = Ok
%      : answer
% \end{Coqanswer}

% Let us give greater values of $i$, still with the ordinal $\omega$.

% \begin{Coqsrc}
% Compute large_set_check omega 2 3.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Remaining 1
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check omega 3 3.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Remaining 3
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check omega 2 4.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Ok
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check omega 3 6.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Ok
%      : answer
% \end{Coqanswer}

% It looks like every request to compute (\texttt{large\_set\_check omega $i$ $2\times i$})  will succeed. Let us try an example.

% \begin{Coqsrc}
% Compute large_set_check omega 49 98.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Ok
%      : answer
% \end{Coqanswer}

% \subsubsection{\texorpdfstring{$\omega^2$}{omega\^{}2}-large intervals}

% Still using \texttt{Compute} and \texttt{large\_set\_check}, we obtained the
% following values of $j$, the least integer such that the interval $[i,j]$ is $\omega^2$ large.

% $$
% \begin{array}{|c|c|}
% \hline
%   i & j \\
% \hline
% 1 & 4 \\
% 2 & 14 \\
% 3 & 38 \\
% 4 & 94 \\
% 5 & 222 \\
% % 6 & 510
% \hline
% \end{array}
% $$

% \begin{exercise}
% Please give the 6-th and 7-th line of the array above.
% \end{exercise}

% \subsubsection{The limits of (pure) computation}

% Let us now play with bigger ordinals, for instance $\alpha=\omega^\omega$ or
% $\alpha=\omega^{\omega + 1}$. We notice that, even for small values of $i$, it is hard
% to guess values of $j$ such that $[i,i+j]$ is $\alpha$-large.

% \begin{Coqsrc}
% Compute large_set_check (omega ^ omega) 1 4.
% \end{Coqsrc}

% \begin{Coqanswer}
%  = Ok
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check (omega ^ omega) 2 38.
% \end{Coqsrc}

% \begin{Coqanswer}
%  = Ok
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check (omega ^ omega) 3 1000.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Remaining (omega ^ 2 * 2 + omega * 220 + 798)%pT1
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check (omega ^ omega) 3 1798.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Remaining (omega ^ 2 * 2 + omega * 220)%pT1
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check (omega ^ omega) 3 5000.
% \end{Coqsrc}

% \begin{Coqanswer}
%   = Remaining (omega ^ 2 * 2 + omega * 218 + 2198)%pT1
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check (omega ^ (omega + 1)) 3 5000.
% \end{Coqsrc}

% \begin{Coqanswer}
%  = Remaining
%          (omega ^ omega * 2 + omega ^ 3 * 4 +
%           omega ^ 2 * 4 + omega * 1148 +  4222)%pT1
%      : answer
% \end{Coqanswer}

% \begin{Coqsrc}
% Compute large_set_check (omega ^ (omega + 1)) 3 10000.
% \end{Coqsrc}

% \begin{Coqanswer}
% Warning: To avoid stack overflow, large numbers in nat are interpreted as
% applications of Init.Nat.of_uint. [abstract-large-number,numbers]

%     = Remaining
%          (omega ^ omega * 2 + omega ^ 3 * 4 +
%           omega ^ 2 * 4 + omega * 1147 +
%           8446)%pT1
%      : answer
% \end{Coqanswer}

% Since computation is not enough, let us comme back to proofs, or, better, proofs \emph{and} computations.

% \subsection{Proving largeness}

% %%% ICI %%%

% \subsection{$n$-large and $\omega$-large intervals }

% A finite ordinal is just made out of \texttt{zero} and \texttt{succ} constructions.
% Thus any sequence of strictly positive integers of length greater than  or equal to $n$ will completely gnaw the ordinal $n$.

% Concerning the first limit ordinal $\omega$ the largeness of a sequence $s$ depends only on its first element and the length of the rest of the sequence (please keep in mind that the argument $i$ of $\canonseq{\alpha}{i}$ is meaningful only if $\alpha$ is a limit ordinal).
% The following proposition is labeled $4.2$ in~\cite{KS81}.

% \begin{proposition}
%   For $n<\omega$, a set $X$id $n$-large if and only if $|X|\geq n$.
% A finite set $X$ is $\omega$-large if $|X|>\min{X}$.
% \end{proposition}

% Rewritten in terms of list of strictly positive integers, we get the following statements:

% \begin{Coqsrc}
% Lemma large_n_iff : forall s (n:nat) , ~ In 0 s  ->
%                                   large n s  <-> (n <= List.length s)%nat.
% \end{Coqsrc}

% \begin{Coqsrc}
% Lemma large_omega_iff : forall s n,  ~In 0 (n::s) ->
%                                             large omega (n::s) <->
%                                             (n <=  List.length s)%nat.
% \end{Coqsrc}

% % \begin{Coqsrc}
% % (* sorted list of natural numbers greater than or equal to n *)

% % Inductive sorted_ge (n: nat) : list nat -> Prop :=
% % | sorted_ge_nil : sorted_ge n nil
% % | sorted_ge_one : forall p, n<=p ->
% %                             sorted_ge n (p::nil)
% % | sorted_ge_cons: forall p q s,  n<=p -> p<q ->
% %                                  sorted_ge p (q::s) ->
% %                                  sorted_ge n (p::q::s).
% % \end{Coqsrc}

% \subsection{Mimimal large sequences}

% Let us consider \emph{minimal} large sequences, \emph{i.e.} large sequences
% the strict prefix of which do not lead to $0$. In other words, only the last ordinal
% defined by the sequence is null.  For this purpose, we use the predicate \texttt{path\_to} introduced page~\pageref{path-to-definition}.

% \begin{Coqsrc}
% Definition mlarge alpha s := path_to zero s alpha.
% \end{Coqsrc}

%------------------------------------------------------
\section{A certified catalogue of rapidly growing functions}

In this section, we try to present an abstract of the properties of the main variants of fast-growing hierarchies of functions
we found in the literature or we had to define as helpers in our proofs.

\subsection{Ketonen-Solovay's \texttt{F\_alpha}}

  This hierarchy is presented p.280 of~\cite{KS81} as `` a trivial variant of one introduced by Wainer ''.
  Let us recall the equations shown in Sect.~\vref{F_equations}.

\begin{itemize}
\item $F_0(i)=i+1$
\item $F_{\beta+1}(i)= (F_\beta)^{(i+1)}(i)$, where $f^{(i)}$ is the $i$-th iterate of $f$.
\item $F_\alpha(i) = F_{\canonseq{\alpha}{i}} (i)$ if $\alpha$ is a limit ordinal.
\end{itemize}

Note that \cite{KS81} defines also $F_{\epsilon_0}$ (by the third equation). Since $\epsilon_0$ is not representable in type \texttt{E0}, our translation in \coq{} does not take $F_{\epsilon_0}$ into account.

Several properties of $F_\alpha$ are already presented in Sect.~\ref{F_equations}.

%----------------------------------------------------------------------
\chapter[Countable ordinals (after Sch\"{u}tte)]{Kurt Schütte's axiomatic definition of countable ordinals}

\label{chap:schutte}
%ON

In the present chapter, we  compare our implementation of the segment $[0,\epsilon_0)$ with a mathematical text in order to ``validate'' our constructions.
Our reference here is the axiomatic definition of the set of countable ordinals,
in chapter V of Kurt Schütte's book `` Proof Theory ''~\cite{schutte}.

\begin{remark}
\emph{In all this chapter, the word ``ordinal'' will be considered as a synonymous of
``countable ordinal''}
\end{remark}

Schütte's definition of countable ordinals relies on the following three axioms:

There  exists a strictly ordered set , such that
\begin{enumerate}
\item  $(\mathbb{O},<)$ is well-ordered
\item Every bounded subset of $\mathbb{O}$  is countable
\item Every countable subset of $\mathbb{O}$  is bounded.
\end{enumerate}

Starting with these three axioms, Schütte re-defines the vocabulary about ordinal numbers: the null ordinal $0$, limits and successors, the addition of ordinals, the infinite ordinals $\omega$, $\epsilon_0$, $\Gamma_0$, etc.

This chapter describes an adaptation to \coq{} of Schütte's axiomatization.
 Unlike the rest of our libraries, our library
\href{../theories/html/hydras.Schutte.Schutte.html}{hydras.Schutte}
is not constructive, and relies on several axioms.

\begin{itemize}
\item First, please keep in mind  that the set of countable ordinals is not countable. Thus, we cannot hope to represent all countable ordinals as finite terms of an inductive type, which was possible with  the set of ordinals strictly less than $\epsilon_0$ (resp. $\Gamma_0$)
\item We tried to be as close as possible to K. Schütte's text, which uses ``classical'' mathematics : excluded middle, Hilbert's $\epsilon$ (choice) and Russel's $\iota$ (definite description) operators. Both operators allow us to write definitions close to the natural mathematical language, such as ``$\textrm{succ}$ is \emph{the} least ordinal strictly greater than $\alpha$''
\item Please note that only the library \href{../theories/html/hydras.Schutte.Schutte.html}{Schutte/*.v} is ``contaminated'' by axioms, and that the rest of our libraries remain constructive.
\end{itemize}

\section{Declarations and axioms}

Let us declare a type
\texttt{Ord} for representing countable ordinals, and a binary relation
 \texttt{lt}. Note that, in our development, \texttt{Ord} is a type, while the \emph{set} of countable ordinals (called $\mathbb{O}$ by Schütte)
is the full set over the type \texttt{Ord}.

\label{types:Ord}

We use Florian Hatat's library on countable sets, written as he was a student of  \emph{\'Ecole Normale Supérieure de Lyon}. A set $A$ is countable if there is an injective function from $A$ to $\mathbb{N}$ (see
Library \href{../theories/html/hydras.Schutte.Countable.html}%
{\texttt{Schutte.Countable}}).

\vspace{6pt}

\emph{From Module\href{../theories/html/hydras.Schutte.Schutte_basics.html}%
{\texttt{Schutte.Schutte\_basics}}}

\index{hydras}{Library Schutte!Types!Ord}

\input{movies/snippets/Schutte_basics/OrdDecl}

Schütte's first axiom tells that \texttt{lt} is a well order on the set
\texttt{ordinal} (The  class \texttt{WO} is defined in
Module~\href{../theories/html/hydras.Schutte.Well_Orders.html}{Schutte.Well\_Orders.v}).

\index{hydras}{Library Schutte!Type classes!WO@ WO (well order)}

\label{types:WO}

\input{movies/snippets/Well_Orders/Mdecl}

\input{movies/snippets/Well_Orders/WODef}

\input{movies/snippets/Schutte_basics/AX1}

The second and third axioms say that a subset $X$ of $\mathbb{O}$ is
(strictly) bounded if and only if it is countable.

\input{movies/snippets/Schutte_basics/AX23}

\texttt{AX2} and \texttt{AX3} could have been replaced by a single axiom (using the \texttt{iff} connector), but we decided to respect as most as possible the structure of Schütte's definitions.

\section{Additional  axioms}

The adaptation of Schütte's mathematical discourse to \coq{} led us to
import a few axioms from the standard library. We encourage the reader to consult \coq{}'s FAQ about the safe use of axioms
 \url{https://github.com/coq/coq/wiki/The-Logic-of-Coq#axioms}.

\subsubsection{Classical logic}

In order to work with classical logic, we import the module
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Logic.Classical.html}{Coq.Logic.Classical}  of \coq{}'s standard library, specifically the following axiom:

\begin{Coqsrc}
 Axiom classic : forall P:Prop, P \/ ~P.
\end{Coqsrc}

\subsubsection{Description operators}

In order to respect Schütte's style, we imported also the library
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Logic.Epsilon.html}{\texttt{Coq.Logic.Epsilon}}.  The rest of this section presents a few examples of
how Hilbert's choice operator and Church's definite description allow us
 to write understandable definitions (close to the mathematical natural language).

\subsubsection{The definition of zero}

According to the  definition of a well order, every non-empty subset of \texttt{Ord} has a least element. Furthermore, this least element is unique. We would like to call this element  \texttt{zero}.

\input{movies/snippets/Schutte_basics/iotaDemo}

Indeed, the basic logic of  \coq{} does not allow us to eliminate a proof of a proposition
$\exists!\,x:A,\,P(x)$ for building a term whose type lies in the sort \texttt{Type}.
The reasons for this impossibility are explained in many documents~\cite{BC04, chlipalacpdt2011, Coq}.

Let us import the library \texttt{Coq.Logic.Epsilon}, which contains the following axiom and lemmas.

\begin{Coqsrc}
Axiom epsilon_statement:
  forall (A : Type) (P : A->Prop), inhabited A ->
    {x : A | (exists x, P x) -> P x}.
\end{Coqsrc}

Hilbert's $\epsilon$ \emph{operator} is derived from this  axiom.

\begin{Coqsrc}
Definition epsilon (A : Type) (i:inhabited A) (P : A->Prop) : A
  := proj1_sig (epsilon_statement P i).

Lemma constructive_indefinite_description :
  forall (A : Type) (P : A->Prop),
    (exists x, P x) -> { x : A | P x }.
\end{Coqsrc}

If we consider the \emph{unique existential} quantifier $\exists!$, we obtain
Church's \emph{definite description operator}.

\begin{Coqsrc}
Definition iota (A : Type) (i:inhabited A) (P : A->Prop) : A
  := proj1_sig (iota_statement P i).
\end{Coqsrc}

\begin{Coqsrc}
 Lemma constructive_definite_description :
  forall (A : Type) (P : A->Prop),
    (exists! x, P x) -> { x : A | P x }.
\end{Coqsrc}

\begin{Coqsrc}
Definition iota_spec (A : Type) (i:inhabited A) (P : A->Prop) :
  (exists! x:A, P x) -> P (iota i P)
  := proj2_sig (iota_statement P i).
\end{Coqsrc}

Indeed, the operators \texttt{epsilon} and \texttt{iota} allowed us to make our definitions
quite close to Schütte's text. Our libraries \href{../theories/html/hydras.Schutte.MoreEpsilonIota.html}%
{\texttt{Schutte.MoreEpsilonIota}}
and
\href{../theories/html/hydras.Schutte.PartialFun.html}%
{\texttt{Schutte.PartialFun}} are extensions of \texttt{Coq.logic.Epsilon} for making easier
such definitions. See also an article in french~\cite{PCiota}.

\input{movies/snippets/MoreEpsilonIota/Defs}

In order to use these tools,  we have to tell \coq{}  that the declared type \texttt{Ord} is not empty:

\input{movies/snippets/Schutte_basics/inhOrd}

We are now able to define \texttt{zero} as the least ordinal. For this purpose,
we define a function returning the least element of any [non-empty]  subset.

\emph{From Module\href{../theories/html/hydras.Schutte.Well_Orders.html}%
  {\texttt{Schutte.Well\_Orders}}}

\input{movies/snippets/Well_Orders/leastMemberDef}
\input{movies/snippets/Well_Orders/theLeast}

\vspace{4pt}

From Module \href{../theories/html/hydras.Schutte.Schutte_basics.html}%
{\texttt{~Schutte.Schutte\_basics}}

\label{Constants:zero:Ord}
\index{hydras}{Library Schutte!Constants!zero}

\input{movies/snippets/Schutte_basics/zeroDef}

We want to prove now that zero is less than or equal to any ordinal number.

\input{movies/snippets/Schutte_basics/zeroLe}

\subsubsection{Remarks on \texttt{epsilon} and \texttt{iota}}

 What would happen in case of a misuse of \texttt{epsilon} or \texttt{iota} ?
For instance, one could give a unsatisfiable specification to \texttt{epsilon} or
a specification for \texttt{iota} that admits several realizations.

Let us consider an example:

\input{movies/snippets/Schutte_basics/BadBottoma}

Since we won't be able to prove the proposition
\linebreak \Verb|{exists! a: Ord, least_member (Empty_set Ord) a|, the only properties we would be able to prove about \texttt{bottom} would be \emph{trivial} properties,
\emph{i.e.}, satisfied by \emph{any} element of type \texttt{Ord}, like for instance
\texttt{bottom = bottom}, or \texttt{zero <= bottom}.

\input{movies/snippets/Schutte_basics/trivialProps}

On the other hand, the following attempt fails, because of the unprovable first subgoal (please notice that the second subgoal is easy to solve !).

\input{movies/snippets/Schutte_basics/Failure}

In short, using \texttt{epsilon} and \texttt{iota} in our implementation of countable ordinals after Schütte has two main advantages.

\begin{itemize}
\item It allows us to give a \emph{name} (using \texttt{Definition}) two witnesses
of existential quantifiers (let us recall that, in classical logic, one may consider non-constructive proofs of existential statements)
\item By separating definitions from proofs of [unique] existence, one may make definitions  more concise and readable. Look for instance at
the definitions of  \texttt{zero}, \texttt{succ}, \texttt{plus}, etc. in the rest of this chapter.
\end{itemize}
%%%% ICI ICI

\section{The  successor function}

The definition of the function \texttt{succ:Ord -> Ord} is very concise. The successor of any ordinal $\alpha$ is the smallest ordinal strictly greater than $\alpha$.

\label{Functions:succ-sch}
\index{hydras}{Library Schutte!Functions!succ}

\input{movies/snippets/Schutte_basics/succDef}

Using \texttt{succ}, we define the following predicates.

\input{movies/snippets/Schutte_basics/isSuccIsLimit}

% \begin{remark}
% Please look at remark~\vref{warning:coercions}.

How do we prove properties of the successor function?
First, we make its specification explicit.

\input{movies/snippets/Schutte_basics/succSpec}

Then, we prove that our function \texttt{succ} meets this specification.

\input{movies/snippets/Schutte_basics/succOka}

We have now to prove that the set of all ordinals strictly greater than $\alpha$ has a unique least element. But the singleton set $\{\alpha\}$ is countable, hence  bounded (by the axiom \texttt{AX3}). Hence; the set $\{\beta\in\mathbb{O}|\alpha < \beta\}$ is not empty
and therefore has a unique least element.

The rest of the \coq{} proof script is quite short.

\input{movies/snippets/Schutte_basics/succOkb}

We can ``uncap'' the description operator for proving properties of the
\texttt{succ} function.

\input{movies/snippets/Schutte_basics/succProps}

\section{Finite ordinals}

Using \texttt{succ}, it is now easy to define recursively all the finite ordinals.

\label{sect:notation-F-sch}

\input{movies/snippets/Schutte_basics/finiteDef}

\section{The definition of \texttt{omega}}
In order to define $\omega$, the first infinite ordinal, we use an operator which
``returns'' the least upper bound (if it exists) of a subset $X\subseteq \mathbb{O}$.
For that purpose, we first use a predicate:
(\texttt{is\_lub $D$ \textit{lt} $X$ $a$}) if $a$ belongs to $D$ and is the least
upper bound  of $X$ (with respect to \textit{lt}).

\input{movies/snippets/Lub/isLubDef}

\input{movies/snippets/Schutte_basics/supDef}

Then, we define the function \texttt{omega\_limit} which returns the least upper bound
of the  (denumerable) range of any sequence \texttt{s: nat -> Ord}.
By \texttt{AX3} this range is bounded, hence the set of its upper bounds is not empty and has a least element.
Then we define \texttt{omega} as the limit of the sequence of finite ordinals.

\input{movies/snippets/Schutte_basics/omegaDef}

\label{sect:notation-omega}

Among the numerous properties of the ordinal $\omega$, let us quote the following ones
(proved in Module
\href{../theories/html/hydras.Schutte.Schutte_basics.html\#finite_lt_omega}{\texttt{Schutte.Schutte\_basics}})

\input{movies/snippets/Schutte_basics/omegaProps}

\subsection{Ordering functions and ordinal addition}

After having defined the finite ordinals and the infinite ordinal $\omega$, we  define the sum $\alpha+\beta$ of two countable ordinals.
Schütte's definition looks like the following one:

\begin{quote}
``$\alpha+\beta$ is the $\beta$-th ordinal greater than or equal to $\alpha$''
\end{quote}

The purpose of this section is to give a meaning to the construction
``the $\alpha$-th element of $X$''  where $X$ is any non-empty subset of $\mathbb{O}$.
We follow Schütte's approach, by defining the notion of \emph{ordering functions},
a way to associate a unique ordinal to each element of $X$.
Complete definitions and proofs can be found in Module
 \href{../theories/html/hydras.Schutte.Ordering_Functions.html}%
{\texttt{Schutte.Ordering\_Functions}} ).

\subsection{Definitions}

A \emph{segment} is a set $A$ of ordinals such that, whenever  $\alpha\in A$ and
$\beta<\alpha$, then $\beta\in A$; a segment is  \emph{proper} if it strictly included in $\mathbb{O}$.

\input{movies/snippets/Ordering_Functions/segmentDef}

Let  $A$ be a segment, and $B$ a subset of $\mathbb{O}$ : an \emph{ordering function for $A$ and  $B$} is a strictly increasing bijection from $A$ to $B$.
The set $B$ is said to be an \emph{ordering segment} of $A$.
Our definition in \coq{} is a direct translation of the mathematical text of~\cite{schutte}.

\index{maths}{Ordinal numbers!Ordering functions}
\index{hydras}{Library Schutte!Predicates!ordering function@ordering\_function}

\input{movies/snippets/Ordering_Functions/orderingFunctionDef}

We are now able to associate with any subset $B$ of $\mathbb{O}$ its ordering segment and ordering function.

\input{movies/snippets/Ordering_Functions/ordDef}

Thus (\texttt{ord $B \;\alpha$}) is the $\alpha$-th element of $B$.
Please note that the last definition uses the epsilon-based operator \texttt{some} and
not \texttt{the}. This is due to the fact that we cannot prove the unicity (w.r.t. Leibniz' equality) of the ordering function of a given set.
By contrast, we admit the axiom  \texttt{Extensionality\_Ensembles}, from the library
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Sets.Ensembles.html}{Coq.Sets.Ensembles}, so we use the operator \texttt{the} in the definition of
\texttt{the\_ordering\_segment}.

One of the main theorems of
\href{../theories/html/hydras.Schutte.Ordering_Functions.html\#ordering_function_ex}%
{\texttt{Ordering\_Functions}}
associates a unique segment and a unique (up to extensionality) ordering function to every subset $B$ of $\mathbb{O}$.

\input{movies/snippets/Ordering_Functions/orderingFunctionEx}

Thus,  our function \texttt{ord}  which enumerates the elements of $B$ is defined in a non-ambiguous way.
Let us quote the following theorems (see Library
\href{../theories/html/hydras.Schutte.Ordering_Functions.html}%
{\texttt{Schutte.Ordering\_Functions}} for more details).

\input{movies/snippets/Ordering_Functions/orderingLe}
\input{movies/snippets/Ordering_Functions/Th1352}

\subsection{Ordinal addition}

We are now ready to define and study addition on the type \texttt{Ord}.
The following definitions and proofs can be consulted in Module
\href{../theories/html/hydras.Schutte.Addition.html}%
{\texttt{Schutte.Addition.v}}.

\index{hydras}{Library Schutte!Functions!plus}

\input{movies/snippets/Addition/additionDef}

In other words,  $\alpha + \beta$ is the  $\beta$-th ordinal greater than or equal to $\alpha$.
Thanks to generic properties of ordering functions, we can show the following
properties of addition on $\mathbb{O}$. First, we prove a useful lemma:

\begin{Coqsrc}
Lemma plus_elim (alpha : Ord) :
  forall P : (Ord->Ord)->Prop,
    (forall f: Ord->Ord,
        ordering_function f ordinal (ge alpha)-> P f) ->
    P (plus alpha).
\end{Coqsrc}

As a use-case, let us prove that $0$ is a right neutral element of $+$.

\input{movies/snippets/Addition/alphaPlusZero}

The following lemmas are proved the same way.

\input{movies/snippets/Addition/bunchOfLemmas}

The following lemmas are not direct applications of \texttt{plus\_elim}.

\input{movies/snippets/Addition/plusAssoc}
\input{movies/snippets/Addition/finitePlusInfinite}

It is interesting to compare the proof of these lemmas with the
computational proofs of the corresponding statements in Module
\href{../theories/html/hydras.Epsilon0.T1.html}%
{\texttt{Epsilon0.T1}}.
For instance, the proof of the lemma
\texttt{one\_plus\_omega} uses the continuity of ordering functions (applied to  \texttt{(plus 1)}) and compares the limit of the $\omega$-sequences $i_{(i \in \mathbb{N})}$ and
$(1+i)i_{(i \in \mathbb{N})}$, whereas in the library  \texttt{Epsilon0/T1}, the equality
$1+\omega=\omega$ is just proved with \texttt{reflexivity}!

\subsubsection{Multiplication by a natural number}

The multiplication of an ordinal by a natural number is defined in terms of addition.
This operation is useful for the study of Cantor normal forms.

\input{movies/snippets/Addition/multFin}

\section{The exponential of basis \texorpdfstring{$\omega$}{omega}}

In this section, we define the function which maps any $\alpha\in\mathbb{O}$ to
the ordinal  $\omega^\alpha$, also written
$\phi_0(\alpha)$.
It is an opportunity to apply the definitions and results of the preceding section.
Indeed,  Schütte first defines a subset of $\mathbb{O}$: the set of additive principal ordinals, and $\phi_0$  is just defined as the ordering function of this set.

\subsection{Additive principal ordinals}

\index{maths}{Ordinal numbers!Additive principal ordinals}
\index{hydras}{Library Schutte!Predicates!AP@AP (additive principal ordinals)}

\begin{definition}
A non-zero ordinal  $\alpha$ is said to be \emph{additive principal} if, for all  $\beta<\alpha$, $\beta+\alpha$ is equal to  $\alpha$.
We call \texttt{AP} the set of additive principal ordinals.

\end{definition}

\noindent\emph{From Module \href{../theories/html/hydras.Schutte.AP.html}%
{\texttt{Schutte.AP}}}

\input{movies/snippets/AP/APDef}

\subsection{The function \texttt{phi0}}

Let us call  $\phi_0$ the ordering function of \texttt{AP}.
In the mathematical text, we shall use indifferently the notations  $\omega^\alpha$ and$\phi_0(\alpha)$.

\index{hydras}{Library Schutte!Functions!phi0}

\input{movies/snippets/AP/phi0Def}

\subsection{Omega-towers and the ordinal \texorpdfstring{$\epsilon_0$}{epsilon0}}

Using $\phi_0$, we can define recursively the set of finite omega-towers.

\input{movies/snippets/AP/omegaTower}

\label{sect:epsilon0-as-limit}
Then, the ordinal  $\epsilon_0$ is defined as the limit of the sequence of all finite towers (a kind of infinite tower).

\input{movies/snippets/AP/epsilon0Def}

The rest of our library \texttt{AP} is devoted to the proof of properties of additive principal ordinals, hence of the ordering function  $\phi0$ and the ordinal $\epsilon_0$ (which we could not express within the type \texttt{T1}).

\subsection{Properties of the set  \texttt{AP}}

The set of additive principal ordinals is not empty: it contains at least the ordinals  $1$ and  $\omega$.

\inputsnippets{AP/APOne,AP/APOne_least_AP,AP/APOne_AP_omega,AP/APOne_omega_second_AP}

The set  \texttt{AP} is  \emph{closed} under addition, and unbounded.

\input{movies/snippets/AP/APPlusClosed}

\input{movies/snippets/AP/APUnbounded}

Finally, \texttt{AP} is (topologically) \emph{closed} and ordered by the segment of all countable ordinals.

\index{hydras}{Library Schutte!Predicates!Closed}

From Module \href{../theories/html/hydras.Schutte.Schutte_basics.html}%
{\texttt{~Schutte.Schutte\_basics}}

\input{movies/snippets/Schutte_basics/ClosedDef}
\input{movies/snippets/AP/APClosed}

\subsubsection{Properties of the function \texorpdfstring{$\phi_0$}{phi0}}

The ordering function $\phi_0$ of the set \texttt{AP} is defined on the full set $\mathbb{O}$ and is continuous (Schütte calls such a  function  \emph{normal}).

\begin{Coqsrc}
Theorem normal_phi0 : normal phi0 AP.
\end{Coqsrc}

The following properties come from  the definition of $\phi_0$ as the ordering function of \texttt{AP}. It may be interesting to compare these proofs with the computational ones described in Chapter ~\ref{chap:T1}.

\input{movies/snippets/AP/APPhi0}

\section{More about \texorpdfstring{$\epsilon_0$}{\texttt{epsilon0}}}

Let us recall that the limit ordinal  $\epsilon_0$ cannot be written within the type \texttt{T1}. Since we are now considering the set of all countable ordinals, we can now prove some properties of this ordinal.

We prove the inequality  $\alpha<\omega^\alpha$ whenever $\alpha < \epsilon_0$.
\emph{Note that this condition was implicit in Module
\href{../theories/html/hydras.Epsilon0.T1.html\#lt_phi0}{Epsilon0.T1}.}

\input{movies/snippets/AP/ltPhi0}

The proof is as follows:
\begin{enumerate}
\item Since $\alpha<\epsilon_0$, consider the least $i$ such that $\alpha$ is strictly less than the omega-tower of height $i$.
\item
  \begin{itemize}
  \item If $i=0$, then the result is trivial (because $\alpha=0$)
 \item  Otherwise let $i=j+1$;
          $\alpha$ is greater than or equal to the omega-tower of height $j$.
         By monotonicity,  $\phi_0(\alpha)$ is greater than or equal to
        the omega-tower of height $j+1$, thus strictly greater than $\alpha$
  \end{itemize}
 \end{enumerate}

Moreover,  $\epsilon_0$ is the least ordinal $\alpha$ that verifies the equality
$\alpha = \omega^\alpha$, in other words, the least fixpoint of the function  $\phi_0$.

\input{movies/snippets/AP/epsilon0Lfp}

\section{Critical ordinals}

\index{maths}{Ordinal numbers!Critical ordinals}
\index{hydras}{Library Schutte!Predicates!Cr@Cr (critical ordinals)}

For any  (countable) ordinal $\alpha$, the set $\textit{Cr}(\alpha)$ is inductively defined
as follows by Schütte (p.81 of~\cite{schutte}).

\begin{quote}
  \begin{itemize}
  \item $\textit{Cr}(0)$ is the set \textit{AP} of additive principal ordinals.
  \item If $0<\alpha$, then $\textit{Cr}(\alpha)$ is the intersection of all the sets of fixpoints of the $\textit{Cr}(\beta)$ for $\beta<\alpha$.
  \end{itemize}
\end{quote}

This definition is translated in \coq{} in
Module \href{../theories/html/hydras.Schutte.Critical.html}%
{\texttt{Schutte.Critical}}, as the least fixpoint of a functional.

\input{movies/snippets/Critical/CrDef}

Lets us denote by $\varphi_\alpha$ the ordering function of the set $\textit{Cr}(\alpha)$ and by $A_\alpha$ its ordering segment.

\input{movies/snippets/Critical/phiDef}

\label{sect:phi-schutte}

For instance,  we prove that $\textit{Cr}(0)$ is the set of additive principals and that $\epsilon_0$
belongs to $\textit{Cr}(1)$.

\input{movies/snippets/Critical/CrZeroAP}
\input{movies/snippets/Critical/epsilon0Cr1}

\index{hydras}{Exercises}

\begin{exercise}
 Prove that $\epsilon_0$ is the least element of $\textit{Cr}(1)$.
\end{exercise}

\subsection{A flavor of infinity}

The family of the $\textit{Cr}(\alpha)$s is made of infinitely many unbounded (hence infinite) sets.
Let us quote Lemma 5, p. 82  of~\cite{schutte}:
\begin{quote}
  For all $\alpha$, the set $\textit{Cr}(\alpha)$ is closed (for the least upper bound of non-empty countable sets) and unbounded.
\end{quote}

We prove this result by a transfinite induction on $\alpha$ of the conjunction of  both properties.

\index{maths}{Transfinite induction}

\input{movies/snippets/Critical/Lemma5}

\section{Cantor normal form}

The notion of Cantor normal form is defined for all countable ordinals.
Nevertheless, note that, contrary to the implementation based on type \texttt{T1},
the Cantor normal form of an ordinal $\alpha$ may contain $\alpha$ as a
sub-term\footnote{This would prevent us from trying to represent Cantor normal forms as finite trees (like in Sect.~\ref{sec:T1-inductive-def})}.

\index{maths}{Ordinal numbers!Cantor normal form}
\index{hydras}{Library Schutte!Predicates!is\_cnf\_of@is\_cnf\_of (to be a Cantor normal form of}

We represent  Cantor normal forms as lists of ordinals.
A  list $l$ is a Cantor normal form of a given ordinal $\alpha$ if it satisfies two conditions:

\begin{itemize}
\item The list  $l$ is sorted (in decreasing order) w.r.t. the order $\leq$
\item The sum of all the  $\omega^{\beta_i}$ where the $\beta_i$ are the terms of $l$ (in this order) is equal to $\alpha$.
\end{itemize}

\vspace{4pt}

\noindent\emph{From \href{../theories/html/hydras.Schutte.CNF.html\#cnf_t}%
{\texttt{Schutte.CNF}}}

\input{movies/snippets/CNF/Defs}

\index{maths}{Transfinite induction}

By transfinite induction on $\alpha$, we prove that every countable ordinal $\alpha$
 has at least a Cantor normal form.

\input{movies/snippets/CNF/cnfExists}

By structural induction on lists, we prove that this normal form is unique.

\input{movies/snippets/CNF/cnfUnicity}

\input{movies/snippets/CNF/cnfExUnique}

Finally, the following two lemmas relate  $\epsilon_0$ with Cantor normal forms.

If $\alpha<\epsilon_0$, then the Cantor normal form of $\alpha$ is made of ordinals strictly less than $\alpha$.

\input{movies/snippets/CNF/cnfLtEpsilon0}

\index{hydras}{Exercises}

\begin{exercise}
Please consider the following statement :

\begin{Coqsrc}
Lemma cnf_lt_epsilon0_iff :
 forall l alpha,
   is_cnf_of alpha l ->
   (alpha < epsilon0 <->  Forall (fun beta =>  beta < alpha) l).
\end{Coqsrc}

Is it true ?

\emph{You may start this exercise with the file
    \href{https://github.com/coq-community/hydra-battles/tree/master/exercises/ordinals/schutte_cnf_counter_example.v}{exercises/ordinals/schutte\_cnf\_counter\_example.v}.}
\end{exercise}

Finally, the Cantor normal form of $\epsilon_0$ is just $\omega^{\epsilon_0}$.

\input{movies/snippets/CNF/cnfOfEpsilon0}

\index{hydras}{Projects}

\begin{project}
Implement pages 82 to 85 of~\cite{schutte} (critical, strongly critical, maximal critical ordinals, Feferman's ordinal $\Gamma_0$).
\end{project}

\begin{remark}
The sub-directory
    \href{https://github.com/coq-community/hydra-battles/tree/master/theories/ordinals/Gamma0}{theories/oridinals/Gamma0} contains an (incomplete, still undocumented) implementation of the set of ordinals below $\Gamma_0$, represented in Veblen normal form.
\end{remark}

\section{An embedding of \texttt{T1} into \texttt{Ord}}

Our library
\href{../theories/html/hydras.Schutte.Correctness_E0.html}%
{\texttt{Schutte.Correctness\_E0}} establishes the link between two very different modelizations of ordinal numbers. In other words, it ``validates'' a data structure in terms of
a classical mathematical discourse considered as a model.
First, we define a function from \texttt{T1} into  \texttt{Ord} by structural recursion.

\input{movies/snippets/Correctness_E0/injectDef}

This function enjoys good commutation properties with respect to the main operations which
allow us to build Cantor normal forms.

\input{movies/snippets/Correctness_E0/commutationLemmas}
\input{movies/snippets/Correctness_E0/injectPlus}
\input{movies/snippets/Correctness_E0/injectMultFinR}

% \begin{Coqsrc}
% Theorem inject_mono (beta gamma : T1) :
%   T1.lt  beta gamma ->
%   T1.nf beta -> T1.nf gamma ->
%   inject beta < inject gamma.

% Theorem inject_injective (beta gamma : T1) : nf beta -> nf gamma ->
%   inject beta = inject gamma -> beta = gamma.
% \end{Coqsrc}

Finally, we prove that \texttt{inject} is a bijection from the set of all terms of \texttt{T1} in normal form to the set
\texttt{members epsilon0} of the elements of \texttt{Ord} strictly less than  $\epsilon_0$.

\input{movies/snippets/Correctness_E0/injectLtEpsilon0}
\input{movies/snippets/Correctness_E0/embedding}

\subsection{Remarks}
Let us recall that the library \href{../theories/html/hydras.Schutte.Schutte.html}%
{\texttt{Schutte}} depends on five \emph{axioms} and lies explicitly in the
framework of classical logic with a weak version of the axiom of choice
(please look at the documentation of
\href{https://coq.inria.fr/distrib/current/stdlib/Coq.Logic.ChoiceFacts.html}{\texttt{Coq.Logic.ChoiceFacts}}).
Nevertheless, the other modules:
\href{../theories/html/hydras.Epsilon0.Epsilon0.html}%
{\texttt{Epsilon0}},
\href{../theories/html/hydras.Hydra.Hydra.html}%
{\texttt{Hydra}}, et
\href{../theories/html/hydras.Gamma0.Gamma0.html}%
{\texttt{Gamma0}}
do not import any axioms and are really constructive.

\index{hydras}{Projects}
\begin{project}
There is no construction of ordinal multiplication in~\cite{schutte}.
It would be interesting to derive this operation from Schütte's axioms,
and prove its consistence with multiplication in ordinal notations for
$\epsilon_0$ and $\Gamma_0$.
\end{project}

\section{Related work}

In~\cite{grimm:hal-00911710}, José Grimm establishes the consistency between our ordinal notations \texttt{T1} and \texttt{T2} (Veblen normal form) and his implementation
of ordinal numbers after Bourbaki's set theory.

The Gaia project ~\url{https://github.com/coq-community/gaia} maintains Grimm's  theory of ordinals as part of coq-community on GitHub. Integration
of the present ordinal theory with Gaia, i.e., relating the different notions of ordinals
and transferring relevant results, is an interesting project.
First experiments in that direction are developped in
the \href{https://github.com/coq-community/hydra-battles/blob/master/theories/gaia/}{theories/gaia/} directory.

\chapter{The Ordinal \texorpdfstring{$\Gamma_0$}{Gamma0} (first draft)}

\emph{This chapter and the files it presents are still very incomplete, considering the impressive properties of $\Gamma_0$~\cite{Gallier91}.  We hope to add new material soon, and accept contributions!}

\section{Introduction}
We present a notation system for the ordinal $\Gamma_0$, following Chapter V, Section 14 of~\cite{schutte}: ``A notation system for the ordinals $<\Gamma_0$''.
We try to be as close as possible to Schütte's text and usual practices of \coq{} developments.

The ordinal $\Gamma_0$ is defined in Section 13 of ~\cite{schutte} as the least \emph{strongly critical ordinal}. It is widely known as the \emph{Feferman-Schütte ordinal}.

Section V, 13 of~\cite{schutte} defines \emph{strongly critical} and
\emph{maximal $\alpha$-critical} ordinals:

\begin{itemize}
\item $\alpha$ is strongly critical if
$\alpha$ is $\alpha$-critical,
\item $\gamma$ is maximal $\alpha$-critical if $\gamma$ is $\alpha$-critical, and, for all $\xi>\alpha$, $\gamma$ is not $\xi$-critical.

\end{itemize}

\vspace{4pt}

\noindent\emph{From \href{../theories/html/hydras.Schutte.Critical.html\#strongly_critical}%
{\texttt{Schutte.Critical}}}

\input{movies/snippets/Critical/Gamma0Def}

\index{hydras}{Projects}
\begin{project}
Prove that a (countable)  ordinal $\alpha$ is strongly critical iff
$\phi_\alpha(0)=\alpha$ (Theorem 13.13 of~\cite{schutte} ).
\end{project}

\index{hydras}{Projects}
\begin{project}
Prove that the set of strongly critical ordinals is unbounded and closed (Theorem 13.14 of~\cite{schutte} ). Thus this set is not empty,  hence has a least element. Otherwise, the definition of $\Gamma_0$ above would be useless.
\end{project}

In the present version of this development, we  only study $\Gamma_0$ as a notation system, much more powerful than the ordinal notation for $\epsilon_0$.

%\index{Projects}
%
%\begin{project}
% Schûtte's section 13 of~\cite{schutte} contain several definitions and lemmas which give another view on $\Gamma_0$.  We leave it as a project to implement them in \coq{}.
%\end{project}

\section{The type \texttt{T2} of ordinal terms}

The notation system for ordinals less than $\gamma_0$ comes from the following theorem of~\cite{schutte}, where $\psi\,\alpha$ is the ordering function
of the set of maximal $\alpha$-critical ordinals.

\index{hydras}{Library Gamma0!Types!T2}

\begin{quote}
  Any ordinal $\not= 0$ which is not strongly critical can be expressed in terms of $+$ and $\psi$.
\end{quote}

\index{hydras}{Projects}
\begin{project}
This theorem is not formally proved in this development yet. It should be!
\end{project}

Like in Chapter~\ref{chap:T1}, we define an inductive type with two constructors, one for $0$, the other for the construction $\psi(\alpha,\beta)\times(n+1)+\gamma$, adapting a Manolios-Vroon-like notation~\cite{Manolios2005} to
\emph{Veblen normal forms}.
\label{types:T2}

\noindent\emph{From \href{../theories/html/hydras.Gamma0.T2.html\#T2}%
{\texttt{Gamma0.T2}}}

\input{movies/snippets/T2/T2Def}

\begin{figure}[h]
  \centering
  \includegraphics[width=11cm]{epsilon0.jpg}
  \caption{Veblen normal form}
  \label{fig:gamma0}
\end{figure}

Like in chapter~\ref{chap:T1}, we get familiar with the type \texttt{T2} by recognizing simple constructs like finite ordinals, $\omega$, etc., as inhabitants of \texttt{T2}.

\input{movies/snippets/T2/Notations}

\section{How big is \texorpdfstring{$\Gamma_0$}{\texttt{Gamma0}}?}

Let us define a strict order on type \texttt{T2}. The following definition is
an adaptation of Schütte's, taking into account the multiplications by a natural number (inspired by~\cite{Manolios2005}, and also present in \texttt{T1}).

\label{sect:t2-lt-def}

\input{movies/snippets/T2/ltDef}

Seven constructors! In order to get accustomed with this definition, let us look at a small set of examples, covering all the constructors of \texttt{lt}.

\input{movies/snippets/T2/ltExamples}

\index{hydras}{Projects}
\begin{project}
Write a tactic that solves automatically goals of the form (\texttt{$\alpha$ t2< $\beta$}), where $\alpha$ and $\beta$ are closed terms of type \texttt{T2}.
\end{project}

\section{Veblen normal form}
\begin{definition}
  A term of the form $\psi(\alpha_1,\beta_1)\times n_1+ \psi(\alpha_2,\beta_2)\times n_2+\dots+\psi(\alpha_k,\beta_k)\times n_k$ is said to be in
 \emph{[Veblen] normal form} if for every $i<n$, $\psi(\alpha_i,\beta_i)<\psi(\alpha_{i+1},\beta_{i+1})$, all the $\alpha_i$ and $\beta_i$ are in normal form, and all the $n_i$ are strictly positive integers.
\end{definition}

\input{movies/snippets/T2/nfDef}

Let us look at some positive examples (we have to prove some inversion lemmas before proving counter-examples).

\input{movies/snippets/T2/nfExamples}

\subsection{Length of a term}

The notion of \emph{term length} is introduced by Schütte as a helper for proving (at least) the \emph{trichotomy} property and transitivity of the strict order \texttt{lt} on \texttt{T2}. These properties are proved by induction on length.

\subsection{Trichotomy}

\emph{Trichotomy} is another name for the well-known property of decidable total ordering (like Standard Library's \texttt{Compare\_dec.lt\_eq\_lt\_dec}).

We first prove by induction on $l$ the following lemma:

\vspace{4pt}

\noindent\emph{From \href{../theories/html/hydras.Gamma0.Gamma0\#tricho_aux}%
{\texttt{Gamma0.Gamma0}}}

\input{movies/snippets/Gamma0/tricho}

\input{movies/snippets/Gamma0/compare}

With the help of \texttt{compare}, we get a boolean version of \texttt{nf}
(being in Veblen normal form).

\input{movies/snippets/Gamma0/nfb}

\section{Main functions on \texttt{T2}}

\subsection{Successor}
The successor function is defined by structural recursion.

\noindent\emph{From \href{../theories/html/hydras.Gamma0.T2.html\#succ}%
{\texttt{Gamma0.T2}}}

\input{movies/snippets/T2/succDef}

\subsection{Addition}

Like for Cantor normal forms (see Sect.~\ref{sect:infix-plus-T1}),  the definition of addition in \texttt{T2}  requires comparison between ordinal terms.

\noindent\emph{From \href{../theories/html/hydras.Gamma0.Gamma0T2.html\#succ}%
  {\texttt{Gamma0.Gamma0}}}

\input{movies/snippets/Gamma0/plusDef}

\subsection{The Veblen function \texorpdfstring{$\phi$}{\texttt{phi}}}

The enumeration function of critical ordinals, presented in Sect.~\vref{sect:phi-schutte}, is recursively defined in type \texttt{T2}.

\input{movies/snippets/Gamma0/phiDef}

Despite its complexity, the function \texttt{phi} is well adapted to proofs by simplification or computation.

The relation between the constructor $\psi$ and the function $\phi$ is
studied in~\cite{schutte}, and partially implemented in this development.
\emph{Please contribute!}

For instance, the following theorem states that, if $\gamma$ is the sum of a limit ordinal $\beta$ and a finite ordinal $n$, and $\beta$ is a fixpoint of
$\phi(\alpha)$, then $\psi(\alpha,\gamma)=\phi_\alpha(\gamma+1)$.

\input{movies/snippets/Gamma0/phiPsi}
\input{movies/snippets/Gamma0/Ex9}

On the other hand, $\phi$ can be expressed in terms of $\psi$.

\input{movies/snippets/Gamma0/phiOfPsi}
\input{movies/snippets/Gamma0/Ex10}

\index{hydras}{Projects}
\begin{project}
Please study a way to pretty print ordinal terms in Veblen normal form (see Section~\vref{sect:ppT1}).
\end{project}

\section{An ordinal notation for \texorpdfstring{$\Gamma_0$}{\texttt{Gamma0}}}

In order to consider type \texttt{T2} as an ordinal notation, we have to build an instance of class \texttt{ON} (See Definition page~\pageref{types:ON}).

First, we define a type that contains only terms in Veblen normal form, and redefine \texttt{lt} and \texttt{compare} by delegation (see for comparison the construction of type \texttt{E0} in Sect.~\vref{sect:E0-def}).

\input{movies/snippets/Gamma0/G0a}
\input{movies/snippets/Gamma0/G0b}

Then, we buils an instance of class \texttt{ON}.
function \texttt{compare} is correct.

\input{movies/snippets/Gamma0/ltSto}
\input{movies/snippets/Gamma0/ltWf}
\input{movies/snippets/Gamma0/ONGamma0}

\begin{remark}
The proof of \texttt{lt\_wf} has been written by \'Evelyne Contejean, using her library on the recursive path ordering (see also remark~\vref{remark:a3pat}).
\end{remark}

\index{hydras}{Projects}
\begin{project}
Prove that \texttt{Epsilon0} (page~\pageref{instance-epsilon0})
is a sub-notation system of \texttt{Gamma0}.

Prove that the implementations of \texttt{succ}, \texttt{+}, $\phi_0$, etc.
are compatible in both notation systems.

Note that a function \texttt{T1\_inj} from \texttt{T1} to \texttt{T2} has already been defined. It may help to complete the task.

\noindent\emph{From \href{../theories/html/hydras.Gamma0.T2.html\#T1_to_T2}%
{\texttt{Gamma0.T2}}}

\input{movies/snippets/T2/T1ToT2}

\end{project}

\begin{project}
Prove that the notation system \texttt{Gamma0} is a correct implementation
of the segment $[0,\Gamma_0)$ of the set of countable ordinals.
\end{project}