(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)
(* <O___,, *       (see CREDITS file for the list of authors)           *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)
(** An ultrametric distance over [N] numbers *)
Inductive natinf : Set :=
| infty : natinf
| ni : nat -> natinf.
Fixpoint Pplength (p:positive) : nat :=
match p with
| xH => 0
| xI _ => 0
| xO p' => S (Pplength p')
end.
Definition Nplength (a:N) :=
match a with
| N0 => infty
| Npos p => ni (Pplength p)
end.
Definition ni_min (d d':natinf) :=
match d with
| infty => d'
| ni n => match d' with
| infty => d
| ni n' => ni (min n n')
end
end.
Definition ni_le (d d':natinf) := ni_min d d' = d.
(** We define an ultrametric distance between [N] numbers: $d(a,a')=1/2^pd(a,a')$, where $pd(a,a')$ is the number of identical bits at the beginning of $a$ and $a'$ (infinity if $a=a'$). Instead of working with $d$, we work with $pd$, namely [Npdist]: *)
Definition Npdist (a a':N) := Nplength (N.lxor a a').
(** d is a distance, so $d(a,a')=0$ iff $a=a'$; this means that $pd(a,a')=infty$ iff $a=a'$: *)
(** $d$ is a distance, so $d(a,a')=d(a',a)$: *)
(** $d$ is an ultrametric distance, that is, not only $d(a,a')\leq d(a,a'')+d(a'',a')$, but in fact $d(a,a')\leq max(d(a,a''),d(a'',a'))$. This means that $min(pd(a,a''),pd(a'',a'))<=pd(a,a')$ (lemma [Npdist_ultra] below). This follows from the fact that $a ~Ra~|a| = 1/2^{\texttt{Nplength}}(a))$ is an ultrametric norm, i.e. that $|a-a'| \leq max (|a-a''|, |a''-a'|)$, or equivalently that $|a+b|<=max(|a|,|b|)$, i.e. that min $(\texttt{Nplength}(a), \texttt{Nplength}(b)) \leq \texttt{Nplength} (a~\texttt{xor}~ b)$ (lemma [Nplength_ultra]). *)

Lemma Nplength_ultra_1 :
forall a a':N,
ni_le (Nplength a) (Nplength a') ->
ni_le (Nplength a) (Nplength (N.lxor a a')).