import Mathlib import OAI.Combinatorics.KServer.RankProportions import OAI.Combinatorics.KServer.Rounding namespace OAI /-! A literal finite complete-prefix tree, numbered parent-before-child. The unused words are retained, as required for an unconditioned finite key tape. -/ noncomputable section open scoped BigOperators namespace KServer.PrefixTree variable (A:Type) [Fintype A] (L:ℕ) abbrev Vertex := (j:Fin (L+1)) × (Fin j.val→A) def root : Vertex A L := ⟨0,Fin.elim0⟩ instance : Nonempty (Vertex A L) := ⟨root A L⟩ def code (v:Vertex A L) : Lex (ℕ×ℕ) := toLex (v.1.val,(Fintype.equivFin (Fin v.1.val→A) v.2).val) lemma code_injective : Function.Injective (code A L) := by rintro ⟨j,f⟩ ⟨j',g⟩ h have hj:j=j':=Fin.ext (congrArg (fun p:Lex (ℕ×ℕ)=>(ofLex p).1) h) subst j' have hf:(Fintype.equivFin (Fin j.val→A) f).val=(Fintype.equivFin (Fin j.val→A) g).val := congrArg (fun p:Lex (ℕ×ℕ)=>(ofLex p).2) h have he:f=g:=(Fintype.equivFin _).injective (Fin.ext hf) subst g rfl instance : LinearOrder (Vertex A L) := LinearOrder.lift' (code A L) (code_injective A L) lemma root_le (v:Vertex A L) : root A L≤v := by by_cases hj:v.1.val=0 · have he:v=root A L:=by rcases v with ⟨j,f⟩ have hj':j=0:=Fin.ext hj subst j congr exact funext (fun i=>Fin.elim0 i) rw [he] · change code A L (root A L)≤code A L v exact Prod.Lex.toLex_le_toLex.mpr (Or.inl (Nat.pos_of_ne_zero hj)) instance : NeZero (Fintype.card (Vertex A L)) := ⟨Nat.ne_of_gt Fintype.card_pos⟩ def numbering : Fin (Fintype.card (Vertex A L)) ≃o Vertex A L := Fintype.orderIsoFinOfCardEq _ rfl lemma numbering_zero : numbering A L 0=root A L := by apply le_antisymm · rw [←(numbering A L).apply_symm_apply (root A L)] apply (numbering A L).monotone exact Fin.zero_le _ · exact root_le A L _ def parent (v:Vertex A L) : Vertex A L := if h:v.1.val=0 then root A L else ⟨⟨v.1.val-1,by omega⟩,fun i=>v.2 ⟨i.val,by have hi : i.valFin.elim0 i) change code A L (parent A L v)