source stringlengths 17 118 | lean4 stringlengths 0 335k |
|---|---|
.lake/packages/mathlib/Mathlib/Data/Semiquot.lean | import Mathlib.Data.Set.Lattice
/-! # Semiquotients
A data type for semiquotients, which are classically equivalent to
nonempty sets, but are useful for programming; the idea is that
a semiquotient set `S` represents some (particular but unknown)
element of `S`. This can be used to model nondeterministic functions,
which return something in a range of values (represented by the
predicate `S`) but are not completely determined.
-/
/-- A member of `Semiquot α` is classically a nonempty `Set α`,
and in the VM is represented by an element of `α`; the relation
between these is that the VM element is required to be a member
of the set `s`. The specific element of `s` that the VM computes
is hidden by a quotient construction, allowing for the representation
of nondeterministic functions. -/
structure Semiquot (α : Type*) where mk' ::
/-- Set containing some element of `α` -/
s : Set α
/-- Assertion of non-emptiness via `Trunc` -/
val : Trunc s
namespace Semiquot
variable {α : Type*} {β : Type*}
instance : Membership α (Semiquot α) :=
⟨fun q a => a ∈ q.s⟩
/-- Construct a `Semiquot α` from `h : a ∈ s` where `s : Set α`. -/
def mk {a : α} {s : Set α} (h : a ∈ s) : Semiquot α :=
⟨s, Trunc.mk ⟨a, h⟩⟩
theorem ext_s {q₁ q₂ : Semiquot α} : q₁ = q₂ ↔ q₁.s = q₂.s := by
refine ⟨congr_arg _, fun h => ?_⟩
obtain ⟨_, v₁⟩ := q₁; obtain ⟨_, v₂⟩ := q₂; congr
exact Subsingleton.helim (congrArg Trunc (congrArg Set.Elem h)) v₁ v₂
theorem ext {q₁ q₂ : Semiquot α} : q₁ = q₂ ↔ ∀ a, a ∈ q₁ ↔ a ∈ q₂ :=
ext_s.trans Set.ext_iff
theorem exists_mem (q : Semiquot α) : ∃ a, a ∈ q :=
let ⟨⟨a, h⟩, _⟩ := q.2.exists_rep
⟨a, h⟩
theorem eq_mk_of_mem {q : Semiquot α} {a : α} (h : a ∈ q) : q = @mk _ a q.1 h :=
ext_s.2 rfl
theorem nonempty (q : Semiquot α) : q.s.Nonempty :=
q.exists_mem
/-- `pure a` is `a` reinterpreted as an unspecified element of `{a}`. -/
protected def pure (a : α) : Semiquot α :=
mk (Set.mem_singleton a)
@[simp]
theorem mem_pure' {a b : α} : a ∈ Semiquot.pure b ↔ a = b :=
Set.mem_singleton_iff
/-- Replace `s` in a `Semiquot` with a superset. -/
def blur' (q : Semiquot α) {s : Set α} (h : q.s ⊆ s) : Semiquot α :=
⟨s, Trunc.lift (fun a : q.s => Trunc.mk ⟨a.1, h a.2⟩) (fun _ _ => Trunc.eq _ _) q.2⟩
/-- Replace `s` in a `q : Semiquot α` with a union `s ∪ q.s` -/
def blur (s : Set α) (q : Semiquot α) : Semiquot α :=
blur' q (s.subset_union_right (t := q.s))
theorem blur_eq_blur' (q : Semiquot α) (s : Set α) (h : q.s ⊆ s) : blur s q = blur' q h := by
unfold blur; congr; exact Set.union_eq_self_of_subset_right h
@[simp]
theorem mem_blur' (q : Semiquot α) {s : Set α} (h : q.s ⊆ s) {a : α} : a ∈ blur' q h ↔ a ∈ s :=
Iff.rfl
/-- Convert a `Trunc α` to a `Semiquot α`. -/
def ofTrunc (q : Trunc α) : Semiquot α :=
⟨Set.univ, q.map fun a => ⟨a, trivial⟩⟩
/-- Convert a `Semiquot α` to a `Trunc α`. -/
def toTrunc (q : Semiquot α) : Trunc α :=
q.2.map Subtype.val
/-- If `f` is a constant on `q.s`, then `q.liftOn f` is the value of `f`
at any point of `q`. -/
def liftOn (q : Semiquot α) (f : α → β) (h : ∀ a ∈ q, ∀ b ∈ q, f a = f b) : β :=
Trunc.liftOn q.2 (fun x => f x.1) fun x y => h _ x.2 _ y.2
theorem liftOn_ofMem (q : Semiquot α) (f : α → β)
(h : ∀ a ∈ q, ∀ b ∈ q, f a = f b) (a : α) (aq : a ∈ q) : liftOn q f h = f a := by
revert h; rw [eq_mk_of_mem aq]; intro; rfl
/-- Apply a function to the unknown value stored in a `Semiquot α`. -/
def map (f : α → β) (q : Semiquot α) : Semiquot β :=
⟨f '' q.1, q.2.map fun x => ⟨f x.1, Set.mem_image_of_mem _ x.2⟩⟩
@[simp]
theorem mem_map (f : α → β) (q : Semiquot α) (b : β) : b ∈ map f q ↔ ∃ a, a ∈ q ∧ f a = b :=
Set.mem_image _ _ _
/-- Apply a function returning a `Semiquot` to a `Semiquot`. -/
def bind (q : Semiquot α) (f : α → Semiquot β) : Semiquot β :=
⟨⋃ a ∈ q.1, (f a).1, q.2.bind fun a => (f a.1).2.map fun b => ⟨b.1, Set.mem_biUnion a.2 b.2⟩⟩
@[simp]
theorem mem_bind (q : Semiquot α) (f : α → Semiquot β) (b : β) :
b ∈ bind q f ↔ ∃ a ∈ q, b ∈ f a := by simp_rw [← exists_prop]; exact Set.mem_iUnion₂
instance : Monad Semiquot where
pure := @Semiquot.pure
map := @Semiquot.map
bind := @Semiquot.bind
@[simp]
theorem map_def {β} : ((· <$> ·) : (α → β) → Semiquot α → Semiquot β) = map :=
rfl
@[simp]
theorem bind_def {β} : ((· >>= ·) : Semiquot α → (α → Semiquot β) → Semiquot β) = bind :=
rfl
@[simp]
theorem mem_pure {a b : α} : a ∈ (pure b : Semiquot α) ↔ a = b :=
Set.mem_singleton_iff
theorem mem_pure_self (a : α) : a ∈ (pure a : Semiquot α) :=
Set.mem_singleton a
@[simp]
theorem pure_inj {a b : α} : (pure a : Semiquot α) = pure b ↔ a = b :=
ext_s.trans Set.singleton_eq_singleton_iff
instance : LawfulMonad Semiquot := LawfulMonad.mk'
(pure_bind := fun {α β} x f => ext.2 <| by simp)
(bind_assoc := fun {α β} γ s f g =>
ext.2 <| by
simp only [bind_def, mem_bind]
exact fun c => ⟨fun ⟨b, ⟨a, as, bf⟩, cg⟩ => ⟨a, as, b, bf, cg⟩,
fun ⟨a, as, b, bf, cg⟩ => ⟨b, ⟨a, as, bf⟩, cg⟩⟩)
(id_map := fun {α} q => ext.2 <| by simp)
(bind_pure_comp := fun {α β} f s => ext.2 <| by simp [eq_comm])
instance : LE (Semiquot α) :=
⟨fun s t => s.s ⊆ t.s⟩
instance partialOrder : PartialOrder (Semiquot α) where
le s t := ∀ ⦃x⦄, x ∈ s → x ∈ t
le_refl _ := Set.Subset.refl _
le_trans _ _ _ := Set.Subset.trans
le_antisymm _ _ h₁ h₂ := ext_s.2 (Set.Subset.antisymm h₁ h₂)
instance : SemilatticeSup (Semiquot α) :=
{ Semiquot.partialOrder with
sup := fun s => blur s.s
le_sup_left := fun _ _ => Set.subset_union_left
le_sup_right := fun _ _ => Set.subset_union_right
sup_le := fun _ _ _ => Set.union_subset }
@[simp]
theorem pure_le {a : α} {s : Semiquot α} : pure a ≤ s ↔ a ∈ s :=
Set.singleton_subset_iff
/-- Assert that a `Semiquot` contains only one possible value. -/
def IsPure (q : Semiquot α) : Prop :=
∀ a ∈ q, ∀ b ∈ q, a = b
/-- Extract the value from an `IsPure` semiquotient. -/
def get (q : Semiquot α) (h : q.IsPure) : α :=
liftOn q id h
theorem get_mem {q : Semiquot α} (p) : get q p ∈ q := by
let ⟨a, h⟩ := exists_mem q
unfold get; rw [liftOn_ofMem q _ _ a h]; exact h
theorem eq_pure {q : Semiquot α} (p) : q = pure (get q p) :=
ext.2 fun a => by simpa using ⟨fun h => p _ h _ (get_mem _), fun e => e.symm ▸ get_mem _⟩
@[simp]
theorem pure_isPure (a : α) : IsPure (pure a)
| b, ab, c, ac => by
rw [mem_pure] at ab ac
rwa [← ac] at ab
theorem isPure_iff {s : Semiquot α} : IsPure s ↔ ∃ a, s = pure a :=
⟨fun h => ⟨_, eq_pure h⟩, fun ⟨_, e⟩ => e.symm ▸ pure_isPure _⟩
theorem IsPure.mono {s t : Semiquot α} (st : s ≤ t) (h : IsPure t) : IsPure s
| _, as, _, bs => h _ (st as) _ (st bs)
theorem IsPure.min {s t : Semiquot α} (h : IsPure t) : s ≤ t ↔ s = t :=
⟨fun st =>
le_antisymm st <| by
rw [eq_pure h, eq_pure (h.mono st)]; simpa using h _ (get_mem _) _ (st <| get_mem _),
le_of_eq⟩
theorem isPure_of_subsingleton [Subsingleton α] (q : Semiquot α) : IsPure q
| _, _, _, _ => Subsingleton.elim _ _
/-- `univ : Semiquot α` represents an unspecified element of `univ : Set α`. -/
def univ [Inhabited α] : Semiquot α :=
mk <| Set.mem_univ default
instance [Inhabited α] : Inhabited (Semiquot α) :=
⟨univ⟩
@[simp]
theorem mem_univ [Inhabited α] : ∀ a, a ∈ @univ α _ :=
@Set.mem_univ α
@[congr]
theorem univ_unique (I J : Inhabited α) : @univ _ I = @univ _ J :=
ext.2 fun a => refl (a ∈ univ)
@[simp]
theorem isPure_univ [Inhabited α] : @IsPure α univ ↔ Subsingleton α :=
⟨fun h => ⟨fun a b => h a trivial b trivial⟩, fun ⟨h⟩ a _ b _ => h a b⟩
instance [Inhabited α] : OrderTop (Semiquot α) where
top := univ
le_top _ := Set.subset_univ _
end Semiquot |
.lake/packages/mathlib/Mathlib/Data/TypeVec.lean | import Mathlib.Data.Fin.Fin2
import Mathlib.Logic.Function.Basic
import Mathlib.Tactic.Common
/-!
# Tuples of types, and their categorical structure.
## Features
* `TypeVec n` - n-tuples of types
* `α ⟹ β` - n-tuples of maps
* `f ⊚ g` - composition
Also, support functions for operating with n-tuples of types, such as:
* `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple
* `drop α` - drops the last element of an (n+1)-tuple
* `last α` - returns the last element of an (n+1)-tuple
* `appendFun f g` - appends a function g to an n-tuple of functions
* `dropFun f` - drops the last function from an n+1-tuple
* `lastFun f` - returns the last function of a tuple.
Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal
to it, we need support functions and lemmas to mediate between constructions.
-/
universe u v w x
/-- n-tuples of types, as a category -/
@[pp_with_univ]
def TypeVec (n : ℕ) :=
Fin2 n → Type*
instance {n} : Inhabited (TypeVec.{u} n) :=
⟨fun _ => PUnit⟩
namespace TypeVec
variable {n : ℕ}
/-- arrow in the category of `TypeVec` -/
def Arrow (α : TypeVec.{u} n) (β : TypeVec.{v} n) :=
∀ i : Fin2 n, α i → β i
@[inherit_doc] scoped[MvFunctor] infixl:40 " ⟹ " => TypeVec.Arrow
open MvFunctor
variable {α : TypeVec.{u} n} {β : TypeVec.{v} n} {γ : TypeVec.{w} n} {δ : TypeVec.{x} n} in
section
/-- Extensionality for arrows -/
@[ext]
theorem Arrow.ext (f g : α ⟹ β) :
(∀ i, f i = g i) → f = g := by
intro h; funext i; apply h
instance Arrow.inhabited (α β : TypeVec n) [∀ i, Inhabited (β i)] : Inhabited (α ⟹ β) :=
⟨fun _ _ => default⟩
/-- identity of arrow composition -/
def id {α : TypeVec n} : α ⟹ α := fun _ x => x
/-- arrow composition in the category of `TypeVec` -/
def comp (g : β ⟹ γ) (f : α ⟹ β)
: α ⟹ γ :=
fun i x => g i (f i x)
@[inherit_doc] scoped[MvFunctor] infixr:80 " ⊚ " => TypeVec.comp -- type as \oo
@[simp]
theorem id_comp (f : α ⟹ β) : id ⊚ f = f :=
rfl
@[simp]
theorem comp_id (f : α ⟹ β) : f ⊚ id = f :=
rfl
theorem comp_assoc
(h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) :
(h ⊚ g) ⊚ f = h ⊚ g ⊚ f :=
rfl
end
/-- Support for extending a `TypeVec` by one element. -/
def append1 (α : TypeVec n) (β : Type*) : TypeVec (n + 1)
| Fin2.fs i => α i
| Fin2.fz => β
@[inherit_doc] infixl:67 " ::: " => append1
/-- retain only a `n-length` prefix of the argument -/
def drop (α : TypeVec.{u} (n + 1)) : TypeVec n := fun i => α i.fs
/-- take the last value of a `(n+1)-length` vector -/
def last (α : TypeVec.{u} (n + 1)) : Type _ :=
α Fin2.fz
instance last.inhabited (α : TypeVec (n + 1)) [Inhabited (α Fin2.fz)] : Inhabited (last α) :=
⟨show α Fin2.fz from default⟩
theorem drop_append1 {α : TypeVec n} {β : Type*} {i : Fin2 n} : drop (append1 α β) i = α i :=
rfl
theorem drop_append1' {α : TypeVec n} {β : Type*} : drop (append1 α β) = α :=
funext fun _ => drop_append1
theorem last_append1 {α : TypeVec n} {β : Type*} : last (append1 α β) = β :=
rfl
@[simp]
theorem append1_drop_last (α : TypeVec (n + 1)) : append1 (drop α) (last α) = α :=
funext fun i => by cases i <;> rfl
/-- cases on `(n+1)-length` vectors -/
@[elab_as_elim]
def append1Cases {C : TypeVec (n + 1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by
rw [← @append1_drop_last _ γ]; apply H
@[simp]
theorem append1_cases_append1 {C : TypeVec (n + 1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) :
@append1Cases _ C H (append1 α β) = H α β :=
rfl
/-- append an arrow and a function for arbitrary source and target type vectors -/
def splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α'
| Fin2.fs i => f i
| Fin2.fz => g
/-- append an arrow and a function as well as their respective source and target types / typevecs -/
def appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
append1 α β ⟹ append1 α' β' :=
splitFun f g
@[inherit_doc] infixl:0 " ::: " => appendFun
/-- split off the prefix of an arrow -/
def dropFun {α β : TypeVec (n + 1)} (f : α ⟹ β) : drop α ⟹ drop β := fun i => f i.fs
/-- split off the last function of an arrow -/
def lastFun {α β : TypeVec (n + 1)} (f : α ⟹ β) : last α → last β :=
f Fin2.fz
/-- arrow in the category of `0-length` vectors -/
def nilFun {α : TypeVec 0} {β : TypeVec 0} : α ⟹ β := fun i => by apply Fin2.elim0 i
theorem eq_of_drop_last_eq {α β : TypeVec (n + 1)} {f g : α ⟹ β} (h₀ : dropFun f = dropFun g)
(h₁ : lastFun f = lastFun g) : f = g := by
refine funext (fun x => ?_)
cases x
· apply h₁
· apply congr_fun h₀
@[simp]
theorem dropFun_splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') :
dropFun (splitFun f g) = f :=
rfl
/-- turn an equality into an arrow -/
def Arrow.mp {α β : TypeVec n} (h : α = β) : α ⟹ β
| _ => Eq.mp (congr_fun h _)
/-- turn an equality into an arrow, with reverse direction -/
def Arrow.mpr {α β : TypeVec n} (h : α = β) : β ⟹ α
| _ => Eq.mpr (congr_fun h _)
/-- decompose a vector into its prefix appended with its last element -/
def toAppend1DropLast {α : TypeVec (n + 1)} : α ⟹ (drop α ::: last α) :=
Arrow.mpr (append1_drop_last _)
/-- stitch two bits of a vector back together -/
def fromAppend1DropLast {α : TypeVec (n + 1)} : (drop α ::: last α) ⟹ α :=
Arrow.mp (append1_drop_last _)
@[simp]
theorem lastFun_splitFun {α α' : TypeVec (n + 1)} (f : drop α ⟹ drop α') (g : last α → last α') :
lastFun (splitFun f g) = g :=
rfl
@[simp]
theorem dropFun_appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
dropFun (f ::: g) = f :=
rfl
@[simp]
theorem lastFun_appendFun {α α' : TypeVec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') :
lastFun (f ::: g) = g :=
rfl
theorem split_dropFun_lastFun {α α' : TypeVec (n + 1)} (f : α ⟹ α') :
splitFun (dropFun f) (lastFun f) = f :=
eq_of_drop_last_eq rfl rfl
theorem splitFun_inj {α α' : TypeVec (n + 1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'}
(H : splitFun f g = splitFun f' g') : f = f' ∧ g = g' := by
rw [← dropFun_splitFun f g, H, ← lastFun_splitFun f g, H]; simp
theorem appendFun_inj {α α' : TypeVec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} :
(f ::: g : (α ::: β) ⟹ _) = (f' ::: g' : (α ::: β) ⟹ _)
→ f = f' ∧ g = g' :=
splitFun_inj
theorem splitFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : drop α₀ ⟹ drop α₁)
(f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) :
splitFun (f₁ ⊚ f₀) (g₁ ∘ g₀) = splitFun f₁ g₁ ⊚ splitFun f₀ g₀ :=
eq_of_drop_last_eq rfl rfl
theorem appendFun_comp_splitFun {α γ : TypeVec n} {β δ : Type*} {ε : TypeVec (n + 1)}
(f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) :
appendFun f₁ g₁ ⊚ splitFun f₀ g₀ = splitFun (α' := γ.append1 δ) (f₁ ⊚ f₀) (g₁ ∘ g₀) :=
(splitFun_comp _ _ _ _).symm
theorem appendFun_comp {α₀ α₁ α₂ : TypeVec n}
{β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂)
(g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(f₁ ⊚ f₀ ::: g₁ ∘ g₀) = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) :=
eq_of_drop_last_eq rfl rfl
theorem appendFun_comp' {α₀ α₁ α₂ : TypeVec n} {β₀ β₁ β₂ : Type*}
(f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(f₁ ::: g₁) ⊚ (f₀ ::: g₀) = (f₁ ⊚ f₀ ::: g₁ ∘ g₀) :=
eq_of_drop_last_eq rfl rfl
theorem nilFun_comp {α₀ : TypeVec 0} (f₀ : α₀ ⟹ Fin2.elim0) : nilFun ⊚ f₀ = f₀ :=
funext Fin2.elim0
theorem appendFun_comp_id {α : TypeVec n} {β₀ β₁ β₂ : Type u} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) :
(@id _ α ::: g₁ ∘ g₀) = (id ::: g₁) ⊚ (id ::: g₀) :=
eq_of_drop_last_eq rfl rfl
@[simp]
theorem dropFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
dropFun (f₁ ⊚ f₀) = dropFun f₁ ⊚ dropFun f₀ :=
rfl
@[simp]
theorem lastFun_comp {α₀ α₁ α₂ : TypeVec (n + 1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) :
lastFun (f₁ ⊚ f₀) = lastFun f₁ ∘ lastFun f₀ :=
rfl
theorem appendFun_aux {α α' : TypeVec n} {β β' : Type*} (f : (α ::: β) ⟹ (α' ::: β')) :
(dropFun f ::: lastFun f) = f :=
eq_of_drop_last_eq rfl rfl
theorem appendFun_id_id {α : TypeVec n} {β : Type*} :
(@TypeVec.id n α ::: @_root_.id β) = TypeVec.id :=
eq_of_drop_last_eq rfl rfl
instance subsingleton0 : Subsingleton (TypeVec 0) :=
⟨fun _ _ => funext Fin2.elim0⟩
-- See `Mathlib/Tactic/Attr/Register.lean` for `register_simp_attr typevec`
/-- cases distinction for 0-length type vector -/
protected def casesNil {β : TypeVec 0 → Sort*} (f : β Fin2.elim0) : ∀ v, β v :=
fun v => cast (by congr; funext i; cases i) f
/-- cases distinction for (n+1)-length type vector -/
protected def casesCons (n : ℕ) {β : TypeVec (n + 1) → Sort*}
(f : ∀ (t) (v : TypeVec n), β (v ::: t)) :
∀ v, β v :=
fun v : TypeVec (n + 1) => cast (by simp) (f v.last v.drop)
protected theorem casesNil_append1 {β : TypeVec 0 → Sort*} (f : β Fin2.elim0) :
TypeVec.casesNil f Fin2.elim0 = f :=
rfl
protected theorem casesCons_append1 (n : ℕ) {β : TypeVec (n + 1) → Sort*}
(f : ∀ (t) (v : TypeVec n), β (v ::: t)) (v : TypeVec n) (α) :
TypeVec.casesCons n f (v ::: α) = f α v :=
rfl
/-- cases distinction for an arrow in the category of 0-length type vectors -/
def typevecCasesNil₃ {β : ∀ v v' : TypeVec 0, v ⟹ v' → Sort*}
(f : β Fin2.elim0 Fin2.elim0 nilFun) :
∀ v v' fs, β v v' fs := fun v v' fs => by
refine cast ?_ f
have eq₁ : v = Fin2.elim0 := by funext i; contradiction
have eq₂ : v' = Fin2.elim0 := by funext i; contradiction
have eq₃ : fs = nilFun := by funext i; contradiction
cases eq₁; cases eq₂; cases eq₃; rfl
/-- cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevecCasesCons₃ (n : ℕ) {β : ∀ v v' : TypeVec (n + 1), v ⟹ v' → Sort*}
(F : ∀ (t t') (f : t → t') (v v' : TypeVec n) (fs : v ⟹ v'),
β (v ::: t) (v' ::: t') (fs ::: f)) :
∀ v v' fs, β v v' fs := by
intro v v'
rw [← append1_drop_last v, ← append1_drop_last v']
intro fs
rw [← split_dropFun_lastFun fs]
apply F
/-- specialized cases distinction for an arrow in the category of 0-length type vectors -/
def typevecCasesNil₂ {β : Fin2.elim0 ⟹ Fin2.elim0 → Sort*} (f : β nilFun) : ∀ f, β f := by
intro g
suffices g = nilFun by rwa [this]
ext ⟨⟩
/-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/
def typevecCasesCons₂ (n : ℕ) (t t' : Type*) (v v' : TypeVec n)
{β : (v ::: t) ⟹ (v' ::: t') → Sort*}
(F : ∀ (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : ∀ fs, β fs := by
intro fs
rw [← split_dropFun_lastFun fs]
apply F
theorem typevecCasesNil₂_appendFun {β : Fin2.elim0 ⟹ Fin2.elim0 → Sort*} (f : β nilFun) :
typevecCasesNil₂ f nilFun = f :=
rfl
theorem typevecCasesCons₂_appendFun (n : ℕ) (t t' : Type*) (v v' : TypeVec n)
{β : (v ::: t) ⟹ (v' ::: t') → Sort*}
(F : ∀ (f : t → t') (fs : v ⟹ v'), β (fs ::: f))
(f fs) :
typevecCasesCons₂ n t t' v v' F (fs ::: f) = F f fs :=
rfl
-- for lifting predicates and relations
/-- `PredLast α p x` predicates `p` of the last element of `x : α.append1 β`. -/
def PredLast (α : TypeVec n) {β : Type*} (p : β → Prop) : ∀ ⦃i⦄, (α.append1 β) i → Prop
| Fin2.fs _ => fun _ => True
| Fin2.fz => p
/-- `RelLast α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and
all the other elements are equal. -/
def RelLast (α : TypeVec n) {β γ : Type u} (r : β → γ → Prop) :
∀ ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop
| Fin2.fs _ => Eq
| Fin2.fz => r
section Liftp'
open Nat
/-- `repeat n t` is a `n-length` type vector that contains `n` occurrences of `t` -/
def «repeat» : ∀ (n : ℕ), Type u → TypeVec n
| 0, _ => Fin2.elim0
| Nat.succ i, t => append1 («repeat» i t) t
/-- `prod α β` is the pointwise product of the components of `α` and `β` -/
def prod : ∀ {n}, TypeVec.{u} n → TypeVec.{u} n → TypeVec n
| 0, _, _ => Fin2.elim0
| n + 1, α, β => (@prod n (drop α) (drop β)) ::: (last α × last β)
@[inherit_doc] scoped[MvFunctor] infixl:45 " ⊗ " => TypeVec.prod
/-- `const x α` is an arrow that ignores its source and constructs a `TypeVec` that
contains nothing but `x` -/
protected def const {β} (x : β) : ∀ {n} (α : TypeVec n), α ⟹ «repeat» _ β
| succ _, α, Fin2.fs _ => TypeVec.const x (drop α) _
| succ _, _, Fin2.fz => fun _ => x
open Function (uncurry)
/-- vector of equality on a product of vectors -/
def repeatEq : ∀ {n} (α : TypeVec n), (α ⊗ α) ⟹ «repeat» _ Prop
| 0, _ => nilFun
| succ _, α => repeatEq (drop α) ::: uncurry Eq
theorem const_append1 {β γ} (x : γ) {n} (α : TypeVec n) :
TypeVec.const x (α ::: β) = appendFun (TypeVec.const x α) fun _ => x := by
ext i : 1; cases i <;> rfl
theorem eq_nilFun {α β : TypeVec 0} (f : α ⟹ β) : f = nilFun := by
ext x; cases x
theorem id_eq_nilFun {α : TypeVec 0} : @id _ α = nilFun := by
ext x; cases x
theorem const_nil {β} (x : β) (α : TypeVec 0) : TypeVec.const x α = nilFun := by
ext i : 1; cases i
@[typevec]
theorem repeat_eq_append1 {β} {n} (α : TypeVec n) :
repeatEq (α ::: β) = splitFun (α := (α ⊗ α) ::: _)
(α' := («repeat» n Prop) ::: _) (repeatEq α) (uncurry Eq) := by
induction n <;> rfl
@[typevec]
theorem repeat_eq_nil (α : TypeVec 0) : repeatEq α = nilFun := by ext i; cases i
/-- predicate on a type vector to constrain only the last object -/
def PredLast' (α : TypeVec n) {β : Type*} (p : β → Prop) :
(α ::: β) ⟹ «repeat» (n + 1) Prop :=
splitFun (TypeVec.const True α) p
/-- predicate on the product of two type vectors to constrain only their last object -/
def RelLast' (α : TypeVec n) {β : Type*} (p : β → β → Prop) :
(α ::: β) ⊗ (α ::: β) ⟹ «repeat» (n + 1) Prop :=
splitFun (repeatEq α) (uncurry p)
/-- given `F : TypeVec.{u} (n+1) → Type u`, `curry F : Type u → TypeVec.{u} → Type u`,
i.e. its first argument can be fed in separately from the rest of the vector of arguments -/
def Curry (F : TypeVec.{u} (n + 1) → Type*) (α : Type u) (β : TypeVec.{u} n) : Type _ :=
F (β ::: α)
instance Curry.inhabited (F : TypeVec.{u} (n + 1) → Type*) (α : Type u) (β : TypeVec.{u} n)
[I : Inhabited (F <| (β ::: α))] : Inhabited (Curry F α β) :=
I
/-- arrow to remove one element of a `repeat` vector -/
def dropRepeat (α : Type*) : ∀ {n}, drop («repeat» (succ n) α) ⟹ «repeat» n α
| succ _, Fin2.fs i => dropRepeat α i
| succ _, Fin2.fz => fun (a : α) => a
/-- projection for a repeat vector -/
def ofRepeat {α : Sort _} : ∀ {n i}, «repeat» n α i → α
| _, Fin2.fz => fun (a : α) => a
| _, Fin2.fs i => @ofRepeat _ _ i
theorem const_iff_true {α : TypeVec n} {i x p} : ofRepeat (TypeVec.const p α i x) ↔ p := by
induction i with
| fz => rfl
| fs _ ih =>
rw [TypeVec.const]
exact ih
section
/-- left projection of a `prod` vector -/
def prod.fst : ∀ {n} {α β : TypeVec.{u} n}, α ⊗ β ⟹ α
| succ _, α, β, Fin2.fs i => @prod.fst _ (drop α) (drop β) i
| succ _, _, _, Fin2.fz => Prod.fst
/-- right projection of a `prod` vector -/
def prod.snd : ∀ {n} {α β : TypeVec.{u} n}, α ⊗ β ⟹ β
| succ _, α, β, Fin2.fs i => @prod.snd _ (drop α) (drop β) i
| succ _, _, _, Fin2.fz => Prod.snd
/-- introduce a product where both components are the same -/
def prod.diag : ∀ {n} {α : TypeVec.{u} n}, α ⟹ α ⊗ α
| succ _, α, Fin2.fs _, x => @prod.diag _ (drop α) _ x
| succ _, _, Fin2.fz, x => (x, x)
/-- constructor for `prod` -/
def prod.mk : ∀ {n} {α β : TypeVec.{u} n} (i : Fin2 n), α i → β i → (α ⊗ β) i
| succ _, α, β, Fin2.fs i => mk (α := fun i => α i.fs) (β := fun i => β i.fs) i
| succ _, _, _, Fin2.fz => Prod.mk
end
@[simp]
theorem prod_fst_mk {α β : TypeVec n} (i : Fin2 n) (a : α i) (b : β i) :
TypeVec.prod.fst i (prod.mk i a b) = a := by
induction i with
| fz => simp_all only [prod.fst, prod.mk]
| fs _ i_ih => apply i_ih
@[simp]
theorem prod_snd_mk {α β : TypeVec n} (i : Fin2 n) (a : α i) (b : β i) :
TypeVec.prod.snd i (prod.mk i a b) = b := by
induction i with
| fz => simp_all [prod.snd, prod.mk]
| fs _ i_ih => apply i_ih
/-- `prod` is functorial -/
protected def prod.map : ∀ {n} {α α' β β' : TypeVec.{u} n}, α ⟹ β → α' ⟹ β' → α ⊗ α' ⟹ β ⊗ β'
| succ _, α, α', β, β', x, y, Fin2.fs _, a =>
@prod.map _ (drop α) (drop α') (drop β) (drop β') (dropFun x) (dropFun y) _ a
| succ _, _, _, _, _, x, y, Fin2.fz, a => (x _ a.1, y _ a.2)
@[inherit_doc] scoped[MvFunctor] infixl:45 " ⊗' " => TypeVec.prod.map
theorem fst_prod_mk {α α' β β' : TypeVec n} (f : α ⟹ β) (g : α' ⟹ β') :
TypeVec.prod.fst ⊚ (f ⊗' g) = f ⊚ TypeVec.prod.fst := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem snd_prod_mk {α α' β β' : TypeVec n} (f : α ⟹ β) (g : α' ⟹ β') :
TypeVec.prod.snd ⊚ (f ⊗' g) = g ⊚ TypeVec.prod.snd := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem fst_diag {α : TypeVec n} : TypeVec.prod.fst ⊚ (prod.diag : α ⟹ _) = id := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem snd_diag {α : TypeVec n} : TypeVec.prod.snd ⊚ (prod.diag : α ⟹ _) = id := by
funext i; induction i with
| fz => rfl
| fs _ i_ih => apply i_ih
theorem repeatEq_iff_eq {α : TypeVec n} {i x y} :
ofRepeat (repeatEq α i (prod.mk _ x y)) ↔ x = y := by
induction i with
| fz => rfl
| fs _ i_ih =>
rw [repeatEq]
exact i_ih
/-- given a predicate vector `p` over vector `α`, `Subtype_ p` is the type of vectors
that contain an `α` that satisfies `p` -/
def Subtype_ : ∀ {n} {α : TypeVec.{u} n}, (α ⟹ «repeat» n Prop) → TypeVec n
| _, _, p, Fin2.fz => Subtype fun x => p Fin2.fz x
| _, _, p, Fin2.fs i => Subtype_ (dropFun p) i
/-- projection on `Subtype_` -/
def subtypeVal : ∀ {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop), Subtype_ p ⟹ α
| succ n, _, _, Fin2.fs i => @subtypeVal n _ _ i
| succ _, _, _, Fin2.fz => Subtype.val
/-- arrow that rearranges the type of `Subtype_` to turn a subtype of vector into
a vector of subtypes -/
def toSubtype :
∀ {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop),
(fun i : Fin2 n => { x // ofRepeat <| p i x }) ⟹ Subtype_ p
| succ _, _, p, Fin2.fs i, x => toSubtype (dropFun p) i x
| succ _, _, _, Fin2.fz, x => x
/-- arrow that rearranges the type of `Subtype_` to turn a vector of subtypes
into a subtype of vector -/
def ofSubtype {n} {α : TypeVec.{u} n} (p : α ⟹ «repeat» n Prop) :
Subtype_ p ⟹ fun i : Fin2 n => { x // ofRepeat <| p i x }
| Fin2.fs i, x => ofSubtype _ i x
| Fin2.fz, x => x
/-- similar to `toSubtype` adapted to relations (i.e. predicate on product) -/
def toSubtype' {n} {α : TypeVec.{u} n} (p : α ⊗ α ⟹ «repeat» n Prop) :
(fun i : Fin2 n => { x : α i × α i // ofRepeat <| p i (prod.mk _ x.1 x.2) }) ⟹ Subtype_ p
| Fin2.fs i, x => toSubtype' (dropFun p) i x
| Fin2.fz, x => ⟨x.val, cast (by congr) x.property⟩
/-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/
def ofSubtype' {n} {α : TypeVec.{u} n} (p : α ⊗ α ⟹ «repeat» n Prop) :
Subtype_ p ⟹ fun i : Fin2 n => { x : α i × α i // ofRepeat <| p i (prod.mk _ x.1 x.2) }
| Fin2.fs i, x => ofSubtype' _ i x
| Fin2.fz, x => ⟨x.val, cast (by congr) x.property⟩
/-- similar to `diag` but the target vector is a `Subtype_`
guaranteeing the equality of the components -/
def diagSub {n} {α : TypeVec.{u} n} : α ⟹ Subtype_ (repeatEq α)
| Fin2.fs _, x => @diagSub _ (drop α) _ x
| Fin2.fz, x => ⟨(x, x), rfl⟩
theorem subtypeVal_nil {α : TypeVec.{u} 0} (ps : α ⟹ «repeat» 0 Prop) :
TypeVec.subtypeVal ps = nilFun :=
funext <| by rintro ⟨⟩
@[simp]
theorem diag_sub_val {n} {α : TypeVec.{u} n} : subtypeVal (repeatEq α) ⊚ diagSub = prod.diag := by
ext i x
induction i with
| fz => simp only [comp, subtypeVal, repeatEq.eq_2, diagSub, prod.diag]
| fs _ i_ih => apply @i_ih (drop α)
theorem prod_id : ∀ {n} {α β : TypeVec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) := by
intros
ext i a
induction i with
| fz => cases a; rfl
| fs _ i_ih => apply i_ih
theorem append_prod_appendFun {n} {α α' β β' : TypeVec.{u} n} {φ φ' ψ ψ' : Type u}
{f₀ : α ⟹ α'} {g₀ : β ⟹ β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} :
((f₀ ⊗' g₀) ::: (_root_.Prod.map f₁ g₁)) = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) := by
ext i a
cases i
· cases a
rfl
· rfl
end Liftp'
@[simp]
theorem dropFun_diag {α} : dropFun (@prod.diag (n + 1) α) = prod.diag := rfl
@[simp]
theorem dropFun_subtypeVal {α} (p : α ⟹ «repeat» (n + 1) Prop) :
dropFun (subtypeVal p) = subtypeVal _ :=
rfl
@[simp]
theorem lastFun_subtypeVal {α} (p : α ⟹ «repeat» (n + 1) Prop) :
lastFun (subtypeVal p) = Subtype.val :=
rfl
@[simp]
theorem dropFun_toSubtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
dropFun (toSubtype p) = toSubtype _ := rfl
@[simp]
theorem lastFun_toSubtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
lastFun (toSubtype p) = _root_.id := rfl
@[simp]
theorem dropFun_of_subtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
dropFun (ofSubtype p) = ofSubtype _ := rfl
@[simp]
theorem lastFun_of_subtype {α} (p : α ⟹ «repeat» (n + 1) Prop) :
lastFun (ofSubtype p) = _root_.id := rfl
@[simp]
theorem dropFun_RelLast' {α : TypeVec n} {β} (R : β → β → Prop) :
dropFun (RelLast' α R) = repeatEq α :=
rfl
attribute [simp] drop_append1'
@[simp]
theorem dropFun_prod {α α' β β' : TypeVec (n + 1)} (f : α ⟹ β) (f' : α' ⟹ β') :
dropFun (f ⊗' f') = (dropFun f ⊗' dropFun f') := rfl
@[simp]
theorem lastFun_prod {α α' β β' : TypeVec (n + 1)} (f : α ⟹ β) (f' : α' ⟹ β') :
lastFun (f ⊗' f') = Prod.map (lastFun f) (lastFun f') := rfl
@[simp]
theorem dropFun_from_append1_drop_last {α : TypeVec (n + 1)} :
dropFun (@fromAppend1DropLast _ α) = id :=
rfl
@[simp]
theorem lastFun_from_append1_drop_last {α : TypeVec (n + 1)} :
lastFun (@fromAppend1DropLast _ α) = _root_.id :=
rfl
@[simp]
theorem dropFun_id {α : TypeVec (n + 1)} : dropFun (@TypeVec.id _ α) = id :=
rfl
@[simp]
theorem prod_map_id {α β : TypeVec n} : (@TypeVec.id _ α ⊗' @TypeVec.id _ β) = id := prod_id
@[deprecated (since := "2025-08-14")] alias subtypeVal_diagSub := diag_sub_val
@[simp]
theorem toSubtype_of_subtype {α : TypeVec n} (p : α ⟹ «repeat» n Prop) :
toSubtype p ⊚ ofSubtype p = id := by
ext i x
induction i <;> simp only [id, toSubtype, comp, ofSubtype] at *
simp [*]
@[simp]
theorem subtypeVal_toSubtype {α : TypeVec n} (p : α ⟹ «repeat» n Prop) :
subtypeVal p ⊚ toSubtype p = fun _ => Subtype.val := by
ext i x
induction i <;> simp only [toSubtype, comp, subtypeVal] at *
simp [*]
@[simp]
theorem toSubtype_of_subtype_assoc
{α β : TypeVec n} (p : α ⟹ «repeat» n Prop) (f : β ⟹ Subtype_ p) :
@toSubtype n _ p ⊚ ofSubtype _ ⊚ f = f := by
rw [← comp_assoc, toSubtype_of_subtype]; simp
@[simp]
theorem toSubtype'_of_subtype' {α : TypeVec n} (r : α ⊗ α ⟹ «repeat» n Prop) :
toSubtype' r ⊚ ofSubtype' r = id := by
ext i x
induction i
<;> dsimp only [id, toSubtype', comp, ofSubtype'] at *
<;> simp [*]
theorem subtypeVal_toSubtype' {α : TypeVec n} (r : α ⊗ α ⟹ «repeat» n Prop) :
subtypeVal r ⊚ toSubtype' r = fun i x => prod.mk i x.1.fst x.1.snd := by
ext i x
induction i <;> simp only [toSubtype', comp, subtypeVal, prod.mk] at *
simp [*]
end TypeVec |
.lake/packages/mathlib/Mathlib/Data/Bracket.lean | import Mathlib.Tactic.TypeStar
/-!
# Bracket Notation
This file provides notation which can be used for the Lie bracket, for the commutator of two
subgroups, and for other similar operations.
## Main Definitions
* `Bracket L M` for a binary operation that takes something in `L` and something in `M` and
produces something in `M`.
Defining an instance of this structure gives access to the notation `⁅ ⁆`
## Notation
We introduce the notation `⁅x, y⁆` for the `bracket` of any `Bracket` structure. Note that
these are the Unicode "square with quill" brackets rather than the usual square brackets.
-/
/-- The `Bracket` class has three intended uses:
1. for certain binary operations on structures, like the product `⁅x, y⁆` of two elements
`x`, `y` in a Lie algebra or the commutator of two elements `x` and `y` in a group.
2. for certain actions of one structure on another, like the action `⁅x, m⁆` of an element `x`
of a Lie algebra on an element `m` in one of its modules (analogous to `SMul` in the
associative setting).
3. for binary operations on substructures, like the commutator `⁅H, K⁆` of two subgroups `H` and
`K` of a group. -/
class Bracket (L M : Type*) where
/-- `⁅x, y⁆` is the result of a bracket operation on elements `x` and `y`.
It is supported by the `Bracket` typeclass. -/
bracket : L → M → M
@[inherit_doc] notation "⁅" x ", " y "⁆" => Bracket.bracket x y |
.lake/packages/mathlib/Mathlib/Data/Vector3.lean | import Mathlib.Data.Fin.Fin2
import Mathlib.Util.Notation3
import Mathlib.Tactic.TypeStar
/-!
# Alternate definition of `Vector` in terms of `Fin2`
This file provides a scope `Vector3` which overrides the `[a, b, c]` notation to create a `Vector3`
instead of a `List`.
The `::` notation is also overloaded by this file to mean `Vector3.cons`.
-/
open Fin2 Nat
universe u
variable {α : Type*} {m n : ℕ}
/-- Alternate definition of `Vector` based on `Fin2`. -/
def Vector3 (α : Type u) (n : ℕ) : Type u :=
Fin2 n → α
instance [Inhabited α] : Inhabited (Vector3 α n) where
default := fun _ => default
namespace Vector3
/-- The empty vector -/
@[match_pattern]
def nil : Vector3 α 0 :=
nofun
/-- The vector cons operation -/
@[match_pattern]
def cons (a : α) (v : Vector3 α n) : Vector3 α (n + 1) := fun i => by
refine i.cases' ?_ ?_
· exact a
· exact v
section
open Lean
scoped macro_rules | `([$l,*]) => `(expand_foldr% (h t => cons h t) nil [$(.ofElems l),*])
-- this is copied from `src/Init/NotationExtra.lean`
/-- Unexpander for `Vector3.nil` -/
@[app_unexpander Vector3.nil] def unexpandNil : Lean.PrettyPrinter.Unexpander
| `($(_)) => `([])
-- this is copied from `src/Init/NotationExtra.lean`
/-- Unexpander for `Vector3.cons` -/
@[app_unexpander Vector3.cons] def unexpandCons : Lean.PrettyPrinter.Unexpander
| `($(_) $x []) => `([$x])
| `($(_) $x [$xs,*]) => `([$x, $xs,*])
| _ => throw ()
end
-- Overloading the usual `::` notation for `List.cons` with `Vector3.cons`.
@[inherit_doc]
scoped notation a " :: " b => cons a b
@[simp]
theorem cons_fz (a : α) (v : Vector3 α n) : (a :: v) fz = a :=
rfl
@[simp]
theorem cons_fs (a : α) (v : Vector3 α n) (i) : (a :: v) (fs i) = v i :=
rfl
/-- Get the `i`th element of a vector -/
abbrev nth (i : Fin2 n) (v : Vector3 α n) : α :=
v i
/-- Construct a vector from a function on `Fin2`. -/
abbrev ofFn (f : Fin2 n → α) : Vector3 α n :=
f
/-- Get the head of a nonempty vector. -/
def head (v : Vector3 α (n + 1)) : α :=
v fz
/-- Get the tail of a nonempty vector. -/
def tail (v : Vector3 α (n + 1)) : Vector3 α n := fun i => v (fs i)
theorem eq_nil (v : Vector3 α 0) : v = [] :=
funext fun i => nomatch i
theorem cons_head_tail (v : Vector3 α (n + 1)) : (head v :: tail v) = v :=
funext fun i => Fin2.cases' rfl (fun _ => rfl) i
/-- Eliminator for an empty vector. -/
@[elab_as_elim]
def nilElim {C : Vector3 α 0 → Sort u} (H : C []) (v : Vector3 α 0) : C v := by
rw [eq_nil v]; apply H
/-- Recursion principle for a nonempty vector. -/
@[elab_as_elim]
def consElim {C : Vector3 α (n + 1) → Sort u} (H : ∀ (a : α) (t : Vector3 α n), C (a :: t))
(v : Vector3 α (n + 1)) : C v := by rw [← cons_head_tail v]; apply H
@[simp]
theorem consElim_cons {C H a t} : @consElim α n C H (a :: t) = H a t :=
rfl
/-- Recursion principle with the vector as first argument. -/
@[elab_as_elim]
protected def recOn {C : ∀ {n}, Vector3 α n → Sort u} {n} (v : Vector3 α n) (H0 : C [])
(Hs : ∀ {n} (a) (w : Vector3 α n), C w → C (a :: w)) : C v :=
match n with
| 0 => v.nilElim H0
| _ + 1 => v.consElim fun a t => Hs a t (Vector3.recOn t H0 Hs)
@[simp]
theorem recOn_nil {C H0 Hs} : @Vector3.recOn α (@C) 0 [] H0 @Hs = H0 :=
rfl
@[simp]
theorem recOn_cons {C H0 Hs n a v} :
@Vector3.recOn α (@C) (n + 1) (a :: v) H0 @Hs = Hs a v (@Vector3.recOn α (@C) n v H0 @Hs) :=
rfl
/-- Append two vectors -/
def append (v : Vector3 α m) (w : Vector3 α n) : Vector3 α (n + m) :=
v.recOn w (fun a _ IH => a :: IH)
/--
A local infix notation for `Vector3.append`
-/
local infixl:65 " +-+ " => Vector3.append
@[simp]
theorem append_nil (w : Vector3 α n) : [] +-+ w = w :=
rfl
@[simp]
theorem append_cons (a : α) (v : Vector3 α m) (w : Vector3 α n) : (a :: v) +-+ w = a :: v +-+ w :=
rfl
@[simp]
theorem append_left :
∀ {m} (i : Fin2 m) (v : Vector3 α m) {n} (w : Vector3 α n), (v +-+ w) (left n i) = v i
| _, @fz m, v, _, _ => v.consElim fun a _t => by simp [*, left]
| _, @fs m i, v, n, w => v.consElim fun _a t => by simp [append_left, left]
@[simp]
theorem append_add :
∀ {m} (v : Vector3 α m) {n} (w : Vector3 α n) (i : Fin2 n), (v +-+ w) (add i m) = w i
| 0, _, _, _, _ => rfl
| m + 1, v, n, w, i => v.consElim fun _a t => by simp [append_add, add]
/-- Insert `a` into `v` at index `i`. -/
def insert (a : α) (v : Vector3 α n) (i : Fin2 (n + 1)) : Vector3 α (n + 1) := fun j =>
(a :: v) (insertPerm i j)
@[simp]
theorem insert_fz (a : α) (v : Vector3 α n) : insert a v fz = a :: v := by
refine funext fun j => j.cases' ?_ ?_ <;> intros <;> rfl
@[simp]
theorem insert_fs (a : α) (b : α) (v : Vector3 α n) (i : Fin2 (n + 1)) :
insert a (b :: v) (fs i) = b :: insert a v i :=
funext fun j => by
refine j.cases' (by simp [insert, insertPerm]) fun j => ?_
simp only [insert, insertPerm, succ_eq_add_one, cons_fs]
refine Fin2.cases' ?_ ?_ (insertPerm i j) <;> simp
theorem append_insert (a : α) (t : Vector3 α m) (v : Vector3 α n) (i : Fin2 (n + 1))
(e : (n + 1) + m = (n + m) + 1) :
insert a (t +-+ v) (Eq.recOn e (i.add m)) = Eq.recOn e (t +-+ insert a v i) := by
refine Vector3.recOn t (fun e => ?_) (@fun k b t IH _ => ?_) e
· rfl
have e' : (n + 1) + k = (n + k) + 1 := by omega
change
insert a (b :: t +-+ v)
(Eq.recOn (congr_arg (· + 1) e' : _ + 1 = _) (fs (add i k))) =
Eq.recOn (congr_arg (· + 1) e' : _ + 1 = _) (b :: t +-+ insert a v i)
rw [← (Eq.recOn e' rfl :
fs (Eq.recOn e' (i.add k) : Fin2 ((n + k) + 1)) =
Eq.recOn (congr_arg (· + 1) e' : _ + 1 = _) (fs (i.add k)))]
simpa [IH] using Eq.recOn e' rfl
end Vector3
section Vector3
open Vector3
/-- "Curried" exists, i.e. `∃ x₁ ... xₙ, f [x₁, ..., xₙ]`. -/
def VectorEx : ∀ k, (Vector3 α k → Prop) → Prop
| 0, f => f []
| succ k, f => ∃ x : α, VectorEx k fun v => f (x :: v)
/-- "Curried" forall, i.e. `∀ x₁ ... xₙ, f [x₁, ..., xₙ]`. -/
def VectorAll : ∀ k, (Vector3 α k → Prop) → Prop
| 0, f => f []
| succ k, f => ∀ x : α, VectorAll k fun v => f (x :: v)
theorem exists_vector_zero (f : Vector3 α 0 → Prop) : Exists f ↔ f [] :=
⟨fun ⟨v, fv⟩ => by rw [← eq_nil v]; exact fv, fun f0 => ⟨[], f0⟩⟩
theorem exists_vector_succ (f : Vector3 α (succ n) → Prop) : Exists f ↔ ∃ x v, f (x :: v) :=
⟨fun ⟨v, fv⟩ => ⟨_, _, by rw [cons_head_tail v]; exact fv⟩, fun ⟨_, _, fxv⟩ => ⟨_, fxv⟩⟩
theorem vectorEx_iff_exists : ∀ {n} (f : Vector3 α n → Prop), VectorEx n f ↔ Exists f
| 0, f => (exists_vector_zero f).symm
| succ _, f =>
Iff.trans (exists_congr fun _ => vectorEx_iff_exists _) (exists_vector_succ f).symm
theorem vectorAll_iff_forall : ∀ {n} (f : Vector3 α n → Prop), VectorAll n f ↔ ∀ v, f v
| 0, _ => ⟨fun f0 v => v.nilElim f0, fun al => al []⟩
| succ _, f =>
(forall_congr' fun x => vectorAll_iff_forall fun v => f (x :: v)).trans
⟨fun al v => v.consElim al, fun al x v => al (x :: v)⟩
/-- `VectorAllP p v` is equivalent to `∀ i, p (v i)`, but unfolds directly to a conjunction,
i.e. `VectorAllP p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/
def VectorAllP (p : α → Prop) (v : Vector3 α n) : Prop :=
Vector3.recOn v True fun a v IH =>
@Vector3.recOn _ (fun _ => Prop) _ v (p a) fun _ _ _ => p a ∧ IH
@[simp]
theorem vectorAllP_nil (p : α → Prop) : VectorAllP p [] = True :=
rfl
@[simp]
theorem vectorAllP_singleton (p : α → Prop) (x : α) : VectorAllP p (cons x []) = p x :=
rfl
@[simp]
theorem vectorAllP_cons (p : α → Prop) (x : α) (v : Vector3 α n) :
VectorAllP p (x :: v) ↔ p x ∧ VectorAllP p v :=
Vector3.recOn v (iff_of_eq (and_true _)).symm fun _ _ _ => Iff.rfl
theorem vectorAllP_iff_forall (p : α → Prop) (v : Vector3 α n) :
VectorAllP p v ↔ ∀ i, p (v i) := by
refine v.recOn ?_ ?_
· exact ⟨fun _ => Fin2.elim0, fun _ => trivial⟩
· simp only [vectorAllP_cons]
refine fun {n} a v IH =>
(and_congr_right fun _ => IH).trans
⟨fun ⟨pa, h⟩ i => by
refine i.cases' ?_ ?_
exacts [pa, h], fun h => ⟨?_, fun i => ?_⟩⟩
· simpa using h fz
· simpa using h (fs i)
theorem VectorAllP.imp {p q : α → Prop} (h : ∀ x, p x → q x) {v : Vector3 α n}
(al : VectorAllP p v) : VectorAllP q v :=
(vectorAllP_iff_forall _ _).2 fun _ => h _ <| (vectorAllP_iff_forall _ _).1 al _
end Vector3 |
.lake/packages/mathlib/Mathlib/Data/Char.lean | import Mathlib.Data.Nat.Basic
import Mathlib.Order.Defs.LinearOrder
/-!
# More `Char` instances
This file provides a `LinearOrder` instance on `Char`. `Char` is the type of Unicode scalar values.
Provides an additional definition to truncate a `Char` to `UInt8` and a theorem on conversion to
`Nat`.
-/
/--
Provides a `LinearOrder` instance on `Char`. `Char` is the type of Unicode scalar values.
-/
instance : LinearOrder Char where
le_refl := fun _ => @le_refl ℕ _ _
le_trans := fun _ _ _ => @le_trans ℕ _ _ _ _
le_antisymm := fun _ _ h₁ h₂ => Char.eq_of_val_eq <| UInt32.eq_of_toBitVec_eq <|
BitVec.le_antisymm h₁ h₂
lt_iff_le_not_ge := fun _ _ => @lt_iff_le_not_ge ℕ _ _ _
le_total := fun _ _ => @le_total ℕ _ _ _
min := fun a b => if a ≤ b then a else b
max := fun a b => if a ≤ b then b else a
toDecidableLE := inferInstance
toDecidableEq := inferInstance
toDecidableLT := inferInstance |
.lake/packages/mathlib/Mathlib/Data/PEquiv.lean | import Mathlib.Data.Option.Basic
import Batteries.Tactic.Congr
import Mathlib.Data.Set.Basic
import Mathlib.Tactic.Contrapose
/-!
# Partial Equivalences
In this file, we define partial equivalences `PEquiv`, which are a bijection between a subset of `α`
and a subset of `β`. Notationally, a `PEquiv` is denoted by "`≃.`" (note that the full stop is part
of the notation). The way we store these internally is with two functions `f : α → Option β` and
the reverse function `g : β → Option α`, with the condition that if `f a` is `some b`,
then `g b` is `some a`.
## Main results
- `PEquiv.ofSet`: creates a `PEquiv` from a set `s`,
which sends an element to itself if it is in `s`.
- `PEquiv.single`: given two elements `a : α` and `b : β`, create a `PEquiv` that sends them to
each other, and ignores all other elements.
- `PEquiv.injective_of_forall_ne_isSome`/`injective_of_forall_isSome`: If the domain of a `PEquiv`
is all of `α` (except possibly one point), its `toFun` is injective.
## Canonical order
`PEquiv` is canonically ordered by inclusion; that is, if a function `f` defined on a subset `s`
is equal to `g` on that subset, but `g` is also defined on a larger set, then `f ≤ g`. We also have
a definition of `⊥`, which is the empty `PEquiv` (sends all to `none`), which in the end gives us a
`SemilatticeInf` with an `OrderBot` instance.
## Tags
pequiv, partial equivalence
-/
assert_not_exists RelIso
universe u v w x
/-- A `PEquiv` is a partial equivalence, a representation of a bijection between a subset
of `α` and a subset of `β`. See also `PartialEquiv` for a version that requires `toFun` and
`invFun` to be globally defined functions and has `source` and `target` sets as extra fields. -/
structure PEquiv (α : Type u) (β : Type v) where
/-- The underlying partial function of a `PEquiv` -/
toFun : α → Option β
/-- The partial inverse of `toFun` -/
invFun : β → Option α
/-- `invFun` is the partial inverse of `toFun` -/
inv : ∀ (a : α) (b : β), invFun b = some a ↔ toFun a = some b
/-- A `PEquiv` is a partial equivalence, a representation of a bijection between a subset
of `α` and a subset of `β`. See also `PartialEquiv` for a version that requires `toFun` and
`invFun` to be globally defined functions and has `source` and `target` sets as extra fields. -/
infixr:25 " ≃. " => PEquiv
namespace PEquiv
variable {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
open Function Option
instance : FunLike (α ≃. β) α (Option β) :=
{ coe := toFun
coe_injective' := by
rintro ⟨f₁, f₂, hf⟩ ⟨g₁, g₂, hg⟩ (rfl : f₁ = g₁)
congr with y x
simp only [hf, hg] }
@[simp] theorem coe_mk (f₁ : α → Option β) (f₂ h) : (mk f₁ f₂ h : α → Option β) = f₁ :=
rfl
theorem coe_mk_apply (f₁ : α → Option β) (f₂ : β → Option α) (h) (x : α) :
(PEquiv.mk f₁ f₂ h : α → Option β) x = f₁ x :=
rfl
@[ext] theorem ext {f g : α ≃. β} (h : ∀ x, f x = g x) : f = g :=
DFunLike.ext f g h
/-- The identity map as a partial equivalence. -/
@[refl]
protected def refl (α : Type*) : α ≃. α where
toFun := some
invFun := some
inv _ _ := eq_comm
/-- The inverse partial equivalence. -/
@[symm]
protected def symm (f : α ≃. β) : β ≃. α where
toFun := f.2
invFun := f.1
inv _ _ := (f.inv _ _).symm
theorem mem_iff_mem (f : α ≃. β) : ∀ {a : α} {b : β}, a ∈ f.symm b ↔ b ∈ f a :=
f.3 _ _
theorem eq_some_iff (f : α ≃. β) : ∀ {a : α} {b : β}, f.symm b = some a ↔ f a = some b :=
f.3 _ _
/-- Composition of partial equivalences `f : α ≃. β` and `g : β ≃. γ`. -/
@[trans]
protected def trans (f : α ≃. β) (g : β ≃. γ) :
α ≃. γ where
toFun a := (f a).bind g
invFun a := (g.symm a).bind f.symm
inv a b := by simp_all [and_comm, eq_some_iff f, eq_some_iff g, bind_eq_some_iff]
@[simp]
theorem refl_apply (a : α) : PEquiv.refl α a = some a :=
rfl
@[simp]
theorem symm_refl : (PEquiv.refl α).symm = PEquiv.refl α :=
rfl
@[simp]
theorem symm_symm (f : α ≃. β) : f.symm.symm = f := rfl
theorem symm_bijective : Function.Bijective (PEquiv.symm : (α ≃. β) → β ≃. α) :=
Function.bijective_iff_has_inverse.mpr ⟨_, symm_symm, symm_symm⟩
theorem symm_injective : Function.Injective (@PEquiv.symm α β) :=
symm_bijective.injective
theorem trans_assoc (f : α ≃. β) (g : β ≃. γ) (h : γ ≃. δ) :
(f.trans g).trans h = f.trans (g.trans h) :=
ext fun _ => Option.bind_assoc _ _ _
theorem mem_trans (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) :
c ∈ f.trans g a ↔ ∃ b, b ∈ f a ∧ c ∈ g b :=
Option.bind_eq_some_iff
theorem trans_eq_some (f : α ≃. β) (g : β ≃. γ) (a : α) (c : γ) :
f.trans g a = some c ↔ ∃ b, f a = some b ∧ g b = some c :=
Option.bind_eq_some_iff
theorem trans_eq_none (f : α ≃. β) (g : β ≃. γ) (a : α) :
f.trans g a = none ↔ ∀ b c, b ∉ f a ∨ c ∉ g b := by
simp only [eq_none_iff_forall_not_mem, mem_trans, imp_iff_not_or.symm]
push_neg
exact forall_swap
@[simp]
theorem refl_trans (f : α ≃. β) : (PEquiv.refl α).trans f = f := by
ext; dsimp [PEquiv.trans]; rfl
@[simp]
theorem trans_refl (f : α ≃. β) : f.trans (PEquiv.refl β) = f := by
ext; dsimp [PEquiv.trans]; simp
protected theorem inj (f : α ≃. β) {a₁ a₂ : α} {b : β} (h₁ : b ∈ f a₁) (h₂ : b ∈ f a₂) :
a₁ = a₂ := by rw [← mem_iff_mem] at *; cases h : f.symm b <;> simp_all
/-- If the domain of a `PEquiv` is `α` except a point, its forward direction is injective. -/
theorem injective_of_forall_ne_isSome (f : α ≃. β) (a₂ : α)
(h : ∀ a₁ : α, a₁ ≠ a₂ → isSome (f a₁)) : Injective f :=
HasLeftInverse.injective
⟨fun b => Option.recOn b a₂ fun b' => Option.recOn (f.symm b') a₂ id, fun x => by
classical
cases hfx : f x
· have : x = a₂ := not_imp_comm.1 (h x) (hfx.symm ▸ by simp)
simp [this]
· dsimp only
rw [(eq_some_iff f).2 hfx]
rfl⟩
/-- If the domain of a `PEquiv` is all of `α`, its forward direction is injective. -/
theorem injective_of_forall_isSome {f : α ≃. β} (h : ∀ a : α, isSome (f a)) : Injective f :=
(Classical.em (Nonempty α)).elim
(fun hn => injective_of_forall_ne_isSome f (Classical.choice hn) fun a _ => h a) fun hn x =>
(hn ⟨x⟩).elim
section OfSet
variable (s : Set α) [DecidablePred (· ∈ s)]
/-- Creates a `PEquiv` that is the identity on `s`, and `none` outside of it. -/
def ofSet (s : Set α) [DecidablePred (· ∈ s)] :
α ≃. α where
toFun a := if a ∈ s then some a else none
invFun a := if a ∈ s then some a else none
inv a b := by
split_ifs with hb ha ha
· simp [eq_comm]
· simp [ne_of_mem_of_not_mem hb ha]
· simp [ne_of_mem_of_not_mem ha hb]
· simp
theorem mem_ofSet_self_iff {s : Set α} [DecidablePred (· ∈ s)] {a : α} : a ∈ ofSet s a ↔ a ∈ s := by
dsimp [ofSet]; split_ifs <;> simp [*]
theorem mem_ofSet_iff {s : Set α} [DecidablePred (· ∈ s)] {a b : α} :
a ∈ ofSet s b ↔ a = b ∧ a ∈ s := by
dsimp [ofSet]
grind
@[simp]
theorem ofSet_eq_some_iff {s : Set α} {_ : DecidablePred (· ∈ s)} {a b : α} :
ofSet s b = some a ↔ a = b ∧ a ∈ s :=
mem_ofSet_iff
theorem ofSet_eq_some_self_iff {s : Set α} {_ : DecidablePred (· ∈ s)} {a : α} :
ofSet s a = some a ↔ a ∈ s :=
mem_ofSet_self_iff
@[simp]
theorem ofSet_symm : (ofSet s).symm = ofSet s :=
rfl
@[simp]
theorem ofSet_univ : ofSet Set.univ = PEquiv.refl α :=
rfl
@[simp]
theorem ofSet_eq_refl {s : Set α} [DecidablePred (· ∈ s)] :
ofSet s = PEquiv.refl α ↔ s = Set.univ :=
⟨fun h => by
rw [Set.eq_univ_iff_forall]
intro
rw [← mem_ofSet_self_iff, h]
exact rfl, fun h => by simp only [← ofSet_univ, h]⟩
end OfSet
theorem symm_trans_rev (f : α ≃. β) (g : β ≃. γ) : (f.trans g).symm = g.symm.trans f.symm :=
rfl
theorem self_trans_symm (f : α ≃. β) : f.trans f.symm = ofSet { a | (f a).isSome } := by
ext
dsimp [PEquiv.trans]
simp only [eq_some_iff f, Option.isSome_iff_exists, bind_eq_some_iff,
ofSet_eq_some_iff]
constructor
· rintro ⟨b, hb₁, hb₂⟩
exact ⟨PEquiv.inj _ hb₂ hb₁, b, hb₂⟩
· simp +contextual
theorem symm_trans_self (f : α ≃. β) : f.symm.trans f = ofSet { b | (f.symm b).isSome } :=
symm_injective <| by simp [symm_trans_rev, self_trans_symm, -symm_symm]
theorem trans_symm_eq_iff_forall_isSome {f : α ≃. β} :
f.trans f.symm = PEquiv.refl α ↔ ∀ a, isSome (f a) := by
rw [self_trans_symm, ofSet_eq_refl, Set.eq_univ_iff_forall]; rfl
instance instBotPEquiv : Bot (α ≃. β) :=
⟨{ toFun := fun _ => none
invFun := fun _ => none
inv := by simp }⟩
instance : Inhabited (α ≃. β) :=
⟨⊥⟩
@[simp]
theorem bot_apply (a : α) : (⊥ : α ≃. β) a = none :=
rfl
@[simp]
theorem symm_bot : (⊥ : α ≃. β).symm = ⊥ :=
rfl
@[simp]
theorem trans_bot (f : α ≃. β) : f.trans (⊥ : β ≃. γ) = ⊥ := by
ext; dsimp [PEquiv.trans]; simp
@[simp]
theorem bot_trans (f : β ≃. γ) : (⊥ : α ≃. β).trans f = ⊥ := by
ext; dsimp [PEquiv.trans]; simp
theorem isSome_symm_get (f : α ≃. β) {a : α} (h : isSome (f a)) :
isSome (f.symm (Option.get _ h)) :=
isSome_iff_exists.2 ⟨a, by rw [f.eq_some_iff, some_get]⟩
section Single
variable [DecidableEq α] [DecidableEq β] [DecidableEq γ]
/-- Create a `PEquiv` which sends `a` to `b` and `b` to `a`, but is otherwise `none`. -/
def single (a : α) (b : β) :
α ≃. β where
toFun x := if x = a then some b else none
invFun x := if x = b then some a else none
inv x y := by
split_ifs with h1 h2
· simp [*]
· simp only [some.injEq, iff_false] at *
exact Ne.symm h2
· simp only [some.injEq, false_iff] at *
exact Ne.symm h1
· simp
theorem mem_single (a : α) (b : β) : b ∈ single a b a :=
if_pos rfl
theorem mem_single_iff (a₁ a₂ : α) (b₁ b₂ : β) : b₁ ∈ single a₂ b₂ a₁ ↔ a₁ = a₂ ∧ b₁ = b₂ := by
dsimp [single]; split_ifs <;> simp [*, eq_comm]
@[simp]
theorem symm_single (a : α) (b : β) : (single a b).symm = single b a :=
rfl
@[simp]
theorem single_apply (a : α) (b : β) : single a b a = some b :=
if_pos rfl
theorem single_apply_of_ne {a₁ a₂ : α} (h : a₁ ≠ a₂) (b : β) : single a₁ b a₂ = none :=
if_neg h.symm
theorem single_trans_of_mem (a : α) {b : β} {c : γ} {f : β ≃. γ} (h : c ∈ f b) :
(single a b).trans f = single a c := by
ext
dsimp [single, PEquiv.trans]
split_ifs <;> simp_all
theorem trans_single_of_mem {a : α} {b : β} (c : γ) {f : α ≃. β} (h : b ∈ f a) :
f.trans (single b c) = single a c :=
symm_injective <| single_trans_of_mem _ ((mem_iff_mem f).2 h)
@[simp]
theorem single_trans_single (a : α) (b : β) (c : γ) :
(single a b).trans (single b c) = single a c :=
single_trans_of_mem _ (mem_single _ _)
@[simp]
theorem single_subsingleton_eq_refl [Subsingleton α] (a b : α) : single a b = PEquiv.refl α := by
ext i j
dsimp [single]
rw [if_pos (Subsingleton.elim i a), Subsingleton.elim i j, Subsingleton.elim b j]
theorem trans_single_of_eq_none {b : β} (c : γ) {f : δ ≃. β} (h : f.symm b = none) :
f.trans (single b c) = ⊥ := by
ext
simp only [eq_none_iff_forall_not_mem, Option.mem_def, f.eq_some_iff] at h
dsimp [PEquiv.trans, single]
simp only [bind_eq_some_iff, iff_false, not_exists, not_and, reduceCtorEq]
intros
split_ifs <;> simp_all
theorem single_trans_of_eq_none (a : α) {b : β} {f : β ≃. δ} (h : f b = none) :
(single a b).trans f = ⊥ :=
symm_injective <| trans_single_of_eq_none _ h
theorem single_trans_single_of_ne {b₁ b₂ : β} (h : b₁ ≠ b₂) (a : α) (c : γ) :
(single a b₁).trans (single b₂ c) = ⊥ :=
single_trans_of_eq_none _ (single_apply_of_ne h.symm _)
end Single
section Order
instance instPartialOrderPEquiv : PartialOrder (α ≃. β) where
le f g := ∀ (a : α) (b : β), b ∈ f a → b ∈ g a
le_refl _ _ _ := id
le_trans _ _ _ fg gh a b := gh a b ∘ fg a b
le_antisymm f g fg gf :=
ext
(by
intro a
rcases h : g a with _ | b
· exact eq_none_iff_forall_not_mem.2 fun b hb => Option.not_mem_none b <| h ▸ fg a b hb
· exact gf _ _ h)
theorem le_def {f g : α ≃. β} : f ≤ g ↔ ∀ (a : α) (b : β), b ∈ f a → b ∈ g a :=
Iff.rfl
instance : OrderBot (α ≃. β) :=
{ instBotPEquiv with bot_le := fun _ _ _ h => (not_mem_none _ h).elim }
instance [DecidableEq α] [DecidableEq β] : SemilatticeInf (α ≃. β) :=
{ instPartialOrderPEquiv with
inf := fun f g =>
{ toFun := fun a => if f a = g a then f a else none
invFun := fun b => if f.symm b = g.symm b then f.symm b else none
inv := fun a b => by
have hf := @mem_iff_mem _ _ f a b
have hg := @mem_iff_mem _ _ g a b
simp only [Option.mem_def] at *
grind }
inf_le_left := fun _ _ _ _ => by simp only [coe_mk, mem_def]; split_ifs <;> simp [*]
inf_le_right := fun _ _ _ _ => by simp only [coe_mk, mem_def]; split_ifs <;> simp [*]
le_inf := fun f g h fg gh a b => by
intro H
have hf := fg a b H
have hg := gh a b H
simp only [Option.mem_def, PEquiv.coe_mk_apply] at *
rw [hf, hg, if_pos rfl] }
end Order
end PEquiv
namespace Equiv
variable {α : Type*} {β : Type*} {γ : Type*}
/-- Turns an `Equiv` into a `PEquiv` of the whole type. -/
def toPEquiv (f : α ≃ β) : α ≃. β where
toFun := some ∘ f
invFun := some ∘ f.symm
inv := by simp [Equiv.eq_symm_apply, eq_comm]
@[simp]
theorem toPEquiv_refl : (Equiv.refl α).toPEquiv = PEquiv.refl α :=
rfl
theorem toPEquiv_trans (f : α ≃ β) (g : β ≃ γ) :
(f.trans g).toPEquiv = f.toPEquiv.trans g.toPEquiv :=
rfl
theorem toPEquiv_symm (f : α ≃ β) : f.symm.toPEquiv = f.toPEquiv.symm :=
rfl
@[simp]
theorem toPEquiv_apply (f : α ≃ β) (x : α) : f.toPEquiv x = some (f x) :=
rfl
end Equiv |
.lake/packages/mathlib/Mathlib/Data/UInt.lean | import Mathlib.Init
import Mathlib.Algebra.Ring.InjSurj
import Mathlib.Data.ZMod.Defs
import Mathlib.Data.BitVec
/-!
# Adds Mathlib specific instances to the `UIntX` data types.
The `CommRing` instances (and the `NatCast` and `IntCast` instances from which they is built) are
scoped in the `UIntX.CommRing` namespace, rather than available globally. As a result, the `ring`
tactic will not work on `UIntX` types without `open scoped UIntX.Ring`.
This is because the presence of these casting operations contradicts assumptions made by the
expression tree elaborator, namely that coercions do not form a cycle.
The UInt
version also interferes more with software-verification use-cases, which is reason to be more
cautious here.
-/
-- these theorems are fragile, so do them first
set_option hygiene false in
run_cmd
for typeName' in [`UInt8, `UInt16, `UInt32, `UInt64, `USize] do
let typeName := Lean.mkIdent typeName'
Lean.Elab.Command.elabCommand (← `(
namespace $typeName
open $typeName (toBitVec_mul) in
protected theorem toBitVec_nsmul (n : ℕ) (a : $typeName) :
(n • a).toBitVec = n • a.toBitVec := by
rw [Lean.Grind.Semiring.nsmul_eq_natCast_mul, toBitVec_mul,
nsmul_eq_mul, BitVec.natCast_eq_ofNat]
rfl
attribute [local instance] natCast intCast
@[simp, int_toBitVec]
protected theorem toBitVec_natCast (n : ℕ) :
(n : $typeName).toBitVec = n := rfl
open $typeName (toBitVec_neg) in
@[simp, int_toBitVec]
protected theorem toBitVec_intCast (z : ℤ) :
(z : $typeName).toBitVec = z := by
obtain ⟨z, rfl | rfl⟩ := z.eq_nat_or_neg
· erw [intCast_ofNat]; rfl
· rw [intCast_neg, toBitVec_neg]
erw [intCast_ofNat]
simp
open $typeName (toBitVec_mul toBitVec_intCast) in
@[simp, int_toBitVec]
protected theorem toBitVec_zsmul (z : ℤ) (a : $typeName) :
(z • a).toBitVec = z • a.toBitVec := by
change (z * a).toBitVec = BitVec.ofInt _ z * a.toBitVec
rw [toBitVec_mul]
congr 1
rw [toBitVec_intCast]
rfl
end $typeName
))
-- Note that these construct no new data, so cannot form diamonds with core.
set_option hygiene false in
run_cmd
for typeName' in [`UInt8, `UInt16, `UInt32, `UInt64, `USize] do
let typeName := Lean.mkIdent typeName'
Lean.Elab.Command.elabCommand (← `(
namespace $typeName
open $typeName (eq_of_toFin_eq) in
lemma toFin_injective : Function.Injective toFin := @eq_of_toFin_eq
open $typeName (eq_of_toBitVec_eq) in
lemma toBitVec_injective : Function.Injective toBitVec := @eq_of_toBitVec_eq
open $typeName (toBitVec_one toBitVec_mul toBitVec_pow) in
instance instCommMonoid : CommMonoid $typeName :=
Function.Injective.commMonoid toBitVec toBitVec_injective
toBitVec_one (fun _ _ => toBitVec_mul) (fun _ _ => toBitVec_pow _ _)
open $typeName (
toBitVec_zero toBitVec_add toBitVec_mul toBitVec_neg toBitVec_sub toBitVec_nsmul
toBitVec_zsmul) in
instance instNonUnitalCommRing : NonUnitalCommRing $typeName :=
Function.Injective.nonUnitalCommRing toBitVec toBitVec_injective
toBitVec_zero (fun _ _ => toBitVec_add) (fun _ _ => toBitVec_mul) (fun _ => toBitVec_neg)
(fun _ _ => toBitVec_sub)
(fun _ _ => toBitVec_nsmul _ _) (fun _ _ => toBitVec_zsmul _ _)
attribute [local instance] intCast natCast
open $typeName (
toBitVec_zero toBitVec_one toBitVec_add toBitVec_mul toBitVec_neg
toBitVec_sub toBitVec_nsmul toBitVec_zsmul toBitVec_pow
toBitVec_natCast toBitVec_intCast) in
local instance instCommRing : CommRing $typeName :=
Function.Injective.commRing toBitVec toBitVec_injective
toBitVec_zero toBitVec_one (fun _ _ => toBitVec_add) (fun _ _ => toBitVec_mul)
(fun _ => toBitVec_neg) (fun _ _ => toBitVec_sub)
(fun _ _ => toBitVec_nsmul _ _) (fun _ _ => toBitVec_zsmul _ _)
(fun _ _ => toBitVec_pow _ _)
toBitVec_natCast toBitVec_intCast
namespace CommRing
attribute [scoped instance] instCommRing natCast intCast
end CommRing
end $typeName
))
-- interpolating docstrings above is more trouble than it's worth
let docString :=
s!"To use this instance, use `open scoped {typeName'}.CommRing`.\n\n" ++
"See the module docstring for an explanation"
Lean.addDocStringCore (typeName'.mkStr "instCommRing") docString
-- TODO: add these docstrings in core?
-- Lean.addDocStringCore (typeName'.mkStr "instNatCast") docString
-- Lean.addDocStringCore (typeName'.mkStr "instIntCast") docString
namespace UInt8
/-- Is this an uppercase ASCII letter? -/
def isASCIIUpper (c : UInt8) : Bool :=
c ≥ 65 && c ≤ 90
/-- Is this a lowercase ASCII letter? -/
def isASCIILower (c : UInt8) : Bool :=
c ≥ 97 && c ≤ 122
/-- Is this an alphabetic ASCII character? -/
def isASCIIAlpha (c : UInt8) : Bool :=
c.isASCIIUpper || c.isASCIILower
/-- Is this an ASCII digit character? -/
def isASCIIDigit (c : UInt8) : Bool :=
c ≥ 48 && c ≤ 57
/-- Is this an alphanumeric ASCII character? -/
def isASCIIAlphanum (c : UInt8) : Bool :=
c.isASCIIAlpha || c.isASCIIDigit
/-- The numbers from 0 to 256 are all valid UTF-8 characters, so we can embed one in the other. -/
def toChar (n : UInt8) : Char := ⟨n.toUInt32, .inl (Nat.lt_trans n.toBitVec.isLt (by decide))⟩
end UInt8 |
.lake/packages/mathlib/Mathlib/Data/Bundle.lean | import Mathlib.Data.Set.Basic
/-!
# Bundle
Basic data structure to implement fiber bundles, vector bundles (maybe fibrations?), etc. This file
should contain all possible results that do not involve any topology.
We represent a bundle `E` over a base space `B` as a dependent type `E : B → Type*`.
We define `Bundle.TotalSpace F E` to be the type of pairs `⟨b, x⟩`, where `b : B` and `x : E b`.
This type is isomorphic to `Σ x, E x` and uses an extra argument `F` for reasons explained below. In
general, the constructions of fiber bundles we will make will be of this form.
## Main Definitions
* `Bundle.TotalSpace` the total space of a bundle.
* `Bundle.TotalSpace.proj` the projection from the total space to the base space.
* `Bundle.TotalSpace.mk` the constructor for the total space.
## Implementation Notes
- We use a custom structure for the total space of a bundle instead of using a type synonym for the
canonical disjoint union `Σ x, E x` because the total space usually has a different topology and
Lean 4 `simp` fails to apply lemmas about `Σ x, E x` to elements of the total space.
- The definition of `Bundle.TotalSpace` has an unused argument `F`. The reason is that in some
constructions (e.g., the bundle of continuous linear maps) we need access to the atlas of
trivializations of original fiber bundles to construct the topology on the total space of the new
fiber bundle.
## References
- https://en.wikipedia.org/wiki/Bundle_(mathematics)
-/
assert_not_exists RelIso
open Function Set
namespace Bundle
variable {B F : Type*} (E : B → Type*)
/-- `Bundle.TotalSpace F E` is the total space of the bundle. It consists of pairs
`(proj : B, snd : E proj)`.
-/
@[ext]
structure TotalSpace (F : Type*) (E : B → Type*) where
/-- `Bundle.TotalSpace.proj` is the canonical projection `Bundle.TotalSpace F E → B` from the
total space to the base space. -/
proj : B
snd : E proj
instance [Inhabited B] [Inhabited (E default)] : Inhabited (TotalSpace F E) :=
⟨⟨default, default⟩⟩
variable {E}
@[inherit_doc]
scoped notation:max "π " F':max E':max => Bundle.TotalSpace.proj (F := F') (E := E')
abbrev TotalSpace.mk' (F : Type*) (x : B) (y : E x) : TotalSpace F E := ⟨x, y⟩
theorem TotalSpace.mk_cast {x x' : B} (h : x = x') (b : E x) :
.mk' F x' (cast (congr_arg E h) b) = TotalSpace.mk x b := by subst h; rfl
@[simp 1001, mfld_simps 1001]
theorem TotalSpace.mk_inj {b : B} {y y' : E b} : mk' F b y = mk' F b y' ↔ y = y' := by
simp [TotalSpace.ext_iff]
theorem TotalSpace.mk_injective (b : B) : Injective (mk b : E b → TotalSpace F E) := fun _ _ ↦
mk_inj.1
instance {x : B} : CoeTC (E x) (TotalSpace F E) :=
⟨TotalSpace.mk x⟩
theorem TotalSpace.eta (z : TotalSpace F E) : TotalSpace.mk z.proj z.2 = z := rfl
@[simp]
theorem TotalSpace.exists {p : TotalSpace F E → Prop} : (∃ x, p x) ↔ ∃ b y, p ⟨b, y⟩ :=
⟨fun ⟨x, hx⟩ ↦ ⟨x.1, x.2, hx⟩, fun ⟨b, y, h⟩ ↦ ⟨⟨b, y⟩, h⟩⟩
@[simp]
theorem TotalSpace.range_mk (b : B) : range ((↑) : E b → TotalSpace F E) = π F E ⁻¹' {b} := by
apply Subset.antisymm
· rintro _ ⟨x, rfl⟩
rfl
· rintro ⟨_, x⟩ rfl
exact ⟨x, rfl⟩
/-- Notation for the direct sum of two bundles over the same base. -/
notation:100 E₁ " ×ᵇ " E₂ => fun x => E₁ x × E₂ x
/-- `Bundle.Trivial B F` is the trivial bundle over `B` of fiber `F`. -/
@[reducible, nolint unusedArguments]
def Trivial (B : Type*) (F : Type*) : B → Type _ := fun _ => F
/-- The trivial bundle, unlike other bundles, has a canonical projection on the fiber. -/
def TotalSpace.trivialSnd (B : Type*) (F : Type*) : TotalSpace F (Bundle.Trivial B F) → F :=
TotalSpace.snd
/-- A trivial bundle is equivalent to the product `B × F`. -/
@[simps (attr := mfld_simps)]
def TotalSpace.toProd (B F : Type*) : (TotalSpace F fun _ : B => F) ≃ B × F where
toFun x := (x.1, x.2)
invFun x := ⟨x.1, x.2⟩
section Pullback
variable {B' : Type*}
/-- The pullback of a bundle `E` over a base `B` under a map `f : B' → B`, denoted by
`Bundle.Pullback f E` or `f *ᵖ E`, is the bundle over `B'` whose fiber over `b'` is `E (f b')`. -/
def Pullback (f : B' → B) (E : B → Type*) : B' → Type _ := fun x => E (f x)
@[inherit_doc]
notation f " *ᵖ " E:arg => Pullback f E
instance {f : B' → B} {x : B'} [Nonempty (E (f x))] : Nonempty ((f *ᵖ E) x) :=
‹Nonempty (E (f x))›
/-- Natural embedding of the total space of `f *ᵖ E` into `B' × TotalSpace F E`. -/
@[simp]
def pullbackTotalSpaceEmbedding (f : B' → B) : TotalSpace F (f *ᵖ E) → B' × TotalSpace F E :=
fun z => (z.proj, TotalSpace.mk (f z.proj) z.2)
/-- The base map `f : B' → B` lifts to a canonical map on the total spaces. -/
@[simps (attr := mfld_simps)]
def Pullback.lift (f : B' → B) : TotalSpace F (f *ᵖ E) → TotalSpace F E := fun z => ⟨f z.proj, z.2⟩
@[simp, mfld_simps]
theorem Pullback.lift_mk (f : B' → B) (x : B') (y : E (f x)) :
Pullback.lift f (.mk' F x y) = ⟨f x, y⟩ :=
rfl
end Pullback
end Bundle |
.lake/packages/mathlib/Mathlib/Data/Prod/PProd.lean | import Batteries.Logic
import Mathlib.Tactic.TypeStar
/-!
# Extra facts about `PProd`
-/
open Function
variable {α β γ δ : Sort*}
namespace PProd
def mk.injArrow {α : Type*} {β : Type*} {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} :
(x₁, y₁) = (x₂, y₂) → ∀ ⦃P : Sort*⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
fun h₁ _ h₂ ↦ Prod.noConfusion h₁ h₂
@[simp]
theorem mk.eta {p : PProd α β} : PProd.mk p.1 p.2 = p :=
rfl
@[simp]
theorem «forall» {p : PProd α β → Prop} : (∀ x, p x) ↔ ∀ a b, p ⟨a, b⟩ :=
⟨fun h a b ↦ h ⟨a, b⟩, fun h ⟨a, b⟩ ↦ h a b⟩
@[simp]
theorem «exists» {p : PProd α β → Prop} : (∃ x, p x) ↔ ∃ a b, p ⟨a, b⟩ :=
⟨fun ⟨⟨a, b⟩, h⟩ ↦ ⟨a, b, h⟩, fun ⟨a, b, h⟩ ↦ ⟨⟨a, b⟩, h⟩⟩
theorem forall' {p : α → β → Prop} : (∀ x : PProd α β, p x.1 x.2) ↔ ∀ a b, p a b :=
PProd.forall
theorem exists' {p : α → β → Prop} : (∃ x : PProd α β, p x.1 x.2) ↔ ∃ a b, p a b :=
PProd.exists
end PProd
theorem Function.Injective.pprod_map {f : α → β} {g : γ → δ} (hf : Injective f) (hg : Injective g) :
Injective (fun x ↦ ⟨f x.1, g x.2⟩ : PProd α γ → PProd β δ) := fun _ _ h ↦
have A := congr_arg PProd.fst h
have B := congr_arg PProd.snd h
congr_arg₂ PProd.mk (hf A) (hg B) |
.lake/packages/mathlib/Mathlib/Data/Prod/Lex.lean | import Mathlib.Data.Prod.Basic
import Mathlib.Order.Lattice
import Mathlib.Order.BoundedOrder.Basic
import Mathlib.Tactic.Tauto
/-!
# Lexicographic order
This file defines the lexicographic relation for pairs of orders, partial orders and linear orders.
## Main declarations
* `Prod.Lex.<pre/partial/linear>Order`: Instances lifting the orders on `α` and `β` to `α ×ₗ β`.
## Notation
* `α ×ₗ β`: `α × β` equipped with the lexicographic order
## See also
Related files are:
* `Data.Finset.CoLex`: Colexicographic order on finite sets.
* `Data.List.Lex`: Lexicographic order on lists.
* `Data.Pi.Lex`: Lexicographic order on `Πₗ i, α i`.
* `Data.PSigma.Order`: Lexicographic order on `Σ' i, α i`.
* `Data.Sigma.Order`: Lexicographic order on `Σ i, α i`.
-/
variable {α β : Type*}
namespace Prod.Lex
@[inherit_doc] notation:35 α " ×ₗ " β:34 => Lex (Prod α β)
/-- Dictionary / lexicographic ordering on pairs. -/
instance instLE (α β : Type*) [LT α] [LE β] : LE (α ×ₗ β) where le := Prod.Lex (· < ·) (· ≤ ·)
instance instLT (α β : Type*) [LT α] [LT β] : LT (α ×ₗ β) where lt := Prod.Lex (· < ·) (· < ·)
theorem toLex_le_toLex [LT α] [LE β] {x y : α × β} :
toLex x ≤ toLex y ↔ x.1 < y.1 ∨ x.1 = y.1 ∧ x.2 ≤ y.2 :=
Prod.lex_def
theorem toLex_lt_toLex [LT α] [LT β] {x y : α × β} :
toLex x < toLex y ↔ x.1 < y.1 ∨ x.1 = y.1 ∧ x.2 < y.2 :=
Prod.lex_def
lemma le_iff [LT α] [LE β] {x y : α ×ₗ β} :
x ≤ y ↔ (ofLex x).1 < (ofLex y).1 ∨ (ofLex x).1 = (ofLex y).1 ∧ (ofLex x).2 ≤ (ofLex y).2 :=
Prod.lex_def
lemma lt_iff [LT α] [LT β] {x y : α ×ₗ β} :
x < y ↔ (ofLex x).1 < (ofLex y).1 ∨ (ofLex x).1 = (ofLex y).1 ∧ (ofLex x).2 < (ofLex y).2 :=
Prod.lex_def
instance [LT α] [LT β] [WellFoundedLT α] [WellFoundedLT β] : WellFoundedLT (α ×ₗ β) :=
instIsWellFounded
instance [LT α] [LT β] [WellFoundedLT α] [WellFoundedLT β] : WellFoundedRelation (α ×ₗ β) :=
⟨(· < ·), wellFounded_lt⟩
/-- Dictionary / lexicographic preorder for pairs. -/
instance instPreorder (α β : Type*) [Preorder α] [Preorder β] : Preorder (α ×ₗ β) where
le_refl := refl_of <| Prod.Lex _ _
le_trans _ _ _ := trans_of <| Prod.Lex _ _
lt_iff_le_not_ge x₁ x₂ := by aesop (add simp [le_iff, lt_iff, lt_iff_le_not_ge])
/-- See also `monotone_fst_ofLex` for a version stated in terms of `Monotone`. -/
theorem monotone_fst [Preorder α] [LE β] (t c : α ×ₗ β) (h : t ≤ c) :
(ofLex t).1 ≤ (ofLex c).1 := by
cases toLex_le_toLex.mp h with
| inl h' => exact h'.le
| inr h' => exact h'.1.le
section Preorder
variable [Preorder α] [Preorder β]
theorem monotone_fst_ofLex : Monotone fun x : α ×ₗ β ↦ (ofLex x).1 := monotone_fst
theorem _root_.WCovBy.fst_ofLex {a b : α ×ₗ β} (h : a ⩿ b) : (ofLex a).1 ⩿ (ofLex b).1 :=
⟨monotone_fst _ _ h.1, fun c hac hcb ↦ h.2 (c := toLex (c, a.2)) (.left _ _ hac) (.left _ _ hcb)⟩
theorem toLex_covBy_toLex_iff {a₁ a₂ : α} {b₁ b₂ : β} :
toLex (a₁, b₁) ⋖ toLex (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ ⋖ b₂ ∨ a₁ ⋖ a₂ ∧ IsMax b₁ ∧ IsMin b₂ := by
simp only [CovBy, toLex_lt_toLex, toLex.surjective.forall, Prod.forall, isMax_iff_forall_not_lt,
isMin_iff_forall_not_lt]
grind
theorem covBy_iff {a b : α ×ₗ β} :
a ⋖ b ↔ (ofLex a).1 = (ofLex b).1 ∧ (ofLex a).2 ⋖ (ofLex b).2 ∨
(ofLex a).1 ⋖ (ofLex b).1 ∧ IsMax (ofLex a).2 ∧ IsMin (ofLex b).2 :=
toLex_covBy_toLex_iff
end Preorder
section PartialOrderPreorder
variable [PartialOrder α] [Preorder β] {x y : α × β}
/-- Variant of `Prod.Lex.toLex_le_toLex` for partial orders. -/
lemma toLex_le_toLex' : toLex x ≤ toLex y ↔ x.1 ≤ y.1 ∧ (x.1 = y.1 → x.2 ≤ y.2) := by
simp only [toLex_le_toLex, lt_iff_le_not_ge, le_antisymm_iff]
tauto
/-- Variant of `Prod.Lex.toLex_lt_toLex` for partial orders. -/
lemma toLex_lt_toLex' : toLex x < toLex y ↔ x.1 ≤ y.1 ∧ (x.1 = y.1 → x.2 < y.2) := by
rw [toLex_lt_toLex]
simp only [lt_iff_le_not_ge, le_antisymm_iff]
tauto
/-- Variant of `Prod.Lex.le_iff` for partial orders. -/
lemma le_iff' {x y : α ×ₗ β} :
x ≤ y ↔ (ofLex x).1 ≤ (ofLex y).1 ∧ ((ofLex x).1 = (ofLex y).1 → (ofLex x).2 ≤ (ofLex y).2) :=
toLex_le_toLex'
/-- Variant of `Prod.Lex.lt_iff` for partial orders. -/
lemma lt_iff' {x y : α ×ₗ β} :
x < y ↔ (ofLex x).1 ≤ (ofLex y).1 ∧ ((ofLex x).1 = (ofLex y).1 → (ofLex x).2 < (ofLex y).2) :=
toLex_lt_toLex'
theorem toLex_mono : Monotone (toLex : α × β → α ×ₗ β) :=
fun _x _y hxy ↦ toLex_le_toLex'.2 ⟨hxy.1, fun _ ↦ hxy.2⟩
theorem toLex_strictMono : StrictMono (toLex : α × β → α ×ₗ β) := by
rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h
obtain rfl | ha : a₁ = a₂ ∨ _ := h.le.1.eq_or_lt
· exact right _ (Prod.mk_lt_mk_iff_right.1 h)
· exact left _ _ ha
end PartialOrderPreorder
/-- Dictionary / lexicographic partial order for pairs. -/
instance instPartialOrder (α β : Type*) [PartialOrder α] [PartialOrder β] :
PartialOrder (α ×ₗ β) where
le_antisymm _ _ := antisymm_of (Prod.Lex _ _)
instance instOrdLexProd [Ord α] [Ord β] : Ord (α ×ₗ β) := lexOrd
theorem compare_def [Ord α] [Ord β] : @compare (α ×ₗ β) _ =
compareLex (compareOn fun x => (ofLex x).1) (compareOn fun x => (ofLex x).2) := rfl
theorem _root_.lexOrd_eq [Ord α] [Ord β] : @lexOrd α β _ _ = instOrdLexProd := rfl
theorem _root_.Ord.lex_eq [oα : Ord α] [oβ : Ord β] : Ord.lex oα oβ = instOrdLexProd := rfl
instance [Ord α] [Ord β] [Std.OrientedOrd α] [Std.OrientedOrd β] : Std.OrientedOrd (α ×ₗ β) :=
inferInstanceAs (Std.OrientedCmp (compareLex _ _))
instance [Ord α] [Ord β] [Std.TransOrd α] [Std.TransOrd β] : Std.TransOrd (α ×ₗ β) :=
inferInstanceAs (Std.TransCmp (compareLex _ _))
/-- Dictionary / lexicographic linear order for pairs. -/
instance instLinearOrder (α β : Type*) [LinearOrder α] [LinearOrder β] : LinearOrder (α ×ₗ β) :=
{ Prod.Lex.instPartialOrder α β with
le_total := total_of (Prod.Lex _ _)
toDecidableLE := Prod.Lex.decidable _ _
toDecidableLT := Prod.Lex.decidable _ _
toDecidableEq := instDecidableEqLex _
compare_eq_compareOfLessAndEq := fun a b => by
have : DecidableLT (α ×ₗ β) := Prod.Lex.decidable _ _
have : Std.LawfulBEqOrd (α ×ₗ β) := ⟨by
simp [compare_def, compareLex, compareOn, Ordering.then_eq_eq]⟩
have : Std.LawfulLTOrd (α ×ₗ β) := ⟨by
simp [compare_def, compareLex, compareOn, Ordering.then_eq_lt, toLex_lt_toLex,
compare_lt_iff_lt]⟩
convert Std.LawfulLTCmp.eq_compareOfLessAndEq (cmp := compare) a b }
instance orderBot [PartialOrder α] [Preorder β] [OrderBot α] [OrderBot β] : OrderBot (α ×ₗ β) where
bot := toLex ⊥
bot_le _ := toLex_mono bot_le
instance orderTop [PartialOrder α] [Preorder β] [OrderTop α] [OrderTop β] : OrderTop (α ×ₗ β) where
top := toLex ⊤
le_top _ := toLex_mono le_top
instance boundedOrder [PartialOrder α] [Preorder β] [BoundedOrder α] [BoundedOrder β] :
BoundedOrder (α ×ₗ β) :=
{ Lex.orderBot, Lex.orderTop with }
instance [Preorder α] [Preorder β] [DenselyOrdered α] [DenselyOrdered β] :
DenselyOrdered (α ×ₗ β) where
dense := by
rintro _ _ (@⟨a₁, b₁, a₂, b₂, h⟩ | @⟨a, b₁, b₂, h⟩)
· obtain ⟨c, h₁, h₂⟩ := exists_between h
exact ⟨(c, b₁), left _ _ h₁, left _ _ h₂⟩
· obtain ⟨c, h₁, h₂⟩ := exists_between h
exact ⟨(a, c), right _ h₁, right _ h₂⟩
instance noMaxOrder_of_left [Preorder α] [Preorder β] [NoMaxOrder α] : NoMaxOrder (α ×ₗ β) where
exists_gt := by
rintro ⟨a, b⟩
obtain ⟨c, h⟩ := exists_gt a
exact ⟨⟨c, b⟩, left _ _ h⟩
instance noMinOrder_of_left [Preorder α] [Preorder β] [NoMinOrder α] : NoMinOrder (α ×ₗ β) where
exists_lt := by
rintro ⟨a, b⟩
obtain ⟨c, h⟩ := exists_lt a
exact ⟨⟨c, b⟩, left _ _ h⟩
instance noMaxOrder_of_right [Preorder α] [Preorder β] [NoMaxOrder β] : NoMaxOrder (α ×ₗ β) where
exists_gt := by
rintro ⟨a, b⟩
obtain ⟨c, h⟩ := exists_gt b
exact ⟨⟨a, c⟩, right _ h⟩
instance noMinOrder_of_right [Preorder α] [Preorder β] [NoMinOrder β] : NoMinOrder (α ×ₗ β) where
exists_lt := by
rintro ⟨a, b⟩
obtain ⟨c, h⟩ := exists_lt b
exact ⟨⟨a, c⟩, right _ h⟩
end Prod.Lex |
.lake/packages/mathlib/Mathlib/Data/Prod/Basic.lean | import Mathlib.Logic.Function.Defs
import Mathlib.Logic.Function.Iterate
import Aesop
import Mathlib.Tactic.Inhabit
/-!
# Extra facts about `Prod`
This file proves various simple lemmas about `Prod`.
It also defines better delaborators for product projections.
-/
variable {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
namespace Prod
lemma swap_eq_iff_eq_swap {x : α × β} {y : β × α} : x.swap = y ↔ x = y.swap := by aesop
def mk.injArrow {x₁ : α} {y₁ : β} {x₂ : α} {y₂ : β} :
(x₁, y₁) = (x₂, y₂) → ∀ ⦃P : Sort*⦄, (x₁ = x₂ → y₁ = y₂ → P) → P :=
fun h₁ _ h₂ ↦ Prod.noConfusion h₁ h₂
@[simp]
theorem mk.eta : ∀ {p : α × β}, (p.1, p.2) = p
| (_, _) => rfl
theorem forall' {p : α → β → Prop} : (∀ x : α × β, p x.1 x.2) ↔ ∀ a b, p a b :=
Prod.forall
theorem exists' {p : α → β → Prop} : (∃ x : α × β, p x.1 x.2) ↔ ∃ a b, p a b :=
Prod.exists
@[simp]
theorem snd_comp_mk (x : α) : Prod.snd ∘ (Prod.mk x : β → α × β) = id :=
rfl
@[simp]
theorem fst_comp_mk (x : α) : Prod.fst ∘ (Prod.mk x : β → α × β) = Function.const β x :=
rfl
attribute [mfld_simps] map_apply
-- This was previously a `simp` lemma, but no longer is on the basis that it destructures the pair.
-- See `map_apply`, `map_fst`, and `map_snd` for slightly weaker lemmas in the `simp` set.
theorem map_apply' (f : α → γ) (g : β → δ) (p : α × β) : map f g p = (f p.1, g p.2) :=
rfl
theorem map_fst' (f : α → γ) (g : β → δ) : Prod.fst ∘ map f g = f ∘ Prod.fst :=
funext <| map_fst f g
theorem map_snd' (f : α → γ) (g : β → δ) : Prod.snd ∘ map f g = g ∘ Prod.snd :=
funext <| map_snd f g
theorem mk_inj {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) = (a₂, b₂) ↔ a₁ = a₂ ∧ b₁ = b₂ := by simp
theorem mk_right_injective {α β : Type*} (a : α) : (mk a : β → α × β).Injective := by
intro b₁ b₂ h
simpa only [true_and, Prod.mk_inj, eq_self_iff_true] using h
theorem mk_left_injective {α β : Type*} (b : β) : (fun a ↦ mk a b : α → α × β).Injective := by
intro b₁ b₂ h
simpa only [and_true, eq_self_iff_true, mk_inj] using h
lemma mk_right_inj {a : α} {b₁ b₂ : β} : (a, b₁) = (a, b₂) ↔ b₁ = b₂ :=
(mk_right_injective _).eq_iff
lemma mk_left_inj {a₁ a₂ : α} {b : β} : (a₁, b) = (a₂, b) ↔ a₁ = a₂ := (mk_left_injective _).eq_iff
theorem map_def {f : α → γ} {g : β → δ} : Prod.map f g = fun p : α × β ↦ (f p.1, g p.2) :=
funext fun p ↦ Prod.ext (map_fst f g p) (map_snd f g p)
theorem id_prod : (fun p : α × β ↦ (p.1, p.2)) = id :=
rfl
@[simp]
theorem map_iterate (f : α → α) (g : β → β) (n : ℕ) :
(Prod.map f g)^[n] = Prod.map f^[n] g^[n] := by induction n <;> simp [*, Prod.map_comp_map]
theorem fst_surjective [h : Nonempty β] : Function.Surjective (@fst α β) :=
fun x ↦ h.elim fun y ↦ ⟨⟨x, y⟩, rfl⟩
theorem snd_surjective [h : Nonempty α] : Function.Surjective (@snd α β) :=
fun y ↦ h.elim fun x ↦ ⟨⟨x, y⟩, rfl⟩
theorem fst_injective [Subsingleton β] : Function.Injective (@fst α β) :=
fun _ _ h ↦ Prod.ext h (Subsingleton.elim _ _)
theorem snd_injective [Subsingleton α] : Function.Injective (@snd α β) :=
fun _ _ h ↦ Prod.ext (Subsingleton.elim _ _) h
@[simp]
theorem swap_leftInverse : Function.LeftInverse (@swap α β) swap :=
swap_swap
@[simp]
theorem swap_rightInverse : Function.RightInverse (@swap α β) swap :=
swap_swap
theorem swap_injective : Function.Injective (@swap α β) :=
swap_leftInverse.injective
theorem swap_surjective : Function.Surjective (@swap α β) :=
swap_leftInverse.surjective
theorem swap_bijective : Function.Bijective (@swap α β) :=
⟨swap_injective, swap_surjective⟩
theorem _root_.Function.Semiconj.swap_map (f : α → α) (g : β → β) :
Function.Semiconj swap (map f g) (map g f) :=
Function.semiconj_iff_comp_eq.2 (map_comp_swap g f).symm
theorem eq_iff_fst_eq_snd_eq : ∀ {p q : α × β}, p = q ↔ p.1 = q.1 ∧ p.2 = q.2
| ⟨p₁, p₂⟩, ⟨q₁, q₂⟩ => by simp
theorem fst_eq_iff : ∀ {p : α × β} {x : α}, p.1 = x ↔ p = (x, p.2)
| ⟨a, b⟩, x => by simp
theorem snd_eq_iff : ∀ {p : α × β} {x : β}, p.2 = x ↔ p = (p.1, x)
| ⟨a, b⟩, x => by simp
variable {r : α → α → Prop} {s : β → β → Prop} {x y : α × β}
lemma lex_iff : Prod.Lex r s x y ↔ r x.1 y.1 ∨ x.1 = y.1 ∧ s x.2 y.2 := lex_def
instance Lex.decidable [DecidableEq α]
(r : α → α → Prop) (s : β → β → Prop) [DecidableRel r] [DecidableRel s] :
DecidableRel (Prod.Lex r s) :=
fun _ _ ↦ decidable_of_decidable_of_iff lex_def.symm
@[refl]
theorem Lex.refl_left (r : α → α → Prop) (s : β → β → Prop) [IsRefl α r] : ∀ x, Prod.Lex r s x x
| (_, _) => Lex.left _ _ (refl _)
instance {r : α → α → Prop} {s : β → β → Prop} [IsRefl α r] : IsRefl (α × β) (Prod.Lex r s) :=
⟨Lex.refl_left _ _⟩
@[refl]
theorem Lex.refl_right (r : α → α → Prop) (s : β → β → Prop) [IsRefl β s] : ∀ x, Prod.Lex r s x x
| (_, _) => Lex.right _ (refl _)
instance {r : α → α → Prop} {s : β → β → Prop} [IsRefl β s] : IsRefl (α × β) (Prod.Lex r s) :=
⟨Lex.refl_right _ _⟩
instance isIrrefl [IsIrrefl α r] [IsIrrefl β s] : IsIrrefl (α × β) (Prod.Lex r s) :=
⟨by rintro ⟨i, a⟩ (⟨_, _, h⟩ | ⟨_, h⟩) <;> exact irrefl _ h⟩
@[trans]
theorem Lex.trans {r : α → α → Prop} {s : β → β → Prop} [IsTrans α r] [IsTrans β s] :
∀ {x y z : α × β}, Prod.Lex r s x y → Prod.Lex r s y z → Prod.Lex r s x z
| (_, _), (_, _), (_, _), left _ _ hxy₁, left _ _ hyz₁ => left _ _ (_root_.trans hxy₁ hyz₁)
| (_, _), (_, _), (_, _), left _ _ hxy₁, right _ _ => left _ _ hxy₁
| (_, _), (_, _), (_, _), right _ _, left _ _ hyz₁ => left _ _ hyz₁
| (_, _), (_, _), (_, _), right _ hxy₂, right _ hyz₂ => right _ (_root_.trans hxy₂ hyz₂)
instance {r : α → α → Prop} {s : β → β → Prop} [IsTrans α r] [IsTrans β s] :
IsTrans (α × β) (Prod.Lex r s) :=
⟨fun _ _ _ ↦ Lex.trans⟩
instance {r : α → α → Prop} {s : β → β → Prop} [IsStrictOrder α r] [IsAntisymm β s] :
IsAntisymm (α × β) (Prod.Lex r s) :=
⟨fun x₁ x₂ h₁₂ h₂₁ ↦
match x₁, x₂, h₁₂, h₂₁ with
| (a, _), (_, _), .left _ _ hr₁, .left _ _ hr₂ => (irrefl a (_root_.trans hr₁ hr₂)).elim
| (_, _), (_, _), .left _ _ hr₁, .right _ _ => (irrefl _ hr₁).elim
| (_, _), (_, _), .right _ _, .left _ _ hr₂ => (irrefl _ hr₂).elim
| (_, _), (_, _), .right _ hs₁, .right _ hs₂ => antisymm hs₁ hs₂ ▸ rfl⟩
instance isTotal_left {r : α → α → Prop} {s : β → β → Prop} [IsTotal α r] :
IsTotal (α × β) (Prod.Lex r s) :=
⟨fun ⟨a₁, _⟩ ⟨a₂, _⟩ ↦ (IsTotal.total a₁ a₂).imp (Lex.left _ _) (Lex.left _ _)⟩
instance isTotal_right {r : α → α → Prop} {s : β → β → Prop} [IsTrichotomous α r] [IsTotal β s] :
IsTotal (α × β) (Prod.Lex r s) :=
⟨fun ⟨i, a⟩ ⟨j, b⟩ ↦ by
obtain hij | rfl | hji := trichotomous_of r i j
· exact Or.inl (.left _ _ hij)
· exact (total_of s a b).imp (.right _) (.right _)
· exact Or.inr (.left _ _ hji) ⟩
instance IsTrichotomous [IsTrichotomous α r] [IsTrichotomous β s] :
IsTrichotomous (α × β) (Prod.Lex r s) :=
⟨fun ⟨i, a⟩ ⟨j, b⟩ ↦ by
obtain hij | rfl | hji := trichotomous_of r i j
{ exact Or.inl (Lex.left _ _ hij) }
{ exact (trichotomous_of (s) a b).imp3 (Lex.right _) (congr_arg _) (Lex.right _) }
{ exact Or.inr (Or.inr <| Lex.left _ _ hji) }⟩
instance [IsAsymm α r] [IsAsymm β s] :
IsAsymm (α × β) (Prod.Lex r s) where
asymm
| (_a₁, _a₂), (_b₁, _b₂), .left _ _ h₁, .left _ _ h₂ => IsAsymm.asymm _ _ h₂ h₁
| (_a₁, _a₂), (_, _b₂), .left _ _ h₁, .right _ _ => IsAsymm.asymm _ _ h₁ h₁
| (_a₁, _a₂), (_, _b₂), .right _ _, .left _ _ h₂ => IsAsymm.asymm _ _ h₂ h₂
| (_a₁, _a₂), (_, _b₂), .right _ h₁, .right _ h₂ => IsAsymm.asymm _ _ h₁ h₂
end Prod
open Prod
namespace Function
variable {f : α → γ} {g : β → δ} {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α} {g₂ : δ → γ}
theorem Injective.prodMap (hf : Injective f) (hg : Injective g) : Injective (map f g) :=
fun _ _ h ↦ Prod.ext (hf <| congr_arg Prod.fst h) (hg <| congr_arg Prod.snd h)
theorem Surjective.prodMap (hf : Surjective f) (hg : Surjective g) : Surjective (map f g) :=
fun p ↦
let ⟨x, hx⟩ := hf p.1
let ⟨y, hy⟩ := hg p.2
⟨(x, y), Prod.ext hx hy⟩
theorem Bijective.prodMap (hf : Bijective f) (hg : Bijective g) : Bijective (map f g) :=
⟨hf.1.prodMap hg.1, hf.2.prodMap hg.2⟩
theorem LeftInverse.prodMap (hf : LeftInverse f₁ f₂) (hg : LeftInverse g₁ g₂) :
LeftInverse (map f₁ g₁) (map f₂ g₂) :=
fun a ↦ by rw [Prod.map_map, hf.comp_eq_id, hg.comp_eq_id, map_id, id]
theorem RightInverse.prodMap :
RightInverse f₁ f₂ → RightInverse g₁ g₂ → RightInverse (map f₁ g₁) (map f₂ g₂) :=
LeftInverse.prodMap
theorem Involutive.prodMap {f : α → α} {g : β → β} :
Involutive f → Involutive g → Involutive (map f g) :=
LeftInverse.prodMap
end Function
namespace Prod
open Function
@[simp]
theorem map_injective [Nonempty α] [Nonempty β] {f : α → γ} {g : β → δ} :
Injective (map f g) ↔ Injective f ∧ Injective g :=
⟨fun h =>
⟨fun a₁ a₂ ha => by
inhabit β
injection
@h (a₁, default) (a₂, default) (congr_arg (fun c : γ => Prod.mk c (g default)) ha :),
fun b₁ b₂ hb => by
inhabit α
injection @h (default, b₁) (default, b₂) (congr_arg (Prod.mk (f default)) hb :)⟩,
fun h => h.1.prodMap h.2⟩
@[simp]
theorem map_surjective [Nonempty γ] [Nonempty δ] {f : α → γ} {g : β → δ} :
Surjective (map f g) ↔ Surjective f ∧ Surjective g :=
⟨fun h =>
⟨fun c => by
inhabit δ
obtain ⟨⟨a, b⟩, h⟩ := h (c, default)
exact ⟨a, congr_arg Prod.fst h⟩,
fun d => by
inhabit γ
obtain ⟨⟨a, b⟩, h⟩ := h (default, d)
exact ⟨b, congr_arg Prod.snd h⟩⟩,
fun h => h.1.prodMap h.2⟩
@[simp]
theorem map_bijective [Nonempty α] [Nonempty β] {f : α → γ} {g : β → δ} :
Bijective (map f g) ↔ Bijective f ∧ Bijective g := by
haveI := Nonempty.map f ‹_›
haveI := Nonempty.map g ‹_›
exact (map_injective.and map_surjective).trans and_and_and_comm
@[simp]
theorem map_leftInverse [Nonempty β] [Nonempty δ] {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α}
{g₂ : δ → γ} : LeftInverse (map f₁ g₁) (map f₂ g₂) ↔ LeftInverse f₁ f₂ ∧ LeftInverse g₁ g₂ :=
⟨fun h =>
⟨fun b => by
inhabit δ
exact congr_arg Prod.fst (h (b, default)),
fun d => by
inhabit β
exact congr_arg Prod.snd (h (default, d))⟩,
fun h => h.1.prodMap h.2 ⟩
@[simp]
theorem map_rightInverse [Nonempty α] [Nonempty γ] {f₁ : α → β} {g₁ : γ → δ} {f₂ : β → α}
{g₂ : δ → γ} : RightInverse (map f₁ g₁) (map f₂ g₂) ↔ RightInverse f₁ f₂ ∧ RightInverse g₁ g₂ :=
map_leftInverse
@[simp]
theorem map_involutive [Nonempty α] [Nonempty β] {f : α → α} {g : β → β} :
Involutive (map f g) ↔ Involutive f ∧ Involutive g :=
map_leftInverse
namespace PrettyPrinting
open Lean PrettyPrinter Delaborator
/--
When true, then `Prod.fst x` and `Prod.snd x` pretty print as `x.1` and `x.2`
rather than as `x.fst` and `x.snd`.
-/
register_option pp.numericProj.prod : Bool := {
defValue := true
descr := "enable pretty printing `Prod.fst x` as `x.1` and `Prod.snd x` as `x.2`."
}
/-- Tell whether pretty-printing should use numeric projection notations `.1`
and `.2` for `Prod.fst` and `Prod.snd`. -/
def getPPNumericProjProd (o : Options) : Bool :=
o.get pp.numericProj.prod.name pp.numericProj.prod.defValue
/-- Delaborator for `Prod.fst x` as `x.1`. -/
@[app_delab Prod.fst]
def delabProdFst : Delab :=
whenPPOption getPPNumericProjProd <|
whenPPOption getPPFieldNotation <|
whenNotPPOption getPPExplicit <|
withOverApp 3 do
let x ← SubExpr.withAppArg delab
`($(x).1)
/-- Delaborator for `Prod.snd x` as `x.2`. -/
@[app_delab Prod.snd]
def delabProdSnd : Delab :=
whenPPOption getPPNumericProjProd <|
whenPPOption getPPFieldNotation <|
whenNotPPOption getPPExplicit <|
withOverApp 3 do
let x ← SubExpr.withAppArg delab
`($(x).2)
end PrettyPrinting
end Prod |
.lake/packages/mathlib/Mathlib/Data/Prod/TProd.lean | import Mathlib.Data.List.Nodup
import Mathlib.Data.Set.Prod
/-!
# Finite products of types
This file defines the product of types over a list. For `l : List ι` and `α : ι → Type v` we define
`List.TProd α l = l.foldr (fun i β ↦ α i × β) PUnit`.
This type should not be used if `∀ i, α i` or `∀ i ∈ l, α i` can be used instead
(in the last expression, we could also replace the list `l` by a set or a finset).
This type is used as an intermediary between binary products and finitary products.
The application of this type is finitary product measures, but it could be used in any
construction/theorem that is easier to define/prove on binary products than on finitary products.
* Once we have the construction on binary products (like binary product measures in
`MeasureTheory.prod`), we can easily define a finitary version on the type `TProd l α`
by iterating. Properties can also be easily extended from the binary case to the finitary case
by iterating.
* Then we can use the equivalence `List.TProd.piEquivTProd` below (or enhanced versions of it,
like a `MeasurableEquiv` for product measures) to get the construction on `∀ i : ι, α i`, at
least when assuming `[Fintype ι] [Encodable ι]` (using `Encodable.sortedUniv`).
Using `attribute [local instance] Fintype.toEncodable` we can get rid of the argument
`[Encodable ι]`.
## Main definitions
* We have the equivalence `TProd.piEquivTProd : (∀ i, α i) ≃ TProd α l`
if `l` contains every element of `ι` exactly once.
* The product of sets is `Set.tprod : (∀ i, Set (α i)) → Set (TProd α l)`.
-/
open List Function
universe u v
variable {ι : Type u} {α : ι → Type v} {i j : ι} {l : List ι}
namespace List
variable (α) in
/-- The product of a family of types over a list. -/
abbrev TProd (l : List ι) : Type v :=
l.foldr (fun i β => α i × β) PUnit
namespace TProd
/-- Turning a function `f : ∀ i, α i` into an element of the iterated product `TProd α l`. -/
protected def mk : ∀ (l : List ι) (_f : ∀ i, α i), TProd α l
| [] => fun _ => PUnit.unit
| i :: is => fun f => (f i, TProd.mk is f)
instance [∀ i, Inhabited (α i)] : Inhabited (TProd α l) :=
⟨TProd.mk l default⟩
@[simp]
theorem fst_mk (i : ι) (l : List ι) (f : ∀ i, α i) : (TProd.mk (i :: l) f).1 = f i :=
rfl
@[simp]
theorem snd_mk (i : ι) (l : List ι) (f : ∀ i, α i) :
(TProd.mk.{u, v} (i :: l) f).2 = TProd.mk.{u, v} l f :=
rfl
variable [DecidableEq ι]
/-- Given an element of the iterated product `l.Prod α`, take a projection into direction `i`.
If `i` appears multiple times in `l`, this chooses the first component in direction `i`. -/
protected def elim : ∀ {l : List ι} (_ : TProd α l) {i : ι} (_ : i ∈ l), α i
| i :: is, v, j, hj =>
if hji : j = i then by
subst hji
exact v.1
else TProd.elim v.2 ((List.mem_cons.mp hj).resolve_left hji)
@[simp]
theorem elim_self (v : TProd α (i :: l)) : v.elim mem_cons_self = v.1 := by simp [TProd.elim]
@[simp]
theorem elim_of_ne (hj : j ∈ i :: l) (hji : j ≠ i) (v : TProd α (i :: l)) :
v.elim hj = TProd.elim v.2 ((List.mem_cons.mp hj).resolve_left hji) := by simp [TProd.elim, hji]
@[simp]
theorem elim_of_mem (hl : (i :: l).Nodup) (hj : j ∈ l) (v : TProd α (i :: l)) :
v.elim (mem_cons_of_mem _ hj) = TProd.elim v.2 hj := by
apply elim_of_ne
rintro rfl
exact hl.notMem hj
theorem elim_mk : ∀ (l : List ι) (f : ∀ i, α i) {i : ι} (hi : i ∈ l), (TProd.mk l f).elim hi = f i
| i :: is, f, j, hj => by
by_cases hji : j = i
· subst hji
simp
· rw [TProd.elim_of_ne _ hji, snd_mk, elim_mk is]
@[ext]
theorem ext :
∀ {l : List ι} (_ : l.Nodup) {v w : TProd α l}
(_ : ∀ (i) (hi : i ∈ l), v.elim hi = w.elim hi), v = w
| [], _, v, w, _ => PUnit.ext v w
| i :: is, hl, v, w, hvw => by
apply Prod.ext
· rw [← elim_self v, hvw, elim_self]
refine ext (nodup_cons.mp hl).2 fun j hj => ?_
rw [← elim_of_mem hl, hvw, elim_of_mem hl]
/-- A version of `TProd.elim` when `l` contains all elements. In this case we get a function into
`Π i, α i`. -/
@[simp]
protected def elim' (h : ∀ i, i ∈ l) (v : TProd α l) (i : ι) : α i :=
v.elim (h i)
theorem mk_elim (hnd : l.Nodup) (h : ∀ i, i ∈ l) (v : TProd α l) : TProd.mk l (v.elim' h) = v :=
TProd.ext hnd fun i hi => by simp [elim_mk]
/-- Pi-types are equivalent to iterated products. -/
def piEquivTProd (hnd : l.Nodup) (h : ∀ i, i ∈ l) : (∀ i, α i) ≃ TProd α l :=
⟨TProd.mk l, TProd.elim' h, fun f => funext fun i => elim_mk l f (h i), mk_elim hnd h⟩
end TProd
end List
namespace Set
/-- A product of sets in `TProd α l`. -/
@[simp]
protected def tprod : ∀ (l : List ι) (_t : ∀ i, Set (α i)), Set (TProd α l)
| [], _ => univ
| i :: is, t => t i ×ˢ Set.tprod is t
theorem mk_preimage_tprod :
∀ (l : List ι) (t : ∀ i, Set (α i)), TProd.mk l ⁻¹' Set.tprod l t = { i | i ∈ l }.pi t
| [], t => by simp [Set.tprod]
| i :: l, t => by
ext f
have h : TProd.mk l f ∈ Set.tprod l t ↔ ∀ i : ι, i ∈ l → f i ∈ t i := by
change f ∈ TProd.mk l ⁻¹' Set.tprod l t ↔ f ∈ { x | x ∈ l }.pi t
rw [mk_preimage_tprod l t]
-- `simp [Set.TProd, TProd.mk, this]` can close this goal but is slow.
rw [Set.tprod, TProd.mk, mem_preimage, mem_pi, prodMk_mem_set_prod_eq]
simp_rw [mem_setOf_eq, mem_cons]
rw [forall_eq_or_imp, and_congr_right_iff]
exact fun _ => h
theorem elim_preimage_pi [DecidableEq ι] {l : List ι} (hnd : l.Nodup) (h : ∀ i, i ∈ l)
(t : ∀ i, Set (α i)) : TProd.elim' h ⁻¹' pi univ t = Set.tprod l t := by
have h2 : { i | i ∈ l } = univ := by
ext i
simp [h]
rw [← h2, ← mk_preimage_tprod, preimage_preimage]
simp only [TProd.mk_elim hnd h]
dsimp
end Set |
.lake/packages/mathlib/Mathlib/Data/Ordmap/Ordset.lean | import Mathlib.Data.Ordmap.Invariants
/-!
# Verification of `Ordnode`
This file uses the invariants defined in `Mathlib/Data/Ordmap/Invariants.lean` to construct
`Ordset α`, a wrapper around `Ordnode α` which includes the correctness invariant of the type.
It exposes parallel operations like `insert` as functions on `Ordset` that do the same thing but
bundle the correctness proofs.
The advantage is that it is possible to, for example, prove that the result of `find` on `insert`
will actually find the element, while `Ordnode` cannot guarantee this if the input tree did not
satisfy the type invariants.
## Main definitions
* `Ordnode.Valid`: The validity predicate for an `Ordnode` subtree.
* `Ordset α`: A well-formed set of values of type `α`.
## Implementation notes
Because the `Ordnode` file was ported from Haskell, the correctness invariants of some
of the functions have not been spelled out, and some theorems like
`Ordnode.Valid'.balanceL_aux` show very intricate assumptions on the sizes,
which may need to be revised if it turns out some operations violate these assumptions,
because there is a decent amount of slop in the actual data structure invariants, so the
theorem will go through with multiple choices of assumption.
-/
variable {α : Type*}
namespace Ordnode
section Valid
variable [Preorder α]
/-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are
correct, the tree is balanced, and the elements of the tree are organized according to the
ordering. This version of `Valid` also puts all elements in the tree in the interval `(lo, hi)`. -/
structure Valid' (lo : WithBot α) (t : Ordnode α) (hi : WithTop α) : Prop where
ord : t.Bounded lo hi
sz : t.Sized
bal : t.Balanced
/-- The validity predicate for an `Ordnode` subtree. This asserts that the `size` fields are
correct, the tree is balanced, and the elements of the tree are organized according to the
ordering. -/
def Valid (t : Ordnode α) : Prop :=
Valid' ⊥ t ⊤
theorem Valid'.mono_left {x y : α} (xy : x ≤ y) {t : Ordnode α} {o} (h : Valid' y t o) :
Valid' x t o :=
⟨h.1.mono_left xy, h.2, h.3⟩
theorem Valid'.mono_right {x y : α} (xy : x ≤ y) {t : Ordnode α} {o} (h : Valid' o t x) :
Valid' o t y :=
⟨h.1.mono_right xy, h.2, h.3⟩
theorem Valid'.trans_left {t₁ t₂ : Ordnode α} {x : α} {o₁ o₂} (h : Bounded t₁ o₁ x)
(H : Valid' x t₂ o₂) : Valid' o₁ t₂ o₂ :=
⟨h.trans_left H.1, H.2, H.3⟩
theorem Valid'.trans_right {t₁ t₂ : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t₁ x)
(h : Bounded t₂ x o₂) : Valid' o₁ t₁ o₂ :=
⟨H.1.trans_right h, H.2, H.3⟩
theorem Valid'.of_lt {t : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t o₂) (h₁ : Bounded nil o₁ x)
(h₂ : All (· < x) t) : Valid' o₁ t x :=
⟨H.1.of_lt h₁ h₂, H.2, H.3⟩
theorem Valid'.of_gt {t : Ordnode α} {x : α} {o₁ o₂} (H : Valid' o₁ t o₂) (h₁ : Bounded nil x o₂)
(h₂ : All (· > x) t) : Valid' x t o₂ :=
⟨H.1.of_gt h₁ h₂, H.2, H.3⟩
theorem Valid'.valid {t o₁ o₂} (h : @Valid' α _ o₁ t o₂) : Valid t :=
⟨h.1.weak, h.2, h.3⟩
theorem valid'_nil {o₁ o₂} (h : Bounded nil o₁ o₂) : Valid' o₁ (@nil α) o₂ :=
⟨h, ⟨⟩, ⟨⟩⟩
theorem valid_nil : Valid (@nil α) :=
valid'_nil ⟨⟩
theorem Valid'.node {s l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : BalancedSz (size l) (size r)) (hs : s = size l + size r + 1) :
Valid' o₁ (@node α s l x r) o₂ :=
⟨⟨hl.1, hr.1⟩, ⟨hs, hl.2, hr.2⟩, ⟨H, hl.3, hr.3⟩⟩
theorem Valid'.dual : ∀ {t : Ordnode α} {o₁ o₂}, Valid' o₁ t o₂ → @Valid' αᵒᵈ _ o₂ (dual t) o₁
| .nil, _, _, h => valid'_nil h.1.dual
| .node _ l _ r, _, _, ⟨⟨ol, Or⟩, ⟨rfl, sl, sr⟩, ⟨b, bl, br⟩⟩ =>
let ⟨ol', sl', bl'⟩ := Valid'.dual ⟨ol, sl, bl⟩
let ⟨or', sr', br'⟩ := Valid'.dual ⟨Or, sr, br⟩
⟨⟨or', ol'⟩, ⟨by simp [size_dual, add_comm], sr', sl'⟩,
⟨by rw [size_dual, size_dual]; exact b.symm, br', bl'⟩⟩
theorem Valid'.dual_iff {t : Ordnode α} {o₁ o₂} : Valid' o₁ t o₂ ↔ @Valid' αᵒᵈ _ o₂ (.dual t) o₁ :=
⟨Valid'.dual, fun h => by
have := Valid'.dual h; rwa [dual_dual, OrderDual.Preorder.dual_dual] at this⟩
theorem Valid.dual {t : Ordnode α} : Valid t → @Valid αᵒᵈ _ (.dual t) :=
Valid'.dual
theorem Valid.dual_iff {t : Ordnode α} : Valid t ↔ @Valid αᵒᵈ _ (.dual t) :=
Valid'.dual_iff
theorem Valid'.left {s l x r o₁ o₂} (H : Valid' o₁ (@Ordnode.node α s l x r) o₂) : Valid' o₁ l x :=
⟨H.1.1, H.2.2.1, H.3.2.1⟩
theorem Valid'.right {s l x r o₁ o₂} (H : Valid' o₁ (@Ordnode.node α s l x r) o₂) : Valid' x r o₂ :=
⟨H.1.2, H.2.2.2, H.3.2.2⟩
nonrec theorem Valid.left {s l x r} (H : Valid (@node α s l x r)) : Valid l :=
H.left.valid
nonrec theorem Valid.right {s l x r} (H : Valid (@node α s l x r)) : Valid r :=
H.right.valid
theorem Valid.size_eq {s l x r} (H : Valid (@node α s l x r)) :
size (@node α s l x r) = size l + size r + 1 :=
H.2.1
theorem Valid'.node' {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : BalancedSz (size l) (size r)) : Valid' o₁ (@node' α l x r) o₂ :=
hl.node hr H rfl
theorem valid'_singleton {x : α} {o₁ o₂} (h₁ : Bounded nil o₁ x) (h₂ : Bounded nil x o₂) :
Valid' o₁ (singleton x : Ordnode α) o₂ :=
(valid'_nil h₁).node (valid'_nil h₂) (Or.inl zero_le_one) rfl
theorem valid_singleton {x : α} : Valid (singleton x : Ordnode α) :=
valid'_singleton ⟨⟩ ⟨⟩
theorem Valid'.node3L {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y)
(hr : Valid' y r o₂) (H1 : BalancedSz (size l) (size m))
(H2 : BalancedSz (size l + size m + 1) (size r)) : Valid' o₁ (@node3L α l x m y r) o₂ :=
(hl.node' hm H1).node' hr H2
theorem Valid'.node3R {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y)
(hr : Valid' y r o₂) (H1 : BalancedSz (size l) (size m + size r + 1))
(H2 : BalancedSz (size m) (size r)) : Valid' o₁ (@node3R α l x m y r) o₂ :=
hl.node' (hm.node' hr H2) H1
theorem Valid'.node4L_lemma₁ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9)
(mr₂ : b + c + 1 ≤ 3 * d) (mm₁ : b ≤ 3 * c) : b < 3 * a + 1 := by cutsat
theorem Valid'.node4L_lemma₂ {b c d : ℕ} (mr₂ : b + c + 1 ≤ 3 * d) : c ≤ 3 * d := by cutsat
theorem Valid'.node4L_lemma₃ {b c d : ℕ} (mr₁ : 2 * d ≤ b + c + 1) (mm₁ : b ≤ 3 * c) :
d ≤ 3 * c := by cutsat
theorem Valid'.node4L_lemma₄ {a b c d : ℕ} (lr₁ : 3 * a ≤ b + c + 1 + d) (mr₂ : b + c + 1 ≤ 3 * d)
(mm₁ : b ≤ 3 * c) : a + b + 1 ≤ 3 * (c + d + 1) := by cutsat
theorem Valid'.node4L_lemma₅ {a b c d : ℕ} (lr₂ : 3 * (b + c + 1 + d) ≤ 16 * a + 9)
(mr₁ : 2 * d ≤ b + c + 1) (mm₂ : c ≤ 3 * b) : c + d + 1 ≤ 3 * (a + b + 1) := by cutsat
theorem Valid'.node4L {l} {x : α} {m} {y : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hm : Valid' x m y)
(hr : Valid' (↑y) r o₂) (Hm : 0 < size m)
(H : size l = 0 ∧ size m = 1 ∧ size r ≤ 1 ∨
0 < size l ∧
ratio * size r ≤ size m ∧
delta * size l ≤ size m + size r ∧
3 * (size m + size r) ≤ 16 * size l + 9 ∧ size m ≤ delta * size r) :
Valid' o₁ (@node4L α l x m y r) o₂ := by
obtain - | ⟨s, ml, z, mr⟩ := m; · cases Hm
suffices
BalancedSz (size l) (size ml) ∧
BalancedSz (size mr) (size r) ∧ BalancedSz (size l + size ml + 1) (size mr + size r + 1) from
Valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2
rcases H with (⟨l0, m1, r0⟩ | ⟨l0, mr₁, lr₁, lr₂, mr₂⟩)
· rw [hm.2.size_eq, Nat.succ_inj, add_eq_zero] at m1
rw [l0, m1.1, m1.2]; revert r0; rcases size r with (_ | _ | _) <;>
[decide; decide; (intro r0; unfold BalancedSz delta; cutsat)]
· rcases Nat.eq_zero_or_pos (size r) with r0 | r0
· rw [r0] at mr₂; cases not_le_of_gt Hm mr₂
rw [hm.2.size_eq] at lr₁ lr₂ mr₁ mr₂
by_cases mm : size ml + size mr ≤ 1
· dsimp [delta, ratio] at lr₁ mr₁
have r1 : r.size = 1 := by omega
have l1 : l.size = 1 := by omega
rw [r1, add_assoc] at lr₁
rw [l1, r1]
revert mm; cases size ml <;> cases size mr <;> intro mm
· decide
· rw [zero_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩)
decide
· rcases mm with (_ | ⟨⟨⟩⟩); decide
· rw [Nat.succ_add] at mm; rcases mm with (_ | ⟨⟨⟩⟩)
rcases hm.3.1.resolve_left mm with ⟨mm₁, mm₂⟩
rcases Nat.eq_zero_or_pos (size ml) with ml0 | ml0
· rw [ml0, mul_zero, Nat.le_zero] at mm₂
rw [ml0, mm₂] at mm; cases mm (by decide)
have : 2 * size l ≤ size ml + size mr + 1 := by
have := Nat.mul_le_mul_left ratio lr₁
rw [mul_left_comm, mul_add] at this
have := le_trans this (add_le_add_left mr₁ _)
rw [← Nat.succ_mul] at this
exact (mul_le_mul_iff_right₀ (by decide)).1 this
refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩
· refine (mul_le_mul_iff_right₀ (by decide)).1 (le_trans this ?_)
rw [two_mul, Nat.succ_le_iff]
refine add_lt_add_of_lt_of_le ?_ mm₂
simpa using mul_lt_mul_of_pos_right (by decide : 1 < 3) ml0
· exact Nat.le_of_lt_succ (Valid'.node4L_lemma₁ lr₂ mr₂ mm₁)
· exact Valid'.node4L_lemma₂ mr₂
· exact Valid'.node4L_lemma₃ mr₁ mm₁
· exact Valid'.node4L_lemma₄ lr₁ mr₂ mm₁
· exact Valid'.node4L_lemma₅ lr₂ mr₁ mm₂
theorem Valid'.rotateL_lemma₁ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (hb₂ : c ≤ 3 * b) : a ≤ 3 * b := by
cutsat
theorem Valid'.rotateL_lemma₂ {a b c : ℕ} (H3 : 2 * (b + c) ≤ 9 * a + 3) (h : b < 2 * c) :
b < 3 * a + 1 := by cutsat
theorem Valid'.rotateL_lemma₃ {a b c : ℕ} (H2 : 3 * a ≤ b + c) (h : b < 2 * c) : a + b < 3 * c := by
cutsat
theorem Valid'.rotateL_lemma₄ {a b : ℕ} (H3 : 2 * b ≤ 9 * a + 3) : 3 * b ≤ 16 * a + 9 := by
cutsat
theorem Valid'.rotateL {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H1 : ¬size l + size r ≤ 1) (H2 : delta * size l < size r)
(H3 : 2 * size r ≤ 9 * size l + 5 ∨ size r ≤ 3) : Valid' o₁ (@rotateL α l x r) o₂ := by
obtain - | ⟨rs, rl, rx, rr⟩ := r; · cases H2
rw [hr.2.size_eq, Nat.lt_succ_iff] at H2
rw [hr.2.size_eq] at H3
replace H3 : 2 * (size rl + size rr) ≤ 9 * size l + 3 ∨ size rl + size rr ≤ 2 :=
H3.imp (@Nat.le_of_add_le_add_right _ 2 _) Nat.le_of_succ_le_succ
have H3_0 (l0 : size l = 0) : size rl + size rr ≤ 2 := by omega
have H3p : size l > 0 → 2 * (size rl + size rr) ≤ 9 * size l + 3 := fun l0 : 1 ≤ size l =>
(or_iff_left_of_imp <| by cutsat).1 H3
have ablem : ∀ {a b : ℕ}, 1 ≤ a → a + b ≤ 2 → b ≤ 1 := by omega
have hlp : size l > 0 → ¬size rl + size rr ≤ 1 := fun l0 hb =>
absurd (le_trans (le_trans (Nat.mul_le_mul_left _ l0) H2) hb) (by decide)
rw [Ordnode.rotateL_node]; split_ifs with h
· have rr0 : size rr > 0 :=
(mul_lt_mul_iff_right₀ (by decide)).1 (lt_of_le_of_lt (Nat.zero_le _) h : ratio * 0 < _)
suffices BalancedSz (size l) (size rl) ∧ BalancedSz (size l + size rl + 1) (size rr) by
exact hl.node3L hr.left hr.right this.1 this.2
rcases Nat.eq_zero_or_pos (size l) with l0 | l0
· rw [l0]; replace H3 := H3_0 l0
have := hr.3.1
rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0
· rw [rl0] at this ⊢
rw [le_antisymm (balancedSz_zero.1 this.symm) rr0]
decide
have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0
rw [add_comm] at H3
rw [rr1, show size rl = 1 from le_antisymm (ablem rr0 H3) rl0]
decide
replace H3 := H3p l0
rcases hr.3.1.resolve_left (hlp l0) with ⟨_, hb₂⟩
refine ⟨Or.inr ⟨?_, ?_⟩, Or.inr ⟨?_, ?_⟩⟩
· exact Valid'.rotateL_lemma₁ H2 hb₂
· exact Nat.le_of_lt_succ (Valid'.rotateL_lemma₂ H3 h)
· exact Valid'.rotateL_lemma₃ H2 h
· exact
le_trans hb₂
(Nat.mul_le_mul_left _ <| le_trans (Nat.le_add_left _ _) (Nat.le_add_right _ _))
· rcases Nat.eq_zero_or_pos (size rl) with rl0 | rl0
· rw [rl0, not_lt, Nat.le_zero, Nat.mul_eq_zero] at h
replace h := h.resolve_left (by decide)
rw [rl0, h, Nat.le_zero, Nat.mul_eq_zero] at H2
rw [hr.2.size_eq, rl0, h, H2.resolve_left (by decide)] at H1
cases H1 (by decide)
refine hl.node4L hr.left hr.right rl0 ?_
rcases Nat.eq_zero_or_pos (size l) with l0 | l0
· replace H3 := H3_0 l0
rcases Nat.eq_zero_or_pos (size rr) with rr0 | rr0
· have := hr.3.1
rw [rr0] at this
exact Or.inl ⟨l0, le_antisymm (balancedSz_zero.1 this) rl0, rr0.symm ▸ zero_le_one⟩
exact Or.inl ⟨l0, le_antisymm (ablem rr0 <| by rwa [add_comm]) rl0, ablem rl0 H3⟩
exact
Or.inr ⟨l0, not_lt.1 h, H2, Valid'.rotateL_lemma₄ (H3p l0), (hr.3.1.resolve_left (hlp l0)).1⟩
theorem Valid'.rotateR {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H1 : ¬size l + size r ≤ 1) (H2 : delta * size r < size l)
(H3 : 2 * size l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@rotateR α l x r) o₂ := by
refine Valid'.dual_iff.2 ?_
rw [dual_rotateR]
refine hr.dual.rotateL hl.dual ?_ ?_ ?_
· rwa [size_dual, size_dual, add_comm]
· rwa [size_dual, size_dual]
· rwa [size_dual, size_dual]
theorem Valid'.balance'_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H₁ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3)
(H₂ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@balance' α l x r) o₂ := by
rw [balance']; split_ifs with h h_1 h_2
· exact hl.node' hr (Or.inl h)
· exact hl.rotateL hr h h_1 H₁
· exact hl.rotateR hr h h_2 H₂
· exact hl.node' hr (Or.inr ⟨not_lt.1 h_2, not_lt.1 h_1⟩)
theorem Valid'.balance'_lemma {α l l' r r'} (H1 : BalancedSz l' r')
(H2 : Nat.dist (@size α l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l') :
2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3 := by
suffices @size α r ≤ 3 * (size l + 1) by cutsat
rcases H2 with (⟨hl, rfl⟩ | ⟨hr, rfl⟩) <;> rcases H1 with (h | ⟨_, h₂⟩)
· exact le_trans (Nat.le_add_left _ _) (le_trans h (Nat.le_add_left _ _))
· exact
le_trans h₂
(Nat.mul_le_mul_left _ <| le_trans (Nat.dist_tri_right _ _) (Nat.add_le_add_left hl _))
· exact
le_trans (Nat.dist_tri_left' _ _)
(le_trans (add_le_add hr (le_trans (Nat.le_add_left _ _) h)) (by cutsat))
· rw [Nat.mul_succ]
exact le_trans (Nat.dist_tri_right' _ _) (add_le_add h₂ (le_trans hr (by decide)))
theorem Valid'.balance' {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : ∃ l' r', BalancedSz l' r' ∧
(Nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l')) :
Valid' o₁ (@balance' α l x r) o₂ :=
let ⟨_, _, H1, H2⟩ := H
Valid'.balance'_aux hl hr (Valid'.balance'_lemma H1 H2) (Valid'.balance'_lemma H1.symm H2.symm)
theorem Valid'.balance {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : ∃ l' r', BalancedSz l' r' ∧
(Nat.dist (size l) l' ≤ 1 ∧ size r = r' ∨ Nat.dist (size r) r' ≤ 1 ∧ size l = l')) :
Valid' o₁ (@balance α l x r) o₂ := by
rw [balance_eq_balance' hl.3 hr.3 hl.2 hr.2]; exact hl.balance' hr H
theorem Valid'.balanceL_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H₁ : size l = 0 → size r ≤ 1) (H₂ : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l)
(H₃ : 2 * @size α l ≤ 9 * size r + 5 ∨ size l ≤ 3) : Valid' o₁ (@balanceL α l x r) o₂ := by
rw [balanceL_eq_balance hl.2 hr.2 H₁ H₂, balance_eq_balance' hl.3 hr.3 hl.2 hr.2]
refine hl.balance'_aux hr (Or.inl ?_) H₃
rcases Nat.eq_zero_or_pos (size r) with r0 | r0
· rw [r0]; exact Nat.zero_le _
rcases Nat.eq_zero_or_pos (size l) with l0 | l0
· rw [l0]; exact le_trans (Nat.mul_le_mul_left _ (H₁ l0)) (by decide)
replace H₂ : _ ≤ 3 * _ := H₂ l0 r0; cutsat
theorem Valid'.balanceL {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : (∃ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨
∃ r', Raised (size r) r' ∧ BalancedSz (size l) r') :
Valid' o₁ (@balanceL α l x r) o₂ := by
rw [balanceL_eq_balance' hl.3 hr.3 hl.2 hr.2 H]
refine hl.balance' hr ?_
rcases H with (⟨l', e, H⟩ | ⟨r', e, H⟩)
· exact ⟨_, _, H, Or.inl ⟨e.dist_le', rfl⟩⟩
· exact ⟨_, _, H, Or.inr ⟨e.dist_le, rfl⟩⟩
theorem Valid'.balanceR_aux {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H₁ : size r = 0 → size l ≤ 1) (H₂ : 1 ≤ size r → 1 ≤ size l → size l ≤ delta * size r)
(H₃ : 2 * @size α r ≤ 9 * size l + 5 ∨ size r ≤ 3) : Valid' o₁ (@balanceR α l x r) o₂ := by
rw [Valid'.dual_iff, dual_balanceR]
have := hr.dual.balanceL_aux hl.dual
rw [size_dual, size_dual] at this
exact this H₁ H₂ H₃
theorem Valid'.balanceR {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂)
(H : (∃ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨
∃ r', Raised r' (size r) ∧ BalancedSz (size l) r') :
Valid' o₁ (@balanceR α l x r) o₂ := by
rw [Valid'.dual_iff, dual_balanceR]; exact hr.dual.balanceL hl.dual (balance_sz_dual H)
theorem Valid'.eraseMax_aux {s l x r o₁ o₂} (H : Valid' o₁ (.node s l x r) o₂) :
Valid' o₁ (@eraseMax α (.node' l x r)) ↑(findMax' x r) ∧
size (.node' l x r) = size (eraseMax (.node' l x r)) + 1 := by
have := H.2.eq_node'; rw [this] at H; clear this
induction r generalizing l x o₁ with
| nil => exact ⟨H.left, rfl⟩
| node rs rl rx rr _ IHrr =>
have := H.2.2.2.eq_node'; rw [this] at H ⊢
rcases IHrr H.right with ⟨h, e⟩
refine ⟨Valid'.balanceL H.left h (Or.inr ⟨_, Or.inr e, H.3.1⟩), ?_⟩
rw [eraseMax, size_balanceL H.3.2.1 h.3 H.2.2.1 h.2 (Or.inr ⟨_, Or.inr e, H.3.1⟩)]
rw [size_node, e]; rfl
theorem Valid'.eraseMin_aux {s l} {x : α} {r o₁ o₂} (H : Valid' o₁ (.node s l x r) o₂) :
Valid' ↑(findMin' l x) (@eraseMin α (.node' l x r)) o₂ ∧
size (.node' l x r) = size (eraseMin (.node' l x r)) + 1 := by
have := H.dual.eraseMax_aux
rwa [← dual_node', size_dual, ← dual_eraseMin, size_dual, ← Valid'.dual_iff, findMax'_dual]
at this
theorem eraseMin.valid : ∀ {t}, @Valid α _ t → Valid (eraseMin t)
| nil, _ => valid_nil
| node _ l x r, h => by rw [h.2.eq_node']; exact h.eraseMin_aux.1.valid
theorem eraseMax.valid {t} (h : @Valid α _ t) : Valid (eraseMax t) := by
rw [Valid.dual_iff, dual_eraseMax]; exact eraseMin.valid h.dual
theorem Valid'.glue_aux {l r o₁ o₂} (hl : Valid' o₁ l o₂) (hr : Valid' o₁ r o₂)
(sep : l.All fun x => r.All fun y => x < y) (bal : BalancedSz (size l) (size r)) :
Valid' o₁ (@glue α l r) o₂ ∧ size (glue l r) = size l + size r := by
obtain - | ⟨ls, ll, lx, lr⟩ := l; · exact ⟨hr, (zero_add _).symm⟩
obtain - | ⟨rs, rl, rx, rr⟩ := r; · exact ⟨hl, rfl⟩
dsimp [glue]; split_ifs
· rw [splitMax_eq]
· obtain ⟨v, e⟩ := Valid'.eraseMax_aux hl
suffices H : _ by
refine ⟨Valid'.balanceR v (hr.of_gt ?_ ?_) H, ?_⟩
· refine findMax'_all (P := fun a : α => Bounded nil (a : WithTop α) o₂)
lx lr hl.1.2.to_nil (sep.2.2.imp ?_)
exact fun x h => hr.1.2.to_nil.mono_left (le_of_lt h.2.1)
· exact @findMax'_all _ (fun a => All (· > a) (.node rs rl rx rr)) lx lr sep.2.1 sep.2.2
· rw [size_balanceR v.3 hr.3 v.2 hr.2 H, add_right_comm, ← e, hl.2.1]; rfl
refine Or.inl ⟨_, Or.inr e, ?_⟩
rwa [hl.2.eq_node'] at bal
· rw [splitMin_eq]
· obtain ⟨v, e⟩ := Valid'.eraseMin_aux hr
suffices H : _ by
refine ⟨Valid'.balanceL (hl.of_lt ?_ ?_) v H, ?_⟩
· refine @findMin'_all (P := fun a : α => Bounded nil o₁ (a : WithBot α))
_ rl rx (sep.2.1.1.imp ?_) hr.1.1.to_nil
exact fun y h => hl.1.1.to_nil.mono_right (le_of_lt h)
· exact
@findMin'_all _ (fun a => All (· < a) (.node ls ll lx lr)) rl rx
(all_iff_forall.2 fun x hx => sep.imp fun y hy => all_iff_forall.1 hy.1 _ hx)
(sep.imp fun y hy => hy.2.1)
· rw [size_balanceL hl.3 v.3 hl.2 v.2 H, add_assoc, ← e, hr.2.1]; rfl
refine Or.inr ⟨_, Or.inr e, ?_⟩
rwa [hr.2.eq_node'] at bal
theorem Valid'.glue {l} {x : α} {r o₁ o₂} (hl : Valid' o₁ l x) (hr : Valid' x r o₂) :
BalancedSz (size l) (size r) →
Valid' o₁ (@glue α l r) o₂ ∧ size (@glue α l r) = size l + size r :=
Valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1)
theorem Valid'.merge_lemma {a b c : ℕ} (h₁ : 3 * a < b + c + 1) (h₂ : b ≤ 3 * c) :
2 * (a + b) ≤ 9 * c + 5 := by cutsat
theorem Valid'.merge_aux₁ {o₁ o₂ ls ll lx lr rs rl rx rr t}
(hl : Valid' o₁ (@Ordnode.node α ls ll lx lr) o₂) (hr : Valid' o₁ (.node rs rl rx rr) o₂)
(h : delta * ls < rs) (v : Valid' o₁ t rx) (e : size t = ls + size rl) :
Valid' o₁ (.balanceL t rx rr) o₂ ∧ size (.balanceL t rx rr) = ls + rs := by
rw [hl.2.1] at e
rw [hl.2.1, hr.2.1, delta] at h
rcases hr.3.1 with (H | ⟨hr₁, hr₂⟩); · cutsat
suffices H₂ : _ by
suffices H₁ : _ by
refine ⟨Valid'.balanceL_aux v hr.right H₁ H₂ ?_, ?_⟩
· rw [e]; exact Or.inl (Valid'.merge_lemma h hr₁)
· rw [balanceL_eq_balance v.2 hr.2.2.2 H₁ H₂, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2,
size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1]
abel
· rw [e, add_right_comm]; rintro ⟨⟩
intro _ _; rw [e]; unfold delta at hr₂ ⊢; cutsat
theorem Valid'.merge_aux {l r o₁ o₂} (hl : Valid' o₁ l o₂) (hr : Valid' o₁ r o₂)
(sep : l.All fun x => r.All fun y => x < y) :
Valid' o₁ (@merge α l r) o₂ ∧ size (merge l r) = size l + size r := by
induction l generalizing o₁ o₂ r with
| nil => exact ⟨hr, (zero_add _).symm⟩
| node ls ll lx lr _ IHlr => ?_
induction r generalizing o₁ o₂ with
| nil => exact ⟨hl, rfl⟩
| node rs rl rx rr IHrl _ => ?_
rw [merge_node]; split_ifs with h h_1
· obtain ⟨v, e⟩ := IHrl (hl.of_lt hr.1.1.to_nil <| sep.imp fun x h => h.2.1) hr.left
(sep.imp fun x h => h.1)
exact Valid'.merge_aux₁ hl hr h v e
· obtain ⟨v, e⟩ := IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2
have := Valid'.merge_aux₁ hr.dual hl.dual h_1 v.dual
rw [size_dual, add_comm, size_dual, ← dual_balanceR, ← Valid'.dual_iff, size_dual,
add_comm rs] at this
exact this e
· refine Valid'.glue_aux hl hr sep (Or.inr ⟨not_lt.1 h_1, not_lt.1 h⟩)
theorem Valid.merge {l r} (hl : Valid l) (hr : Valid r)
(sep : l.All fun x => r.All fun y => x < y) : Valid (@merge α l r) :=
(Valid'.merge_aux hl hr sep).1
theorem insertWith.valid_aux [IsTotal α (· ≤ ·)] [DecidableLE α] (f : α → α) (x : α)
(hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) :
∀ {t o₁ o₂},
Valid' o₁ t o₂ →
Bounded nil o₁ x →
Bounded nil x o₂ →
Valid' o₁ (insertWith f x t) o₂ ∧ Raised (size t) (size (insertWith f x t))
| nil, _, _, _, bl, br => ⟨valid'_singleton bl br, Or.inr rfl⟩
| node sz l y r, o₁, o₂, h, bl, br => by
rw [insertWith, cmpLE]
split_ifs with h_1 h_2 <;> dsimp only
· rcases h with ⟨⟨lx, xr⟩, hs, hb⟩
rcases hf _ ⟨h_1, h_2⟩ with ⟨xf, fx⟩
refine
⟨⟨⟨lx.mono_right (le_trans h_2 xf), xr.mono_left (le_trans fx h_1)⟩, hs, hb⟩, Or.inl rfl⟩
· rcases insertWith.valid_aux f x hf h.left bl (lt_of_le_not_ge h_1 h_2) with ⟨vl, e⟩
suffices H : _ by
refine ⟨vl.balanceL h.right H, ?_⟩
rw [size_balanceL vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq]
exact (e.add_right _).add_right _
exact Or.inl ⟨_, e, h.3.1⟩
· have : y < x := lt_of_le_not_ge ((total_of (· ≤ ·) _ _).resolve_left h_1) h_1
rcases insertWith.valid_aux f x hf h.right this br with ⟨vr, e⟩
suffices H : _ by
refine ⟨h.left.balanceR vr H, ?_⟩
rw [size_balanceR h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq]
exact (e.add_left _).add_right _
exact Or.inr ⟨_, e, h.3.1⟩
theorem insertWith.valid [IsTotal α (· ≤ ·)] [DecidableLE α] (f : α → α) (x : α)
(hf : ∀ y, x ≤ y ∧ y ≤ x → x ≤ f y ∧ f y ≤ x) {t} (h : Valid t) : Valid (insertWith f x t) :=
(insertWith.valid_aux _ _ hf h ⟨⟩ ⟨⟩).1
theorem insert_eq_insertWith [DecidableLE α] (x : α) :
∀ t, Ordnode.insert x t = insertWith (fun _ => x) x t
| nil => rfl
| node _ l y r => by
unfold Ordnode.insert insertWith; cases cmpLE x y <;> simp [insert_eq_insertWith]
theorem insert.valid [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) {t} (h : Valid t) :
Valid (Ordnode.insert x t) := by
rw [insert_eq_insertWith]; exact insertWith.valid _ _ (fun _ _ => ⟨le_rfl, le_rfl⟩) h
theorem insert'_eq_insertWith [DecidableLE α] (x : α) :
∀ t, insert' x t = insertWith id x t
| nil => rfl
| node _ l y r => by
unfold insert' insertWith; cases cmpLE x y <;> simp [insert'_eq_insertWith]
theorem insert'.valid [IsTotal α (· ≤ ·)] [DecidableLE α]
(x : α) {t} (h : Valid t) : Valid (insert' x t) := by
rw [insert'_eq_insertWith]; exact insertWith.valid _ _ (fun _ => id) h
theorem Valid'.map_aux {β} [Preorder β] {f : α → β} (f_strict_mono : StrictMono f) {t a₁ a₂}
(h : Valid' a₁ t a₂) :
Valid' (Option.map f a₁) (map f t) (Option.map f a₂) ∧ (map f t).size = t.size := by
induction t generalizing a₁ a₂ with
| nil =>
simp only [map, size_nil, and_true]; apply valid'_nil
cases a₁; · trivial
cases a₂; · trivial
simp only [Option.map, Bounded]
exact f_strict_mono h.ord
| node _ _ _ _ t_ih_l t_ih_r =>
have t_ih_l' := t_ih_l h.left
have t_ih_r' := t_ih_r h.right
clear t_ih_l t_ih_r
obtain ⟨t_l_valid, t_l_size⟩ := t_ih_l'
obtain ⟨t_r_valid, t_r_size⟩ := t_ih_r'
simp only [map, size_node, and_true]
constructor
· exact And.intro t_l_valid.ord t_r_valid.ord
· constructor
· rw [t_l_size, t_r_size]; exact h.sz.1
· constructor
· exact t_l_valid.sz
· exact t_r_valid.sz
· constructor
· rw [t_l_size, t_r_size]; exact h.bal.1
· constructor
· exact t_l_valid.bal
· exact t_r_valid.bal
theorem map.valid {β} [Preorder β] {f : α → β} (f_strict_mono : StrictMono f) {t} (h : Valid t) :
Valid (map f t) :=
(Valid'.map_aux f_strict_mono h).1
theorem Valid'.erase_aux [DecidableLE α] (x : α) {t a₁ a₂} (h : Valid' a₁ t a₂) :
Valid' a₁ (erase x t) a₂ ∧ Raised (erase x t).size t.size := by
induction t generalizing a₁ a₂ with
| nil =>
simpa [erase, Raised]
| node _ t_l t_x t_r t_ih_l t_ih_r =>
simp only [erase, size_node]
have t_ih_l' := t_ih_l h.left
have t_ih_r' := t_ih_r h.right
clear t_ih_l t_ih_r
obtain ⟨t_l_valid, t_l_size⟩ := t_ih_l'
obtain ⟨t_r_valid, t_r_size⟩ := t_ih_r'
cases cmpLE x t_x <;> rw [h.sz.1]
· suffices h_balanceable : _ by
constructor
· exact Valid'.balanceR t_l_valid h.right h_balanceable
· rw [size_balanceR t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable]
repeat apply Raised.add_right
exact t_l_size
left; exists t_l.size; exact And.intro t_l_size h.bal.1
· have h_glue := Valid'.glue h.left h.right h.bal.1
obtain ⟨h_glue_valid, h_glue_sized⟩ := h_glue
constructor
· exact h_glue_valid
· right; rw [h_glue_sized]
· suffices h_balanceable : _ by
constructor
· exact Valid'.balanceL h.left t_r_valid h_balanceable
· rw [size_balanceL h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable]
apply Raised.add_right
apply Raised.add_left
exact t_r_size
right; exists t_r.size; exact And.intro t_r_size h.bal.1
theorem erase.valid [DecidableLE α] (x : α) {t} (h : Valid t) : Valid (erase x t) :=
(Valid'.erase_aux x h).1
theorem size_erase_of_mem [DecidableLE α] {x : α} {t a₁ a₂} (h : Valid' a₁ t a₂)
(h_mem : x ∈ t) : size (erase x t) = size t - 1 := by
induction t generalizing a₁ a₂ with
| nil =>
contradiction
| node _ t_l t_x t_r t_ih_l t_ih_r =>
have t_ih_l' := t_ih_l h.left
have t_ih_r' := t_ih_r h.right
clear t_ih_l t_ih_r
dsimp only [Membership.mem, mem] at h_mem
unfold erase
revert h_mem; cases cmpLE x t_x <;> intro h_mem <;> dsimp only at h_mem ⊢
· have t_ih_l := t_ih_l' h_mem
clear t_ih_l' t_ih_r'
have t_l_h := Valid'.erase_aux x h.left
obtain ⟨t_l_valid, t_l_size⟩ := t_l_h
rw [size_balanceR t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz
(Or.inl (Exists.intro t_l.size (And.intro t_l_size h.bal.1)))]
rw [t_ih_l, h.sz.1]
have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem
revert h_pos_t_l_size; rcases t_l.size with - | t_l_size <;> intro h_pos_t_l_size
· cases h_pos_t_l_size
· simp [Nat.add_right_comm]
· rw [(Valid'.glue h.left h.right h.bal.1).2, h.sz.1]; rfl
· have t_ih_r := t_ih_r' h_mem
clear t_ih_l' t_ih_r'
have t_r_h := Valid'.erase_aux x h.right
obtain ⟨t_r_valid, t_r_size⟩ := t_r_h
rw [size_balanceL h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz
(Or.inr (Exists.intro t_r.size (And.intro t_r_size h.bal.1)))]
rw [t_ih_r, h.sz.1]
have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem
revert h_pos_t_r_size; rcases t_r.size with - | t_r_size <;> intro h_pos_t_r_size
· cases h_pos_t_r_size
· simp [Nat.add_assoc]
end Valid
end Ordnode
/-- An `Ordset α` is a finite set of values, represented as a tree. The operations on this type
maintain that the tree is balanced and correctly stores subtree sizes at each level. The
correctness property of the tree is baked into the type, so all operations on this type are correct
by construction. -/
def Ordset (α : Type*) [Preorder α] :=
{ t : Ordnode α // t.Valid }
namespace Ordset
open Ordnode
variable [Preorder α]
/-- O(1). The empty set. -/
nonrec def nil : Ordset α :=
⟨nil, ⟨⟩, ⟨⟩, ⟨⟩⟩
/-- O(1). Get the size of the set. -/
def size (s : Ordset α) : ℕ :=
s.1.size
/-- O(1). Construct a singleton set containing value `a`. -/
protected def singleton (a : α) : Ordset α :=
⟨singleton a, valid_singleton⟩
instance instEmptyCollection : EmptyCollection (Ordset α) :=
⟨nil⟩
instance instInhabited : Inhabited (Ordset α) :=
⟨nil⟩
instance instSingleton : Singleton α (Ordset α) :=
⟨Ordset.singleton⟩
/-- O(1). Is the set empty? -/
def Empty (s : Ordset α) : Prop :=
s = ∅
theorem empty_iff {s : Ordset α} : s = ∅ ↔ s.1.empty :=
⟨fun h => by cases h; exact rfl,
fun h => by cases s with | mk s_val _ => cases s_val <;> [rfl; cases h]⟩
instance Empty.instDecidablePred : DecidablePred (@Empty α _) :=
fun _ => decidable_of_iff' _ empty_iff
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, this replaces it. -/
protected def insert [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) (s : Ordset α) :
Ordset α :=
⟨Ordnode.insert x s.1, insert.valid _ s.2⟩
instance instInsert [IsTotal α (· ≤ ·)] [DecidableLE α] : Insert α (Ordset α) :=
⟨Ordset.insert⟩
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, the set is returned as is. -/
nonrec def insert' [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) (s : Ordset α) :
Ordset α :=
⟨insert' x s.1, insert'.valid _ s.2⟩
section
variable [DecidableLE α]
/-- O(log n). Does the set contain the element `x`? That is,
is there an element that is equivalent to `x` in the order? -/
def mem (x : α) (s : Ordset α) : Bool :=
x ∈ s.val
/-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order,
if it exists. -/
def find (x : α) (s : Ordset α) : Option α :=
Ordnode.find x s.val
instance instMembership : Membership α (Ordset α) :=
⟨fun s x => mem x s⟩
instance mem.decidable (x : α) (s : Ordset α) : Decidable (x ∈ s) :=
instDecidableEqBool _ _
theorem pos_size_of_mem {x : α} {t : Ordset α} (h_mem : x ∈ t) : 0 < size t := by
simp only [Membership.mem, mem, Bool.decide_eq_true] at h_mem
apply Ordnode.pos_size_of_mem t.property.sz h_mem
end
/-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there
is no such element. -/
def erase [DecidableLE α] (x : α) (s : Ordset α) : Ordset α :=
⟨Ordnode.erase x s.val, Ordnode.erase.valid x s.property⟩
/-- O(n). Map a function across a tree, without changing the structure. -/
def map {β} [Preorder β] (f : α → β) (f_strict_mono : StrictMono f) (s : Ordset α) : Ordset β :=
⟨Ordnode.map f s.val, Ordnode.map.valid f_strict_mono s.property⟩
end Ordset |
.lake/packages/mathlib/Mathlib/Data/Ordmap/Ordnode.lean | import Mathlib.Order.Compare
import Mathlib.Data.Nat.PSub
import Mathlib.Data.Option.Basic
/-!
# Ordered sets
This file defines a data structure for ordered sets, supporting a
variety of useful operations including insertion and deletion,
logarithmic time lookup, set operations, folds,
and conversion from lists.
The `Ordnode α` operations all assume that `α` has the structure of
a total preorder, meaning a `≤` operation that is
* Transitive: `x ≤ y → y ≤ z → x ≤ z`
* Reflexive: `x ≤ x`
* Total: `x ≤ y ∨ y ≤ x`
For example, in order to use this data structure as a map type, one
can store pairs `(k, v)` where `(k, v) ≤ (k', v')` is defined to mean
`k ≤ k'` (assuming that the key values are linearly ordered).
Two values `x,y` are equivalent if `x ≤ y` and `y ≤ x`. An `Ordnode α`
maintains the invariant that it never stores two equivalent nodes;
the insertion operation comes with two variants depending on whether
you want to keep the old value or the new value in case you insert a value
that is equivalent to one in the set.
The operations in this file are not verified, in the sense that they provide
"raw operations" that work for programming purposes but the invariants
are not explicitly in the structure. See `Ordset` for a verified version
of this data structure.
## Main definitions
* `Ordnode α`: A set of values of type `α`
## Implementation notes
Based on weight balanced trees:
* Stephen Adams, "Efficient sets: a balancing act",
Journal of Functional Programming 3(4):553-562, October 1993,
<http://www.swiss.ai.mit.edu/~adams/BB/>.
* J. Nievergelt and E.M. Reingold,
"Binary search trees of bounded balance",
SIAM journal of computing 2(1), March 1973.
Ported from Haskell's `Data.Set`.
## Tags
ordered map, ordered set, data structure
-/
universe u
/-- An `Ordnode α` is a finite set of values, represented as a tree.
The operations on this type maintain that the tree is balanced
and correctly stores subtree sizes at each level. -/
inductive Ordnode (α : Type u) : Type u
| nil : Ordnode α
| node (size : ℕ) (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α
compile_inductive% Ordnode
namespace Ordnode
variable {α : Type*}
instance : EmptyCollection (Ordnode α) :=
⟨nil⟩
instance : Inhabited (Ordnode α) :=
⟨nil⟩
/-- **Internal use only**
The maximal relative difference between the sizes of
two trees, it corresponds with the `w` in Adams' paper.
According to the Haskell comment, only `(delta, ratio)` settings
of `(3, 2)` and `(4, 2)` will work, and the proofs in
`Ordset.lean` assume `delta := 3` and `ratio := 2`. -/
@[inline]
def delta :=
3
/-- **Internal use only**
The ratio between an outer and inner sibling of the
heavier subtree in an unbalanced setting. It determines
whether a double or single rotation should be performed
to restore balance. It is corresponds with the inverse
of `α` in Adam's article. -/
@[inline]
def ratio :=
2
/-- O(1). Construct a singleton set containing value `a`.
singleton 3 = {3} -/
@[inline]
protected def singleton (a : α) : Ordnode α :=
node 1 nil a nil
local prefix:arg "ι" => Ordnode.singleton
instance : Singleton α (Ordnode α) :=
⟨Ordnode.singleton⟩
/-- O(1). Get the size of the set.
`size {2, 1, 1, 4} = 3` -/
@[inline]
def size : Ordnode α → ℕ
| nil => 0
| node sz _ _ _ => sz
@[simp] theorem size_nil : size (nil : Ordnode α) = 0 :=
rfl
@[simp] theorem size_node (sz : ℕ) (l : Ordnode α) (x : α) (r : Ordnode α) :
size (node sz l x r) = sz :=
rfl
/-- O(1). Is the set empty?
empty ∅ = tt
empty {1, 2, 3} = ff -/
@[inline]
def empty : Ordnode α → Bool
| nil => true
| node _ _ _ _ => false
/-- **Internal use only**, because it violates the BST property on the original order.
O(n). The dual of a tree is a tree with its left and right sides reversed throughout.
The dual of a valid BST is valid under the dual order. This is convenient for exploiting
symmetries in the algorithms. -/
@[simp]
def dual : Ordnode α → Ordnode α
| nil => nil
| node s l x r => node s (dual r) x (dual l)
/-- **Internal use only**
O(1). Construct a node with the correct size information, without rebalancing. -/
@[inline, reducible]
def node' (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α :=
node (size l + size r + 1) l x r
/-- Basic pretty printing for `Ordnode α` that shows the structure of the tree.
repr {3, 1, 2, 4} = ((∅ 1 ∅) 2 ((∅ 3 ∅) 4 ∅)) -/
def repr {α} [Repr α] (o : Ordnode α) (n : ℕ) : Std.Format :=
match o with
| nil => (Std.Format.text "∅")
| node _ l x r =>
let fmt := Std.Format.joinSep
[repr l n, Repr.reprPrec x n, repr r n]
" "
Std.Format.paren fmt
instance {α} [Repr α] : Repr (Ordnode α) :=
⟨repr⟩
-- Note: The function has been written with tactics to avoid extra junk
/-- **Internal use only**
O(1). Rebalance a tree which was previously balanced but has had its left
side grow by 1, or its right side shrink by 1. -/
def balanceL (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α := by
rcases id r with _ | rs
· rcases id l with _ | ⟨ls, ll, lx, lr⟩
· exact ι x
· rcases id ll with _ | lls
· rcases lr with _ | ⟨_, _, lrx⟩
· exact node 2 l x nil
· exact node 3 (ι lx) lrx ι x
· rcases id lr with _ | ⟨lrs, lrl, lrx, lrr⟩
· exact node 3 ll lx ι x
· exact
if lrs < ratio * lls then node (ls + 1) ll lx (node (lrs + 1) lr x nil)
else
node (ls + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + 1) lrr x nil)
· rcases id l with _ | ⟨ls, ll, lx, lr⟩
· exact node (rs + 1) nil x r
· refine if ls > delta * rs then ?_ else node (ls + rs + 1) l x r
rcases id ll with _ | lls
· exact nil
--should not happen
rcases id lr with _ | ⟨lrs, lrl, lrx, lrr⟩
· exact nil
--should not happen
exact
if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (rs + lrs + 1) lr x r)
else
node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + rs + 1) lrr x r)
/-- **Internal use only**
O(1). Rebalance a tree which was previously balanced but has had its right
side grow by 1, or its left side shrink by 1. -/
def balanceR (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α := by
rcases id l with _ | ls
· rcases id r with _ | ⟨rs, rl, rx, rr⟩
· exact ι x
· rcases id rr with _ | rrs
· rcases rl with _ | ⟨_, _, rlx⟩
· exact node 2 nil x r
· exact node 3 (ι x) rlx ι rx
· rcases id rl with _ | ⟨rls, rll, rlx, rlr⟩
· exact node 3 (ι x) rx rr
· exact
if rls < ratio * rrs then node (rs + 1) (node (rls + 1) nil x rl) rx rr
else
node (rs + 1) (node (size rll + 1) nil x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
· rcases id r with _ | ⟨rs, rl, rx, rr⟩
· exact node (ls + 1) l x nil
· refine if rs > delta * ls then ?_ else node (ls + rs + 1) l x r
rcases id rr with _ | rrs
· exact nil
--should not happen
rcases id rl with _ | ⟨rls, rll, rlx, rlr⟩
· exact nil
--should not happen
exact
if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr
else
node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
/-- **Internal use only**
O(1). Rebalance a tree which was previously balanced but has had one side change
by at most 1. -/
def balance (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α := by
rcases id l with _ | ⟨ls, ll, lx, lr⟩
· rcases id r with _ | ⟨rs, rl, rx, rr⟩
· exact ι x
· rcases id rl with _ | ⟨rls, rll, rlx, rlr⟩
· cases id rr
· exact node 2 nil x r
· exact node 3 (ι x) rx rr
· rcases id rr with _ | rrs
· exact node 3 (ι x) rlx ι rx
· exact
if rls < ratio * rrs then node (rs + 1) (node (rls + 1) nil x rl) rx rr
else
node (rs + 1) (node (size rll + 1) nil x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
· rcases id r with _ | ⟨rs, rl, rx, rr⟩
· rcases id ll with _ | lls
· rcases lr with _ | ⟨_, _, lrx⟩
· exact node 2 l x nil
· exact node 3 (ι lx) lrx ι x
· rcases id lr with _ | ⟨lrs, lrl, lrx, lrr⟩
· exact node 3 ll lx ι x
· exact
if lrs < ratio * lls then node (ls + 1) ll lx (node (lrs + 1) lr x nil)
else
node (ls + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + 1) lrr x nil)
· refine
if delta * ls < rs then ?_ else if delta * rs < ls then ?_ else node (ls + rs + 1) l x r
· rcases id rl with _ | ⟨rls, rll, rlx, rlr⟩
· exact nil
--should not happen
rcases id rr with _ | rrs
· exact nil
--should not happen
exact
if rls < ratio * rrs then node (ls + rs + 1) (node (ls + rls + 1) l x rl) rx rr
else
node (ls + rs + 1) (node (ls + size rll + 1) l x rll) rlx
(node (size rlr + rrs + 1) rlr rx rr)
· rcases id ll with _ | lls
· exact nil
--should not happen
rcases id lr with _ | ⟨lrs, lrl, lrx, lrr⟩
· exact nil
--should not happen
exact
if lrs < ratio * lls then node (ls + rs + 1) ll lx (node (lrs + rs + 1) lr x r)
else
node (ls + rs + 1) (node (lls + size lrl + 1) ll lx lrl) lrx
(node (size lrr + rs + 1) lrr x r)
/-- O(n). Does every element of the map satisfy property `P`?
All (fun x ↦ x < 5) {1, 2, 3} = True
All (fun x ↦ x < 5) {1, 2, 3, 5} = False -/
def All (P : α → Prop) : Ordnode α → Prop
| nil => True
| node _ l x r => All P l ∧ P x ∧ All P r
instance All.decidable {P : α → Prop} : (t : Ordnode α) → [DecidablePred P] → Decidable (All P t)
| nil => isTrue trivial
| node _ l m r =>
have : Decidable (All P l) := All.decidable l
have : Decidable (All P r) := All.decidable r
inferInstanceAs <| Decidable (All P l ∧ P m ∧ All P r)
/-- O(n). Does any element of the map satisfy property `P`?
Any (fun x ↦ x < 2) {1, 2, 3} = True
Any (fun x ↦ x < 2) {2, 3, 5} = False -/
def Any (P : α → Prop) : Ordnode α → Prop
| nil => False
| node _ l x r => Any P l ∨ P x ∨ Any P r
instance Any.decidable {P : α → Prop} : (t : Ordnode α) → [DecidablePred P] → Decidable (Any P t)
| nil => isFalse id
| node _ l m r =>
have : Decidable (Any P l) := Any.decidable l
have : Decidable (Any P r) := Any.decidable r
inferInstanceAs <| Decidable (Any P l ∨ P m ∨ Any P r)
/-- O(n). Exact membership in the set. This is useful primarily for stating
correctness properties; use `∈` for a version that actually uses the BST property
of the tree.
Emem 2 {1, 2, 3} = true
Emem 4 {1, 2, 3} = false -/
def Emem (x : α) : Ordnode α → Prop :=
Any (Eq x)
instance Emem.decidable (x : α) [DecidableEq α] : ∀ t, Decidable (Emem x t) := by
dsimp [Emem]; infer_instance
/-- O(n). Approximate membership in the set, that is, whether some element in the
set is equivalent to this one in the preorder. This is useful primarily for stating
correctness properties; use `∈` for a version that actually uses the BST property
of the tree.
Amem 2 {1, 2, 3} = true
Amem 4 {1, 2, 3} = false
To see the difference with `Emem`, we need a preorder that is not a partial order.
For example, suppose we compare pairs of numbers using only their first coordinate. Then:
-- TODO: Verify below example
Emem (0, 1) {(0, 0), (1, 2)} = false
Amem (0, 1) {(0, 0), (1, 2)} = true
(0, 1) ∈ {(0, 0), (1, 2)} = true
The `∈` relation is equivalent to `Amem` as long as the `Ordnode` is well formed,
and should always be used instead of `Amem`. -/
def Amem [LE α] (x : α) : Ordnode α → Prop :=
Any fun y => x ≤ y ∧ y ≤ x
instance Amem.decidable [LE α] [DecidableLE α] (x : α) : ∀ t, Decidable (Amem x t) := by
dsimp [Amem]; infer_instance
/-- O(log n). Return the minimum element of the tree, or the provided default value.
findMin' 37 {1, 2, 3} = 1
findMin' 37 ∅ = 37 -/
def findMin' : Ordnode α → α → α
| nil, x => x
| node _ l x _, _ => findMin' l x
/-- O(log n). Return the minimum element of the tree, if it exists.
findMin {1, 2, 3} = some 1
findMin ∅ = none -/
def findMin : Ordnode α → Option α
| nil => none
| node _ l x _ => some (findMin' l x)
/-- O(log n). Return the maximum element of the tree, or the provided default value.
findMax' 37 {1, 2, 3} = 3
findMax' 37 ∅ = 37 -/
def findMax' : α → Ordnode α → α
| x, nil => x
| _, node _ _ x r => findMax' x r
/-- O(log n). Return the maximum element of the tree, if it exists.
findMax {1, 2, 3} = some 3
findMax ∅ = none -/
def findMax : Ordnode α → Option α
| nil => none
| node _ _ x r => some (findMax' x r)
/-- O(log n). Remove the minimum element from the tree, or do nothing if it is already empty.
eraseMin {1, 2, 3} = {2, 3}
eraseMin ∅ = ∅ -/
def eraseMin : Ordnode α → Ordnode α
| nil => nil
| node _ nil _ r => r
| node _ (node sz l' y r') x r => balanceR (eraseMin (node sz l' y r')) x r
/-- O(log n). Remove the maximum element from the tree, or do nothing if it is already empty.
eraseMax {1, 2, 3} = {1, 2}
eraseMax ∅ = ∅ -/
def eraseMax : Ordnode α → Ordnode α
| nil => nil
| node _ l _ nil => l
| node _ l x (node sz l' y r') => balanceL l x (eraseMax (node sz l' y r'))
/-- **Internal use only**, because it requires a balancing constraint on the inputs.
O(log n). Extract and remove the minimum element from a nonempty tree. -/
def splitMin' : Ordnode α → α → Ordnode α → α × Ordnode α
| nil, x, r => (x, r)
| node _ ll lx lr, x, r =>
let (xm, l') := splitMin' ll lx lr
(xm, balanceR l' x r)
/-- O(log n). Extract and remove the minimum element from the tree, if it exists.
split_min {1, 2, 3} = some (1, {2, 3})
split_min ∅ = none -/
def splitMin : Ordnode α → Option (α × Ordnode α)
| nil => none
| node _ l x r => splitMin' l x r
/-- **Internal use only**, because it requires a balancing constraint on the inputs.
O(log n). Extract and remove the maximum element from a nonempty tree. -/
def splitMax' : Ordnode α → α → Ordnode α → Ordnode α × α
| l, x, nil => (l, x)
| l, x, node _ rl rx rr =>
let (r', xm) := splitMax' rl rx rr
(balanceL l x r', xm)
/-- O(log n). Extract and remove the maximum element from the tree, if it exists.
split_max {1, 2, 3} = some ({1, 2}, 3)
split_max ∅ = none -/
def splitMax : Ordnode α → Option (Ordnode α × α)
| nil => none
| node _ x l r => splitMax' x l r
/-- **Internal use only**
O(log(m + n)). Concatenate two trees that are balanced and ordered with respect to each other. -/
def glue : Ordnode α → Ordnode α → Ordnode α
| nil, r => r
| l@(node _ _ _ _), nil => l
| l@(node sl ll lx lr), r@(node sr rl rx rr) =>
if sl > sr then
let (l', m) := splitMax' ll lx lr
balanceR l' m r
else
let (m, r') := splitMin' rl rx rr
balanceL l m r'
/-- O(log(m + n)). Concatenate two trees that are ordered with respect to each other.
merge {1, 2} {3, 4} = {1, 2, 3, 4}
merge {3, 4} {1, 2} = precondition violation -/
def merge (l : Ordnode α) : Ordnode α → Ordnode α :=
(Ordnode.recOn (motive := fun _ => Ordnode α → Ordnode α) l fun r => r)
fun ls ll lx lr _ IHlr r =>
(Ordnode.recOn (motive := fun _ => Ordnode α) r (node ls ll lx lr))
fun rs rl rx rr IHrl _ =>
if delta * ls < rs then balanceL IHrl rx rr
else
if delta * rs < ls then balanceR ll lx (IHlr <| node rs rl rx rr)
else glue (node ls ll lx lr) (node rs rl rx rr)
/-- O(log n). Insert an element above all the others, without any comparisons.
(Assumes that the element is in fact above all the others).
insertMax {1, 2} 4 = {1, 2, 4}
insertMax {1, 2} 0 = precondition violation -/
def insertMax : Ordnode α → α → Ordnode α
| nil, x => ι x
| node _ l y r, x => balanceR l y (insertMax r x)
/-- O(log n). Insert an element below all the others, without any comparisons.
(Assumes that the element is in fact below all the others).
insertMin {1, 2} 0 = {0, 1, 2}
insertMin {1, 2} 4 = precondition violation -/
def insertMin (x : α) : Ordnode α → Ordnode α
| nil => ι x
| node _ l y r => balanceR (insertMin x l) y r
/-- O(log(m+n)). Build a tree from an element between two trees, without any
assumption on the relative sizes.
link {1, 2} 4 {5, 6} = {1, 2, 4, 5, 6}
link {1, 3} 2 {5} = precondition violation -/
def link (l : Ordnode α) (x : α) : Ordnode α → Ordnode α :=
match l with
| nil => insertMin x
| node ls ll lx lr => fun r ↦
match r with
| nil => insertMax l x
| node rs rl rx rr =>
if delta * ls < rs then balanceL (link ll x rl) rx rr
else if delta * rs < ls then balanceR ll lx (link lr x rr)
else node' l x r
/-- O(n). Filter the elements of a tree satisfying a predicate.
filter (fun x ↦ x < 3) {1, 2, 4} = {1, 2}
filter (fun x ↦ x > 5) {1, 2, 4} = ∅ -/
def filter (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α
| nil => nil
| node _ l x r => if p x then
link (filter p l) x (filter p r) else
merge (filter p l) (filter p r)
/-- O(n). Split the elements of a tree into those satisfying, and not satisfying, a predicate.
partition (fun x ↦ x < 3) {1, 2, 4} = ({1, 2}, {3}) -/
def partition (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α × Ordnode α
| nil => (nil, nil)
| node _ l x r =>
let (l₁, l₂) := partition p l
let (r₁, r₂) := partition p r
if p x then (link l₁ x r₁, merge l₂ r₂) else (merge l₁ r₁, link l₂ x r₂)
/-- O(n). Map a function across a tree, without changing the structure. Only valid when
the function is strictly monotone, i.e. `x < y → f x < f y`.
partition (fun x ↦ x + 2) {1, 2, 4} = {2, 3, 6}
partition (fun x : ℕ ↦ x - 2) {1, 2, 4} = precondition violation -/
def map {β} (f : α → β) : Ordnode α → Ordnode β
| nil => nil
| node s l x r => node s (map f l) (f x) (map f r)
/-- O(n). Fold a function across the structure of a tree.
fold z f {1, 2, 4} = f (f z 1 z) 2 (f z 4 z)
The exact structure of function applications depends on the tree and so
is unspecified. -/
def fold {β} (z : β) (f : β → α → β → β) : Ordnode α → β
| nil => z
| node _ l x r => f (fold z f l) x (fold z f r)
/-- O(n). Fold a function from left to right (in increasing order) across the tree.
foldl f z {1, 2, 4} = f (f (f z 1) 2) 4 -/
def foldl {β} (f : β → α → β) : β → Ordnode α → β
| z, nil => z
| z, node _ l x r => foldl f (f (foldl f z l) x) r
/-- O(n). Fold a function from right to left (in decreasing order) across the tree.
foldr f {1, 2, 4} z = f 1 (f 2 (f 4 z)) -/
def foldr {β} (f : α → β → β) : Ordnode α → β → β
| nil, z => z
| node _ l x r, z => foldr f l (f x (foldr f r z))
/-- O(n). Build a list of elements in ascending order from the tree.
toList {1, 2, 4} = [1, 2, 4]
toList {2, 1, 1, 4} = [1, 2, 4] -/
def toList (t : Ordnode α) : List α :=
foldr List.cons t []
/-- O(n). Build a list of elements in descending order from the tree.
toRevList {1, 2, 4} = [4, 2, 1]
toRevList {2, 1, 1, 4} = [4, 2, 1] -/
def toRevList (t : Ordnode α) : List α :=
foldl (flip List.cons) [] t
instance [ToString α] : ToString (Ordnode α) :=
⟨fun t => "{" ++ String.intercalate ", " (t.toList.map toString) ++ "}"⟩
instance [Std.ToFormat α] : Std.ToFormat (Ordnode α) where
format := fun t => Std.Format.joinSep (t.toList.map Std.ToFormat.format) (Std.Format.text ", ")
/-- O(n). True if the trees have the same elements, ignoring structural differences.
Equiv {1, 2, 4} {2, 1, 1, 4} = true
Equiv {1, 2, 4} {1, 2, 3} = false -/
def Equiv (t₁ t₂ : Ordnode α) : Prop :=
t₁.size = t₂.size ∧ t₁.toList = t₂.toList
instance [DecidableEq α] : DecidableRel (@Equiv α) := fun x y =>
inferInstanceAs (Decidable (x.size = y.size ∧ x.toList = y.toList))
/-- O(2^n). Constructs the powerset of a given set, that is, the set of all subsets.
powerset {1, 2, 3} = {∅, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} -/
def powerset (t : Ordnode α) : Ordnode (Ordnode α) :=
insertMin nil <| foldr (fun x ts => glue (insertMin (ι x) (map (insertMin x) ts)) ts) t nil
/-- O(m * n). The Cartesian product of two sets: `(a, b) ∈ s.prod t` iff `a ∈ s` and `b ∈ t`.
prod {1, 2} {2, 3} = {(1, 2), (1, 3), (2, 2), (2, 3)} -/
protected def prod {β} (t₁ : Ordnode α) (t₂ : Ordnode β) : Ordnode (α × β) :=
fold nil (fun s₁ a s₂ => merge s₁ <| merge (map (Prod.mk a) t₂) s₂) t₁
/-- O(m + n). Build a set on the disjoint union by combining sets on the factors.
`Or.inl a ∈ s.copair t` iff `a ∈ s`, and `Or.inr b ∈ s.copair t` iff `b ∈ t`.
copair {1, 2} {2, 3} = {inl 1, inl 2, inr 2, inr 3} -/
protected def copair {β} (t₁ : Ordnode α) (t₂ : Ordnode β) : Ordnode (α ⊕ β) :=
merge (map Sum.inl t₁) (map Sum.inr t₂)
/-- O(n). Map a partial function across a set. The result depends on a proof
that the function is defined on all members of the set.
pmap (fin.mk : ∀ n, n < 4 → fin 4) {1, 2} H = {(1 : fin 4), (2 : fin 4)} -/
def pmap {P : α → Prop} {β} (f : ∀ a, P a → β) : ∀ t : Ordnode α, All P t → Ordnode β
| nil, _ => nil
| node s l x r, ⟨hl, hx, hr⟩ => node s (pmap f l hl) (f x hx) (pmap f r hr)
/-- O(n). "Attach" the information that every element of `t` satisfies property
P to these elements inside the set, producing a set in the subtype.
attach' (fun x ↦ x < 4) {1, 2} H = ({1, 2} : Ordnode {x // x<4}) -/
def attach' {P : α → Prop} : ∀ t, All P t → Ordnode { a // P a } :=
pmap Subtype.mk
/-- O(log n). Get the `i`th element of the set, by its index from left to right.
nth {a, b, c, d} 2 = some c
nth {a, b, c, d} 5 = none -/
def nth : Ordnode α → ℕ → Option α
| nil, _ => none
| node _ l x r, i =>
match Nat.psub' i (size l) with
| none => nth l i
| some 0 => some x
| some (j + 1) => nth r j
/-- O(log n). Remove the `i`th element of the set, by its index from left to right.
remove_nth {a, b, c, d} 2 = {a, b, d}
remove_nth {a, b, c, d} 5 = {a, b, c, d} -/
def removeNth : Ordnode α → ℕ → Ordnode α
| nil, _ => nil
| node _ l x r, i =>
match Nat.psub' i (size l) with
| none => balanceR (removeNth l i) x r
| some 0 => glue l r
| some (j + 1) => balanceL l x (removeNth r j)
/-- Auxiliary definition for `take`. (Can also be used in lieu of `take` if you know the
index is within the range of the data structure.)
takeAux {a, b, c, d} 2 = {a, b}
takeAux {a, b, c, d} 5 = {a, b, c, d} -/
def takeAux : Ordnode α → ℕ → Ordnode α
| nil, _ => nil
| node _ l x r, i =>
if i = 0 then nil
else
match Nat.psub' i (size l) with
| none => takeAux l i
| some 0 => l
| some (j + 1) => link l x (takeAux r j)
/-- O(log n). Get the first `i` elements of the set, counted from the left.
take 2 {a, b, c, d} = {a, b}
take 5 {a, b, c, d} = {a, b, c, d} -/
def take (i : ℕ) (t : Ordnode α) : Ordnode α :=
if size t ≤ i then t else takeAux t i
/-- Auxiliary definition for `drop`. (Can also be used in lieu of `drop` if you know the
index is within the range of the data structure.)
drop_aux {a, b, c, d} 2 = {c, d}
drop_aux {a, b, c, d} 5 = ∅ -/
def dropAux : Ordnode α → ℕ → Ordnode α
| nil, _ => nil
| t@(node _ l x r), i =>
if i = 0 then t
else
match Nat.psub' i (size l) with
| none => link (dropAux l i) x r
| some 0 => insertMin x r
| some (j + 1) => dropAux r j
/-- O(log n). Remove the first `i` elements of the set, counted from the left.
drop 2 {a, b, c, d} = {c, d}
drop 5 {a, b, c, d} = ∅ -/
def drop (i : ℕ) (t : Ordnode α) : Ordnode α :=
if size t ≤ i then nil else dropAux t i
/-- Auxiliary definition for `splitAt`. (Can also be used in lieu of `splitAt` if you know the
index is within the range of the data structure.)
splitAtAux {a, b, c, d} 2 = ({a, b}, {c, d})
splitAtAux {a, b, c, d} 5 = ({a, b, c, d}, ∅) -/
def splitAtAux : Ordnode α → ℕ → Ordnode α × Ordnode α
| nil, _ => (nil, nil)
| t@(node _ l x r), i =>
if i = 0 then (nil, t)
else
match Nat.psub' i (size l) with
| none =>
let (l₁, l₂) := splitAtAux l i
(l₁, link l₂ x r)
| some 0 => (glue l r, insertMin x r)
| some (j + 1) =>
let (r₁, r₂) := splitAtAux r j
(link l x r₁, r₂)
/-- O(log n). Split a set at the `i`th element, getting the first `i` and everything else.
splitAt 2 {a, b, c, d} = ({a, b}, {c, d})
splitAt 5 {a, b, c, d} = ({a, b, c, d}, ∅) -/
def splitAt (i : ℕ) (t : Ordnode α) : Ordnode α × Ordnode α :=
if size t ≤ i then (t, nil) else splitAtAux t i
/-- O(log n). Get an initial segment of the set that satisfies the predicate `p`.
`p` is required to be antitone, that is, `x < y → p y → p x`.
takeWhile (fun x ↦ x < 4) {1, 2, 3, 4, 5} = {1, 2, 3}
takeWhile (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/
def takeWhile (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α
| nil => nil
| node _ l x r => if p x then link l x (takeWhile p r) else takeWhile p l
/-- O(log n). Remove an initial segment of the set that satisfies the predicate `p`.
`p` is required to be antitone, that is, `x < y → p y → p x`.
dropWhile (fun x ↦ x < 4) {1, 2, 3, 4, 5} = {4, 5}
dropWhile (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/
def dropWhile (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α
| nil => nil
| node _ l x r => if p x then dropWhile p r else link (dropWhile p l) x r
/-- O(log n). Split the set into those satisfying and not satisfying the predicate `p`.
`p` is required to be antitone, that is, `x < y → p y → p x`.
span (fun x ↦ x < 4) {1, 2, 3, 4, 5} = ({1, 2, 3}, {4, 5})
span (fun x ↦ x > 4) {1, 2, 3, 4, 5} = precondition violation -/
def span (p : α → Prop) [DecidablePred p] : Ordnode α → Ordnode α × Ordnode α
| nil => (nil, nil)
| node _ l x r =>
if p x then
let (r₁, r₂) := span p r
(link l x r₁, r₂)
else
let (l₁, l₂) := span p l
(l₁, link l₂ x r)
/-- Auxiliary definition for `ofAscList`.
**Note:** This function is defined by well-founded recursion, so it will probably not compute
in the kernel, meaning that you probably can't prove things like
`ofAscList [1, 2, 3] = {1, 2, 3}` by `rfl`.
This implementation is optimized for VM evaluation. -/
def ofAscListAux₁ : ∀ l : List α, ℕ → Ordnode α × { l' : List α // l'.length ≤ l.length }
| [] => fun _ => (nil, ⟨[], le_rfl⟩)
| x :: xs => fun s =>
if s = 1 then (ι x, ⟨xs, Nat.le_succ _⟩)
else
match ofAscListAux₁ xs (s <<< 1) with
| (t, ⟨[], _⟩) => (t, ⟨[], Nat.zero_le _⟩)
| (l, ⟨y :: ys, h⟩) =>
have := Nat.le_succ_of_le h
let (r, ⟨zs, h'⟩) := ofAscListAux₁ ys (s <<< 1)
(link l y r, ⟨zs, le_trans h' (le_of_lt this)⟩)
termination_by l => l.length
/-- Auxiliary definition for `ofAscList`. -/
def ofAscListAux₂ : List α → Ordnode α → ℕ → Ordnode α
| [] => fun t _ => t
| x :: xs => fun l s =>
match ofAscListAux₁ xs s with
| (r, ⟨ys, h⟩) =>
have := Nat.lt_succ_of_le h
ofAscListAux₂ ys (link l x r) (s <<< 1)
termination_by l => l.length
/-- O(n). Build a set from a list which is already sorted. Performs no comparisons.
ofAscList [1, 2, 3] = {1, 2, 3}
ofAscList [3, 2, 1] = precondition violation -/
def ofAscList : List α → Ordnode α
| [] => nil
| x :: xs => ofAscListAux₂ xs (ι x) 1
section
variable [LE α] [DecidableLE α]
/-- O(log n). Does the set (approximately) contain the element `x`? That is,
is there an element that is equivalent to `x` in the order?
1 ∈ {1, 2, 3} = true
4 ∈ {1, 2, 3} = false
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
(1, 1) ∈ {(0, 1), (1, 2)} = true
(3, 1) ∈ {(0, 1), (1, 2)} = false -/
def mem (x : α) : Ordnode α → Bool
| nil => false
| node _ l y r =>
match cmpLE x y with
| Ordering.lt => mem x l
| Ordering.eq => true
| Ordering.gt => mem x r
/-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order,
if it exists.
find 1 {1, 2, 3} = some 1
find 4 {1, 2, 3} = none
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
find (1, 1) {(0, 1), (1, 2)} = some (1, 2)
find (3, 1) {(0, 1), (1, 2)} = none -/
def find (x : α) : Ordnode α → Option α
| nil => none
| node _ l y r =>
match cmpLE x y with
| Ordering.lt => find x l
| Ordering.eq => some y
| Ordering.gt => find x r
instance : Membership α (Ordnode α) :=
⟨fun t x => t.mem x⟩
instance mem.decidable (x : α) (t : Ordnode α) : Decidable (x ∈ t) :=
Bool.decEq _ _
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, the function `f` is used to generate
the element to insert (being passed the current value in the set).
insertWith f 0 {1, 2, 3} = {0, 1, 2, 3}
insertWith f 1 {1, 2, 3} = {f 1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
insertWith f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)}
insertWith f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/
def insertWith (f : α → α) (x : α) : Ordnode α → Ordnode α
| nil => ι x
| node sz l y r =>
match cmpLE x y with
| Ordering.lt => balanceL (insertWith f x l) y r
| Ordering.eq => node sz l (f y) r
| Ordering.gt => balanceR l y (insertWith f x r)
/-- O(log n). Modify an element in the set with the given function,
doing nothing if the key is not found.
Note that the element returned by `f` must be equivalent to `x`.
adjustWith f 0 {1, 2, 3} = {1, 2, 3}
adjustWith f 1 {1, 2, 3} = {f 1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
adjustWith f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)}
adjustWith f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/
def adjustWith (f : α → α) (x : α) : Ordnode α → Ordnode α
| nil => nil
| _t@(node sz l y r) =>
match cmpLE x y with
| Ordering.lt => node sz (adjustWith f x l) y r
| Ordering.eq => node sz l (f y) r
| Ordering.gt => node sz l y (adjustWith f x r)
/-- O(log n). Modify an element in the set with the given function,
doing nothing if the key is not found.
Note that the element returned by `f` must be equivalent to `x`.
updateWith f 0 {1, 2, 3} = {1, 2, 3}
updateWith f 1 {1, 2, 3} = {2, 3} if f 1 = none
= {a, 2, 3} if f 1 = some a -/
def updateWith (f : α → Option α) (x : α) : Ordnode α → Ordnode α
| nil => nil
| _t@(node sz l y r) =>
match cmpLE x y with
| Ordering.lt => balanceR (updateWith f x l) y r
| Ordering.eq =>
match f y with
| none => glue l r
| some a => node sz l a r
| Ordering.gt => balanceL l y (updateWith f x r)
/-- O(log n). Modify an element in the set with the given function,
doing nothing if the key is not found.
Note that the element returned by `f` must be equivalent to `x`.
alter f 0 {1, 2, 3} = {1, 2, 3} if f none = none
= {a, 1, 2, 3} if f none = some a
alter f 1 {1, 2, 3} = {2, 3} if f 1 = none
= {a, 2, 3} if f 1 = some a -/
def alter (f : Option α → Option α) (x : α) : Ordnode α → Ordnode α
| nil => Option.recOn (f none) nil Ordnode.singleton
| _t@(node sz l y r) =>
match cmpLE x y with
| Ordering.lt => balance (alter f x l) y r
| Ordering.eq =>
match f (some y) with
| none => glue l r
| some a => node sz l a r
| Ordering.gt => balance l y (alter f x r)
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, this replaces it.
insert 1 {1, 2, 3} = {1, 2, 3}
insert 4 {1, 2, 3} = {1, 2, 3, 4}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
insert (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 1)}
insert (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/
protected def insert (x : α) : Ordnode α → Ordnode α
| nil => ι x
| node sz l y r =>
match cmpLE x y with
| Ordering.lt => balanceL (Ordnode.insert x l) y r
| Ordering.eq => node sz l x r
| Ordering.gt => balanceR l y (Ordnode.insert x r)
instance : Insert α (Ordnode α) :=
⟨Ordnode.insert⟩
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, the set is returned as is.
insert' 1 {1, 2, 3} = {1, 2, 3}
insert' 4 {1, 2, 3} = {1, 2, 3, 4}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
insert' (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)}
insert' (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/
def insert' (x : α) : Ordnode α → Ordnode α
| nil => ι x
| t@(node _ l y r) =>
match cmpLE x y with
| Ordering.lt => balanceL (insert' x l) y r
| Ordering.eq => t
| Ordering.gt => balanceR l y (insert' x r)
/-- O(log n). Split the tree into those smaller than `x` and those greater than it.
If an element equivalent to `x` is in the set, it is discarded.
split 2 {1, 2, 4} = ({1}, {4})
split 3 {1, 2, 4} = ({1, 2}, {4})
split 4 {1, 2, 4} = ({1, 2}, ∅)
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
split (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, ∅)
split (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, ∅) -/
def split (x : α) : Ordnode α → Ordnode α × Ordnode α
| nil => (nil, nil)
| node _ l y r =>
match cmpLE x y with
| Ordering.lt =>
let (lt, gt) := split x l
(lt, link gt y r)
| Ordering.eq => (l, r)
| Ordering.gt =>
let (lt, gt) := split x r
(link l y lt, gt)
/-- O(log n). Split the tree into those smaller than `x` and those greater than it,
plus an element equivalent to `x`, if it exists.
split3 2 {1, 2, 4} = ({1}, some 2, {4})
split3 3 {1, 2, 4} = ({1, 2}, none, {4})
split3 4 {1, 2, 4} = ({1, 2}, some 4, ∅)
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
split3 (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, some (1, 2), ∅)
split3 (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, none, ∅) -/
def split3 (x : α) : Ordnode α → Ordnode α × Option α × Ordnode α
| nil => (nil, none, nil)
| node _ l y r =>
match cmpLE x y with
| Ordering.lt =>
let (lt, f, gt) := split3 x l
(lt, f, link gt y r)
| Ordering.eq => (l, some y, r)
| Ordering.gt =>
let (lt, f, gt) := split3 x r
(link l y lt, f, gt)
/-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there
is no such element.
erase 1 {1, 2, 3} = {2, 3}
erase 4 {1, 2, 3} = {1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
erase (1, 1) {(0, 1), (1, 2)} = {(0, 1)}
erase (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/
def erase (x : α) : Ordnode α → Ordnode α
| nil => nil
| _t@(node _ l y r) =>
match cmpLE x y with
| Ordering.lt => balanceR (erase x l) y r
| Ordering.eq => glue l r
| Ordering.gt => balanceL l y (erase x r)
/-- Auxiliary definition for `findLt`. -/
def findLtAux (x : α) : Ordnode α → α → α
| nil, best => best
| node _ l y r, best => if x ≤ y then findLtAux x l best else findLtAux x r y
/-- O(log n). Get the largest element in the tree that is `< x`.
findLt 2 {1, 2, 4} = some 1
findLt 3 {1, 2, 4} = some 2
findLt 0 {1, 2, 4} = none -/
def findLt (x : α) : Ordnode α → Option α
| nil => none
| node _ l y r => if x ≤ y then findLt x l else some (findLtAux x r y)
/-- Auxiliary definition for `findGt`. -/
def findGtAux (x : α) : Ordnode α → α → α
| nil, best => best
| node _ l y r, best => if y ≤ x then findGtAux x r best else findGtAux x l y
/-- O(log n). Get the smallest element in the tree that is `> x`.
findGt 2 {1, 2, 4} = some 4
findGt 3 {1, 2, 4} = some 4
findGt 4 {1, 2, 4} = none -/
def findGt (x : α) : Ordnode α → Option α
| nil => none
| node _ l y r => if y ≤ x then findGt x r else some (findGtAux x l y)
/-- Auxiliary definition for `findLe`. -/
def findLeAux (x : α) : Ordnode α → α → α
| nil, best => best
| node _ l y r, best =>
match cmpLE x y with
| Ordering.lt => findLeAux x l best
| Ordering.eq => y
| Ordering.gt => findLeAux x r y
/-- O(log n). Get the largest element in the tree that is `≤ x`.
findLe 2 {1, 2, 4} = some 2
findLe 3 {1, 2, 4} = some 2
findLe 0 {1, 2, 4} = none -/
def findLe (x : α) : Ordnode α → Option α
| nil => none
| node _ l y r =>
match cmpLE x y with
| Ordering.lt => findLe x l
| Ordering.eq => some y
| Ordering.gt => some (findLeAux x r y)
/-- Auxiliary definition for `findGe`. -/
def findGeAux (x : α) : Ordnode α → α → α
| nil, best => best
| node _ l y r, best =>
match cmpLE x y with
| Ordering.lt => findGeAux x l y
| Ordering.eq => y
| Ordering.gt => findGeAux x r best
/-- O(log n). Get the smallest element in the tree that is `≥ x`.
findGe 2 {1, 2, 4} = some 2
findGe 3 {1, 2, 4} = some 4
findGe 5 {1, 2, 4} = none -/
def findGe (x : α) : Ordnode α → Option α
| nil => none
| node _ l y r =>
match cmpLE x y with
| Ordering.lt => some (findGeAux x l y)
| Ordering.eq => some y
| Ordering.gt => findGe x r
/-- Auxiliary definition for `findIndex`. -/
def findIndexAux (x : α) : Ordnode α → ℕ → Option ℕ
| nil, _ => none
| node _ l y r, i =>
match cmpLE x y with
| Ordering.lt => findIndexAux x l i
| Ordering.eq => some (i + size l)
| Ordering.gt => findIndexAux x r (i + size l + 1)
/-- O(log n). Get the index, counting from the left,
of an element equivalent to `x` if it exists.
findIndex 2 {1, 2, 4} = some 1
findIndex 4 {1, 2, 4} = some 2
findIndex 5 {1, 2, 4} = none -/
def findIndex (x : α) (t : Ordnode α) : Option ℕ :=
findIndexAux x t 0
/-- Auxiliary definition for `isSubset`. -/
def isSubsetAux : Ordnode α → Ordnode α → Bool
| nil, _ => true
| _, nil => false
| node _ l x r, t =>
let (lt, found, gt) := split3 x t
found.isSome && isSubsetAux l lt && isSubsetAux r gt
/-- O(m + n). Is every element of `t₁` equivalent to some element of `t₂`?
is_subset {1, 4} {1, 2, 4} = tt
is_subset {1, 3} {1, 2, 4} = ff -/
def isSubset (t₁ t₂ : Ordnode α) : Bool :=
decide (size t₁ ≤ size t₂) && isSubsetAux t₁ t₂
/-- O(m + n). Is every element of `t₁` not equivalent to any element of `t₂`?
disjoint {1, 3} {2, 4} = tt
disjoint {1, 2} {2, 4} = ff -/
def disjoint : Ordnode α → Ordnode α → Bool
| nil, _ => true
| _, nil => true
| node _ l x r, t =>
let (lt, found, gt) := split3 x t
found.isNone && disjoint l lt && disjoint r gt
/-- O(m * log(|m ∪ n| + 1)), m ≤ n. The union of two sets, preferring members of
`t₁` over those of `t₂` when equivalent elements are encountered.
union {1, 2} {2, 3} = {1, 2, 3}
union {1, 3} {2} = {1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
union {(1, 1)} {(0, 1), (1, 2)} = {(0, 1), (1, 1)} -/
def union : Ordnode α → Ordnode α → Ordnode α
| t₁, nil => t₁
| nil, t₂ => t₂
| t₁@(node s₁ l₁ x₁ r₁), t₂@(node s₂ _ x₂ _) =>
if s₂ = 1 then insert' x₂ t₁
else
if s₁ = 1 then insert x₁ t₂
else
let (l₂', r₂') := split x₁ t₂
link (union l₁ l₂') x₁ (union r₁ r₂')
/-- O(m * log(|m ∪ n| + 1)), m ≤ n. Difference of two sets.
diff {1, 2} {2, 3} = {1}
diff {1, 2, 3} {2} = {1, 3} -/
def diff : Ordnode α → Ordnode α → Ordnode α
| t₁, nil => t₁
| t₁, t₂@(node _ l₂ x r₂) =>
cond t₁.empty t₂ <|
let (l₁, r₁) := split x t₁
let l₁₂ := diff l₁ l₂
let r₁₂ := diff r₁ r₂
if size l₁₂ + size r₁₂ = size t₁ then t₁ else merge l₁₂ r₁₂
/-- O(m * log(|m ∪ n| + 1)), m ≤ n. Intersection of two sets, preferring members of
`t₁` over those of `t₂` when equivalent elements are encountered.
inter {1, 2} {2, 3} = {2}
inter {1, 3} {2} = ∅ -/
def inter : Ordnode α → Ordnode α → Ordnode α
| nil, _ => nil
| t₁@(node _ l₁ x r₁), t₂ =>
cond t₂.empty t₁ <|
let (l₂, y, r₂) := split3 x t₂
let l₁₂ := inter l₁ l₂
let r₁₂ := inter r₁ r₂
cond y.isSome (link l₁₂ x r₁₂) (merge l₁₂ r₁₂)
/-- O(n * log n). Build a set from a list, preferring elements that appear earlier in the list
in the case of equivalent elements.
ofList [1, 2, 3] = {1, 2, 3}
ofList [2, 1, 1, 3] = {1, 2, 3}
Using a preorder on `ℕ × ℕ` that only compares the first coordinate:
ofList [(1, 1), (0, 1), (1, 2)] = {(0, 1), (1, 1)} -/
def ofList (l : List α) : Ordnode α :=
l.foldr insert nil
/-- O(n * log n). Adaptively chooses between the linear and log-linear algorithm depending
on whether the input list is already sorted.
ofList' [1, 2, 3] = {1, 2, 3}
ofList' [2, 1, 1, 3] = {1, 2, 3} -/
def ofList' : List α → Ordnode α
| [] => nil
| l@(_ :: _) => if List.IsChain (fun a b => ¬b ≤ a) l then ofAscList l else ofList l
/-- O(n * log n). Map a function on a set. Unlike `map` this has no requirements on
`f`, and the resulting set may be smaller than the input if `f` is noninjective.
Equivalent elements are selected with a preference for smaller source elements.
image (fun x ↦ x + 2) {1, 2, 4} = {3, 4, 6}
image (fun x : ℕ ↦ x - 2) {1, 2, 4} = {0, 2} -/
def image {α β} [LE β] [DecidableLE β] (f : α → β) (t : Ordnode α) : Ordnode β :=
ofList (t.toList.map f)
end
end Ordnode |
.lake/packages/mathlib/Mathlib/Data/Ordmap/Invariants.lean | import Mathlib.Algebra.Order.Ring.Nat
import Mathlib.Data.Nat.Dist
import Mathlib.Data.Ordmap.Ordnode
import Mathlib.Tactic.Abel
/-!
# Invariants for the verification of `Ordnode`
An `Ordnode`, defined in `Mathlib/Data/Ordmap/Ordnode.lean`, is an inductive type which describes a
tree which stores the `size` at internal nodes.
In this file we define the correctness invariant of an `Ordnode`, comprising:
* `Ordnode.Sized t`: All internal `size` fields must match the actual measured
size of the tree. (This is not hard to satisfy.)
* `Ordnode.Balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))`
(that is, nil or a single singleton subtree), the two subtrees must satisfy
`size l ≤ δ * size r` and `size r ≤ δ * size l`, where `δ := 3` is a global
parameter of the data structure (and this property must hold recursively at subtrees).
This is why we say this is a "size balanced tree" data structure.
* `Ordnode.Bounded lo hi t`: The members of the tree must be in strictly increasing order,
meaning that if `a` is in the left subtree and `b` is the root, then `a ≤ b` and
`¬(b ≤ a)`. We enforce this using `Ordnode.Bounded` which includes also a global
upper and lower bound.
This whole file is in the `Ordnode` namespace, because we first have to prove the correctness of
all the operations (and defining what correctness means here is somewhat subtle).
The actual `Ordset` operations are in `Mathlib/Data/Ordmap/Ordset.lean`.
## TODO
This file is incomplete, in the sense that the intent is to have verified
versions and lemmas about all the definitions in `Ordnode.lean`, but at the moment only
a few operations are verified (the hard part should be out of the way, but still).
Contributors are encouraged to pick this up and finish the job, if it appeals to you.
## Tags
ordered map, ordered set, data structure, verified programming
-/
variable {α : Type*}
namespace Ordnode
/-! ### delta and ratio -/
theorem not_le_delta {s} (H : 1 ≤ s) : ¬s ≤ delta * 0 :=
not_le_of_gt H
theorem delta_lt_false {a b : ℕ} (h₁ : delta * a < b) (h₂ : delta * b < a) : False :=
not_le_of_gt (lt_trans (mul_lt_mul_of_pos_left h₁ <| by decide) h₂) <| by
simpa [mul_assoc] using Nat.mul_le_mul_right a (by decide : 1 ≤ delta * delta)
/-! ### `singleton` -/
/-! ### `size` and `empty` -/
/-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/
def realSize : Ordnode α → ℕ
| nil => 0
| node _ l _ r => realSize l + realSize r + 1
/-! ### `Sized` -/
/-- The `Sized` property asserts that all the `size` fields in nodes match the actual size of the
respective subtrees. -/
def Sized : Ordnode α → Prop
| nil => True
| node s l _ r => s = size l + size r + 1 ∧ Sized l ∧ Sized r
theorem Sized.node' {l x r} (hl : @Sized α l) (hr : Sized r) : Sized (node' l x r) :=
⟨rfl, hl, hr⟩
theorem Sized.eq_node' {s l x r} (h : @Sized α (node s l x r)) : node s l x r = .node' l x r := by
rw [h.1]
theorem Sized.size_eq {s l x r} (H : Sized (@node α s l x r)) :
size (@node α s l x r) = size l + size r + 1 :=
H.1
@[elab_as_elim]
theorem Sized.induction {t} (hl : @Sized α t) {C : Ordnode α → Prop} (H0 : C nil)
(H1 : ∀ l x r, C l → C r → C (.node' l x r)) : C t := by
induction t with
| nil => exact H0
| node _ _ _ _ t_ih_l t_ih_r =>
rw [hl.eq_node']
exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2)
theorem size_eq_realSize : ∀ {t : Ordnode α}, Sized t → size t = realSize t
| nil, _ => rfl
| node s l x r, ⟨h₁, h₂, h₃⟩ => by
rw [size, h₁, size_eq_realSize h₂, size_eq_realSize h₃]; rfl
@[simp]
theorem Sized.size_eq_zero {t : Ordnode α} (ht : Sized t) : size t = 0 ↔ t = nil := by
cases t <;> [simp; simp [ht.1]]
theorem Sized.pos {s l x r} (h : Sized (@node α s l x r)) : 0 < s := by
rw [h.1]; apply Nat.le_add_left
/-! `dual` -/
theorem dual_dual : ∀ t : Ordnode α, dual (dual t) = t
| nil => rfl
| node s l x r => by rw [dual, dual, dual_dual l, dual_dual r]
@[simp]
theorem size_dual (t : Ordnode α) : size (dual t) = size t := by cases t <;> rfl
/-! `Balanced` -/
/-- The `BalancedSz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is
balanced: either `l ≤ δ * r` and `r ≤ δ * r`, or the tree is trivial with a singleton on one side
and nothing on the other. -/
def BalancedSz (l r : ℕ) : Prop :=
l + r ≤ 1 ∨ l ≤ delta * r ∧ r ≤ delta * l
instance BalancedSz.dec : DecidableRel BalancedSz := fun _ _ => inferInstanceAs (Decidable (_ ∨ _))
/-- The `Balanced t` asserts that the tree `t` satisfies the balance invariants
(at every level). -/
def Balanced : Ordnode α → Prop
| nil => True
| node _ l _ r => BalancedSz (size l) (size r) ∧ Balanced l ∧ Balanced r
instance Balanced.dec : DecidablePred (@Balanced α)
| nil => by
unfold Balanced
infer_instance
| node _ l _ r => by
unfold Balanced
haveI := Balanced.dec l
haveI := Balanced.dec r
infer_instance
@[symm]
theorem BalancedSz.symm {l r : ℕ} : BalancedSz l r → BalancedSz r l :=
Or.imp (by rw [add_comm]; exact id) And.symm
theorem balancedSz_zero {l : ℕ} : BalancedSz l 0 ↔ l ≤ 1 := by
simp +contextual [BalancedSz]
theorem balancedSz_up {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ r₂ ≤ delta * l)
(H : BalancedSz l r₁) : BalancedSz l r₂ := by
refine or_iff_not_imp_left.2 fun h => ?_
refine ⟨?_, h₂.resolve_left h⟩
cases H with
| inl H =>
cases r₂
· cases h (le_trans (Nat.add_le_add_left (Nat.zero_le _) _) H)
· exact le_trans (le_trans (Nat.le_add_right _ _) H) (Nat.le_add_left 1 _)
| inr H =>
exact le_trans H.1 (Nat.mul_le_mul_left _ h₁)
theorem balancedSz_down {l r₁ r₂ : ℕ} (h₁ : r₁ ≤ r₂) (h₂ : l + r₂ ≤ 1 ∨ l ≤ delta * r₁)
(H : BalancedSz l r₂) : BalancedSz l r₁ :=
have : l + r₂ ≤ 1 → BalancedSz l r₁ := fun H => Or.inl (le_trans (Nat.add_le_add_left h₁ _) H)
Or.casesOn H this fun H => Or.casesOn h₂ this fun h₂ => Or.inr ⟨h₂, le_trans h₁ H.2⟩
theorem Balanced.dual : ∀ {t : Ordnode α}, Balanced t → Balanced (dual t)
| nil, _ => ⟨⟩
| node _ l _ r, ⟨b, bl, br⟩ => ⟨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dual⟩
/-! ### `rotate` and `balance` -/
/-- Build a tree from three nodes, left associated (ignores the invariants). -/
def node3L (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) : Ordnode α :=
node' (node' l x m) y r
/-- Build a tree from three nodes, right associated (ignores the invariants). -/
def node3R (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) : Ordnode α :=
node' l x (node' m y r)
/-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/
def node4L : Ordnode α → α → Ordnode α → α → Ordnode α → Ordnode α
| l, x, node _ ml y mr, z, r => node' (node' l x ml) y (node' mr z r)
| l, x, nil, z, r => node3L l x nil z r
-- should not happen
/-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/
def node4R : Ordnode α → α → Ordnode α → α → Ordnode α → Ordnode α
| l, x, node _ ml y mr, z, r => node' (node' l x ml) y (node' mr z r)
| l, x, nil, z, r => node3R l x nil z r
-- should not happen
/-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)`
if balance is upset. -/
def rotateL : Ordnode α → α → Ordnode α → Ordnode α
| l, x, node _ m y r => if size m < ratio * size r then node3L l x m y r else node4L l x m y r
| l, x, nil => node' l x nil
theorem rotateL_node (l : Ordnode α) (x : α) (sz : ℕ) (m : Ordnode α) (y : α) (r : Ordnode α) :
rotateL l x (node sz m y r) =
if size m < ratio * size r then node3L l x m y r else node4L l x m y r :=
rfl
theorem rotateL_nil (l : Ordnode α) (x : α) : rotateL l x nil = node' l x nil :=
rfl
-- should not happen
/-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))`
if balance is upset. -/
def rotateR : Ordnode α → α → Ordnode α → Ordnode α
| node _ l x m, y, r => if size m < ratio * size l then node3R l x m y r else node4R l x m y r
| nil, y, r => node' nil y r
theorem rotateR_node (sz : ℕ) (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) :
rotateR (node sz l x m) y r =
if size m < ratio * size l then node3R l x m y r else node4R l x m y r :=
rfl
theorem rotateR_nil (y : α) (r : Ordnode α) : rotateR nil y r = node' nil y r :=
rfl
-- should not happen
/-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are
not too far from balanced. -/
def balanceL' (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α :=
if size l + size r ≤ 1 then node' l x r
else if size l > delta * size r then rotateR l x r else node' l x r
/-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are
not too far from balanced. -/
def balanceR' (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α :=
if size l + size r ≤ 1 then node' l x r
else if size r > delta * size l then rotateL l x r else node' l x r
/-- The full balance operation. This is the same as `balance`, but with less manual inlining.
It is somewhat easier to work with this version in proofs. -/
def balance' (l : Ordnode α) (x : α) (r : Ordnode α) : Ordnode α :=
if size l + size r ≤ 1 then node' l x r
else
if size r > delta * size l then rotateL l x r
else if size l > delta * size r then rotateR l x r else node' l x r
theorem dual_node' (l : Ordnode α) (x : α) (r : Ordnode α) :
dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm]
theorem dual_node3L (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) :
dual (node3L l x m y r) = node3R (dual r) y (dual m) x (dual l) := by
simp [node3L, node3R, add_comm]
theorem dual_node3R (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) :
dual (node3R l x m y r) = node3L (dual r) y (dual m) x (dual l) := by
simp [node3L, node3R, add_comm]
theorem dual_node4L (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) :
dual (node4L l x m y r) = node4R (dual r) y (dual m) x (dual l) := by
cases m <;> simp [node4L, node4R, node3R, dual_node3L, add_comm]
theorem dual_node4R (l : Ordnode α) (x : α) (m : Ordnode α) (y : α) (r : Ordnode α) :
dual (node4R l x m y r) = node4L (dual r) y (dual m) x (dual l) := by
cases m <;> simp [node4L, node4R, node3L, dual_node3R, add_comm]
theorem dual_rotateL (l : Ordnode α) (x : α) (r : Ordnode α) :
dual (rotateL l x r) = rotateR (dual r) x (dual l) := by
cases r <;> simp [rotateL, rotateR]; split_ifs <;>
simp [dual_node3L, dual_node4L, node3R]
theorem dual_rotateR (l : Ordnode α) (x : α) (r : Ordnode α) :
dual (rotateR l x r) = rotateL (dual r) x (dual l) := by
rw [← dual_dual (rotateL _ _ _), dual_rotateL, dual_dual, dual_dual]
theorem dual_balance' (l : Ordnode α) (x : α) (r : Ordnode α) :
dual (balance' l x r) = balance' (dual r) x (dual l) := by
simp [balance', add_comm]; split_ifs with h h_1 h_2 <;>
simp [dual_rotateL, dual_rotateR, add_comm]
cases delta_lt_false h_1 h_2
theorem dual_balanceL (l : Ordnode α) (x : α) (r : Ordnode α) :
dual (balanceL l x r) = balanceR (dual r) x (dual l) := by
unfold balanceL balanceR
obtain - | ⟨rs, rl, rx, rr⟩ := r
· obtain - | ⟨ls, ll, lx, lr⟩ := l; · rfl
obtain - | ⟨lls, lll, llx, llr⟩ := ll <;> obtain - | ⟨lrs, lrl, lrx, lrr⟩ := lr <;>
dsimp only [dual, id] <;> try rfl
split_ifs with h <;> repeat simp [add_comm]
· obtain - | ⟨ls, ll, lx, lr⟩ := l; · rfl
dsimp only [dual, id]
split_ifs; swap; · simp [add_comm]
obtain - | ⟨lls, lll, llx, llr⟩ := ll <;> obtain - | ⟨lrs, lrl, lrx, lrr⟩ := lr <;> try rfl
dsimp only [dual, id]
split_ifs with h <;> simp [add_comm]
theorem dual_balanceR (l : Ordnode α) (x : α) (r : Ordnode α) :
dual (balanceR l x r) = balanceL (dual r) x (dual l) := by
rw [← dual_dual (balanceL _ _ _), dual_balanceL, dual_dual, dual_dual]
theorem Sized.node3L {l x m y r} (hl : @Sized α l) (hm : Sized m) (hr : Sized r) :
Sized (node3L l x m y r) :=
(hl.node' hm).node' hr
theorem Sized.node3R {l x m y r} (hl : @Sized α l) (hm : Sized m) (hr : Sized r) :
Sized (node3R l x m y r) :=
hl.node' (hm.node' hr)
theorem Sized.node4L {l x m y r} (hl : @Sized α l) (hm : Sized m) (hr : Sized r) :
Sized (node4L l x m y r) := by
cases m <;> [exact (hl.node' hm).node' hr; exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)]
theorem node3L_size {l x m y r} : size (@node3L α l x m y r) = size l + size m + size r + 2 := by
dsimp [node3L, node', size]; rw [add_right_comm _ 1]
theorem node3R_size {l x m y r} : size (@node3R α l x m y r) = size l + size m + size r + 2 := by
dsimp [node3R, node', size]; rw [← add_assoc, ← add_assoc]
theorem node4L_size {l x m y r} (hm : Sized m) :
size (@node4L α l x m y r) = size l + size m + size r + 2 := by
cases m
· simp [node4L, node3L, node']
abel
· simp [node4L, node', size, hm.1]; abel
theorem Sized.dual : ∀ {t : Ordnode α}, Sized t → Sized (dual t)
| nil, _ => ⟨⟩
| node _ l _ r, ⟨rfl, sl, sr⟩ => ⟨by simp [size_dual, add_comm], Sized.dual sr, Sized.dual sl⟩
theorem Sized.dual_iff {t : Ordnode α} : Sized (.dual t) ↔ Sized t :=
⟨fun h => by rw [← dual_dual t]; exact h.dual, Sized.dual⟩
theorem Sized.rotateL {l x r} (hl : @Sized α l) (hr : Sized r) : Sized (rotateL l x r) := by
cases r; · exact hl.node' hr
rw [Ordnode.rotateL_node]; split_ifs
· exact hl.node3L hr.2.1 hr.2.2
· exact hl.node4L hr.2.1 hr.2.2
theorem Sized.rotateR {l x r} (hl : @Sized α l) (hr : Sized r) : Sized (rotateR l x r) :=
Sized.dual_iff.1 <| by rw [dual_rotateR]; exact hr.dual.rotateL hl.dual
theorem Sized.rotateL_size {l x r} (hm : Sized r) :
size (@Ordnode.rotateL α l x r) = size l + size r + 1 := by
cases r <;> simp [Ordnode.rotateL]
simp only [hm.1]
split_ifs <;> simp [node3L_size, node4L_size hm.2.1] <;> abel
theorem Sized.rotateR_size {l x r} (hl : Sized l) :
size (@Ordnode.rotateR α l x r) = size l + size r + 1 := by
rw [← size_dual, dual_rotateR, hl.dual.rotateL_size, size_dual, size_dual, add_comm (size l)]
theorem Sized.balance' {l x r} (hl : @Sized α l) (hr : Sized r) : Sized (balance' l x r) := by
unfold Ordnode.balance'; split_ifs
· exact hl.node' hr
· exact hl.rotateL hr
· exact hl.rotateR hr
· exact hl.node' hr
theorem size_balance' {l x r} (hl : @Sized α l) (hr : Sized r) :
size (@balance' α l x r) = size l + size r + 1 := by
unfold balance'; split_ifs
· rfl
· exact hr.rotateL_size
· exact hl.rotateR_size
· rfl
/-! ## `All`, `Any`, `Emem`, `Amem` -/
theorem All.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, All P t → All Q t
| nil, _ => ⟨⟩
| node _ _ _ _, ⟨h₁, h₂, h₃⟩ => ⟨h₁.imp H, H _ h₂, h₃.imp H⟩
theorem Any.imp {P Q : α → Prop} (H : ∀ a, P a → Q a) : ∀ {t}, Any P t → Any Q t
| nil => id
| node _ _ _ _ => Or.imp (Any.imp H) <| Or.imp (H _) (Any.imp H)
theorem all_singleton {P : α → Prop} {x : α} : All P (singleton x) ↔ P x :=
⟨fun h => h.2.1, fun h => ⟨⟨⟩, h, ⟨⟩⟩⟩
theorem any_singleton {P : α → Prop} {x : α} : Any P (singleton x) ↔ P x :=
⟨by rintro (⟨⟨⟩⟩ | h | ⟨⟨⟩⟩); exact h, fun h => Or.inr (Or.inl h)⟩
theorem all_dual {P : α → Prop} : ∀ {t : Ordnode α}, All P (dual t) ↔ All P t
| nil => Iff.rfl
| node _ _l _x _r =>
⟨fun ⟨hr, hx, hl⟩ => ⟨all_dual.1 hl, hx, all_dual.1 hr⟩, fun ⟨hl, hx, hr⟩ =>
⟨all_dual.2 hr, hx, all_dual.2 hl⟩⟩
theorem all_iff_forall {P : α → Prop} : ∀ {t}, All P t ↔ ∀ x, Emem x t → P x
| nil => (iff_true_intro <| by rintro _ ⟨⟩).symm
| node _ l x r => by simp [All, Emem, all_iff_forall, Any, or_imp, forall_and]
theorem any_iff_exists {P : α → Prop} : ∀ {t}, Any P t ↔ ∃ x, Emem x t ∧ P x
| nil => ⟨by rintro ⟨⟩, by rintro ⟨_, ⟨⟩, _⟩⟩
| node _ l x r => by simp only [Emem]; simp [Any, any_iff_exists, or_and_right, exists_or]
theorem emem_iff_all {x : α} {t} : Emem x t ↔ ∀ P, All P t → P x :=
⟨fun h _ al => all_iff_forall.1 al _ h, fun H => H _ <| all_iff_forall.2 fun _ => id⟩
theorem all_node' {P l x r} : @All α P (node' l x r) ↔ All P l ∧ P x ∧ All P r :=
Iff.rfl
theorem all_node3L {P l x m y r} :
@All α P (node3L l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := by
simp [node3L, all_node', and_assoc]
theorem all_node3R {P l x m y r} :
@All α P (node3R l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r :=
Iff.rfl
theorem all_node4L {P l x m y r} :
@All α P (node4L l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := by
cases m <;> simp [node4L, all_node', All, all_node3L, and_assoc]
theorem all_node4R {P l x m y r} :
@All α P (node4R l x m y r) ↔ All P l ∧ P x ∧ All P m ∧ P y ∧ All P r := by
cases m <;> simp [node4R, all_node', All, all_node3R, and_assoc]
theorem all_rotateL {P l x r} : @All α P (rotateL l x r) ↔ All P l ∧ P x ∧ All P r := by
cases r <;> simp [rotateL, all_node']; split_ifs <;>
simp [all_node3L, all_node4L, All]
theorem all_rotateR {P l x r} : @All α P (rotateR l x r) ↔ All P l ∧ P x ∧ All P r := by
rw [← all_dual, dual_rotateR, all_rotateL]; simp [all_dual, and_comm, and_left_comm, and_assoc]
theorem all_balance' {P l x r} : @All α P (balance' l x r) ↔ All P l ∧ P x ∧ All P r := by
rw [balance']; split_ifs <;> simp [all_node', all_rotateL, all_rotateR]
/-! ### `toList` -/
theorem foldr_cons_eq_toList : ∀ (t : Ordnode α) (r : List α), t.foldr List.cons r = toList t ++ r
| nil, _ => rfl
| node _ l x r, r' => by
rw [foldr, foldr_cons_eq_toList l, foldr_cons_eq_toList r, ← List.cons_append,
← List.append_assoc, ← foldr_cons_eq_toList l]; rfl
@[simp]
theorem toList_nil : toList (@nil α) = [] :=
rfl
@[simp]
theorem toList_node (s l x r) : toList (@node α s l x r) = toList l ++ x :: toList r := by
rw [toList, foldr, foldr_cons_eq_toList]; rfl
theorem emem_iff_mem_toList {x : α} {t} : Emem x t ↔ x ∈ toList t := by
unfold Emem; induction t <;> simp [Any, *]
theorem length_toList' : ∀ t : Ordnode α, (toList t).length = t.realSize
| nil => rfl
| node _ l _ r => by
rw [toList_node, List.length_append, List.length_cons, length_toList' l,
length_toList' r]; rfl
theorem length_toList {t : Ordnode α} (h : Sized t) : (toList t).length = t.size := by
rw [length_toList', size_eq_realSize h]
theorem equiv_iff {t₁ t₂ : Ordnode α} (h₁ : Sized t₁) (h₂ : Sized t₂) :
Equiv t₁ t₂ ↔ toList t₁ = toList t₂ :=
and_iff_right_of_imp fun h => by rw [← length_toList h₁, h, length_toList h₂]
/-! ### `mem` -/
theorem pos_size_of_mem [LE α] [DecidableLE α] {x : α} {t : Ordnode α} (h : Sized t)
(h_mem : x ∈ t) : 0 < size t := by cases t; · { contradiction }; · { simp [h.1] }
/-! ### `(find/erase/split)(Min/Max)` -/
theorem findMin'_dual : ∀ (t) (x : α), findMin' (dual t) x = findMax' x t
| nil, _ => rfl
| node _ _ x r, _ => findMin'_dual r x
theorem findMax'_dual (t) (x : α) : findMax' x (dual t) = findMin' t x := by
rw [← findMin'_dual, dual_dual]
theorem findMin_dual : ∀ t : Ordnode α, findMin (dual t) = findMax t
| nil => rfl
| node _ _ _ _ => congr_arg some <| findMin'_dual _ _
theorem findMax_dual (t : Ordnode α) : findMax (dual t) = findMin t := by
rw [← findMin_dual, dual_dual]
theorem dual_eraseMin : ∀ t : Ordnode α, dual (eraseMin t) = eraseMax (dual t)
| nil => rfl
| node _ nil _ _ => rfl
| node _ (node sz l' y r') x r => by
rw [eraseMin, dual_balanceR, dual_eraseMin (node sz l' y r'), dual, dual, dual, eraseMax]
theorem dual_eraseMax (t : Ordnode α) : dual (eraseMax t) = eraseMin (dual t) := by
rw [← dual_dual (eraseMin _), dual_eraseMin, dual_dual]
theorem splitMin_eq :
∀ (s l) (x : α) (r), splitMin' l x r = (findMin' l x, eraseMin (node s l x r))
| _, nil, _, _ => rfl
| _, node ls ll lx lr, x, r => by rw [splitMin', splitMin_eq ls ll lx lr, findMin', eraseMin]
theorem splitMax_eq :
∀ (s l) (x : α) (r), splitMax' l x r = (eraseMax (node s l x r), findMax' x r)
| _, _, _, nil => rfl
| _, l, x, node ls ll lx lr => by rw [splitMax', splitMax_eq ls ll lx lr, findMax', eraseMax]
@[elab_as_elim]
theorem findMin'_all {P : α → Prop} : ∀ (t) (x : α), All P t → P x → P (findMin' t x)
| nil, _x, _, hx => hx
| node _ ll lx _, _, ⟨h₁, h₂, _⟩, _ => findMin'_all ll lx h₁ h₂
@[elab_as_elim]
theorem findMax'_all {P : α → Prop} : ∀ (x : α) (t), P x → All P t → P (findMax' x t)
| _x, nil, hx, _ => hx
| _, node _ _ lx lr, _, ⟨_, h₂, h₃⟩ => findMax'_all lx lr h₂ h₃
/-! ### `glue` -/
/-! ### `merge` -/
@[simp]
theorem merge_nil_left (t : Ordnode α) : merge t nil = t := by cases t <;> rfl
@[simp]
theorem merge_nil_right (t : Ordnode α) : merge nil t = t :=
rfl
@[simp]
theorem merge_node {ls ll lx lr rs rl rx rr} :
merge (@node α ls ll lx lr) (node rs rl rx rr) =
if delta * ls < rs then balanceL (merge (node ls ll lx lr) rl) rx rr
else if delta * rs < ls then balanceR ll lx (merge lr (node rs rl rx rr))
else glue (node ls ll lx lr) (node rs rl rx rr) :=
rfl
/-! ### `insert` -/
theorem dual_insert [LE α] [IsTotal α (· ≤ ·)] [DecidableLE α] (x : α) :
∀ t : Ordnode α, dual (Ordnode.insert x t) = @Ordnode.insert αᵒᵈ _ _ x (dual t)
| nil => rfl
| node _ l y r => by
have : @cmpLE αᵒᵈ _ _ x y = cmpLE y x := rfl
rw [Ordnode.insert, dual, Ordnode.insert, this, ← cmpLE_swap x y]
cases cmpLE x y <;>
simp [Ordering.swap, dual_balanceL, dual_balanceR, dual_insert]
/-! ### `balance` properties -/
theorem balance_eq_balance' {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l)
(sr : Sized r) : @balance α l x r = balance' l x r := by
obtain - | ⟨ls, ll, lx, lr⟩ := l
· obtain - | ⟨rs, rl, rx, rr⟩ := r
· rfl
· rw [sr.eq_node'] at hr ⊢
obtain - | ⟨rls, rll, rlx, rlr⟩ := rl <;> obtain - | ⟨rrs, rrl, rrx, rrr⟩ := rr <;>
dsimp [balance, balance']
· rfl
· have : size rrl = 0 ∧ size rrr = 0 := by
have := balancedSz_zero.1 hr.1.symm
rwa [size, sr.2.2.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero] at this
cases sr.2.2.2.1.size_eq_zero.1 this.1
cases sr.2.2.2.2.size_eq_zero.1 this.2
obtain rfl : rrs = 1 := sr.2.2.1
rw [if_neg, if_pos, rotateL_node, if_pos]; · rfl
all_goals dsimp only [size]; decide
· have : size rll = 0 ∧ size rlr = 0 := by
have := balancedSz_zero.1 hr.1
rwa [size, sr.2.1.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero] at this
cases sr.2.1.2.1.size_eq_zero.1 this.1
cases sr.2.1.2.2.size_eq_zero.1 this.2
obtain rfl : rls = 1 := sr.2.1.1
rw [if_neg, if_pos, rotateL_node, if_neg]; · rfl
all_goals dsimp only [size]; decide
· symm; rw [zero_add, if_neg, if_pos, rotateL]
· dsimp only [size_node]; split_ifs
· simp [node3L, node']; abel
· simp [node4L, node', sr.2.1.1]; abel
· apply Nat.zero_lt_succ
· exact not_le_of_gt (Nat.succ_lt_succ (add_pos sr.2.1.pos sr.2.2.pos))
· obtain - | ⟨rs, rl, rx, rr⟩ := r
· rw [sl.eq_node'] at hl ⊢
obtain - | ⟨lls, lll, llx, llr⟩ := ll <;> obtain - | ⟨lrs, lrl, lrx, lrr⟩ := lr <;>
dsimp [balance, balance']
· rfl
· have : size lrl = 0 ∧ size lrr = 0 := by
have := balancedSz_zero.1 hl.1.symm
rwa [size, sl.2.2.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero] at this
cases sl.2.2.2.1.size_eq_zero.1 this.1
cases sl.2.2.2.2.size_eq_zero.1 this.2
obtain rfl : lrs = 1 := sl.2.2.1
rw [if_neg, if_pos, rotateR_node, if_neg]; · rfl
all_goals dsimp only [size]; decide
· have : size lll = 0 ∧ size llr = 0 := by
have := balancedSz_zero.1 hl.1
rwa [size, sl.2.1.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero] at this
cases sl.2.1.2.1.size_eq_zero.1 this.1
cases sl.2.1.2.2.size_eq_zero.1 this.2
obtain rfl : lls = 1 := sl.2.1.1
rw [if_neg, if_pos, rotateR_node, if_pos]; · rfl
all_goals dsimp only [size]; decide
· symm; rw [if_neg, if_pos, rotateR]
· dsimp only [size_node]; split_ifs
· simp [node3R, node']; abel
· simp [node4R, node', sl.2.2.1]; abel
· apply Nat.zero_lt_succ
· exact not_le_of_gt (Nat.succ_lt_succ (add_pos sl.2.1.pos sl.2.2.pos))
· simp only [balance, id_eq, balance', size_node, gt_iff_lt]
symm; rw [if_neg]
· split_ifs with h h_1
· have rd : delta ≤ size rl + size rr := by
have := lt_of_le_of_lt (Nat.mul_le_mul_left _ sl.pos) h
rwa [sr.1, Nat.lt_succ_iff] at this
obtain - | ⟨rls, rll, rlx, rlr⟩ := rl
· rw [size, zero_add] at rd
exact absurd (le_trans rd (balancedSz_zero.1 hr.1.symm)) (by decide)
obtain - | ⟨rrs, rrl, rrx, rrr⟩ := rr
· exact absurd (le_trans rd (balancedSz_zero.1 hr.1)) (by decide)
dsimp [rotateL]; split_ifs
· simp [node3L, node', sr.1]; abel
· simp [node4L, node', sr.1, sr.2.1.1]; abel
· have ld : delta ≤ size ll + size lr := by
have := lt_of_le_of_lt (Nat.mul_le_mul_left _ sr.pos) h_1
rwa [sl.1, Nat.lt_succ_iff] at this
obtain - | ⟨lls, lll, llx, llr⟩ := ll
· rw [size, zero_add] at ld
exact absurd (le_trans ld (balancedSz_zero.1 hl.1.symm)) (by decide)
obtain - | ⟨lrs, lrl, lrx, lrr⟩ := lr
· exact absurd (le_trans ld (balancedSz_zero.1 hl.1)) (by decide)
dsimp [rotateR]; split_ifs
· simp [node3R, node', sl.1]; abel
· simp [node4R, node', sl.1, sl.2.2.1]; abel
· simp [node']
· exact not_le_of_gt (add_le_add (Nat.succ_le_of_lt sl.pos) (Nat.succ_le_of_lt sr.pos))
theorem balanceL_eq_balance {l x r} (sl : Sized l) (sr : Sized r) (H1 : size l = 0 → size r ≤ 1)
(H2 : 1 ≤ size l → 1 ≤ size r → size r ≤ delta * size l) :
@balanceL α l x r = balance l x r := by
obtain - | ⟨rs, rl, rx, rr⟩ := r
· rfl
· obtain - | ⟨ls, ll, lx, lr⟩ := l
· have : size rl = 0 ∧ size rr = 0 := by
have := H1 rfl
rwa [size, sr.1, Nat.succ_le_succ_iff, Nat.le_zero, add_eq_zero] at this
cases sr.2.1.size_eq_zero.1 this.1
cases sr.2.2.size_eq_zero.1 this.2
rw [sr.eq_node']; rfl
· replace H2 : ¬rs > delta * ls := not_lt_of_ge (H2 sl.pos sr.pos)
simp [balanceL, balance, H2]; split_ifs <;> simp [add_comm]
/-- `Raised n m` means `m` is either equal or one up from `n`. -/
def Raised (n m : ℕ) : Prop :=
m = n ∨ m = n + 1
theorem raised_iff {n m} : Raised n m ↔ n ≤ m ∧ m ≤ n + 1 := by
constructor
· rintro (rfl | rfl)
· exact ⟨le_rfl, Nat.le_succ _⟩
· exact ⟨Nat.le_succ _, le_rfl⟩
· rintro ⟨h₁, h₂⟩
rcases eq_or_lt_of_le h₁ with (rfl | h₁)
· exact Or.inl rfl
· exact Or.inr (le_antisymm h₂ h₁)
theorem Raised.dist_le {n m} (H : Raised n m) : Nat.dist n m ≤ 1 := by
obtain ⟨H1, H2⟩ := raised_iff.1 H; rwa [Nat.dist_eq_sub_of_le H1, tsub_le_iff_left]
theorem Raised.dist_le' {n m} (H : Raised n m) : Nat.dist m n ≤ 1 := by
rw [Nat.dist_comm]; exact H.dist_le
theorem Raised.add_left (k) {n m} (H : Raised n m) : Raised (k + n) (k + m) := by
rcases H with (rfl | rfl)
· exact Or.inl rfl
· exact Or.inr rfl
theorem Raised.add_right (k) {n m} (H : Raised n m) : Raised (n + k) (m + k) := by
rw [add_comm, add_comm m]; exact H.add_left _
theorem Raised.right {l x₁ x₂ r₁ r₂} (H : Raised (size r₁) (size r₂)) :
Raised (size (@node' α l x₁ r₁)) (size (@node' α l x₂ r₂)) := by
rw [node', size_node, size_node]; generalize size r₂ = m at H ⊢
rcases H with (rfl | rfl)
· exact Or.inl rfl
· exact Or.inr rfl
theorem balanceL_eq_balance' {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l)
(sr : Sized r)
(H :
(∃ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨
∃ r', Raised (size r) r' ∧ BalancedSz (size l) r') :
@balanceL α l x r = balance' l x r := by
rw [← balance_eq_balance' hl hr sl sr, balanceL_eq_balance sl sr]
· intro l0; rw [l0] at H
rcases H with (⟨_, ⟨⟨⟩⟩ | ⟨⟨⟩⟩, H⟩ | ⟨r', e, H⟩)
· exact balancedSz_zero.1 H.symm
exact le_trans (raised_iff.1 e).1 (balancedSz_zero.1 H.symm)
· intro l1 _
rcases H with (⟨l', e, H | ⟨_, H₂⟩⟩ | ⟨r', e, H | ⟨_, H₂⟩⟩)
· exact le_trans (le_trans (Nat.le_add_left _ _) H) (mul_pos (by decide) l1 : (0 : ℕ) < _)
· exact le_trans H₂ (Nat.mul_le_mul_left _ (raised_iff.1 e).1)
· cases raised_iff.1 e; unfold delta; cutsat
· exact le_trans (raised_iff.1 e).1 H₂
theorem balance_sz_dual {l r}
(H : (∃ l', Raised (@size α l) l' ∧ BalancedSz l' (@size α r)) ∨
∃ r', Raised r' (size r) ∧ BalancedSz (size l) r') :
(∃ l', Raised l' (size (dual r)) ∧ BalancedSz l' (size (dual l))) ∨
∃ r', Raised (size (dual l)) r' ∧ BalancedSz (size (dual r)) r' := by
rw [size_dual, size_dual]
exact
H.symm.imp (Exists.imp fun _ => And.imp_right BalancedSz.symm)
(Exists.imp fun _ => And.imp_right BalancedSz.symm)
theorem size_balanceL {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r)
(H : (∃ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨
∃ r', Raised (size r) r' ∧ BalancedSz (size l) r') :
size (@balanceL α l x r) = size l + size r + 1 := by
rw [balanceL_eq_balance' hl hr sl sr H, size_balance' sl sr]
theorem all_balanceL {P l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r)
(H :
(∃ l', Raised l' (size l) ∧ BalancedSz l' (size r)) ∨
∃ r', Raised (size r) r' ∧ BalancedSz (size l) r') :
All P (@balanceL α l x r) ↔ All P l ∧ P x ∧ All P r := by
rw [balanceL_eq_balance' hl hr sl sr H, all_balance']
theorem balanceR_eq_balance' {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l)
(sr : Sized r)
(H : (∃ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨
∃ r', Raised r' (size r) ∧ BalancedSz (size l) r') :
@balanceR α l x r = balance' l x r := by
rw [← dual_dual (balanceR l x r), dual_balanceR,
balanceL_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H), ← dual_balance',
dual_dual]
theorem size_balanceR {l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r)
(H : (∃ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨
∃ r', Raised r' (size r) ∧ BalancedSz (size l) r') :
size (@balanceR α l x r) = size l + size r + 1 := by
rw [balanceR_eq_balance' hl hr sl sr H, size_balance' sl sr]
theorem all_balanceR {P l x r} (hl : Balanced l) (hr : Balanced r) (sl : Sized l) (sr : Sized r)
(H :
(∃ l', Raised (size l) l' ∧ BalancedSz l' (size r)) ∨
∃ r', Raised r' (size r) ∧ BalancedSz (size l) r') :
All P (@balanceR α l x r) ↔ All P l ∧ P x ∧ All P r := by
rw [balanceR_eq_balance' hl hr sl sr H, all_balance']
section Bounded
variable [Preorder α]
/-- `Bounded t lo hi` says that every element `x ∈ t` is in the range `lo < x < hi`, and also this
property holds recursively in subtrees, making the full tree a BST. The bounds can be set to
`lo = ⊥` and `hi = ⊤` if we care only about the internal ordering constraints. -/
def Bounded : Ordnode α → WithBot α → WithTop α → Prop
| nil, some a, some b => a < b
| nil, _, _ => True
| node _ l x r, o₁, o₂ => Bounded l o₁ x ∧ Bounded r (↑x) o₂
theorem Bounded.dual :
∀ {t : Ordnode α} {o₁ o₂}, Bounded t o₁ o₂ → @Bounded αᵒᵈ _ (dual t) o₂ o₁
| nil, o₁, o₂, h => by cases o₁ <;> cases o₂ <;> trivial
| node _ _ _ _, _, _, ⟨ol, Or⟩ => ⟨Or.dual, ol.dual⟩
theorem Bounded.dual_iff {t : Ordnode α} {o₁ o₂} :
Bounded t o₁ o₂ ↔ @Bounded αᵒᵈ _ (.dual t) o₂ o₁ :=
⟨Bounded.dual, fun h => by
have := Bounded.dual h; rwa [dual_dual, OrderDual.Preorder.dual_dual] at this⟩
theorem Bounded.weak_left : ∀ {t : Ordnode α} {o₁ o₂}, Bounded t o₁ o₂ → Bounded t ⊥ o₂
| nil, o₁, o₂, h => by cases o₂ <;> trivial
| node _ _ _ _, _, _, ⟨ol, Or⟩ => ⟨ol.weak_left, Or⟩
theorem Bounded.weak_right : ∀ {t : Ordnode α} {o₁ o₂}, Bounded t o₁ o₂ → Bounded t o₁ ⊤
| nil, o₁, o₂, h => by cases o₁ <;> trivial
| node _ _ _ _, _, _, ⟨ol, Or⟩ => ⟨ol, Or.weak_right⟩
theorem Bounded.weak {t : Ordnode α} {o₁ o₂} (h : Bounded t o₁ o₂) : Bounded t ⊥ ⊤ :=
h.weak_left.weak_right
theorem Bounded.mono_left {x y : α} (xy : x ≤ y) :
∀ {t : Ordnode α} {o}, Bounded t y o → Bounded t x o
| nil, none, _ => ⟨⟩
| nil, some _, h => lt_of_le_of_lt xy h
| node _ _ _ _, _o, ⟨ol, or⟩ => ⟨ol.mono_left xy, or⟩
theorem Bounded.mono_right {x y : α} (xy : x ≤ y) :
∀ {t : Ordnode α} {o}, Bounded t o x → Bounded t o y
| nil, none, _ => ⟨⟩
| nil, some _, h => lt_of_lt_of_le h xy
| node _ _ _ _, _o, ⟨ol, or⟩ => ⟨ol, or.mono_right xy⟩
theorem Bounded.to_lt : ∀ {t : Ordnode α} {x y : α}, Bounded t x y → x < y
| nil, _, _, h => h
| node _ _ _ _, _, _, ⟨h₁, h₂⟩ => lt_trans h₁.to_lt h₂.to_lt
theorem Bounded.to_nil {t : Ordnode α} : ∀ {o₁ o₂}, Bounded t o₁ o₂ → Bounded nil o₁ o₂
| none, _, _ => ⟨⟩
| some _, none, _ => ⟨⟩
| some _, some _, h => h.to_lt
theorem Bounded.trans_left {t₁ t₂ : Ordnode α} {x : α} :
∀ {o₁ o₂}, Bounded t₁ o₁ x → Bounded t₂ x o₂ → Bounded t₂ o₁ o₂
| none, _, _, h₂ => h₂.weak_left
| some _, _, h₁, h₂ => h₂.mono_left (le_of_lt h₁.to_lt)
theorem Bounded.trans_right {t₁ t₂ : Ordnode α} {x : α} :
∀ {o₁ o₂}, Bounded t₁ o₁ x → Bounded t₂ x o₂ → Bounded t₁ o₁ o₂
| _, none, h₁, _ => h₁.weak_right
| _, some _, h₁, h₂ => h₁.mono_right (le_of_lt h₂.to_lt)
theorem Bounded.mem_lt : ∀ {t o} {x : α}, Bounded t o x → All (· < x) t
| nil, _, _, _ => ⟨⟩
| node _ _ _ _, _, _, ⟨h₁, h₂⟩ =>
⟨h₁.mem_lt.imp fun _ h => lt_trans h h₂.to_lt, h₂.to_lt, h₂.mem_lt⟩
theorem Bounded.mem_gt : ∀ {t o} {x : α}, Bounded t x o → All (· > x) t
| nil, _, _, _ => ⟨⟩
| node _ _ _ _, _, _, ⟨h₁, h₂⟩ => ⟨h₁.mem_gt, h₁.to_lt, h₂.mem_gt.imp fun _ => lt_trans h₁.to_lt⟩
theorem Bounded.of_lt :
∀ {t o₁ o₂} {x : α}, Bounded t o₁ o₂ → Bounded nil o₁ x → All (· < x) t → Bounded t o₁ x
| nil, _, _, _, _, hn, _ => hn
| node _ _ _ _, _, _, _, ⟨h₁, h₂⟩, _, ⟨_, al₂, al₃⟩ => ⟨h₁, h₂.of_lt al₂ al₃⟩
theorem Bounded.of_gt :
∀ {t o₁ o₂} {x : α}, Bounded t o₁ o₂ → Bounded nil x o₂ → All (· > x) t → Bounded t x o₂
| nil, _, _, _, _, hn, _ => hn
| node _ _ _ _, _, _, _, ⟨h₁, h₂⟩, _, ⟨al₁, al₂, _⟩ => ⟨h₁.of_gt al₂ al₁, h₂⟩
theorem Bounded.to_sep {t₁ t₂ o₁ o₂} {x : α}
(h₁ : Bounded t₁ o₁ (x : WithTop α)) (h₂ : Bounded t₂ (x : WithBot α) o₂) :
t₁.All fun y => t₂.All fun z : α => y < z := by
refine h₁.mem_lt.imp fun y yx => ?_
exact h₂.mem_gt.imp fun z xz => lt_trans yx xz
end Bounded
end Ordnode |
.lake/packages/mathlib/Mathlib/Data/Sym/Card.lean | import Mathlib.Data.Finset.Sym
import Mathlib.Data.Fintype.Sum
import Mathlib.Data.Fintype.Prod
import Mathlib.Algebra.BigOperators.Group.Finset.Basic
/-!
# Stars and bars
In this file, we prove (in `Sym.card_sym_eq_multichoose`) that the function `multichoose n k`
defined in `Data/Nat/Choose/Basic` counts the number of multisets of cardinality `k` over an
alphabet of cardinality `n`. In conjunction with `Nat.multichoose_eq` proved in
`Data/Nat/Choose/Basic`, which shows that `multichoose n k = choose (n + k - 1) k`,
this is central to the "stars and bars" technique in combinatorics, where we switch between
counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements
("stars") separated by `n-1` dividers ("bars").
## Informal statement
Many problems in mathematics are of the form of (or can be reduced to) putting `k` indistinguishable
objects into `n` distinguishable boxes; for example, the problem of finding natural numbers
`x1, ..., xn` whose sum is `k`. This is equivalent to forming a multiset of cardinality `k` from
an alphabet of cardinality `n` -- for each box `i ∈ [1, n]` the multiset contains as many copies
of `i` as there are items in the `i`th box.
The "stars and bars" technique arises from another way of presenting the same problem. Instead of
putting `k` items into `n` boxes, we take a row of `k` items (the "stars") and separate them by
inserting `n-1` dividers (the "bars"). For example, the pattern `*|||**|*|` exhibits 4 items
distributed into 6 boxes -- note that any box, including the first and last, may be empty.
Such arrangements of `k` stars and `n-1` bars are in 1-1 correspondence with multisets of size `k`
over an alphabet of size `n`, and are counted by `choose (n + k - 1) k`.
Note that this problem is one component of Gian-Carlo Rota's "Twelvefold Way"
https://en.wikipedia.org/wiki/Twelvefold_way
## Formal statement
Here we generalise the alphabet to an arbitrary fintype `α`, and we use `Sym α k` as the type of
multisets of size `k` over `α`. Thus the statement that these are counted by `multichoose` is:
`Sym.card_sym_eq_multichoose : card (Sym α k) = multichoose (card α) k`
while the "stars and bars" technique gives
`Sym.card_sym_eq_choose : card (Sym α k) = choose (card α + k - 1) k`
## Tags
stars and bars, multichoose
-/
open Finset Fintype Function Sum Nat
variable {α : Type*}
namespace Sym
section Sym
variable (α) (n : ℕ)
/-- Over `Fin (n + 1)`, the multisets of size `k + 1` containing `0` are equivalent to those of size
`k`, as demonstrated by respectively erasing or appending `0`. -/
protected def e1 {n k : ℕ} : { s : Sym (Fin (n + 1)) (k + 1) // ↑0 ∈ s } ≃ Sym (Fin n.succ) k where
toFun s := s.1.erase 0 s.2
invFun s := ⟨cons 0 s, mem_cons_self 0 s⟩
left_inv s := by simp
right_inv s := by simp
/-- The multisets of size `k` over `Fin n+2` not containing `0`
are equivalent to those of size `k` over `Fin n+1`,
as demonstrated by respectively decrementing or incrementing every element of the multiset.
-/
protected def e2 {n k : ℕ} : { s : Sym (Fin n.succ.succ) k // ↑0 ∉ s } ≃ Sym (Fin n.succ) k where
toFun s := map (Fin.predAbove 0) s.1
invFun s :=
⟨map (Fin.succAbove 0) s,
(mt mem_map.1) (not_exists.2 fun t => not_and.2 fun _ => Fin.succAbove_ne _ t)⟩
left_inv s := by
ext1
simp only [map_map]
refine (Sym.map_congr fun v hv ↦ ?_).trans (map_id' _)
exact Fin.succAbove_predAbove (ne_of_mem_of_not_mem hv s.2)
right_inv s := by
simp only [map_map, comp_apply, ← Fin.castSucc_zero, Fin.predAbove_succAbove, map_id']
theorem card_sym_fin_eq_multichoose : ∀ n k : ℕ, card (Sym (Fin n) k) = multichoose n k
| n, 0 => by simp
| 0, k + 1 => by rw [multichoose_zero_succ]; exact card_eq_zero
| 1, k + 1 => by simp
| n + 2, k + 1 => by
rw [multichoose_succ_succ, ← card_sym_fin_eq_multichoose (n + 1) (k + 1),
← card_sym_fin_eq_multichoose (n + 2) k, add_comm (Fintype.card _), ← card_sum]
refine Fintype.card_congr (Equiv.symm ?_)
apply (Sym.e1.symm.sumCongr Sym.e2.symm).trans
apply Equiv.sumCompl
/-- For any fintype `α` of cardinality `n`, `card (Sym α k) = multichoose (card α) k`. -/
theorem card_sym_eq_multichoose (α : Type*) (k : ℕ) [Fintype α] [Fintype (Sym α k)] :
card (Sym α k) = multichoose (card α) k := by
rw [← card_sym_fin_eq_multichoose]
exact card_congr (equivCongr (equivFin α))
/-- The *stars and bars* lemma: the cardinality of `Sym α k` is equal to
`Nat.choose (card α + k - 1) k`. -/
theorem card_sym_eq_choose {α : Type*} [Fintype α] (k : ℕ) [Fintype (Sym α k)] :
card (Sym α k) = (card α + k - 1).choose k := by
rw [card_sym_eq_multichoose, Nat.multichoose_eq]
end Sym
end Sym
namespace Sym2
variable [DecidableEq α]
/-- The `diag` of `s : Finset α` is sent on a finset of `Sym2 α` of card `#s`. -/
theorem card_image_diag (s : Finset α) : #(s.diag.image Sym2.mk) = #s := by
rw [card_image_of_injOn, diag_card]
rintro ⟨x₀, x₁⟩ hx _ _ h
cases Sym2.eq.1 h
· rfl
· simp only [mem_coe, mem_diag] at hx
rw [hx.2]
lemma two_mul_card_image_offDiag (s : Finset α) : 2 * #(s.offDiag.image Sym2.mk) = #s.offDiag := by
rw [card_eq_sum_card_image (Sym2.mk : α × α → _), sum_const_nat (Sym2.ind _), mul_comm]
rintro x y hxy
simp_rw [mem_image, mem_offDiag] at hxy
obtain ⟨a, ⟨ha₁, ha₂, ha⟩, h⟩ := hxy
replace h := Sym2.eq.1 h
obtain ⟨hx, hy, hxy⟩ : x ∈ s ∧ y ∈ s ∧ x ≠ y := by
cases h <;> refine ⟨‹_›, ‹_›, ?_⟩ <;> [exact ha; exact ha.symm]
have hxy' : y ≠ x := hxy.symm
have : {z ∈ s.offDiag | Sym2.mk z = s(x, y)} = {(x, y), (y, x)} := by
ext ⟨x₁, y₁⟩
rw [mem_filter, mem_insert, mem_singleton, Sym2.eq_iff, Prod.mk_inj, Prod.mk_inj,
and_iff_right_iff_imp]
-- `hxy'` is used in `exact`
rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩) <;> rw [mem_offDiag] <;> exact ⟨‹_›, ‹_›, ‹_›⟩
rw [this, card_insert_of_notMem, card_singleton]
simp only [not_and, Prod.mk_inj, mem_singleton]
exact fun _ => hxy'
/-- The `offDiag` of `s : Finset α` is sent on a finset of `Sym2 α` of card `#s.offDiag / 2`.
This is because every element `s(x, y)` of `Sym2 α` not on the diagonal comes from exactly two
pairs: `(x, y)` and `(y, x)`. -/
theorem card_image_offDiag (s : Finset α) : #(s.offDiag.image Sym2.mk) = (#s).choose 2 := by
rw [Nat.choose_two_right, Nat.mul_sub_left_distrib, mul_one, ← offDiag_card,
Nat.div_eq_of_eq_mul_right Nat.zero_lt_two (two_mul_card_image_offDiag s).symm]
theorem card_subtype_diag [Fintype α] : card { a : Sym2 α // a.IsDiag } = card α := by
convert card_image_diag (univ : Finset α)
rw [← filter_image_mk_isDiag, Fintype.card_of_subtype]
rintro x
rw [mem_filter, univ_product_univ, mem_image]
obtain ⟨a, ha⟩ := Quot.exists_rep x
exact and_iff_right ⟨a, mem_univ _, ha⟩
theorem card_subtype_not_diag [Fintype α] :
card { a : Sym2 α // ¬a.IsDiag } = (card α).choose 2 := by
convert card_image_offDiag (univ : Finset α)
rw [← filter_image_mk_not_isDiag, Fintype.card_of_subtype]
rintro x
rw [mem_filter, univ_product_univ, mem_image]
obtain ⟨a, ha⟩ := Quot.exists_rep x
exact and_iff_right ⟨a, mem_univ _, ha⟩
/-- Type **stars and bars** for the case `n = 2`. -/
protected theorem card {α} [Fintype α] : card (Sym2 α) = Nat.choose (card α + 1) 2 :=
Finset.card_sym2 _
end Sym2 |
.lake/packages/mathlib/Mathlib/Data/Sym/Basic.lean | import Mathlib.Algebra.Order.Group.Multiset
import Mathlib.Data.Setoid.Basic
import Mathlib.Data.Vector.Basic
import Mathlib.Logic.Nontrivial.Basic
import Mathlib.Tactic.ApplyFun
/-!
# Symmetric powers
This file defines symmetric powers of a type. The nth symmetric power
consists of homogeneous n-tuples modulo permutations by the symmetric
group.
The special case of 2-tuples is called the symmetric square, which is
addressed in more detail in `Data.Sym.Sym2`.
TODO: This was created as supporting material for `Sym2`; it
needs a fleshed-out interface.
## Tags
symmetric powers
-/
assert_not_exists MonoidWithZero
open List (Vector)
open Function
/-- The nth symmetric power is n-tuples up to permutation. We define it
as a subtype of `Multiset` since these are well developed in the
library. We also give a definition `Sym.sym'` in terms of vectors, and we
show these are equivalent in `Sym.symEquivSym'`.
-/
def Sym (α : Type*) (n : ℕ) :=
{ s : Multiset α // Multiset.card s = n }
deriving [DecidableEq α] → DecidableEq _
/-- The canonical map to `Multiset α` that forgets that `s` has length `n` -/
@[coe] def Sym.toMultiset {α : Type*} {n : ℕ} (s : Sym α n) : Multiset α :=
s.1
instance Sym.hasCoe (α : Type*) (n : ℕ) : CoeOut (Sym α n) (Multiset α) :=
⟨Sym.toMultiset⟩
/-- This is the `List.Perm` setoid lifted to `Vector`.
See note [reducible non-instances].
-/
abbrev List.Vector.Perm.isSetoid (α : Type*) (n : ℕ) : Setoid (Vector α n) :=
(List.isSetoid α).comap Subtype.val
attribute [local instance] Vector.Perm.isSetoid
-- Copy over the `DecidableRel` instance across the definition.
-- (Although `List.Vector.Perm.isSetoid` is an `abbrev`, `List.isSetoid` is not.)
instance {α : Type*} {n : ℕ} [DecidableEq α] :
DecidableRel (· ≈ · : List.Vector α n → List.Vector α n → Prop) :=
fun _ _ => List.decidablePerm _ _
namespace Sym
variable {α β : Type*} {n n' m : ℕ} {s : Sym α n} {a b : α}
theorem coe_injective : Injective ((↑) : Sym α n → Multiset α) :=
Subtype.coe_injective
@[simp, norm_cast]
theorem coe_inj {s₁ s₂ : Sym α n} : (s₁ : Multiset α) = s₂ ↔ s₁ = s₂ :=
coe_injective.eq_iff
@[ext] theorem ext {s₁ s₂ : Sym α n} (h : (s₁ : Multiset α) = ↑s₂) : s₁ = s₂ :=
coe_injective h
@[simp]
theorem val_eq_coe (s : Sym α n) : s.1 = ↑s :=
rfl
/-- Construct an element of the `n`th symmetric power from a multiset of cardinality `n`.
-/
@[match_pattern]
abbrev mk (m : Multiset α) (h : Multiset.card m = n) : Sym α n :=
⟨m, h⟩
/-- The unique element in `Sym α 0`. -/
@[match_pattern]
def nil : Sym α 0 :=
⟨0, Multiset.card_zero⟩
@[simp]
theorem coe_nil : ↑(@Sym.nil α) = (0 : Multiset α) :=
rfl
/-- Inserts an element into the term of `Sym α n`, increasing the length by one.
-/
@[match_pattern]
def cons (a : α) (s : Sym α n) : Sym α n.succ :=
⟨a ::ₘ s.1, by rw [Multiset.card_cons, s.2]⟩
@[inherit_doc]
infixr:67 " ::ₛ " => cons
@[simp]
theorem cons_inj_right (a : α) (s s' : Sym α n) : a ::ₛ s = a ::ₛ s' ↔ s = s' :=
Subtype.ext_iff.trans <| (Multiset.cons_inj_right _).trans Subtype.ext_iff.symm
@[simp]
theorem cons_inj_left (a a' : α) (s : Sym α n) : a ::ₛ s = a' ::ₛ s ↔ a = a' :=
Subtype.ext_iff.trans <| Multiset.cons_inj_left _
theorem cons_swap (a b : α) (s : Sym α n) : a ::ₛ b ::ₛ s = b ::ₛ a ::ₛ s :=
Subtype.ext <| Multiset.cons_swap a b s.1
theorem coe_cons (s : Sym α n) (a : α) : (a ::ₛ s : Multiset α) = a ::ₘ s :=
rfl
/-- This is the quotient map that takes a list of n elements as an n-tuple and produces an nth
symmetric power.
-/
def ofVector : List.Vector α n → Sym α n :=
fun x => ⟨↑x.val, (Multiset.coe_card _).trans x.2⟩
/-- This is the quotient map that takes a list of n elements as an n-tuple and produces an nth
symmetric power.
-/
instance : Coe (List.Vector α n) (Sym α n) where coe x := ofVector x
@[simp]
theorem ofVector_nil : ↑(Vector.nil : List.Vector α 0) = (Sym.nil : Sym α 0) :=
rfl
@[simp]
theorem ofVector_cons (a : α) (v : List.Vector α n) :
↑(Vector.cons a v) = a ::ₛ (↑v : Sym α n) := by
cases v
rfl
@[simp]
theorem card_coe : Multiset.card (s : Multiset α) = n := s.prop
/-- `α ∈ s` means that `a` appears as one of the factors in `s`.
-/
instance : Membership α (Sym α n) :=
⟨fun s a => a ∈ s.1⟩
instance decidableMem [DecidableEq α] (a : α) (s : Sym α n) : Decidable (a ∈ s) :=
s.1.decidableMem _
@[simp, norm_cast] lemma coe_mk (s : Multiset α) (h : Multiset.card s = n) : mk s h = s := rfl
@[simp]
theorem mem_mk (a : α) (s : Multiset α) (h : Multiset.card s = n) : a ∈ mk s h ↔ a ∈ s :=
Iff.rfl
lemma «forall» {p : Sym α n → Prop} :
(∀ s : Sym α n, p s) ↔ ∀ (s : Multiset α) (hs : Multiset.card s = n), p (Sym.mk s hs) := by
simp [Sym]
lemma «exists» {p : Sym α n → Prop} :
(∃ s : Sym α n, p s) ↔ ∃ (s : Multiset α) (hs : Multiset.card s = n), p (Sym.mk s hs) := by
simp [Sym]
@[simp]
theorem notMem_nil (a : α) : a ∉ (nil : Sym α 0) :=
Multiset.notMem_zero a
@[deprecated (since := "2025-05-23")] alias not_mem_nil := notMem_nil
@[simp]
theorem mem_cons : a ∈ b ::ₛ s ↔ a = b ∨ a ∈ s :=
Multiset.mem_cons
@[simp]
theorem mem_coe : a ∈ (s : Multiset α) ↔ a ∈ s :=
Iff.rfl
theorem mem_cons_of_mem (h : a ∈ s) : a ∈ b ::ₛ s :=
Multiset.mem_cons_of_mem h
theorem mem_cons_self (a : α) (s : Sym α n) : a ∈ a ::ₛ s :=
Multiset.mem_cons_self a s.1
theorem cons_of_coe_eq (a : α) (v : List.Vector α n) : a ::ₛ (↑v : Sym α n) = ↑(a ::ᵥ v) :=
Subtype.ext <| by
cases v
rfl
open scoped List in
theorem sound {a b : List.Vector α n} (h : a.val ~ b.val) : (↑a : Sym α n) = ↑b :=
Subtype.ext <| Quotient.sound h
/-- `erase s a h` is the sym that subtracts 1 from the
multiplicity of `a` if a is present in the sym. -/
def erase [DecidableEq α] (s : Sym α (n + 1)) (a : α) (h : a ∈ s) : Sym α n :=
⟨s.val.erase a, (Multiset.card_erase_of_mem h).trans <| s.property.symm ▸ n.pred_succ⟩
@[simp]
theorem erase_mk [DecidableEq α] (m : Multiset α)
(hc : Multiset.card m = n + 1) (a : α) (h : a ∈ m) :
(mk m hc).erase a h = mk (m.erase a)
(by rw [Multiset.card_erase_of_mem h, hc, Nat.add_one, Nat.pred_succ]) :=
rfl
@[simp]
theorem coe_erase [DecidableEq α] {s : Sym α n.succ} {a : α} (h : a ∈ s) :
(s.erase a h : Multiset α) = Multiset.erase s a :=
rfl
@[simp]
theorem cons_erase [DecidableEq α] {s : Sym α n.succ} {a : α} (h : a ∈ s) : a ::ₛ s.erase a h = s :=
coe_injective <| Multiset.cons_erase h
@[simp]
theorem erase_cons_head [DecidableEq α] (s : Sym α n) (a : α)
(h : a ∈ a ::ₛ s := mem_cons_self a s) : (a ::ₛ s).erase a h = s :=
coe_injective <| Multiset.erase_cons_head a s.1
/-- Another definition of the nth symmetric power, using vectors modulo permutations. (See `Sym`.)
-/
def Sym' (α : Type*) (n : ℕ) :=
Quotient (Vector.Perm.isSetoid α n)
/-- This is `cons` but for the alternative `Sym'` definition.
-/
def cons' {α : Type*} {n : ℕ} : α → Sym' α n → Sym' α (Nat.succ n) := fun a =>
Quotient.map (Vector.cons a) fun ⟨_, _⟩ ⟨_, _⟩ h => List.Perm.cons _ h
@[inherit_doc]
scoped notation a " :: " b => cons' a b
/-- Multisets of cardinality n are equivalent to length-n vectors up to permutations.
-/
def symEquivSym' {α : Type*} {n : ℕ} : Sym α n ≃ Sym' α n :=
Equiv.subtypeQuotientEquivQuotientSubtype _ _ (fun _ => by rfl) fun _ _ => by rfl
theorem cons_equiv_eq_equiv_cons (α : Type*) (n : ℕ) (a : α) (s : Sym α n) :
(a::symEquivSym' s) = symEquivSym' (a ::ₛ s) := by
rcases s with ⟨⟨l⟩, _⟩
rfl
instance instZeroSym : Zero (Sym α 0) :=
⟨⟨0, rfl⟩⟩
@[simp] theorem toMultiset_zero : toMultiset (0 : Sym α 0) = 0 := rfl
instance : EmptyCollection (Sym α 0) :=
⟨0⟩
theorem eq_nil_of_card_zero (s : Sym α 0) : s = nil :=
Subtype.ext <| Multiset.card_eq_zero.1 s.2
instance uniqueZero : Unique (Sym α 0) :=
⟨⟨nil⟩, eq_nil_of_card_zero⟩
/-- `replicate n a` is the sym containing only `a` with multiplicity `n`. -/
def replicate (n : ℕ) (a : α) : Sym α n :=
⟨Multiset.replicate n a, Multiset.card_replicate _ _⟩
theorem replicate_succ {a : α} {n : ℕ} : replicate n.succ a = a ::ₛ replicate n a :=
rfl
theorem coe_replicate : (replicate n a : Multiset α) = Multiset.replicate n a :=
rfl
theorem val_replicate : (replicate n a).val = Multiset.replicate n a := by
rw [val_eq_coe, coe_replicate]
@[simp]
theorem mem_replicate : b ∈ replicate n a ↔ n ≠ 0 ∧ b = a :=
Multiset.mem_replicate
theorem eq_replicate_iff : s = replicate n a ↔ ∀ b ∈ s, b = a := by
rw [Subtype.ext_iff, val_replicate, Multiset.eq_replicate]
exact and_iff_right s.2
theorem exists_mem (s : Sym α n.succ) : ∃ a, a ∈ s :=
Multiset.card_pos_iff_exists_mem.1 <| s.2.symm ▸ n.succ_pos
theorem exists_cons_of_mem {s : Sym α (n + 1)} {a : α} (h : a ∈ s) : ∃ t, s = a ::ₛ t := by
obtain ⟨m, h⟩ := Multiset.exists_cons_of_mem h
have : Multiset.card m = n := by
apply_fun Multiset.card at h
rw [s.2, Multiset.card_cons, add_left_inj] at h
exact h.symm
use ⟨m, this⟩
apply Subtype.ext
exact h
theorem exists_eq_cons_of_succ (s : Sym α n.succ) : ∃ (a : α) (s' : Sym α n), s = a ::ₛ s' := by
obtain ⟨a, ha⟩ := exists_mem s
classical exact ⟨a, s.erase a ha, (cons_erase ha).symm⟩
theorem eq_replicate {a : α} {n : ℕ} {s : Sym α n} : s = replicate n a ↔ ∀ b ∈ s, b = a :=
Subtype.ext_iff.trans <| Multiset.eq_replicate.trans <| and_iff_right s.prop
theorem eq_replicate_of_subsingleton [Subsingleton α] (a : α) {n : ℕ} (s : Sym α n) :
s = replicate n a :=
eq_replicate.2 fun _ _ => Subsingleton.elim _ _
instance [Subsingleton α] (n : ℕ) : Subsingleton (Sym α n) :=
⟨by
cases n
· simp [eq_iff_true_of_subsingleton]
· intro s s'
obtain ⟨b, -⟩ := exists_mem s
rw [eq_replicate_of_subsingleton b s', eq_replicate_of_subsingleton b s]⟩
instance inhabitedSym [Inhabited α] (n : ℕ) : Inhabited (Sym α n) :=
⟨replicate n default⟩
instance inhabitedSym' [Inhabited α] (n : ℕ) : Inhabited (Sym' α n) :=
⟨Quotient.mk' (List.Vector.replicate n default)⟩
instance (n : ℕ) [IsEmpty α] : IsEmpty (Sym α n.succ) :=
⟨fun s => by
obtain ⟨a, -⟩ := exists_mem s
exact isEmptyElim a⟩
instance (n : ℕ) [Unique α] : Unique (Sym α n) :=
Unique.mk' _
theorem replicate_right_inj {a b : α} {n : ℕ} (h : n ≠ 0) : replicate n a = replicate n b ↔ a = b :=
Subtype.ext_iff.trans (Multiset.replicate_right_inj h)
theorem replicate_right_injective {n : ℕ} (h : n ≠ 0) :
Function.Injective (replicate n : α → Sym α n) := fun _ _ => (replicate_right_inj h).1
instance (n : ℕ) [Nontrivial α] : Nontrivial (Sym α (n + 1)) :=
(replicate_right_injective n.succ_ne_zero).nontrivial
/-- A function `α → β` induces a function `Sym α n → Sym β n` by applying it to every element of
the underlying `n`-tuple. -/
def map {n : ℕ} (f : α → β) (x : Sym α n) : Sym β n :=
⟨x.val.map f, by simp⟩
@[simp]
theorem mem_map {n : ℕ} {f : α → β} {b : β} {l : Sym α n} :
b ∈ Sym.map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
Multiset.mem_map
/-- Note: `Sym.map_id` is not simp-normal, as simp ends up unfolding `id` with `Sym.map_congr` -/
@[simp]
theorem map_id' {α : Type*} {n : ℕ} (s : Sym α n) : Sym.map (fun x : α => x) s = s := by
ext; simp only [map, Multiset.map_id', ← val_eq_coe]
theorem map_id {α : Type*} {n : ℕ} (s : Sym α n) : Sym.map id s = s := by
ext; simp only [map, id_eq, Multiset.map_id', ← val_eq_coe]
@[simp]
theorem map_map {α β γ : Type*} {n : ℕ} (g : β → γ) (f : α → β) (s : Sym α n) :
Sym.map g (Sym.map f s) = Sym.map (g ∘ f) s :=
Subtype.ext <| by dsimp only [Sym.map]; simp
@[simp]
theorem map_zero (f : α → β) : Sym.map f (0 : Sym α 0) = (0 : Sym β 0) :=
rfl
@[simp]
theorem map_cons {n : ℕ} (f : α → β) (a : α) (s : Sym α n) : (a ::ₛ s).map f = f a ::ₛ s.map f :=
ext <| Multiset.map_cons _ _ _
@[congr]
theorem map_congr {f g : α → β} {s : Sym α n} (h : ∀ x ∈ s, f x = g x) : map f s = map g s :=
Subtype.ext <| Multiset.map_congr rfl h
@[simp]
theorem map_mk {f : α → β} {m : Multiset α} {hc : Multiset.card m = n} :
map f (mk m hc) = mk (m.map f) (by simp [hc]) :=
rfl
@[simp]
theorem coe_map (s : Sym α n) (f : α → β) : ↑(s.map f) = Multiset.map f s :=
rfl
theorem map_injective {f : α → β} (hf : Injective f) (n : ℕ) :
Injective (map f : Sym α n → Sym β n) := fun _ _ h =>
coe_injective <| Multiset.map_injective hf <| coe_inj.2 h
/-- Mapping an equivalence `α ≃ β` using `Sym.map` gives an equivalence between `Sym α n` and
`Sym β n`. -/
@[simps]
def equivCongr (e : α ≃ β) : Sym α n ≃ Sym β n where
toFun := map e
invFun := map e.symm
left_inv x := by rw [map_map, Equiv.symm_comp_self, map_id]
right_inv x := by rw [map_map, Equiv.self_comp_symm, map_id]
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
an element of the symmetric power on `{x // x ∈ s}`. -/
def attach (s : Sym α n) : Sym { x // x ∈ s } n :=
⟨s.val.attach, by (conv_rhs => rw [← s.2, ← Multiset.card_attach])⟩
@[simp]
theorem attach_mk {m : Multiset α} {hc : Multiset.card m = n} :
attach (mk m hc) = mk m.attach (Multiset.card_attach.trans hc) :=
rfl
@[simp]
theorem coe_attach (s : Sym α n) : (s.attach : Multiset { a // a ∈ s }) =
Multiset.attach (s : Multiset α) :=
rfl
theorem attach_map_coe (s : Sym α n) : s.attach.map (↑) = s :=
coe_injective <| Multiset.attach_map_val _
@[simp]
theorem mem_attach (s : Sym α n) (x : { x // x ∈ s }) : x ∈ s.attach :=
Multiset.mem_attach _ _
@[simp]
theorem attach_nil : (nil : Sym α 0).attach = nil :=
rfl
@[simp]
theorem attach_cons (x : α) (s : Sym α n) :
(cons x s).attach =
cons ⟨x, mem_cons_self _ _⟩ (s.attach.map fun x => ⟨x, mem_cons_of_mem x.prop⟩) :=
coe_injective <| Multiset.attach_cons _ _
/-- Change the length of a `Sym` using an equality.
The simp-normal form is for the `cast` to be pushed outward. -/
protected def cast {n m : ℕ} (h : n = m) : Sym α n ≃ Sym α m where
toFun s := ⟨s.val, s.2.trans h⟩
invFun s := ⟨s.val, s.2.trans h.symm⟩
@[simp]
theorem cast_rfl : Sym.cast rfl s = s :=
Subtype.ext rfl
@[simp]
theorem cast_cast {n'' : ℕ} (h : n = n') (h' : n' = n'') :
Sym.cast h' (Sym.cast h s) = Sym.cast (h.trans h') s :=
rfl
@[simp]
theorem coe_cast (h : n = m) : (Sym.cast h s : Multiset α) = s :=
rfl
@[simp]
theorem mem_cast (h : n = m) : a ∈ Sym.cast h s ↔ a ∈ s :=
Iff.rfl
/-- Append a pair of `Sym` terms. -/
def append (s : Sym α n) (s' : Sym α n') : Sym α (n + n') :=
⟨s.1 + s'.1, by rw [Multiset.card_add, s.2, s'.2]⟩
@[simp]
theorem append_inj_right (s : Sym α n) {t t' : Sym α n'} : s.append t = s.append t' ↔ t = t' :=
Subtype.ext_iff.trans <| (add_right_inj _).trans Subtype.ext_iff.symm
@[simp]
theorem append_inj_left {s s' : Sym α n} (t : Sym α n') : s.append t = s'.append t ↔ s = s' :=
Subtype.ext_iff.trans <| (add_left_inj _).trans Subtype.ext_iff.symm
theorem append_comm (s : Sym α n') (s' : Sym α n') :
s.append s' = Sym.cast (add_comm _ _) (s'.append s) := by
simp [append, add_comm]
@[simp, norm_cast]
theorem coe_append (s : Sym α n) (s' : Sym α n') : (s.append s' : Multiset α) = s + s' :=
rfl
theorem mem_append_iff {s' : Sym α m} : a ∈ s.append s' ↔ a ∈ s ∨ a ∈ s' :=
Multiset.mem_add
/-- `a ↦ {a}` as an equivalence between `α` and `Sym α 1`. -/
@[simps apply]
def oneEquiv : α ≃ Sym α 1 where
toFun a := ⟨{a}, by simp⟩
invFun s := (Equiv.subtypeQuotientEquivQuotientSubtype
(·.length = 1) _ (fun _ ↦ Iff.rfl) (fun l l' ↦ by rfl) s).liftOn
(fun l ↦ l.1.head <| List.length_pos_iff.mp <| by simp)
fun ⟨_, _⟩ ⟨_, h⟩ ↦ fun perm ↦ by
obtain ⟨a, rfl⟩ := List.length_eq_one_iff.mp h
exact List.eq_of_mem_singleton (perm.mem_iff.mp <| List.head_mem _)
right_inv := by rintro ⟨⟨l⟩, h⟩; obtain ⟨a, rfl⟩ := List.length_eq_one_iff.mp h; rfl
/-- Fill a term `m : Sym α (n - i)` with `i` copies of `a` to obtain a term of `Sym α n`.
This is a convenience wrapper for `m.append (replicate i a)` that adjusts the term using
`Sym.cast`. -/
def fill (a : α) (i : Fin (n + 1)) (m : Sym α (n - i)) : Sym α n :=
Sym.cast (Nat.sub_add_cancel i.is_le) (m.append (replicate i a))
theorem coe_fill {a : α} {i : Fin (n + 1)} {m : Sym α (n - i)} :
(fill a i m : Multiset α) = m + replicate i a :=
rfl
theorem mem_fill_iff {a b : α} {i : Fin (n + 1)} {s : Sym α (n - i)} :
a ∈ Sym.fill b i s ↔ (i : ℕ) ≠ 0 ∧ a = b ∨ a ∈ s := by
rw [fill, mem_cast, mem_append_iff, or_comm, mem_replicate]
open Multiset
/-- Remove every `a` from a given `Sym α n`.
Yields the number of copies `i` and a term of `Sym α (n - i)`. -/
def filterNe [DecidableEq α] (a : α) (m : Sym α n) : Σ i : Fin (n + 1), Sym α (n - i) :=
⟨⟨m.1.count a, (count_le_card _ _).trans_lt <| by rw [m.2, Nat.lt_succ_iff]⟩,
m.1.filter (a ≠ ·),
Nat.eq_sub_of_add_eq <|
Eq.trans
(by
rw [← countP_eq_card_filter, add_comm]
simp only [eq_comm, Ne, count]
rw [← card_eq_countP_add_countP _ _])
m.2⟩
theorem sigma_sub_ext {m₁ m₂ : Σ i : Fin (n + 1), Sym α (n - i)} (h : (m₁.2 : Multiset α) = m₂.2) :
m₁ = m₂ :=
Sigma.subtype_ext
(Fin.ext <| by
rw [← Nat.sub_sub_self (Nat.le_of_lt_succ m₁.1.is_lt), ← m₁.2.2, val_eq_coe, h,
← val_eq_coe, m₂.2.2, Nat.sub_sub_self (Nat.le_of_lt_succ m₂.1.is_lt)])
h
theorem fill_filterNe [DecidableEq α] (a : α) (m : Sym α n) :
(m.filterNe a).2.fill a (m.filterNe a).1 = m :=
Sym.ext
(by
rw [coe_fill, filterNe, ← val_eq_coe, Subtype.coe_mk, Fin.val_mk]
ext b; dsimp
rw [count_add, count_filter, Sym.coe_replicate, count_replicate]
obtain rfl | h := eq_or_ne a b
· rw [if_pos rfl, if_neg (not_not.2 rfl), zero_add]
· rw [if_pos h, if_neg h, add_zero])
theorem filter_ne_fill
[DecidableEq α] (a : α) (m : Σ i : Fin (n + 1), Sym α (n - i)) (h : a ∉ m.2) :
(m.2.fill a m.1).filterNe a = m :=
sigma_sub_ext
(by
rw [filterNe, ← val_eq_coe, Subtype.coe_mk, val_eq_coe, coe_fill]
rw [filter_add, filter_eq_self.2, add_eq_left, eq_zero_iff_forall_notMem]
· intro b hb
rw [mem_filter, Sym.mem_coe, mem_replicate] at hb
exact hb.2 hb.1.2.symm
· exact fun a ha ha' => h <| ha'.symm ▸ ha)
theorem count_coe_fill_self_of_notMem [DecidableEq α] {a : α} {i : Fin (n + 1)} {s : Sym α (n - i)}
(hx : a ∉ s) :
count a (fill a i s : Multiset α) = i := by
simp [coe_fill, coe_replicate, hx]
@[deprecated (since := "2025-05-23")]
alias count_coe_fill_self_of_not_mem := count_coe_fill_self_of_notMem
theorem count_coe_fill_of_ne [DecidableEq α] {a x : α} {i : Fin (n + 1)} {s : Sym α (n - i)}
(hx : x ≠ a) :
count x (fill a i s : Multiset α) = count x s := by
suffices x ∉ Multiset.replicate i a by simp [coe_fill, coe_replicate, this]
simp [Multiset.mem_replicate, hx]
end Sym
section Equiv
/-! ### Combinatorial equivalences -/
variable {α : Type*} {n : ℕ}
open Sym
namespace SymOptionSuccEquiv
/-- Function from the symmetric product over `Option` splitting on whether or not
it contains a `none`. -/
def encode [DecidableEq α] (s : Sym (Option α) n.succ) : Sym (Option α) n ⊕ Sym α n.succ :=
if h : none ∈ s then Sum.inl (s.erase none h)
else
Sum.inr
(s.attach.map fun o =>
o.1.get <| Option.ne_none_iff_isSome.1 <| ne_of_mem_of_not_mem o.2 h)
@[simp]
theorem encode_of_none_mem [DecidableEq α] (s : Sym (Option α) n.succ) (h : none ∈ s) :
encode s = Sum.inl (s.erase none h) :=
dif_pos h
@[simp]
theorem encode_of_none_notMem [DecidableEq α] (s : Sym (Option α) n.succ) (h : none ∉ s) :
encode s =
Sum.inr
(s.attach.map fun o =>
o.1.get <| Option.ne_none_iff_isSome.1 <| ne_of_mem_of_not_mem o.2 h) :=
dif_neg h
@[deprecated (since := "2025-05-23")]
alias encode_of_not_none_mem := encode_of_none_notMem
/-- Inverse of `Sym_option_succ_equiv.decode`. -/
def decode : Sym (Option α) n ⊕ Sym α n.succ → Sym (Option α) n.succ
| Sum.inl s => none ::ₛ s
| Sum.inr s => s.map Embedding.some
@[simp]
theorem decode_inl (s : Sym (Option α) n) : decode (Sum.inl s) = none ::ₛ s :=
rfl
@[simp]
theorem decode_inr (s : Sym α n.succ) : decode (Sum.inr s) = s.map Embedding.some :=
rfl
@[simp]
theorem decode_encode [DecidableEq α] (s : Sym (Option α) n.succ) : decode (encode s) = s := by
by_cases h : none ∈ s
· simp [h]
· simp only [decode, h, not_false_iff, encode_of_none_notMem, Embedding.some_apply, map_map,
comp_apply, Option.some_get]
convert s.attach_map_coe
@[simp]
theorem encode_decode [DecidableEq α] (s : Sym (Option α) n ⊕ Sym α n.succ) :
encode (decode s) = s := by
obtain s | s := s
· simp
· unfold SymOptionSuccEquiv.encode
split_ifs with h
· obtain ⟨a, _, ha⟩ := Multiset.mem_map.mp h
exact Option.some_ne_none _ ha
· refine congr_arg Sum.inr ?_
refine map_injective (Option.some_injective _) _ ?_
refine Eq.trans ?_ (.trans (SymOptionSuccEquiv.decode (Sum.inr s)).attach_map_coe ?_) <;> simp
end SymOptionSuccEquiv
/-- The symmetric product over `Option` is a disjoint union over simpler symmetric products. -/
--@[simps]
def symOptionSuccEquiv [DecidableEq α] :
Sym (Option α) n.succ ≃ Sym (Option α) n ⊕ Sym α n.succ where
toFun := SymOptionSuccEquiv.encode
invFun := SymOptionSuccEquiv.decode
left_inv := SymOptionSuccEquiv.decode_encode
right_inv := SymOptionSuccEquiv.encode_decode
end Equiv |
.lake/packages/mathlib/Mathlib/Data/Sym/Sym2.lean | import Mathlib.Algebra.Group.Action.Pi
import Mathlib.Data.Finset.Prod
import Mathlib.Data.SetLike.Basic
import Mathlib.Data.Sym.Basic
import Mathlib.Data.Sym.Sym2.Init
/-!
# The symmetric square
This file defines the symmetric square, which is `α × α` modulo
swapping. This is also known as the type of unordered pairs.
More generally, the symmetric square is the second symmetric power
(see `Data.Sym.Basic`). The equivalence is `Sym2.equivSym`.
From the point of view that an unordered pair is equivalent to a
multiset of cardinality two (see `Sym2.equivMultiset`), there is a
`Mem` instance `Sym2.Mem`, which is a `Prop`-valued membership
test. Given `h : a ∈ z` for `z : Sym2 α`, then `Mem.other h` is the other
element of the pair, defined using `Classical.choice`. If `α` has
decidable equality, then `h.other'` computably gives the other element.
The universal property of `Sym2` is provided as `Sym2.lift`, which
states that functions from `Sym2 α` are equivalent to symmetric
two-argument functions from `α`.
Recall that an undirected graph (allowing self loops, but no multiple
edges) is equivalent to a symmetric relation on the vertex type `α`.
Given a symmetric relation on `α`, the corresponding edge set is
constructed by `Sym2.fromRel` which is a special case of `Sym2.lift`.
## Notation
The element `Sym2.mk (a, b)` can be written as `s(a, b)` for short.
## Tags
symmetric square, unordered pairs, symmetric powers
-/
assert_not_exists MonoidWithZero
open List (Vector)
open Finset Function Sym
universe u
variable {α β γ : Type*}
namespace Sym2
/-- This is the relation capturing the notion of pairs equivalent up to permutations. -/
@[aesop (rule_sets := [Sym2]) [safe [constructors, cases], norm]]
inductive Rel (α : Type u) : α × α → α × α → Prop
| refl (x y : α) : Rel _ (x, y) (x, y)
| swap (x y : α) : Rel _ (x, y) (y, x)
attribute [refl] Rel.refl
@[symm]
theorem Rel.symm {x y : α × α} : Rel α x y → Rel α y x := by aesop (rule_sets := [Sym2])
@[trans]
theorem Rel.trans {x y z : α × α} (a : Rel α x y) (b : Rel α y z) : Rel α x z := by
aesop (rule_sets := [Sym2])
theorem Rel.is_equivalence : Equivalence (Rel α) :=
{ refl := fun (x, y) ↦ Rel.refl x y, symm := Rel.symm, trans := Rel.trans }
/-- One can use `attribute [local instance] Sym2.Rel.setoid` to temporarily
make `Quotient` functionality work for `α × α`. -/
def Rel.setoid (α : Type u) : Setoid (α × α) :=
⟨Rel α, Rel.is_equivalence⟩
@[simp]
theorem rel_iff' {p q : α × α} : Rel α p q ↔ p = q ∨ p = q.swap := by
aesop (rule_sets := [Sym2])
theorem rel_iff {x y z w : α} : Rel α (x, y) (z, w) ↔ x = z ∧ y = w ∨ x = w ∧ y = z := by
simp
end Sym2
/-- `Sym2 α` is the symmetric square of `α`, which, in other words, is the
type of unordered pairs.
It is equivalent in a natural way to multisets of cardinality 2 (see
`Sym2.equivMultiset`).
-/
abbrev Sym2 (α : Type u) := Quot (Sym2.Rel α)
/-- Constructor for `Sym2`. This is the quotient map `α × α → Sym2 α`. -/
protected abbrev Sym2.mk {α : Type*} (p : α × α) : Sym2 α := Quot.mk (Sym2.Rel α) p
/-- `s(x, y)` is an unordered pair,
which is to say a pair modulo the action of the symmetric group.
It is equal to `Sym2.mk (x, y)`. -/
notation3 "s(" x ", " y ")" => Sym2.mk (x, y)
namespace Sym2
protected theorem sound {p p' : α × α} (h : Sym2.Rel α p p') : Sym2.mk p = Sym2.mk p' :=
Quot.sound h
protected theorem exact {p p' : α × α} (h : Sym2.mk p = Sym2.mk p') : Sym2.Rel α p p' :=
Quotient.exact (s := Sym2.Rel.setoid α) h
@[simp]
protected theorem eq {p p' : α × α} : Sym2.mk p = Sym2.mk p' ↔ Sym2.Rel α p p' :=
Quotient.eq' (s₁ := Sym2.Rel.setoid α)
@[elab_as_elim, cases_eliminator, induction_eliminator]
protected theorem ind {f : Sym2 α → Prop} (h : ∀ x y, f s(x, y)) : ∀ i, f i :=
Quot.ind <| Prod.rec <| h
@[elab_as_elim]
protected theorem inductionOn {f : Sym2 α → Prop} (i : Sym2 α) (hf : ∀ x y, f s(x, y)) : f i :=
i.ind hf
@[elab_as_elim]
protected theorem inductionOn₂ {f : Sym2 α → Sym2 β → Prop} (i : Sym2 α) (j : Sym2 β)
(hf : ∀ a₁ a₂ b₁ b₂, f s(a₁, a₂) s(b₁, b₂)) : f i j :=
Quot.induction_on₂ i j <| by
intro ⟨a₁, a₂⟩ ⟨b₁, b₂⟩
exact hf _ _ _ _
/-- Dependent recursion principal for `Sym2`. See `Quot.rec`. -/
@[elab_as_elim]
protected def rec {motive : Sym2 α → Sort*}
(f : (p : α × α) → motive (Sym2.mk p))
(h : (p q : α × α) → (h : Sym2.Rel α p q) → Eq.ndrec (f p) (Sym2.sound h) = f q)
(z : Sym2 α) : motive z :=
Quot.rec f h z
/-- Dependent recursion principal for `Sym2` when the target is a `Subsingleton` type.
See `Quot.recOnSubsingleton`. -/
@[elab_as_elim]
protected abbrev recOnSubsingleton {motive : Sym2 α → Sort*}
[(p : α × α) → Subsingleton (motive (Sym2.mk p))]
(z : Sym2 α) (f : (p : α × α) → motive (Sym2.mk p)) : motive z :=
Quot.recOnSubsingleton z f
theorem mk_surjective : Function.Surjective (@Sym2.mk α) := Quot.mk_surjective
protected theorem «exists» {α : Sort _} {f : Sym2 α → Prop} :
(∃ x : Sym2 α, f x) ↔ ∃ x y, f s(x, y) :=
mk_surjective.exists.trans Prod.exists
protected theorem «forall» {α : Sort _} {f : Sym2 α → Prop} :
(∀ x : Sym2 α, f x) ↔ ∀ x y, f s(x, y) :=
mk_surjective.forall.trans Prod.forall
theorem eq_swap {a b : α} : s(a, b) = s(b, a) := Quot.sound (Rel.swap _ _)
@[simp]
theorem mk_prod_swap_eq {p : α × α} : Sym2.mk p.swap = Sym2.mk p := by
cases p
exact eq_swap
theorem congr_right {a b c : α} : s(a, b) = s(a, c) ↔ b = c := by
simp +contextual
theorem congr_left {a b c : α} : s(b, a) = s(c, a) ↔ b = c := by
simp +contextual
theorem eq_iff {x y z w : α} : s(x, y) = s(z, w) ↔ x = z ∧ y = w ∨ x = w ∧ y = z := by
simp
theorem mk_eq_mk_iff {p q : α × α} : Sym2.mk p = Sym2.mk q ↔ p = q ∨ p = q.swap := by
simp
/-- The universal property of `Sym2`; symmetric functions of two arguments are equivalent to
functions from `Sym2`. Note that when `β` is `Prop`, it can sometimes be more convenient to use
`Sym2.fromRel` instead. -/
def lift : { f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁ } ≃ (Sym2 α → β) where
toFun f :=
Quot.lift (uncurry ↑f) <| by
rintro _ _ ⟨⟩
exacts [rfl, f.prop _ _]
invFun F := ⟨curry (F ∘ Sym2.mk), fun _ _ => congr_arg F eq_swap⟩
right_inv _ := funext <| Sym2.ind fun _ _ => rfl
@[simp]
theorem lift_mk (f : { f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁ }) (a₁ a₂ : α) :
lift f s(a₁, a₂) = (f : α → α → β) a₁ a₂ :=
rfl
@[simp]
theorem coe_lift_symm_apply (F : Sym2 α → β) (a₁ a₂ : α) :
(lift.symm F : α → α → β) a₁ a₂ = F s(a₁, a₂) :=
rfl
/-- A two-argument version of `Sym2.lift`. -/
def lift₂ :
{ f : α → α → β → β → γ //
∀ a₁ a₂ b₁ b₂, f a₁ a₂ b₁ b₂ = f a₂ a₁ b₁ b₂ ∧ f a₁ a₂ b₁ b₂ = f a₁ a₂ b₂ b₁ } ≃
(Sym2 α → Sym2 β → γ) where
toFun f :=
Quotient.lift₂ (s₁ := Sym2.Rel.setoid α) (s₂ := Sym2.Rel.setoid β)
(fun (a : α × α) (b : β × β) => f.1 a.1 a.2 b.1 b.2)
(by
rintro _ _ _ _ ⟨⟩ ⟨⟩
exacts [rfl, (f.2 _ _ _ _).2, (f.2 _ _ _ _).1, (f.2 _ _ _ _).1.trans (f.2 _ _ _ _).2])
invFun F :=
⟨fun a₁ a₂ b₁ b₂ => F s(a₁, a₂) s(b₁, b₂), fun a₁ a₂ b₁ b₂ => by
constructor
exacts [congr_arg₂ F eq_swap rfl, congr_arg₂ F rfl eq_swap]⟩
right_inv _ := funext₂ fun a b => Sym2.inductionOn₂ a b fun _ _ _ _ => rfl
@[simp]
theorem lift₂_mk
(f :
{ f : α → α → β → β → γ //
∀ a₁ a₂ b₁ b₂, f a₁ a₂ b₁ b₂ = f a₂ a₁ b₁ b₂ ∧ f a₁ a₂ b₁ b₂ = f a₁ a₂ b₂ b₁ })
(a₁ a₂ : α) (b₁ b₂ : β) : lift₂ f s(a₁, a₂) s(b₁, b₂) = (f : α → α → β → β → γ) a₁ a₂ b₁ b₂ :=
rfl
@[simp]
theorem coe_lift₂_symm_apply (F : Sym2 α → Sym2 β → γ) (a₁ a₂ : α) (b₁ b₂ : β) :
(lift₂.symm F : α → α → β → β → γ) a₁ a₂ b₁ b₂ = F s(a₁, a₂) s(b₁, b₂) :=
rfl
/-- The functor `Sym2` is functorial, and this function constructs the induced maps.
-/
def map (f : α → β) : Sym2 α → Sym2 β :=
Quot.map (Prod.map f f)
(by intro _ _ h; cases h <;> constructor)
@[simp]
theorem map_id : map (@id α) = id := by
ext ⟨⟨x, y⟩⟩
rfl
theorem map_comp {g : β → γ} {f : α → β} : Sym2.map (g ∘ f) = Sym2.map g ∘ Sym2.map f := by
ext ⟨⟨x, y⟩⟩
rfl
theorem map_map {g : β → γ} {f : α → β} (x : Sym2 α) : map g (map f x) = map (g ∘ f) x := by
induction x; aesop
theorem map_mk (f : α → β) (x : α × α) : map f (Sym2.mk x) = Sym2.mk (Prod.map f f x) := rfl
@[simp]
theorem map_pair_eq (f : α → β) (x y : α) : map f s(x, y) = s(f x, f y) :=
rfl
theorem map.injective {f : α → β} (hinj : Injective f) : Injective (map f) := by
intro z z'
refine Sym2.inductionOn₂ z z' (fun x y x' y' => ?_)
simp [hinj.eq_iff]
/-- `mk a` as an embedding. This is the symmetric version of `Function.Embedding.sectL`. -/
@[simps]
def mkEmbedding (a : α) : α ↪ Sym2 α where
toFun b := s(a, b)
inj' b₁ b₁ h := by
simp only [Sym2.eq, Sym2.rel_iff', Prod.mk.injEq, true_and, Prod.swap_prod_mk] at h
obtain rfl | ⟨rfl, rfl⟩ := h <;> rfl
/-- `Sym2.map` as an embedding. -/
@[simps]
def _root_.Function.Embedding.sym2Map (f : α ↪ β) : Sym2 α ↪ Sym2 β where
toFun := map f
inj' := map.injective f.injective
lemma lift_comp_map {g : γ → α} (f : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁}) :
lift f ∘ map g = lift ⟨fun (c₁ c₂ : γ) => f.val (g c₁) (g c₂), fun _ _ => f.prop _ _⟩ :=
lift.symm_apply_eq.mp rfl
lemma lift_map_apply {g : γ → α} (f : {f : α → α → β // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁}) (p : Sym2 γ) :
lift f (map g p) = lift ⟨fun (c₁ c₂ : γ) => f.val (g c₁) (g c₂), fun _ _ => f.prop _ _⟩ p := by
conv_rhs => rw [← lift_comp_map, comp_apply]
section Membership
/-! ### Membership and set coercion -/
/-- This is a predicate that determines whether a given term is a member of a term of the
symmetric square. From this point of view, the symmetric square is the subtype of
cardinality-two multisets on `α`.
-/
protected def Mem (x : α) (z : Sym2 α) : Prop :=
∃ y : α, z = s(x, y)
@[aesop norm (rule_sets := [Sym2])]
theorem mem_iff' {a b c : α} : Sym2.Mem a s(b, c) ↔ a = b ∨ a = c :=
{ mp := by
rintro ⟨_, h⟩
rw [eq_iff] at h
aesop
mpr := by
rintro (rfl | rfl)
· exact ⟨_, rfl⟩
rw [eq_swap]
exact ⟨_, rfl⟩ }
instance : SetLike (Sym2 α) α where
coe z := { x | z.Mem x }
coe_injective' z z' h := by
simp only [Set.ext_iff, Set.mem_setOf_eq] at h
obtain ⟨x, y⟩ := z
obtain ⟨x', y'⟩ := z'
have hx := h x; have hy := h y; have hx' := h x'; have hy' := h y'
simp only [mem_iff'] at hx hy hx' hy'
aesop
@[simp]
theorem mem_iff_mem {x : α} {z : Sym2 α} : Sym2.Mem x z ↔ x ∈ z :=
Iff.rfl
theorem mem_iff_exists {x : α} {z : Sym2 α} : x ∈ z ↔ ∃ y : α, z = s(x, y) :=
Iff.rfl
@[ext]
theorem ext {p q : Sym2 α} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q :=
SetLike.ext h
theorem mem_mk_left (x y : α) : x ∈ s(x, y) :=
⟨y, rfl⟩
theorem mem_mk_right (x y : α) : y ∈ s(x, y) :=
eq_swap ▸ mem_mk_left y x
@[simp, aesop norm (rule_sets := [Sym2])]
theorem mem_iff {a b c : α} : a ∈ s(b, c) ↔ a = b ∨ a = c :=
mem_iff'
theorem out_fst_mem (e : Sym2 α) : e.out.1 ∈ e :=
⟨e.out.2, by rw [Sym2.mk, e.out_eq]⟩
theorem out_snd_mem (e : Sym2 α) : e.out.2 ∈ e :=
⟨e.out.1, by rw [eq_swap, Sym2.mk, e.out_eq]⟩
theorem ball {p : α → Prop} {a b : α} : (∀ c ∈ s(a, b), p c) ↔ p a ∧ p b := by
simp
@[simp] lemma coe_mk {x y : α} : (s(x, y) : Set α) = {x, y} := by ext z; simp
/-- Given an element of the unordered pair, give the other element using `Classical.choose`.
See also `Mem.other'` for the computable version.
-/
noncomputable def Mem.other {a : α} {z : Sym2 α} (h : a ∈ z) : α :=
Classical.choose h
@[simp]
theorem other_spec {a : α} {z : Sym2 α} (h : a ∈ z) : s(a, Mem.other h) = z :=
(Classical.choose_spec h).symm
theorem other_mem {a : α} {z : Sym2 α} (h : a ∈ z) : Mem.other h ∈ z := by
convert mem_mk_right a <| Mem.other h
rw [other_spec h]
theorem mem_and_mem_iff {x y : α} {z : Sym2 α} (hne : x ≠ y) : x ∈ z ∧ y ∈ z ↔ z = s(x, y) := by
constructor
· cases z
rw [mem_iff, mem_iff]
aesop
· rintro rfl
simp
theorem eq_of_ne_mem {x y : α} {z z' : Sym2 α} (h : x ≠ y) (h1 : x ∈ z) (h2 : y ∈ z) (h3 : x ∈ z')
(h4 : y ∈ z') : z = z' :=
((mem_and_mem_iff h).mp ⟨h1, h2⟩).trans ((mem_and_mem_iff h).mp ⟨h3, h4⟩).symm
instance Mem.decidable [DecidableEq α] (x : α) (z : Sym2 α) : Decidable (x ∈ z) :=
z.recOnSubsingleton fun ⟨_, _⟩ => decidable_of_iff' _ mem_iff
end Membership
@[simp]
theorem mem_map {f : α → β} {b : β} {z : Sym2 α} : b ∈ Sym2.map f z ↔ ∃ a, a ∈ z ∧ f a = b := by
cases z
simp only [map_pair_eq, mem_iff, exists_eq_or_imp, exists_eq_left]
aesop
@[congr]
theorem map_congr {f g : α → β} {s : Sym2 α} (h : ∀ x ∈ s, f x = g x) : map f s = map g s := by
ext y
simp only [mem_map]
constructor <;>
· rintro ⟨w, hw, rfl⟩
exact ⟨w, hw, by simp [hw, h]⟩
/-- Note: `Sym2.map_id` will not simplify `Sym2.map id z` due to `Sym2.map_congr`. -/
@[simp]
theorem map_id' : (map fun x : α => x) = id :=
map_id
/--
Partial map. If `f : ∀ a, p a → β` is a partial function defined on `a : α` satisfying `p`,
then `pmap f s h` is essentially the same as `map f s` but is defined only when all members of `s`
satisfy `p`, using the proof to apply `f`.
-/
def pmap {P : α → Prop} (f : ∀ a, P a → β) (s : Sym2 α) : (∀ a ∈ s, P a) → Sym2 β :=
let g (p : α × α) (H : ∀ a ∈ Sym2.mk p, P a) : Sym2 β :=
s(f p.1 (H p.1 <| mem_mk_left _ _), f p.2 (H p.2 <| mem_mk_right _ _))
Quot.recOn s g fun p q hpq => funext fun Hq => by
rw [rel_iff'] at hpq
have Hp : ∀ a ∈ Sym2.mk p, P a := fun a hmem =>
Hq a (Sym2.mk_eq_mk_iff.2 hpq ▸ hmem : a ∈ Sym2.mk q)
have h : ∀ {s₂ e H}, Eq.ndrec (motive := fun s => (∀ a ∈ s, P a) → Sym2 β) (g p) (b := s₂) e H =
g p Hp := by
rintro s₂ rfl _
rfl
refine h.trans (Quot.sound ?_)
rw [rel_iff', Prod.mk.injEq, Prod.swap_prod_mk]
apply hpq.imp <;> rintro rfl <;> simp
theorem forall_mem_pair {P : α → Prop} {a b : α} : (∀ x ∈ s(a, b), P x) ↔ P a ∧ P b := by
simp only [mem_iff, forall_eq_or_imp, forall_eq]
lemma pair_eq_pmap {P : α → Prop} (f : ∀ a, P a → β) (a b : α) (h : P a) (h' : P b) :
s(f a h, f b h') = pmap f s(a, b) (forall_mem_pair.mpr ⟨h, h'⟩) := rfl
lemma pmap_pair {P : α → Prop} (f : ∀ a, P a → β) (a b : α) (h : ∀ x ∈ s(a, b), P x) :
pmap f s(a, b) h = s(f a (h a (mem_mk_left a b)), f b (h b (mem_mk_right a b))) := rfl
@[simp]
lemma mem_pmap_iff {P : α → Prop} (f : ∀ a, P a → β) (z : Sym2 α) (h : ∀ a ∈ z, P a) (b : β) :
b ∈ z.pmap f h ↔ ∃ (a : α) (ha : a ∈ z), b = f a (h a ha) := by
obtain ⟨x, y⟩ := z
rw [pmap_pair f x y h]
aesop
lemma pmap_eq_map {P : α → Prop} (f : α → β) (z : Sym2 α) (h : ∀ a ∈ z, P a) :
z.pmap (fun a _ => f a) h = z.map f := by
cases z; rfl
lemma map_pmap {Q : β → Prop} (f : α → β) (g : ∀ b, Q b → γ) (z : Sym2 α) (h : ∀ b ∈ z.map f, Q b) :
(z.map f).pmap g h =
z.pmap (fun a ha => g (f a) (h (f a) (mem_map.mpr ⟨a, ha, rfl⟩))) (fun _ ha => ha) := by
cases z; rfl
lemma pmap_map {P : α → Prop} {Q : β → Prop} (f : ∀ a, P a → β) (g : β → γ)
(z : Sym2 α) (h : ∀ a ∈ z, P a) (h' : ∀ b ∈ z.pmap f h, Q b) :
(z.pmap f h).map g = z.pmap (fun a ha => g (f a (h a ha))) (fun _ ha ↦ ha) := by
cases z; rfl
lemma pmap_pmap {P : α → Prop} {Q : β → Prop} (f : ∀ a, P a → β) (g : ∀ b, Q b → γ)
(z : Sym2 α) (h : ∀ a ∈ z, P a) (h' : ∀ b ∈ z.pmap f h, Q b) :
(z.pmap f h).pmap g h' = z.pmap (fun a ha => g (f a (h a ha))
(h' _ ((mem_pmap_iff f z h _).mpr ⟨a, ha, rfl⟩))) (fun _ ha ↦ ha) := by
cases z; rfl
@[simp]
lemma pmap_subtype_map_subtypeVal {P : α → Prop} (s : Sym2 α) (h : ∀ a ∈ s, P a) :
(s.pmap Subtype.mk h).map Subtype.val = s := by
cases s; rfl
/--
"Attach" a proof `P a` that holds for all the elements of `s` to produce a new Sym2 object
with the same elements but in the type `{x // P x}`.
-/
def attachWith {P : α → Prop} (s : Sym2 α) (h : ∀ a ∈ s, P a) : Sym2 {a // P a} :=
pmap Subtype.mk s h
@[simp]
lemma attachWith_map_subtypeVal {s : Sym2 α} {P : α → Prop} (h : ∀ a ∈ s, P a) :
(s.attachWith h).map Subtype.val = s := by
cases s; rfl
/-! ### Diagonal -/
variable {e : Sym2 α} {f : α → β}
/-- A type `α` is naturally included in the diagonal of `α × α`, and this function gives the image
of this diagonal in `Sym2 α`.
-/
def diag (x : α) : Sym2 α := s(x, x)
theorem diag_injective : Function.Injective (Sym2.diag : α → Sym2 α) := fun x y h => by
cases Sym2.exact h <;> rfl
/-- A predicate for testing whether an element of `Sym2 α` is on the diagonal.
-/
def IsDiag : Sym2 α → Prop :=
lift ⟨Eq, fun _ _ => propext eq_comm⟩
theorem mk_isDiag_iff {x y : α} : IsDiag s(x, y) ↔ x = y :=
Iff.rfl
@[simp]
theorem isDiag_iff_proj_eq (z : α × α) : IsDiag (Sym2.mk z) ↔ z.1 = z.2 :=
Prod.recOn z fun _ _ => mk_isDiag_iff
protected lemma IsDiag.map : e.IsDiag → (e.map f).IsDiag := Sym2.ind (fun _ _ ↦ congr_arg f) e
lemma isDiag_map (hf : Injective f) : (e.map f).IsDiag ↔ e.IsDiag :=
Sym2.ind (fun _ _ ↦ hf.eq_iff) e
@[simp]
theorem diag_isDiag (a : α) : IsDiag (diag a) :=
Eq.refl a
theorem IsDiag.mem_range_diag {z : Sym2 α} : IsDiag z → z ∈ Set.range (@diag α) := by
obtain ⟨x, y⟩ := z
rintro (rfl : x = y)
exact ⟨_, rfl⟩
theorem isDiag_iff_mem_range_diag (z : Sym2 α) : IsDiag z ↔ z ∈ Set.range (@diag α) :=
⟨IsDiag.mem_range_diag, fun ⟨i, hi⟩ => hi ▸ diag_isDiag i⟩
instance IsDiag.decidablePred (α : Type u) [DecidableEq α] : DecidablePred (@IsDiag α) :=
fun z => z.recOnSubsingleton fun a => decidable_of_iff' _ (isDiag_iff_proj_eq a)
theorem other_ne {a : α} {z : Sym2 α} (hd : ¬IsDiag z) (h : a ∈ z) : Mem.other h ≠ a := by
contrapose! hd
have h' := Sym2.other_spec h
rw [hd] at h'
rw [← h']
simp
section Relations
/-! ### Declarations about symmetric relations -/
variable {r r₁ r₂ : α → α → Prop}
/-- Symmetric relations define a set on `Sym2 α` by taking all those pairs
of elements that are related.
-/
def fromRel (sym : Symmetric r) : Set (Sym2 α) :=
setOf (lift ⟨r, fun _ _ => propext ⟨(sym ·), (sym ·)⟩⟩)
@[simp]
theorem fromRel_proj_prop {sym : Symmetric r} {z : α × α} : Sym2.mk z ∈ fromRel sym ↔ r z.1 z.2 :=
Iff.rfl
theorem fromRel_prop {sym : Symmetric r} {a b : α} : s(a, b) ∈ fromRel sym ↔ r a b :=
Iff.rfl
theorem fromRel_mono_iff (sym₁ : Symmetric r₁) (sym₂ : Symmetric r₂) :
fromRel sym₁ ⊆ fromRel sym₂ ↔ r₁ ≤ r₂ :=
⟨fun hle a b ↦ @hle s(a, b), fun hle ↦ Sym2.ind hle⟩
alias ⟨_, fromRel_mono⟩ := fromRel_mono_iff
/-- `fromRel` induces an order embedding from symmetric relations to `Sym2` sets. -/
def fromRelOrderEmbedding : { r : α → α → Prop // Symmetric r } ↪o Set (Sym2 α) :=
OrderEmbedding.ofMapLEIff (fun r ↦ Sym2.fromRel r.prop) fun _ _ ↦ fromRel_mono_iff ..
theorem fromRel_bot : fromRel (fun (_ _ : α) z => z : Symmetric ⊥) = ∅ := by
apply Set.eq_empty_of_forall_notMem fun e => _
apply Sym2.ind
simp [-Set.bot_eq_empty, Prop.bot_eq_false]
theorem fromRel_top : fromRel (fun (_ _ : α) z => z : Symmetric ⊤) = Set.univ := by
apply Set.eq_univ_of_forall fun e => _
apply Sym2.ind
simp [-Set.top_eq_univ, Prop.top_eq_true]
theorem fromRel_ne : fromRel (fun (_ _ : α) z => z.symm : Symmetric Ne) = {z | ¬IsDiag z} := by
ext z; exact z.ind (by simp)
theorem fromRel_irreflexive {sym : Symmetric r} :
Irreflexive r ↔ ∀ {z}, z ∈ fromRel sym → ¬IsDiag z :=
{ mp := by intro h; apply Sym2.ind; aesop
mpr := fun h _ hr => h (fromRel_prop.mpr hr) rfl }
theorem mem_fromRel_irrefl_other_ne {sym : Symmetric r} (irrefl : Irreflexive r) {a : α}
{z : Sym2 α} (hz : z ∈ fromRel sym) (h : a ∈ z) : Mem.other h ≠ a :=
other_ne (fromRel_irreflexive.mp irrefl hz) h
instance fromRel.decidablePred (sym : Symmetric r) [h : DecidableRel r] :
DecidablePred (· ∈ Sym2.fromRel sym) := fun z => z.recOnSubsingleton fun _ => h _ _
lemma fromRel_relationMap {r : α → α → Prop} (hr : Symmetric r) (f : α → β) :
fromRel (Relation.map_symmetric hr f) = Sym2.map f '' Sym2.fromRel hr := by
ext ⟨a, b⟩
simp only [fromRel_proj_prop, Relation.Map, Set.mem_image, Sym2.exists, map_pair_eq, Sym2.eq,
rel_iff', Prod.mk.injEq, Prod.swap_prod_mk, and_or_left, exists_or, iff_self_or,
forall_exists_index, and_imp]
exact fun c d hcd hc hd ↦ ⟨d, c, hr hcd, hd, hc⟩
/-- The inverse to `Sym2.fromRel`. Given a set on `Sym2 α`, give a symmetric relation on `α`
(see `Sym2.toRel_symmetric`). -/
def ToRel (s : Set (Sym2 α)) (x y : α) : Prop :=
s(x, y) ∈ s
@[simp]
theorem toRel_prop (s : Set (Sym2 α)) (x y : α) : ToRel s x y ↔ s(x, y) ∈ s :=
Iff.rfl
theorem toRel_symmetric (s : Set (Sym2 α)) : Symmetric (ToRel s) := fun x y => by simp [eq_swap]
theorem toRel_fromRel (sym : Symmetric r) : ToRel (fromRel sym) = r :=
rfl
theorem fromRel_toRel (s : Set (Sym2 α)) : fromRel (toRel_symmetric s) = s :=
Set.ext fun z => Sym2.ind (fun _ _ => Iff.rfl) z
end Relations
section ToMultiset
/-- Map an unordered pair to an unordered list. -/
def toMultiset {α : Type*} (z : Sym2 α) : Multiset α := by
refine Sym2.lift ?_ z
use (Multiset.ofList [·, ·])
simp [List.Perm.swap]
/-- Mapping an unordered pair to an unordered list produces a multiset of size `2`. -/
lemma card_toMultiset {α : Type*} (z : Sym2 α) : z.toMultiset.card = 2 := by
induction z
simp [Sym2.toMultiset]
/-- The members of an unordered pair are members of the corresponding unordered list. -/
@[simp]
theorem mem_toMultiset {α : Type*} {x : α} {z : Sym2 α} :
x ∈ (z.toMultiset : Multiset α) ↔ x ∈ z := by
induction z
simp [Sym2.toMultiset]
end ToMultiset
section ToFinset
variable [DecidableEq α]
/-- Map an unordered pair to a finite set. -/
def toFinset (z : Sym2 α) : Finset α := (z.toMultiset : Multiset α).toFinset
/-- The members of an unordered pair are members of the corresponding finite set. -/
@[simp]
theorem mem_toFinset {x : α} {z : Sym2 α} : x ∈ z.toFinset ↔ x ∈ z := by
rw [← Sym2.mem_toMultiset, Sym2.toFinset, Multiset.mem_toFinset]
lemma toFinset_mk_eq {x y : α} : s(x, y).toFinset = {x, y} := by
ext; simp [← Sym2.mem_toFinset, ← Sym2.mem_iff]
/-- Mapping an unordered pair on the diagonal to a finite set produces a finset of size `1`. -/
theorem card_toFinset_of_isDiag (z : Sym2 α) (h : z.IsDiag) : #(z : Sym2 α).toFinset = 1 := by
induction z
rw [Sym2.mk_isDiag_iff] at h
simp [Sym2.toFinset_mk_eq, h]
/-- Mapping an unordered pair off the diagonal to a finite set produces a finset of size `2`. -/
theorem card_toFinset_of_not_isDiag (z : Sym2 α) (h : ¬z.IsDiag) : #(z : Sym2 α).toFinset = 2 := by
induction z
rw [Sym2.mk_isDiag_iff] at h
simp [Sym2.toFinset_mk_eq, h]
/-- Mapping an unordered pair to a finite set produces a finset of size `1` if the pair is on the
diagonal, else of size `2` if the pair is off the diagonal. -/
theorem card_toFinset (z : Sym2 α) : #(z : Sym2 α).toFinset = if z.IsDiag then 1 else 2 := by
by_cases h : z.IsDiag
· simp [card_toFinset_of_isDiag z h, h]
· simp [card_toFinset_of_not_isDiag z h, h]
end ToFinset
section SymEquiv
/-! ### Equivalence to the second symmetric power -/
attribute [local instance] List.Vector.Perm.isSetoid
private def fromVector : List.Vector α 2 → α × α
| ⟨[a, b], _⟩ => (a, b)
private theorem perm_card_two_iff {a₁ b₁ a₂ b₂ : α} :
[a₁, b₁].Perm [a₂, b₂] ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ a₁ = b₂ ∧ b₁ = a₂ :=
{ mp := by
simp only [← Multiset.coe_eq_coe, ← Multiset.cons_coe, Multiset.coe_nil, Multiset.cons_zero,
Multiset.cons_eq_cons, Multiset.singleton_inj, ne_eq, Multiset.singleton_eq_cons_iff,
exists_eq_right_right, and_true]
tauto
mpr := fun
| .inl ⟨h₁, h₂⟩ | .inr ⟨h₁, h₂⟩ => by
rw [h₁, h₂]
first | done | constructor }
/-- The symmetric square is equivalent to length-2 vectors up to permutations. -/
def sym2EquivSym' : Equiv (Sym2 α) (Sym' α 2) where
toFun :=
Quot.map (fun x : α × α => ⟨[x.1, x.2], rfl⟩)
(by
rintro _ _ ⟨_⟩
· constructor; apply List.Perm.refl
apply List.Perm.swap'
rfl)
invFun :=
Quot.map fromVector
(by
rintro ⟨x, hx⟩ ⟨y, hy⟩ h
rcases x with - | ⟨_, x⟩; · simp at hx
rcases x with - | ⟨_, x⟩; · simp at hx
rcases x with - | ⟨_, x⟩; swap
· exfalso
simp at hx
rcases y with - | ⟨_, y⟩; · simp at hy
rcases y with - | ⟨_, y⟩; · simp at hy
rcases y with - | ⟨_, y⟩; swap
· exfalso
simp at hy
rcases perm_card_two_iff.mp h with (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)
· constructor
apply Sym2.Rel.swap)
left_inv := by apply Sym2.ind; aesop (add norm unfold [Sym2.fromVector])
right_inv x := by
refine x.recOnSubsingleton fun x => ?_
obtain ⟨x, hx⟩ := x
obtain - | ⟨-, x⟩ := x
· simp at hx
rcases x with - | ⟨_, x⟩
· simp at hx
rcases x with - | ⟨_, x⟩
swap
· exfalso
simp at hx
rfl
/-- The symmetric square is equivalent to the second symmetric power. -/
def equivSym (α : Type*) : Sym2 α ≃ Sym α 2 :=
Equiv.trans sym2EquivSym' symEquivSym'.symm
/-- The symmetric square is equivalent to multisets of cardinality
two. (This is currently a synonym for `equivSym`, but it's provided
in case the definition for `Sym` changes.) -/
def equivMultiset (α : Type*) : Sym2 α ≃ { s : Multiset α // Multiset.card s = 2 } :=
equivSym α
end SymEquiv
section Decidable
/-- Given `[DecidableEq α]` and `[Fintype α]`, the following instance gives `Fintype (Sym2 α)`.
-/
instance instDecidableRel [DecidableEq α] : DecidableRel (Rel α) :=
fun _ _ => decidable_of_iff' _ rel_iff
section
attribute [local instance] Sym2.Rel.setoid
instance instDecidableRel' [DecidableEq α] : DecidableRel (HasEquiv.Equiv (α := α × α)) :=
instDecidableRel
end
instance [DecidableEq α] : DecidableEq (Sym2 α) :=
inferInstanceAs <| DecidableEq (Quotient (Sym2.Rel.setoid α))
/-! ### The other element of an element of the symmetric square -/
/--
A function that gives the other element of a pair given one of the elements. Used in `Mem.other'`.
-/
@[aesop norm unfold (rule_sets := [Sym2])]
private def pairOther [DecidableEq α] (a : α) (z : α × α) : α :=
if a = z.1 then z.2 else z.1
/-- Get the other element of the unordered pair using the decidable equality.
This is the computable version of `Mem.other`. -/
@[aesop norm unfold (rule_sets := [Sym2])]
def Mem.other' [DecidableEq α] {a : α} {z : Sym2 α} (h : a ∈ z) : α :=
Sym2.rec (fun s _ => pairOther a s) (by
clear h z
intro x y h
ext hy
convert_to Sym2.pairOther a x = _
· have : ∀ {c e h}, @Eq.ndrec (Sym2 α) (Sym2.mk x)
(fun x => a ∈ x → α) (fun _ => Sym2.pairOther a x) c e h = Sym2.pairOther a x := by
intro _ e _; subst e; rfl
apply this
· rw [mem_iff] at hy
aesop (add norm unfold [pairOther]))
z h
@[simp]
theorem other_spec' [DecidableEq α] {a : α} {z : Sym2 α} (h : a ∈ z) : s(a, Mem.other' h) = z := by
induction z
aesop (add norm unfold [Sym2.rec, Quot.rec]) (rule_sets := [Sym2])
@[simp]
theorem other_eq_other' [DecidableEq α] {a : α} {z : Sym2 α} (h : a ∈ z) :
Mem.other h = Mem.other' h := by rw [← congr_right, other_spec' h, other_spec]
theorem other_mem' [DecidableEq α] {a : α} {z : Sym2 α} (h : a ∈ z) : Mem.other' h ∈ z := by
rw [← other_eq_other']
exact other_mem h
theorem other_invol' [DecidableEq α] {a : α} {z : Sym2 α} (ha : a ∈ z) (hb : Mem.other' ha ∈ z) :
Mem.other' hb = a := by
induction z
aesop (rule_sets := [Sym2]) (add norm unfold [Sym2.rec, Quot.rec])
theorem other_invol {a : α} {z : Sym2 α} (ha : a ∈ z) (hb : Mem.other ha ∈ z) :
Mem.other hb = a := by
classical
rw [other_eq_other'] at hb ⊢
convert other_invol' ha hb using 2
apply other_eq_other'
theorem filter_image_mk_isDiag [DecidableEq α] (s : Finset α) :
{a ∈ (s ×ˢ s).image Sym2.mk | a.IsDiag} = s.diag.image Sym2.mk := by
ext ⟨x, y⟩
simp only [mem_image, mem_diag, mem_filter, Prod.exists, mem_product]
constructor
· rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩
rw [← h, Sym2.mk_isDiag_iff] at hab
exact ⟨a, b, ⟨ha, hab⟩, h⟩
· rintro ⟨a, b, ⟨ha, rfl⟩, h⟩
rw [← h]
exact ⟨⟨a, a, ⟨ha, ha⟩, rfl⟩, rfl⟩
theorem filter_image_mk_not_isDiag [DecidableEq α] (s : Finset α) :
{a ∈ (s ×ˢ s).image Sym2.mk | ¬a.IsDiag} = s.offDiag.image Sym2.mk := by
ext z
induction z
simp only [mem_image, mem_offDiag, mem_filter, Prod.exists, mem_product]
constructor
· rintro ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩
rw [← h, Sym2.mk_isDiag_iff] at hab
exact ⟨a, b, ⟨ha, hb, hab⟩, h⟩
· rintro ⟨a, b, ⟨ha, hb, hab⟩, h⟩
rw [Ne, ← Sym2.mk_isDiag_iff, h] at hab
exact ⟨⟨a, b, ⟨ha, hb⟩, h⟩, hab⟩
end Decidable
instance [Subsingleton α] : Subsingleton (Sym2 α) :=
(equivSym α).injective.subsingleton
instance [Unique α] : Unique (Sym2 α) :=
Unique.mk' _
instance [IsEmpty α] : IsEmpty (Sym2 α) :=
(equivSym α).isEmpty
instance [Nontrivial α] : Nontrivial (Sym2 α) :=
diag_injective.nontrivial
-- TODO: use a sort order if available, https://github.com/leanprover-community/mathlib/issues/18166
unsafe instance [Repr α] : Repr (Sym2 α) where
reprPrec s _ := f!"s({repr s.unquot.1}, {repr s.unquot.2})"
lemma lift_smul_lift {α R N} [SMul R N] (f : { f : α → α → R // ∀ a₁ a₂, f a₁ a₂ = f a₂ a₁ })
(g : { g : α → α → N // ∀ a₁ a₂, g a₁ a₂ = g a₂ a₁ }) :
lift f • lift g = lift ⟨f.val • g.val, fun _ _ => by
rw [Pi.smul_apply', Pi.smul_apply', Pi.smul_apply', Pi.smul_apply', f.prop, g.prop]⟩ := by
ext ⟨i, j⟩
simp_all only [Pi.smul_apply', lift_mk]
/--
Multiplication as a function from `Sym2`.
-/
@[to_additive /-- Addition as a function from `Sym2`. -/]
def mul {M} [CommMagma M] : Sym2 M → M := lift ⟨(· * ·), mul_comm⟩
@[to_additive (attr := simp)]
lemma mul_mk {M} [CommMagma M] (xy : M × M) :
mul (.mk xy) = xy.1 * xy.2 := rfl
end Sym2
namespace Set
open Sym2
variable {s : Set α}
/--
For a set `s : Set α`, `s.sym2` is the set of all unordered pairs of elements from `s`.
-/
def sym2 (s : Set α) : Set (Sym2 α) := fromRel (r := fun x y ↦ x ∈ s ∧ y ∈ s) (fun _ _ => .symm)
@[simp] lemma mk'_mem_sym2_iff {xy : α × α} : Sym2.mk xy ∈ s.sym2 ↔ xy ∈ s ×ˢ s := Iff.rfl
lemma mk_mem_sym2_iff {x y : α} : s(x, y) ∈ s.sym2 ↔ x ∈ s ∧ y ∈ s := Iff.rfl
lemma mem_sym2_iff_subset {z : Sym2 α} : z ∈ s.sym2 ↔ (z : Set α) ⊆ s := by
induction z using Sym2.inductionOn
simp [pair_subset_iff]
lemma sym2_eq_mk_image : s.sym2 = Sym2.mk '' s ×ˢ s := by ext ⟨x, y⟩; aesop
@[simp] lemma mk_preimage_sym2 : Sym2.mk ⁻¹' s.sym2 = s ×ˢ s := rfl
@[simp] lemma sym2_empty : (∅ : Set α).sym2 = ∅ := by ext ⟨x, y⟩; simp
@[simp] lemma sym2_univ : (Set.univ : Set α).sym2 = Set.univ := by ext ⟨x, y⟩; simp
@[simp] lemma sym2_singleton (a : α) : ({a} : Set α).sym2 = {s(a, a)} := by ext ⟨x, y⟩; simp
lemma sym2_insert (a : α) (s : Set α) :
(insert a s).sym2 = (fun b ↦ s(a, b)) '' insert a s ∪ s.sym2 := by
ext ⟨x, y⟩; aesop
lemma sym2_preimage {f : α → β} {s : Set β} : (f ⁻¹' s).sym2 = Sym2.map f ⁻¹' s.sym2 := by
ext ⟨x, y⟩
simp
lemma sym2_image {f : α → β} {s : Set α} : (f '' s).sym2 = Sym2.map f '' s.sym2 :=
preimage_injective.mpr Sym2.mk_surjective <| by
simp_rw [sym2_eq_mk_image, prod_image_image_eq, image_image, Sym2.map_mk, Prod.map]
lemma sym2_inter (s t : Set α) : (s ∩ t).sym2 = s.sym2 ∩ t.sym2 :=
preimage_injective.mpr Sym2.mk_surjective <| Set.prod_inter_prod.symm
lemma sym2_iInter {ι : Type*} (f : ι → Set α) : (⋂ i, f i).sym2 = ⋂ i, (f i).sym2 := by
ext ⟨x, y⟩; simp [forall_and]
end Set |
.lake/packages/mathlib/Mathlib/Data/Sym/Sym2/Init.lean | import Mathlib.Init
import Aesop
/-!
# Sym2 Rule Set
This module defines the `Sym2` Aesop rule set. Aesop rule sets only become
visible once the file in which they're declared is imported, so we must put this
declaration into its own file.
-/
declare_aesop_rule_sets [Sym2] |
.lake/packages/mathlib/Mathlib/Data/Sym/Sym2/Order.lean | import Mathlib.Data.Sym.Sym2
import Mathlib.Order.Lattice
/-!
# Sorting the elements of `Sym2`
This file provides `Sym2.sortEquiv`, the forward direction of which is somewhat analogous to
`Multiset.sort`.
-/
namespace Sym2
variable {α}
/-- The supremum of the two elements. -/
def sup [SemilatticeSup α] (x : Sym2 α) : α := Sym2.lift ⟨(· ⊔ ·), sup_comm⟩ x
@[simp] theorem sup_mk [SemilatticeSup α] (a b : α) : s(a, b).sup = a ⊔ b := rfl
/-- The infimum of the two elements. -/
def inf [SemilatticeInf α] (x : Sym2 α) : α := Sym2.lift ⟨(· ⊓ ·), inf_comm⟩ x
@[simp] theorem inf_mk [SemilatticeInf α] (a b : α) : s(a, b).inf = a ⊓ b := rfl
protected theorem inf_le_sup [Lattice α] (s : Sym2 α) : s.inf ≤ s.sup := by
cases s using Sym2.ind; simp
/-- In a linear order, symmetric squares are canonically identified with ordered pairs. -/
@[simps!]
def sortEquiv [LinearOrder α] : Sym2 α ≃ { p : α × α // p.1 ≤ p.2 } where
toFun s := ⟨(s.inf, s.sup), Sym2.inf_le_sup _⟩
invFun p := Sym2.mk p
left_inv := Sym2.ind fun a b => mk_eq_mk_iff.mpr <| by
cases le_total a b with
| inl h => simp [h]
| inr h => simp [h]
right_inv := Subtype.rec <| Prod.rec fun x y hxy =>
Subtype.ext <| Prod.ext (by simp [hxy]) (by simp [hxy])
/-- In a linear order, two symmetric squares are equal if and only if
they have the same infimum and supremum. -/
theorem inf_eq_inf_and_sup_eq_sup [LinearOrder α] {s t : Sym2 α} :
s.inf = t.inf ∧ s.sup = t.sup ↔ s = t := by
induction s with | _ a b
induction t with | _ c d
obtain hab | hba := le_total a b <;> obtain hcd | hdc := le_total c d <;>
aesop (add unsafe le_antisymm)
end Sym2 |
.lake/packages/mathlib/Mathlib/Data/Sym/Sym2/Finsupp.lean | import Mathlib.Algebra.GroupWithZero.Basic
import Mathlib.Data.Finset.Sym
import Mathlib.Data.Finsupp.Defs
/-!
# Finitely supported functions from the symmetric square
This file lifts functions `α →₀ M₀` to functions `Sym2 α →₀ M₀` by precomposing with multiplication.
-/
open Sym2
variable {α M₀ : Type*} [CommMonoidWithZero M₀] {f : α →₀ M₀}
namespace Finsupp
lemma sym2_support_eq_preimage_support_mul [NoZeroDivisors M₀] (f : α →₀ M₀) :
f.support.sym2 = map f ⁻¹' mul.support := by ext ⟨a, b⟩; simp
lemma mem_sym2_support_of_mul_ne_zero (p : Sym2 α) (hp : mul (p.map f) ≠ 0) :
p ∈ f.support.sym2 := by
obtain ⟨a, b⟩ := p
simp only [map_pair_eq, mul_mk, ne_eq] at hp
simpa using .intro (left_ne_zero_of_mul hp) (right_ne_zero_of_mul hp)
/-- The composition of a `Finsupp` with `Sym2.mul` as a `Finsupp`. -/
noncomputable def sym2Mul (f : α →₀ M₀) : Sym2 α →₀ M₀ :=
.onFinset f.support.sym2 (fun p ↦ mul (p.map f)) mem_sym2_support_of_mul_ne_zero
lemma support_sym2Mul_subset : f.sym2Mul.support ⊆ f.support.sym2 := support_onFinset_subset
@[simp, norm_cast] lemma coe_sym2Mul (f : α →₀ M₀) : f.sym2Mul = mul ∘ map f := rfl
lemma sym2Mul_apply_mk (p : α × α) : f.sym2Mul (.mk p) = f p.1 * f p.2 := rfl
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Tree/RBMap.lean | import Batteries.Data.RBMap.Basic
import Mathlib.Data.Tree.Basic
/-!
# Binary tree and RBMaps
In this file we define `Tree.ofRBNode`.
This definition was moved from the main file to avoid a dependency on `RBMap`.
## TODO
Implement a `Traversable` instance for `Tree`.
## References
<https://leanprover-community.github.io/archive/stream/113488-general/topic/tactic.20question.html>
-/
namespace Tree
universe u
variable {α : Type u}
open Batteries (RBNode)
end Tree |
.lake/packages/mathlib/Mathlib/Data/Tree/Traversable.lean | import Mathlib.Data.Tree.Basic
import Mathlib.Control.Applicative
import Mathlib.Control.Traversable.Basic
/-!
# Traversable Binary Tree
Provides a `Traversable` instance for the `Tree` type.
-/
universe u v w
namespace Tree
section Traverse
variable {α β : Type*}
instance : Traversable Tree where
map := map
traverse := traverse
lemma comp_traverse
{F : Type u → Type v} {G : Type v → Type w} [Applicative F] [Applicative G]
[LawfulApplicative G] {β : Type v} {γ : Type u} (f : β → F γ) (g : α → G β)
(t : Tree α) : t.traverse (Functor.Comp.mk ∘ (f <$> ·) ∘ g) =
Functor.Comp.mk ((·.traverse f) <$> (t.traverse g)) := by
induction t with
| nil => rw [traverse, traverse, map_pure, traverse]; rfl
| node v l r hl hr =>
rw [traverse, hl, hr, traverse]
simp only [Function.comp_def, Function.comp_apply, Functor.Comp.map_mk, Functor.map_map,
Comp.seq_mk, seq_map_assoc, map_seq]
rfl
lemma traverse_eq_map_id (f : α → β) (t : Tree α) :
t.traverse ((pure : β → Id β) ∘ f) = pure (t.map f) := by
induction t with
| nil => rw [traverse, map]
| node v l r hl hr =>
rw [traverse, map, hl, hr, Function.comp_apply, map_pure, pure_seq, map_pure, pure_seq,
map_pure]
lemma naturality {F G : Type u → Type*} [Applicative F] [Applicative G] [LawfulApplicative F]
[LawfulApplicative G] (η : ApplicativeTransformation F G) {β : Type u} (f : α → F β)
(t : Tree α) : η (t.traverse f) = t.traverse (η.app β ∘ f : α → G β) := by
induction t with
| nil => rw [traverse, traverse, η.preserves_pure]
| node v l r hl hr =>
rw [traverse, traverse, η.preserves_seq, η.preserves_seq, η.preserves_map, hl, hr,
Function.comp_apply]
instance : LawfulTraversable Tree where
map_const := rfl
id_map := id_map
comp_map := comp_map
id_traverse t := traverse_pure t
comp_traverse := comp_traverse
traverse_eq_map_id := traverse_eq_map_id
naturality η := naturality η
end Traverse
end Tree |
.lake/packages/mathlib/Mathlib/Data/Tree/Basic.lean | import Mathlib.Data.Nat.Notation
import Mathlib.Tactic.TypeStar
import Mathlib.Util.CompileInductive
/-!
# Binary tree
Provides binary tree storage for values of any type, with O(lg n) retrieval.
See also `Lean.Data.RBTree` for red-black trees - this version allows more operations
to be defined and is better suited for in-kernel computation.
We also specialize for `Tree Unit`, which is a binary tree without any
additional data. We provide the notation `a △ b` for making a `Tree Unit` with children
`a` and `b`.
## References
<https://leanprover-community.github.io/archive/stream/113488-general/topic/tactic.20question.html>
-/
/-- A binary tree with values stored in non-leaf nodes. -/
inductive Tree.{u} (α : Type u) : Type u
| nil : Tree α
| node : α → Tree α → Tree α → Tree α
deriving DecidableEq, Repr
compile_inductive% Tree
namespace Tree
universe u
variable {α : Type u}
instance : Inhabited (Tree α) :=
⟨nil⟩
/--
Do an action for every node of the tree.
Actions are taken in node -> left subtree -> right subtree recursive order.
This function is the `traverse` function for the `Traversable Tree` instance.
-/
def traverse {m : Type* → Type*} [Applicative m] {α β} (f : α → m β) : Tree α → m (Tree β)
| .nil => pure nil
| .node a l r => .node <$> f a <*> traverse f l <*> traverse f r
/-- Apply a function to each value in the tree. This is the `map` function for the `Tree` functor.
-/
def map {β} (f : α → β) : Tree α → Tree β
| nil => nil
| node a l r => node (f a) (map f l) (map f r)
theorem id_map (t : Tree α) : t.map id = t := by
induction t with
| nil => rw [map]
| node v l r hl hr => rw [map, hl, hr, id_eq]
theorem comp_map {β γ : Type*} (f : α → β) (g : β → γ) (t : Tree α) :
t.map (g ∘ f) = (t.map f).map g := by
induction t with
| nil => rw [map, map, map]
| node v l r hl hr => rw [map, map, map, hl, hr, Function.comp_apply]
theorem traverse_pure (t : Tree α) {m : Type u → Type*} [Applicative m] [LawfulApplicative m] :
t.traverse (pure : α → m α) = pure t := by
induction t with
| nil => rw [traverse]
| node v l r hl hr =>
rw [traverse, hl, hr, map_pure, pure_seq, seq_pure, map_pure, map_pure]
/-- The number of internal nodes (i.e. not including leaves) of a binary tree -/
@[simp]
def numNodes : Tree α → ℕ
| nil => 0
| node _ a b => a.numNodes + b.numNodes + 1
/-- The number of leaves of a binary tree -/
@[simp]
def numLeaves : Tree α → ℕ
| nil => 1
| node _ a b => a.numLeaves + b.numLeaves
/-- The height - length of the longest path from the root - of a binary tree -/
@[simp]
def height : Tree α → ℕ
| nil => 0
| node _ a b => max a.height b.height + 1
theorem numLeaves_eq_numNodes_succ (x : Tree α) : x.numLeaves = x.numNodes + 1 := by
induction x <;> simp [*, Nat.add_comm, Nat.add_assoc, Nat.add_left_comm]
theorem numLeaves_pos (x : Tree α) : 0 < x.numLeaves := by
rw [numLeaves_eq_numNodes_succ]
exact x.numNodes.zero_lt_succ
theorem height_le_numNodes : ∀ x : Tree α, x.height ≤ x.numNodes
| nil => Nat.le_refl _
| node _ a b => Nat.succ_le_succ <|
Nat.max_le.2 ⟨Nat.le_trans a.height_le_numNodes <| a.numNodes.le_add_right _,
Nat.le_trans b.height_le_numNodes <| b.numNodes.le_add_left _⟩
/-- The left child of the tree, or `nil` if the tree is `nil` -/
@[simp]
def left : Tree α → Tree α
| nil => nil
| node _ l _r => l
/-- The right child of the tree, or `nil` if the tree is `nil` -/
@[simp]
def right : Tree α → Tree α
| nil => nil
| node _ _l r => r
/-- A node with `Unit` data -/
scoped infixr:65 " △ " => Tree.node ()
/-- Induction principle for `Tree Unit`s -/
@[elab_as_elim]
def unitRecOn {motive : Tree Unit → Sort*} (t : Tree Unit) (base : motive nil)
(ind : ∀ x y, motive x → motive y → motive (x △ y)) : motive t :=
t.recOn base fun _u ↦ ind
theorem left_node_right_eq_self : ∀ {x : Tree Unit} (_hx : x ≠ nil), x.left △ x.right = x
| nil, h => by trivial
| node _ _ _, _ => rfl -- Porting note: `a △ b` no longer works in pattern matching
end Tree |
.lake/packages/mathlib/Mathlib/Data/Tree/Get.lean | import Mathlib.Data.Num.Basic
import Mathlib.Data.Ordering.Basic
import Mathlib.Data.Tree.Basic
/-!
# Binary tree get operation
In this file we define `Tree.indexOf`, `Tree.get`, and `Tree.getOrElse`.
These definitions were moved from the main file to avoid a dependency on `Num`.
## References
<https://leanprover-community.github.io/archive/stream/113488-general/topic/tactic.20question.html#170999997>
-/
namespace Tree
variable {α : Type*}
/-- Finds the index of an element in the tree assuming the tree has been
constructed according to the provided decidable order on its elements.
If it hasn't, the result will be incorrect. If it has, but the element
is not in the tree, returns none. -/
def indexOf (lt : α → α → Prop) [DecidableRel lt] (x : α) : Tree α → Option PosNum
| nil => none
| node a t₁ t₂ =>
match cmpUsing lt x a with
| Ordering.lt => PosNum.bit0 <$> indexOf lt x t₁
| Ordering.eq => some PosNum.one
| Ordering.gt => PosNum.bit1 <$> indexOf lt x t₂
/-- Retrieves an element uniquely determined by a `PosNum` from the tree,
taking the following path to get to the element:
- `bit0` - go to left child
- `bit1` - go to right child
- `PosNum.one` - retrieve from here -/
def get : PosNum → Tree α → Option α
| _, nil => none
| PosNum.one, node a _t₁ _t₂ => some a
| PosNum.bit0 n, node _a t₁ _t₂ => t₁.get n
| PosNum.bit1 n, node _a _t₁ t₂ => t₂.get n
/-- Retrieves an element from the tree, or the provided default value
if the index is invalid. See `Tree.get`. -/
def getOrElse (n : PosNum) (t : Tree α) (v : α) : α :=
(t.get n).getD v
end Tree |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Basic.lean | import Mathlib.Data.PFunctor.Multivariate.Basic
/-!
# Multivariate quotients of polynomial functors.
Basic definition of multivariate QPF. QPFs form a compositional framework
for defining inductive and coinductive types, their quotients and nesting.
The idea is based on building ever larger functors. For instance, we can define
a list using a shape functor:
```lean
inductive ListShape (a b : Type)
| nil : ListShape
| cons : a -> b -> ListShape
```
This shape can itself be decomposed as a sum of product which are themselves
QPFs. It follows that the shape is a QPF and we can take its fixed point
and create the list itself:
```lean
def List (a : Type) := fix ListShape a -- not the actual notation
```
We can continue and define the quotient on permutation of lists and create
the multiset type:
```lean
def Multiset (a : Type) := QPF.quot List.perm List a -- not the actual notion
```
And `Multiset` is also a QPF. We can then create a novel data type (for Lean):
```lean
inductive Tree (a : Type)
| node : a -> Multiset Tree -> Tree
```
An unordered tree. This is currently not supported by Lean because it nests
an inductive type inside of a quotient. We can go further and define
unordered, possibly infinite trees:
```lean
coinductive Tree' (a : Type)
| node : a -> Multiset Tree' -> Tree'
```
by using the `cofix` construct. Those options can all be mixed and
matched because they preserve the properties of QPF. The latter example,
`Tree'`, combines fixed point, co-fixed point and quotients.
## Related modules
* constructions
* Fix
* Cofix
* Quot
* Comp
* Sigma / Pi
* Prj
* Const
each proves that some operations on functors preserves the QPF structure
-/
set_option linter.style.longLine false in
/-!
## Reference
[Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u
open MvFunctor
/-- Multivariate quotients of polynomial functors.
-/
class MvQPF {n : ℕ} (F : TypeVec.{u} n → Type*) extends MvFunctor F where
P : MvPFunctor.{u} n
abs : ∀ {α}, P α → F α
repr : ∀ {α}, F α → P α
abs_repr : ∀ {α} (x : F α), abs (repr x) = x
abs_map : ∀ {α β} (f : α ⟹ β) (p : P α), abs (f <$$> p) = f <$$> abs p
namespace MvQPF
variable {n : ℕ} {F : TypeVec.{u} n → Type*} [q : MvQPF F]
open MvFunctor (LiftP LiftR)
/-!
### Show that every MvQPF is a lawful MvFunctor.
-/
protected theorem id_map {α : TypeVec n} (x : F α) : TypeVec.id <$$> x = x := by
rw [← abs_repr x, ← abs_map]
rfl
@[simp]
theorem comp_map {α β γ : TypeVec n} (f : α ⟹ β) (g : β ⟹ γ) (x : F α) :
(g ⊚ f) <$$> x = g <$$> f <$$> x := by
rw [← abs_repr x, ← abs_map, ← abs_map, ← abs_map]
rfl
instance (priority := 100) lawfulMvFunctor : LawfulMvFunctor F where
id_map := @MvQPF.id_map n F _
comp_map := @comp_map n F _
-- Lifting predicates and relations
theorem liftP_iff {α : TypeVec n} (p : ∀ ⦃i⦄, α i → Prop) (x : F α) :
LiftP p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i j, p (f i j) := by
constructor
· rintro ⟨y, hy⟩
rcases h : repr y with ⟨a, f⟩
use a, fun i j => (f i j).val
constructor
· rw [← hy, ← abs_repr y, h, ← abs_map]; rfl
intro i j
apply (f i j).property
rintro ⟨a, f, h₀, h₁⟩
use abs ⟨a, fun i j => ⟨f i j, h₁ i j⟩⟩
rw [← abs_map, h₀]; rfl
theorem liftR_iff {α : TypeVec n} (r : ∀ ⦃i⦄, α i → α i → Prop) (x y : F α) :
LiftR r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i j, r (f₀ i j) (f₁ i j) := by
constructor
· rintro ⟨u, xeq, yeq⟩
rcases h : repr u with ⟨a, f⟩
use a, fun i j => (f i j).val.fst, fun i j => (f i j).val.snd
constructor
· rw [← xeq, ← abs_repr u, h, ← abs_map]; rfl
constructor
· rw [← yeq, ← abs_repr u, h, ← abs_map]; rfl
intro i j
exact (f i j).property
rintro ⟨a, f₀, f₁, xeq, yeq, h⟩
use abs ⟨a, fun i j => ⟨(f₀ i j, f₁ i j), h i j⟩⟩
dsimp; constructor
· rw [xeq, ← abs_map]; rfl
rw [yeq, ← abs_map]; rfl
open Set
theorem mem_supp {α : TypeVec n} (x : F α) (i) (u : α i) :
u ∈ supp x i ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f i '' univ := by
rw [supp]; dsimp; constructor
· intro h a f haf
have : LiftP (fun i u => u ∈ f i '' univ) x := by
rw [liftP_iff]
refine ⟨a, f, haf.symm, ?_⟩
intro i u
exact mem_image_of_mem _ (mem_univ _)
exact h this
grind [liftP_iff]
theorem supp_eq {α : TypeVec n} {i} (x : F α) :
supp x i = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f i '' univ } := by ext; apply mem_supp
theorem has_good_supp_iff {α : TypeVec n} (x : F α) :
(∀ p, LiftP p x ↔ ∀ (i), ∀ u ∈ supp x i, p i u) ↔
∃ a f, abs ⟨a, f⟩ = x ∧ ∀ i a' f', abs ⟨a', f'⟩ = x → f i '' univ ⊆ f' i '' univ := by
constructor
· intro h
have : LiftP (supp x) x := by rw [h]; introv; exact id
rw [liftP_iff] at this
rcases this with ⟨a, f, xeq, h'⟩
refine ⟨a, f, xeq.symm, ?_⟩
intro a' f' h''
rintro hu u ⟨j, _h₂, hfi⟩
have hh : u ∈ supp x a' := by rw [← hfi]; apply h'
exact (mem_supp x _ u).mp hh _ _ hu
rintro ⟨a, f, xeq, h⟩ p; rw [liftP_iff]; constructor
· rintro ⟨a', f', xeq', h'⟩ i u usuppx
rcases (mem_supp x _ u).mp (@usuppx) a' f' xeq'.symm with ⟨i, _, f'ieq⟩
rw [← f'ieq]
apply h'
intro h'
refine ⟨a, f, xeq.symm, ?_⟩; intro j y
apply h'; rw [mem_supp]
intro a' f' xeq'
apply h _ a' f' xeq'
apply mem_image_of_mem _ (mem_univ _)
/-- A qpf is said to be uniform if every polynomial functor
representing a single value all have the same range. -/
def IsUniform : Prop :=
∀ ⦃α : TypeVec n⦄ (a a' : q.P.A) (f : q.P.B a ⟹ α) (f' : q.P.B a' ⟹ α),
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → ∀ i, f i '' univ = f' i '' univ
/-- does `abs` preserve `liftp`? -/
def LiftPPreservation : Prop :=
∀ ⦃α : TypeVec n⦄ (p : ∀ ⦃i⦄, α i → Prop) (x : q.P α), LiftP p (abs x) ↔ LiftP p x
/-- does `abs` preserve `supp`? -/
def SuppPreservation : Prop :=
∀ ⦃α⦄ (x : q.P α), supp (abs x) = supp x
theorem supp_eq_of_isUniform (h : q.IsUniform) {α : TypeVec n} (a : q.P.A) (f : q.P.B a ⟹ α) :
∀ i, supp (abs ⟨a, f⟩) i = f i '' univ := by
intro; ext u; rw [mem_supp]; constructor
· intro h'
apply h' _ _ rfl
intro h' a' f' e
rw [← h _ _ _ _ e.symm]; apply h'
theorem liftP_iff_of_isUniform (h : q.IsUniform) {α : TypeVec n} (x : F α) (p : ∀ i, α i → Prop) :
LiftP p x ↔ ∀ (i), ∀ u ∈ supp x i, p i u := by
rw [liftP_iff, ← abs_repr x]
obtain ⟨a, f⟩ := repr x; constructor
· rintro ⟨a', f', abseq, hf⟩ u
rw [supp_eq_of_isUniform h, h _ _ _ _ abseq]
rintro b ⟨i, _, hi⟩
rw [← hi]
apply hf
intro h'
refine ⟨a, f, rfl, fun _ i => h' _ _ ?_⟩
rw [supp_eq_of_isUniform h]
exact ⟨i, mem_univ i, rfl⟩
theorem supp_map (h : q.IsUniform) {α β : TypeVec n} (g : α ⟹ β) (x : F α) (i) :
supp (g <$$> x) i = g i '' supp x i := by
rw [← abs_repr x]; obtain ⟨a, f⟩ := repr x; rw [← abs_map, MvPFunctor.map_eq]
rw [supp_eq_of_isUniform h, supp_eq_of_isUniform h, ← image_comp]
rfl
theorem suppPreservation_iff_isUniform : q.SuppPreservation ↔ q.IsUniform := by
constructor
· intro h α a a' f f' h' i
rw [← MvPFunctor.supp_eq, ← MvPFunctor.supp_eq, ← h, h', h]
· rintro h α ⟨a, f⟩
ext
rwa [supp_eq_of_isUniform, MvPFunctor.supp_eq]
theorem suppPreservation_iff_liftpPreservation : q.SuppPreservation ↔ q.LiftPPreservation := by
constructor <;> intro h
· rintro α p ⟨a, f⟩
have h' := h
rw [suppPreservation_iff_isUniform] at h'
dsimp only [SuppPreservation, supp] at h
simp only [liftP_iff_of_isUniform, supp_eq_of_isUniform, MvPFunctor.liftP_iff', h',
image_univ, mem_range, exists_imp]
constructor <;> intros <;> subst_vars <;> solve_by_elim
· rintro α ⟨a, f⟩
simp only [LiftPPreservation] at h
ext
simp only [supp, h, mem_setOf_eq]
theorem liftpPreservation_iff_uniform : q.LiftPPreservation ↔ q.IsUniform := by
rw [← suppPreservation_iff_liftpPreservation, suppPreservation_iff_isUniform]
/-- Any type function `F` that is (extensionally) equivalent to a QPF, is itself a QPF,
assuming that the functorial map of `F` behaves similar to `MvFunctor.ofEquiv eqv` -/
def ofEquiv {F F' : TypeVec.{u} n → Type*} [q : MvQPF F'] [MvFunctor F]
(eqv : ∀ α, F α ≃ F' α)
(map_eq : ∀ (α β : TypeVec n) (f : α ⟹ β) (a : F α),
f <$$> a = ((eqv _).symm <| f <$$> eqv _ a) := by intros; rfl) :
MvQPF F where
P := q.P
abs α := (eqv _).symm <| q.abs α
repr α := q.repr <| eqv _ α
abs_repr := by simp [q.abs_repr]
abs_map := by simp [q.abs_map, map_eq]
end MvQPF
/-- Every polynomial functor is a (trivial) QPF -/
instance MvPFunctor.instMvQPFObj {n} (P : MvPFunctor n) : MvQPF P where
P := P
abs := id
repr := id
abs_repr := by intros; rfl
abs_map := by intros; rfl |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Quot.lean | import Mathlib.Data.QPF.Multivariate.Basic
/-!
# The quotient of QPF is itself a QPF
The quotients are here defined using a surjective function and
its right inverse. They are very similar to the `abs` and `repr`
functions found in the definition of `MvQPF`
-/
universe u
open MvFunctor
namespace MvQPF
variable {n : ℕ}
variable {F : TypeVec.{u} n → Type u}
section repr
variable [q : MvQPF F]
variable {G : TypeVec.{u} n → Type u} [MvFunctor G]
variable {FG_abs : ∀ {α}, F α → G α}
variable {FG_repr : ∀ {α}, G α → F α}
/-- If `F` is a QPF then `G` is a QPF as well. Can be used to
construct `MvQPF` instances by transporting them across
surjective functions -/
def quotientQPF (FG_abs_repr : ∀ {α} (x : G α), FG_abs (FG_repr x) = x)
(FG_abs_map : ∀ {α β} (f : α ⟹ β) (x : F α), FG_abs (f <$$> x) = f <$$> FG_abs x) :
MvQPF G where
P := q.P
abs p := FG_abs (abs p)
repr x := repr (FG_repr x)
abs_repr x := by rw [abs_repr, FG_abs_repr]
abs_map f p := by rw [abs_map, FG_abs_map]
end repr
section Rel
variable (R : ∀ ⦃α⦄, F α → F α → Prop)
/-- Functorial quotient type -/
def Quot1 (α : TypeVec n) :=
Quot (@R α)
instance Quot1.inhabited {α : TypeVec n} [Inhabited <| F α] : Inhabited (Quot1 R α) :=
⟨Quot.mk _ default⟩
section
variable [MvFunctor F] (Hfunc : ∀ ⦃α β⦄ (a b : F α) (f : α ⟹ β), R a b → R (f <$$> a) (f <$$> b))
/-- `map` of the `Quot1` functor -/
def Quot1.map ⦃α β⦄ (f : α ⟹ β) : Quot1.{u} R α → Quot1.{u} R β :=
Quot.lift (fun x : F α => Quot.mk _ (f <$$> x : F β)) fun a b h => Quot.sound <| Hfunc a b _ h
/-- `mvFunctor` instance for `Quot1` with well-behaved `R` -/
def Quot1.mvFunctor : MvFunctor (Quot1 R) where map := @Quot1.map _ _ R _ Hfunc
end
section
variable [q : MvQPF F] (Hfunc : ∀ ⦃α β⦄ (a b : F α) (f : α ⟹ β), R a b → R (f <$$> a) (f <$$> b))
/-- `Quot1` is a QPF -/
noncomputable def relQuot : @MvQPF _ (Quot1 R) :=
@quotientQPF n F q _ (MvQPF.Quot1.mvFunctor R Hfunc) (fun x => Quot.mk _ x)
Quot.out (fun _x => Quot.out_eq _) fun _f _x => rfl
end
end Rel
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Comp.lean | import Mathlib.Data.PFunctor.Multivariate.Basic
import Mathlib.Data.QPF.Multivariate.Basic
/-!
# The composition of QPFs is itself a QPF
We define composition between one `n`-ary functor and `n` `m`-ary functors
and show that it preserves the QPF structure
-/
universe u
namespace MvQPF
open MvFunctor
variable {n m : ℕ} (F : TypeVec.{u} n → Type*) (G : Fin2 n → TypeVec.{u} m → Type u)
/-- Composition of an `n`-ary functor with `n` `m`-ary
functors gives us one `m`-ary functor -/
def Comp (v : TypeVec.{u} m) : Type _ :=
F fun i : Fin2 n ↦ G i v
namespace Comp
open MvPFunctor
variable {F G} {α β : TypeVec.{u} m} (f : α ⟹ β)
instance [I : Inhabited (F fun i : Fin2 n ↦ G i α)] : Inhabited (Comp F G α) := I
/-- Constructor for functor composition -/
protected def mk (x : F fun i ↦ G i α) : Comp F G α := x
/-- Destructor for functor composition -/
protected def get (x : Comp F G α) : F fun i ↦ G i α := x
@[simp]
protected theorem mk_get (x : Comp F G α) : Comp.mk (Comp.get x) = x := rfl
@[simp]
protected theorem get_mk (x : F fun i ↦ G i α) : Comp.get (Comp.mk x) = x := rfl
section
variable [MvFunctor F] [∀ i, MvFunctor <| G i]
/-- map operation defined on a vector of functors -/
protected def map' : (fun i : Fin2 n ↦ G i α) ⟹ fun i : Fin2 n ↦ G i β := fun _i ↦ map f
/-- The composition of functors is itself functorial -/
protected def map : (Comp F G) α → (Comp F G) β :=
(map fun _i ↦ map f : (F fun i ↦ G i α) → F fun i ↦ G i β)
instance : MvFunctor (Comp F G) where map f := Comp.map f
theorem map_mk (x : F fun i ↦ G i α) :
f <$$> Comp.mk x = Comp.mk ((fun i (x : G i α) ↦ f <$$> x) <$$> x) := rfl
theorem get_map (x : Comp F G α) :
Comp.get (f <$$> x) = (fun i (x : G i α) ↦ f <$$> x) <$$> Comp.get x := rfl
end
instance [MvQPF F] [∀ i, MvQPF <| G i] : MvQPF (Comp F G) where
P := MvPFunctor.comp (P F) fun i ↦ P <| G i
abs := Comp.mk ∘ (map fun _ ↦ abs) ∘ abs ∘ MvPFunctor.comp.get
repr {α} := MvPFunctor.comp.mk ∘ repr ∘
(map fun i ↦ (repr : G i α → (fun i : Fin2 n ↦ Obj (P (G i)) α) i)) ∘ Comp.get
abs_repr := by
intros
simp +unfoldPartialApp only [Function.comp_def, comp.get_mk, abs_repr,
map_map, TypeVec.comp, MvFunctor.id_map', Comp.mk_get]
abs_map := by
intros
simp only [(· ∘ ·)]
rw [← abs_map]
simp +unfoldPartialApp only [comp.get_map, map_map, TypeVec.comp,
abs_map, map_mk]
end Comp
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Sigma.lean | import Mathlib.Data.PFunctor.Multivariate.Basic
import Mathlib.Data.QPF.Multivariate.Basic
/-!
# Dependent product and sum of QPFs are QPFs
-/
universe u
namespace MvQPF
open MvFunctor
variable {n : ℕ} {A : Type u}
variable (F : A → TypeVec.{u} n → Type u)
/-- Dependent sum of an `n`-ary functor. The sum can range over
data types like `ℕ` or over `Type.{u-1}` -/
def Sigma (v : TypeVec.{u} n) : Type u :=
Σ α : A, F α v
/-- Dependent product of an `n`-ary functor. The sum can range over
data types like `ℕ` or over `Type.{u-1}` -/
def Pi (v : TypeVec.{u} n) : Type u :=
∀ α : A, F α v
instance Sigma.inhabited {α} [Inhabited A] [Inhabited (F default α)] : Inhabited (Sigma F α) :=
⟨⟨default, default⟩⟩
instance Pi.inhabited {α} [∀ a, Inhabited (F a α)] : Inhabited (Pi F α) :=
⟨fun _a => default⟩
namespace Sigma
instance [∀ α, MvFunctor <| F α] : MvFunctor (Sigma F) where
map := fun f ⟨a, x⟩ => ⟨a, f <$$> x⟩
variable [∀ α, MvQPF <| F α]
/-- polynomial functor representation of a dependent sum -/
protected def P : MvPFunctor n :=
⟨Σ a, (P (F a)).A, fun x => (P (F x.1)).B x.2⟩
/-- abstraction function for dependent sums -/
protected def abs ⦃α⦄ : Sigma.P F α → Sigma F α
| ⟨a, f⟩ => ⟨a.1, MvQPF.abs ⟨a.2, f⟩⟩
/-- representation function for dependent sums -/
protected def repr ⦃α⦄ : Sigma F α → Sigma.P F α
| ⟨a, f⟩ =>
let x := MvQPF.repr f
⟨⟨a, x.1⟩, x.2⟩
instance : MvQPF (Sigma F) where
P := Sigma.P F
abs {α} := @Sigma.abs _ _ F _ α
repr {α} := @Sigma.repr _ _ F _ α
abs_repr := by rintro α ⟨x, f⟩; simp only [Sigma.abs, Sigma.repr, Sigma.eta, abs_repr]
abs_map := by rintro α β f ⟨x, g⟩; simp only [Sigma.abs, MvPFunctor.map_eq]
simp only [(· <$$> ·), ← abs_map, ← MvPFunctor.map_eq]
end Sigma
namespace Pi
instance [∀ α, MvFunctor <| F α] : MvFunctor (Pi F) where map f x a := f <$$> x a
variable [∀ α, MvQPF <| F α]
/-- polynomial functor representation of a dependent product -/
protected def P : MvPFunctor n :=
⟨∀ a, (P (F a)).A, fun x i => Σ a, (P (F a)).B (x a) i⟩
/-- abstraction function for dependent products -/
protected def abs ⦃α⦄ : Pi.P F α → Pi F α
| ⟨a, f⟩ => fun x => MvQPF.abs ⟨a x, fun i y => f i ⟨_, y⟩⟩
/-- representation function for dependent products -/
protected def repr ⦃α⦄ : Pi F α → Pi.P F α
| f => ⟨fun a => (MvQPF.repr (f a)).1, fun _i a => (MvQPF.repr (f _)).2 _ a.2⟩
instance : MvQPF (Pi F) where
P := Pi.P F
abs := @Pi.abs _ _ F _
repr := @Pi.repr _ _ F _
abs_repr := by rintro α f; simp only [Pi.abs, Pi.repr, Sigma.eta, abs_repr]
abs_map := by rintro α β f ⟨x, g⟩; simp only [Pi.abs, (· <$$> ·), ← abs_map]; rfl
end Pi
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Const.lean | import Mathlib.Control.Functor.Multivariate
import Mathlib.Data.QPF.Multivariate.Basic
/-!
# Constant functors are QPFs
Constant functors map every type vectors to the same target type. This
is a useful device for constructing data types from more basic types
that are not actually functorial. For instance `Const n Nat` makes
`Nat` into a functor that can be used in a functor-based data type
specification.
-/
universe u
namespace MvQPF
open MvFunctor
variable (n : ℕ)
/-- Constant multivariate functor -/
@[nolint unusedArguments]
def Const (A : Type*) (_v : TypeVec.{u} n) : Type _ := A
instance Const.inhabited {A α} [Inhabited A] : Inhabited (Const n A α) := ⟨(default : A)⟩
namespace Const
open MvPFunctor
variable {n} {A : Type u} {α β : TypeVec.{u} n} (f : α ⟹ β)
/-- Constructor for constant functor -/
protected def mk (x : A) : Const n A α := x
/-- Destructor for constant functor -/
protected def get (x : Const n A α) : A := x
@[simp]
protected theorem mk_get (x : Const n A α) : Const.mk (Const.get x) = x := rfl
@[simp]
protected theorem get_mk (x : A) : Const.get (Const.mk x : Const n A α) = x := rfl
/-- `map` for constant functor -/
protected def map : Const n A α → Const n A β := fun x => x
instance MvFunctor : MvFunctor (Const n A) where map _f := Const.map
theorem map_mk (x : A) : f <$$> Const.mk x = Const.mk x := rfl
theorem get_map (x : (Const n A) α) : Const.get (f <$$> x) = Const.get x := rfl
instance mvqpf : @MvQPF _ (Const n A) where
P := MvPFunctor.const n A
abs x := MvPFunctor.const.get x
repr x := MvPFunctor.const.mk n x
abs_repr := fun _ => const.get_mk _
abs_map := fun _ => const.get_map _
end Const
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Prj.lean | import Mathlib.Control.Functor.Multivariate
import Mathlib.Data.QPF.Multivariate.Basic
/-!
Projection functors are QPFs. The `n`-ary projection functors on `i` is an `n`-ary
functor `F` such that `F (α₀..αᵢ₋₁, αᵢ, αᵢ₊₁..αₙ₋₁) = αᵢ`
-/
universe u v
namespace MvQPF
open MvFunctor
variable {n : ℕ} (i : Fin2 n)
/-- The projection `i` functor -/
def Prj (v : TypeVec.{u} n) : Type u := v i
instance Prj.inhabited {v : TypeVec.{u} n} [Inhabited (v i)] : Inhabited (Prj i v) :=
⟨(default : v i)⟩
/-- `map` on functor `Prj i` -/
def Prj.map ⦃α β : TypeVec n⦄ (f : α ⟹ β) : Prj i α → Prj i β := f _
instance Prj.mvfunctor : MvFunctor (Prj i) where map := @Prj.map _ i
/-- Polynomial representation of the projection functor -/
def Prj.P : MvPFunctor.{u} n where
A := PUnit
B _ j := ULift <| PLift <| i = j
/-- Abstraction function of the `QPF` instance -/
def Prj.abs ⦃α : TypeVec n⦄ : Prj.P i α → Prj i α
| ⟨_x, f⟩ => f _ ⟨⟨rfl⟩⟩
/-- Representation function of the `QPF` instance -/
def Prj.repr ⦃α : TypeVec n⦄ : Prj i α → Prj.P i α := fun x : α i =>
⟨⟨⟩, fun j ⟨⟨h⟩⟩ => (h.rec x : α j)⟩
instance Prj.mvqpf : MvQPF (Prj i) where
P := Prj.P i
abs := @Prj.abs _ i
repr := @Prj.repr _ i
abs_repr := by intros; rfl
abs_map := by intro α β f P; cases P; rfl
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Cofix.lean | import Mathlib.Control.Functor.Multivariate
import Mathlib.Data.PFunctor.Multivariate.Basic
import Mathlib.Data.PFunctor.Multivariate.M
import Mathlib.Data.QPF.Multivariate.Basic
/-!
# The final co-algebra of a multivariate qpf is again a qpf.
For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with
regards to its last argument `αₙ`. The result is an `n`-ary functor: `Fix F (α₀,..,αₙ₋₁)`.
Making `Fix F` into a functor allows us to take the fixed point, compose with other functors
and take a fixed point again.
## Main definitions
* `Cofix.mk` - constructor
* `Cofix.dest` - destructor
* `Cofix.corec` - corecursor: useful for formulating infinite, productive computations
* `Cofix.bisim` - bisimulation: proof technique to show the equality of possibly infinite values
of `Cofix F α`
## Implementation notes
For `F` a QPF, we define `Cofix F α` in terms of the M-type of the polynomial functor `P` of `F`.
We define the relation `Mcongr` and take its quotient as the definition of `Cofix F α`.
`Mcongr` is taken as the weakest bisimulation on M-type. See
[avigad-carneiro-hudon2019] for more details.
## Reference
* Jeremy Avigad, Mario M. Carneiro and Simon Hudon.
[*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u
open MvFunctor
namespace MvQPF
open TypeVec MvPFunctor
open MvFunctor (LiftP LiftR)
variable {n : ℕ} {F : TypeVec.{u} (n + 1) → Type u} [q : MvQPF F]
/-- `corecF` is used as a basis for defining the corecursor of `Cofix F α`. `corecF`
uses corecursion to construct the M-type generated by `q.P` and uses function on `F`
as a corecursive step -/
def corecF {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) : β → q.P.M α :=
M.corec _ fun x => repr (g x)
theorem corecF_eq {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) :
M.dest q.P (corecF g x) = appendFun id (corecF g) <$$> repr (g x) := by
rw [corecF, M.dest_corec]
/-- Characterization of desirable equivalence relations on M-types -/
def IsPrecongr {α : TypeVec n} (r : q.P.M α → q.P.M α → Prop) : Prop :=
∀ ⦃x y⦄,
r x y →
abs (appendFun id (Quot.mk r) <$$> M.dest q.P x) =
abs (appendFun id (Quot.mk r) <$$> M.dest q.P y)
/-- Equivalence relation on M-types representing a value of type `Cofix F` -/
def Mcongr {α : TypeVec n} (x y : q.P.M α) : Prop :=
∃ r, IsPrecongr r ∧ r x y
/-- Greatest fixed point of functor F. The result is a functor with one fewer parameters
than the input. For `F a b c` a ternary functor, fix F is a binary functor such that
```lean
Cofix F a b = F a b (Cofix F a b)
```
-/
def Cofix (F : TypeVec (n + 1) → Type u) [MvQPF F] (α : TypeVec n) :=
Quot (@Mcongr _ F _ α)
instance {α : TypeVec n} [Inhabited q.P.A] [∀ i : Fin2 n, Inhabited (α i)] :
Inhabited (Cofix F α) :=
⟨Quot.mk _ default⟩
/-- maps every element of the W type to a canonical representative -/
def mRepr {α : TypeVec n} : q.P.M α → q.P.M α :=
corecF (abs ∘ M.dest q.P)
/-- the map function for the functor `Cofix F` -/
def Cofix.map {α β : TypeVec n} (g : α ⟹ β) : Cofix F α → Cofix F β :=
Quot.lift (fun x : q.P.M α => Quot.mk Mcongr (g <$$> x))
(by
rintro aa₁ aa₂ ⟨r, pr, ra₁a₂⟩; apply Quot.sound
let r' b₁ b₂ := ∃ a₁ a₂ : q.P.M α, r a₁ a₂ ∧ b₁ = g <$$> a₁ ∧ b₂ = g <$$> a₂
use r'; constructor
· show IsPrecongr r'
rintro b₁ b₂ ⟨a₁, a₂, ra₁a₂, b₁eq, b₂eq⟩
let u : Quot r → Quot r' :=
Quot.lift (fun x : q.P.M α => Quot.mk r' (g <$$> x))
(by
intro a₁ a₂ ra₁a₂
apply Quot.sound
exact ⟨a₁, a₂, ra₁a₂, rfl, rfl⟩)
have hu : (Quot.mk r' ∘ fun x : q.P.M α => g <$$> x) = u ∘ Quot.mk r := by
ext x
rfl
rw [b₁eq, b₂eq, M.dest_map, M.dest_map, ← q.P.comp_map, ← q.P.comp_map]
rw [← appendFun_comp, id_comp, hu, ← comp_id g, appendFun_comp]
rw [q.P.comp_map, q.P.comp_map, abs_map, pr ra₁a₂, ← abs_map]
show r' (g <$$> aa₁) (g <$$> aa₂); exact ⟨aa₁, aa₂, ra₁a₂, rfl, rfl⟩)
instance Cofix.mvfunctor : MvFunctor (Cofix F) where map := @Cofix.map _ _ _
/-- Corecursor for `Cofix F` -/
def Cofix.corec {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) : β → Cofix F α := fun x =>
Quot.mk _ (corecF g x)
/-- Destructor for `Cofix F` -/
def Cofix.dest {α : TypeVec n} : Cofix F α → F (α.append1 (Cofix F α)) :=
Quot.lift (fun x => appendFun id (Quot.mk Mcongr) <$$> abs (M.dest q.P x))
(by
rintro x y ⟨r, pr, rxy⟩
dsimp
have : ∀ x y, r x y → Mcongr x y := by
intro x y h
exact ⟨r, pr, h⟩
rw [← Quot.factor_mk_eq _ _ this]
conv =>
lhs
rw [appendFun_comp_id, comp_map, ← abs_map, pr rxy, abs_map, ← comp_map,
← appendFun_comp_id])
/-- Abstraction function for `cofix F α` -/
def Cofix.abs {α} : q.P.M α → Cofix F α :=
Quot.mk _
/-- Representation function for `Cofix F α` -/
def Cofix.repr {α} : Cofix F α → q.P.M α :=
M.corec _ <| q.repr ∘ Cofix.dest
/-- Corecursor for `Cofix F` -/
def Cofix.corec'₁ {α : TypeVec n} {β : Type u} (g : ∀ {X}, (β → X) → F (α.append1 X)) (x : β) :
Cofix F α :=
Cofix.corec (fun _ => g id) x
/-- More flexible corecursor for `Cofix F`. Allows the return of a fully formed
value instead of making a recursive call -/
def Cofix.corec' {α : TypeVec n} {β : Type u} (g : β → F (α.append1 (Cofix F α ⊕ β))) (x : β) :
Cofix F α :=
let f : (α ::: Cofix F α) ⟹ (α ::: (Cofix F α ⊕ β)) := id ::: Sum.inl
Cofix.corec (Sum.elim (MvFunctor.map f ∘ Cofix.dest) g) (Sum.inr x : Cofix F α ⊕ β)
/-- Corecursor for `Cofix F`. The shape allows recursive calls to
look like recursive calls. -/
def Cofix.corec₁ {α : TypeVec n} {β : Type u}
(g : ∀ {X}, (Cofix F α → X) → (β → X) → β → F (α ::: X)) (x : β) : Cofix F α :=
Cofix.corec' (fun x => g Sum.inl Sum.inr x) x
theorem Cofix.dest_corec {α : TypeVec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) :
Cofix.dest (Cofix.corec g x) = appendFun id (Cofix.corec g) <$$> g x := by
conv =>
lhs
rw [Cofix.dest, Cofix.corec]
dsimp
rw [corecF_eq, abs_map, abs_repr, ← comp_map, ← appendFun_comp]; rfl
/-- constructor for `Cofix F` -/
def Cofix.mk {α : TypeVec n} : F (α.append1 <| Cofix F α) → Cofix F α :=
Cofix.corec fun x => (appendFun id fun i : Cofix F α => Cofix.dest.{u} i) <$$> x
/-!
## Bisimulation principles for `Cofix F`
The following theorems are bisimulation principles. The general idea
is to use a bisimulation relation to prove the equality between
specific values of type `Cofix F α`.
A bisimulation relation `R` for values `x y : Cofix F α`:
* holds for `x y`: `R x y`
* for any values `x y` that satisfy `R`, their root has the same shape
and their children can be paired in such a way that they satisfy `R`.
-/
private theorem Cofix.bisim_aux {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop) (h' : ∀ x, r x x)
(h : ∀ x y, r x y →
appendFun id (Quot.mk r) <$$> Cofix.dest x = appendFun id (Quot.mk r) <$$> Cofix.dest y) :
∀ x y, r x y → x = y := by
intro x
rcases x; clear x; rename M (P F) α => x
intro y
rcases y; clear y; rename M (P F) α => y
intro rxy
apply Quot.sound
let r' := fun x y => r (Quot.mk _ x) (Quot.mk _ y)
have hr' : r' = fun x y => r (Quot.mk _ x) (Quot.mk _ y) := rfl
have : IsPrecongr r' := by
intro a b r'ab
have h₀ :
appendFun id (Quot.mk r ∘ Quot.mk Mcongr) <$$> MvQPF.abs (M.dest q.P a) =
appendFun id (Quot.mk r ∘ Quot.mk Mcongr) <$$> MvQPF.abs (M.dest q.P b) := by
rw [appendFun_comp_id, comp_map, comp_map]; exact h _ _ r'ab
have h₁ : ∀ u v : q.P.M α, Mcongr u v → Quot.mk r' u = Quot.mk r' v := by
intro u v cuv
apply Quot.sound
dsimp [r', hr']
rw [Quot.sound cuv]
apply h'
let f : Quot r → Quot r' :=
Quot.lift (Quot.lift (Quot.mk r') h₁)
(by
intro c
apply Quot.inductionOn
(motive := fun c =>
∀ b, r c b → Quot.lift (Quot.mk r') h₁ c = Quot.lift (Quot.mk r') h₁ b) c
clear c
intro c d
apply Quot.inductionOn
(motive := fun d => r (Quot.mk Mcongr c) d →
Quot.lift (Quot.mk r') h₁ (Quot.mk Mcongr c) = Quot.lift (Quot.mk r') h₁ d) d
clear d
intro d rcd; apply Quot.sound; apply rcd)
have : f ∘ Quot.mk r ∘ Quot.mk Mcongr = Quot.mk r' := rfl
rw [← this, appendFun_comp_id, q.P.comp_map, q.P.comp_map, abs_map, abs_map, abs_map, abs_map,
h₀]
exact ⟨r', this, rxy⟩
/-- Bisimulation principle using `map` and `Quot.mk` to match and relate children of two trees. -/
theorem Cofix.bisim_rel {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop)
(h : ∀ x y, r x y →
appendFun id (Quot.mk r) <$$> Cofix.dest x = appendFun id (Quot.mk r) <$$> Cofix.dest y) :
∀ x y, r x y → x = y := by
let r' (x y) := x = y ∨ r x y
intro x y rxy
apply Cofix.bisim_aux r'
· intro x
left
rfl
· intro x y r'xy
cases r'xy with
| inl h =>
rw [h]
| inr r'xy =>
have : ∀ x y, r x y → r' x y := fun x y h => Or.inr h
rw [← Quot.factor_mk_eq _ _ this]
dsimp [r']
rw [appendFun_comp_id]
rw [@comp_map _ _ q _ _ _ (appendFun id (Quot.mk r)),
@comp_map _ _ q _ _ _ (appendFun id (Quot.mk r))]
rw [h _ _ r'xy]
right; exact rxy
/-- Bisimulation principle using `LiftR` to match and relate children of two trees. -/
theorem Cofix.bisim {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop)
(h : ∀ x y, r x y → LiftR (RelLast α r) (Cofix.dest x) (Cofix.dest y)) :
∀ x y, r x y → x = y := by
apply Cofix.bisim_rel
intro x y rxy
rcases (liftR_iff (fun a b => RelLast α r b) (dest x) (dest y)).mp (h x y rxy)
with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩
rw [dxeq, dyeq, ← abs_map, ← abs_map, MvPFunctor.map_eq, MvPFunctor.map_eq]
rw [← split_dropFun_lastFun f₀, ← split_dropFun_lastFun f₁]
rw [appendFun_comp_splitFun, appendFun_comp_splitFun]
rw [id_comp, id_comp]
congr 2 with (i j); rcases i with - | i
· apply Quot.sound
apply h' _ j
· change f₀ _ j = f₁ _ j
apply h' _ j
/-- Bisimulation principle using `LiftR'` to match and relate children of two trees. -/
theorem Cofix.bisim₂ {α : TypeVec n} (r : Cofix F α → Cofix F α → Prop)
(h : ∀ x y, r x y → LiftR' (RelLast' α r) (Cofix.dest x) (Cofix.dest y)) :
∀ x y, r x y → x = y :=
Cofix.bisim r <| by intros; rw [← LiftR_RelLast_iff]; apply h; assumption
/-- Bisimulation principle the values `⟨a,f⟩` of the polynomial functor representing
`Cofix F α` as well as an invariant `Q : β → Prop` and a state `β` generating the
left-hand side and right-hand side of the equality through functions `u v : β → Cofix F α` -/
theorem Cofix.bisim' {α : TypeVec n} {β : Type*} (Q : β → Prop) (u v : β → Cofix F α)
(h : ∀ x, Q x → ∃ a f' f₀ f₁,
Cofix.dest (u x) = q.abs ⟨a, q.P.appendContents f' f₀⟩ ∧
Cofix.dest (v x) = q.abs ⟨a, q.P.appendContents f' f₁⟩ ∧
∀ i, ∃ x', Q x' ∧ f₀ i = u x' ∧ f₁ i = v x') :
∀ x, Q x → u x = v x := fun x Qx =>
let R := fun w z : Cofix F α => ∃ x', Q x' ∧ w = u x' ∧ z = v x'
Cofix.bisim R
(fun x y ⟨x', Qx', xeq, yeq⟩ => by
rcases h x' Qx' with ⟨a, f', f₀, f₁, ux'eq, vx'eq, h'⟩
rw [liftR_iff]
refine
⟨a, q.P.appendContents f' f₀, q.P.appendContents f' f₁, xeq.symm ▸ ux'eq,
yeq.symm ▸ vx'eq, ?_⟩
intro i; cases i
· apply h'
· intro j
apply Eq.refl)
_ _ ⟨x, Qx, rfl, rfl⟩
theorem Cofix.mk_dest {α : TypeVec n} (x : Cofix F α) : Cofix.mk (Cofix.dest x) = x := by
apply Cofix.bisim_rel (fun x y : Cofix F α => x = Cofix.mk (Cofix.dest y)) _ _ _ rfl
dsimp
intro x y h
rw [h]
conv =>
lhs
congr
rfl
rw [Cofix.mk]
rw [Cofix.dest_corec]
rw [← comp_map, ← appendFun_comp, id_comp]
rw [← comp_map, ← appendFun_comp, id_comp, ← Cofix.mk]
congr 1
apply congrArg
funext x
apply Quot.sound
rfl
theorem Cofix.dest_mk {α : TypeVec n} (x : F (α.append1 <| Cofix F α)) :
Cofix.dest (Cofix.mk x) = x := by
have : Cofix.mk ∘ Cofix.dest = @_root_.id (Cofix F α) := funext Cofix.mk_dest
rw [Cofix.mk, Cofix.dest_corec, ← comp_map, ← Cofix.mk, ← appendFun_comp, this, id_comp,
appendFun_id_id, MvFunctor.id_map]
theorem Cofix.ext {α : TypeVec n} (x y : Cofix F α) (h : x.dest = y.dest) : x = y := by
rw [← Cofix.mk_dest x, h, Cofix.mk_dest]
theorem Cofix.ext_mk {α : TypeVec n} (x y : F (α ::: Cofix F α)) (h : Cofix.mk x = Cofix.mk y) :
x = y := by rw [← Cofix.dest_mk x, h, Cofix.dest_mk]
/-!
`liftR_map`, `liftR_map_last` and `liftR_map_last'` are useful for reasoning about
the induction step in bisimulation proofs.
-/
section LiftRMap
theorem liftR_map {α β : TypeVec n} {F' : TypeVec n → Type u} [MvFunctor F'] [LawfulMvFunctor F']
(R : β ⊗ β ⟹ «repeat» n Prop) (x : F' α) (f g : α ⟹ β) (h : α ⟹ Subtype_ R)
(hh : subtypeVal _ ⊚ h = (f ⊗' g) ⊚ prod.diag) : LiftR' R (f <$$> x) (g <$$> x) := by
rw [LiftR_def]
exists h <$$> x
rw [MvFunctor.map_map, comp_assoc, hh, ← comp_assoc, fst_prod_mk, comp_assoc, fst_diag]
rw [MvFunctor.map_map, comp_assoc, hh, ← comp_assoc, snd_prod_mk, comp_assoc, snd_diag]
dsimp [LiftR']; constructor <;> rfl
open Function
theorem liftR_map_last [lawful : LawfulMvFunctor F]
{α : TypeVec n} {ι ι'} (R : ι' → ι' → Prop)
(x : F (α ::: ι)) (f g : ι → ι') (hh : ∀ x : ι, R (f x) (g x)) :
LiftR' (RelLast' _ R) ((id ::: f) <$$> x) ((id ::: g) <$$> x) :=
let h : ι → { x : ι' × ι' // uncurry R x } := fun x => ⟨(f x, g x), hh x⟩
let b : (α ::: ι) ⟹ _ := @diagSub n α ::: h
let c :
(Subtype_ α.repeatEq ::: { x // uncurry R x }) ⟹
((fun i : Fin2 n => { x // ofRepeat (α.RelLast' R i.fs x) }) ::: Subtype (uncurry R)) :=
ofSubtype _ ::: id
have hh :
subtypeVal _ ⊚ toSubtype _ ⊚ fromAppend1DropLast ⊚ c ⊚ b =
((id ::: f) ⊗' (id ::: g)) ⊚ prod.diag := by
dsimp [b]
apply eq_of_drop_last_eq
· dsimp
simp only [prod_map_id, TypeVec.id_comp]
erw [toSubtype_of_subtype_assoc, TypeVec.id_comp]
clear liftR_map_last q lawful F x R f g hh h b c
ext (i x) : 2
induction i with
| fz => rfl
| fs _ ih =>
apply ih
simp only [lastFun_from_append1_drop_last, lastFun_toSubtype, lastFun_appendFun,
lastFun_subtypeVal, Function.id_comp, lastFun_comp, lastFun_prod]
ext1
rfl
liftR_map _ _ _ _ (toSubtype _ ⊚ fromAppend1DropLast ⊚ c ⊚ b) hh
theorem liftR_map_last' [LawfulMvFunctor F] {α : TypeVec n} {ι} (R : ι → ι → Prop) (x : F (α ::: ι))
(f : ι → ι) (hh : ∀ x : ι, R (f x) x) : LiftR' (RelLast' _ R) ((id ::: f) <$$> x) x := by
have := liftR_map_last R x f id hh
rwa [appendFun_id_id, MvFunctor.id_map] at this
end LiftRMap
variable {F : TypeVec (n + 1) → Type u} [q : MvQPF F]
theorem Cofix.abs_repr {α} (x : Cofix F α) : Quot.mk _ (Cofix.repr x) = x := by
let R := fun x y : Cofix F α => abs (repr y) = x
refine Cofix.bisim₂ R ?_ _ _ rfl
clear x
rintro x y h
subst h
dsimp [Cofix.dest, Cofix.abs]
induction y using Quot.ind
simp only [Cofix.repr, M.dest_corec, abs_map, MvQPF.abs_repr, Function.comp]
conv => congr; rfl; rw [Cofix.dest]
rw [MvFunctor.map_map, MvFunctor.map_map, ← appendFun_comp_id, ← appendFun_comp_id]
apply liftR_map_last
intros
rfl
end MvQPF
namespace Mathlib.Tactic.MvBisim
open Lean Expr Elab Term Tactic Meta Qq
/-- tactic for proof by bisimulation -/
syntax "mv_bisim" (ppSpace colGt term) (" with" (ppSpace colGt binderIdent)+)? : tactic
elab_rules : tactic
| `(tactic| mv_bisim $e $[ with $ids:binderIdent*]?) => do
let ids : TSyntaxArray `Lean.binderIdent := ids.getD #[]
let idsn (n : ℕ) : Name :=
match ids[n]? with
| some s =>
match s with
| `(binderIdent| $n:ident) => n.getId
| `(binderIdent| _) => `_
| _ => unreachable!
| none => `_
let idss (n : ℕ) : TacticM (TSyntax `rcasesPat) := do
match ids[n]? with
| some s =>
match s with
| `(binderIdent| $n:ident) => `(rcasesPat| $n)
| `(binderIdent| _%$b) => `(rcasesPat| _%$b)
| _ => unreachable!
| none => `(rcasesPat| _)
withMainContext do
let e ← Tactic.elabTerm e none
let f ← liftMetaTacticAux fun g => do
let (#[fv], g) ← g.generalize #[{ expr := e }] | unreachable!
return (mkFVar fv, [g])
withMainContext do
let some (t, l, r) ← matchEq? (← getMainTarget) | throwError "goal is not an equality"
let ex ←
withLocalDecl (idsn 1) .default t fun v₀ =>
withLocalDecl (idsn 2) .default t fun v₁ => do
let x₀ ← mkEq v₀ l
let x₁ ← mkEq v₁ r
let xx ← mkAppM ``And #[x₀, x₁]
let ex₁ ← mkLambdaFVars #[f] xx
let ex₂ ← mkAppM ``Exists #[ex₁]
mkLambdaFVars #[v₀, v₁] ex₂
let R ← liftMetaTacticAux fun g => do
let g₁ ← g.define (idsn 0) (← mkArrow t (← mkArrow t (mkSort .zero))) ex
let (Rv, g₂) ← g₁.intro1P
return (mkFVar Rv, [g₂])
withMainContext do
ids[0]?.forM fun s => addLocalVarInfoForBinderIdent R s
let sR ← exprToSyntax R
evalTactic <| ← `(tactic|
refine MvQPF.Cofix.bisim₂ $sR ?_ _ _ ⟨_, rfl, rfl⟩;
rintro $(← idss 1) $(← idss 2) ⟨$(← idss 3), $(← idss 4), $(← idss 5)⟩)
liftMetaTactic fun g => return [← g.clear f.fvarId!]
for h : n in [6 : ids.size] do
let name := ids[n]
logWarningAt name m!"unused name: {name}"
end Mathlib.Tactic.MvBisim
namespace MvQPF
open TypeVec MvPFunctor
open MvFunctor (LiftP LiftR)
variable {n : ℕ} {F : TypeVec.{u} (n + 1) → Type u} [q : MvQPF F]
theorem corec_roll {α : TypeVec n} {X Y} {x₀ : X} (f : X → Y) (g : Y → F (α ::: X)) :
Cofix.corec (g ∘ f) x₀ = Cofix.corec (MvFunctor.map (id ::: f) ∘ g) (f x₀) := by
mv_bisim x₀ with R a b x Ha Hb
rw [Ha, Hb, Cofix.dest_corec, Cofix.dest_corec, Function.comp_apply, Function.comp_apply]
rw [MvFunctor.map_map, ← appendFun_comp_id]
refine liftR_map_last _ _ _ _ ?_
intro a; refine ⟨a, rfl, rfl⟩
theorem Cofix.dest_corec' {α : TypeVec.{u} n} {β : Type u}
(g : β → F (α.append1 (Cofix F α ⊕ β))) (x : β) :
Cofix.dest (Cofix.corec' g x) =
appendFun id (Sum.elim _root_.id (Cofix.corec' g)) <$$> g x := by
rw [Cofix.corec', Cofix.dest_corec]; dsimp
congr!; ext (i | i) <;> erw [corec_roll] <;> dsimp [Cofix.corec']
· mv_bisim i with R a b x Ha Hb
rw [Ha, Hb, Cofix.dest_corec]
dsimp [Function.comp_def]
repeat rw [MvFunctor.map_map, ← appendFun_comp_id]
apply liftR_map_last'
dsimp [Function.comp_def]
intros
exact ⟨_, rfl, rfl⟩
· congr 1 with y
erw [appendFun_id_id]
simp [MvFunctor.id_map, Sum.elim]
theorem Cofix.dest_corec₁ {α : TypeVec n} {β : Type u}
(g : ∀ {X}, (Cofix F α → X) → (β → X) → β → F (α.append1 X)) (x : β)
(h : ∀ (X Y) (f : Cofix F α → X) (f' : β → X) (k : X → Y),
g (k ∘ f) (k ∘ f') x = (id ::: k) <$$> g f f' x) :
Cofix.dest (Cofix.corec₁ (@g) x) = g id (Cofix.corec₁ @g) x := by
rw [Cofix.corec₁, Cofix.dest_corec', ← h]; rfl
instance mvqpfCofix : MvQPF (Cofix F) where
P := q.P.mp
abs := Quot.mk Mcongr
repr := Cofix.repr
abs_repr := Cofix.abs_repr
abs_map := by intros; rfl
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Multivariate/Constructions/Fix.lean | import Mathlib.Data.PFunctor.Multivariate.W
import Mathlib.Data.QPF.Multivariate.Basic
/-!
# The initial algebra of a multivariate qpf is again a qpf.
For an `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with
regards to its last argument `αₙ`. The result is an `n`-ary functor: `Fix F (α₀,..,αₙ₋₁)`.
Making `Fix F` into a functor allows us to take the fixed point, compose with other functors
and take a fixed point again.
## Main definitions
* `Fix.mk` - constructor
* `Fix.dest` - destructor
* `Fix.rec` - recursor: basis for defining functions by structural recursion on `Fix F α`
* `Fix.drec` - dependent recursor: generalization of `Fix.rec` where
the result type of the function is allowed to depend on the `Fix F α` value
* `Fix.rec_eq` - defining equation for `recursor`
* `Fix.ind` - induction principle for `Fix F α`
## Implementation notes
For `F` a `QPF`, we define `Fix F α` in terms of the W-type of the polynomial functor `P` of `F`.
We define the relation `WEquiv` and take its quotient as the definition of `Fix F α`.
See [avigad-carneiro-hudon2019] for more details.
## Reference
* Jeremy Avigad, Mario M. Carneiro and Simon Hudon.
[*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u v
namespace MvQPF
open TypeVec
open MvFunctor (LiftP LiftR)
open MvFunctor
variable {n : ℕ} {F : TypeVec.{u} (n + 1) → Type u} [q : MvQPF F]
/-- `recF` is used as a basis for defining the recursor on `Fix F α`. `recF`
traverses recursively the W-type generated by `q.P` using a function on `F`
as a recursive step -/
def recF {α : TypeVec n} {β : Type u} (g : F (α.append1 β) → β) : q.P.W α → β :=
q.P.wRec fun a f' _f rec => g (abs ⟨a, splitFun f' rec⟩)
theorem recF_eq {α : TypeVec n} {β : Type u} (g : F (α.append1 β) → β) (a : q.P.A)
(f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) :
recF g (q.P.wMk a f' f) = g (abs ⟨a, splitFun f' (recF g ∘ f)⟩) := by
rw [recF, MvPFunctor.wRec_eq]; rfl
theorem recF_eq' {α : TypeVec n} {β : Type u} (g : F (α.append1 β) → β) (x : q.P.W α) :
recF g x = g (abs (appendFun id (recF g) <$$> q.P.wDest' x)) := by
apply q.P.w_cases _ x
intro a f' f
rw [recF_eq, q.P.wDest'_wMk, MvPFunctor.map_eq, appendFun_comp_splitFun, TypeVec.id_comp]
/-- Equivalence relation on W-types that represent the same `Fix F`
value -/
inductive WEquiv {α : TypeVec n} : q.P.W α → q.P.W α → Prop
| ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) :
(∀ x, WEquiv (f₀ x) (f₁ x)) → WEquiv (q.P.wMk a f' f₀) (q.P.wMk a f' f₁)
| abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A)
(f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) :
abs ⟨a₀, q.P.appendContents f'₀ f₀⟩ = abs ⟨a₁, q.P.appendContents f'₁ f₁⟩ →
WEquiv (q.P.wMk a₀ f'₀ f₀) (q.P.wMk a₁ f'₁ f₁)
| trans (u v w : q.P.W α) : WEquiv u v → WEquiv v w → WEquiv u w
theorem recF_eq_of_wEquiv (α : TypeVec n) {β : Type u} (u : F (α.append1 β) → β) (x y : q.P.W α) :
WEquiv x y → recF u x = recF u y := by
apply q.P.w_cases _ x
intro a₀ f'₀ f₀
apply q.P.w_cases _ y
intro a₁ f'₁ f₁ h
-- Porting note: induction on h doesn't work.
refine @WEquiv.recOn _ _ _ _ (fun a a' _ ↦ recF u a = recF u a') _ _ h ?_ ?_ ?_
· intro a f' f₀ f₁ _h ih; simp only [recF_eq]
congr 4; funext; apply ih
· intro a₀ f'₀ f₀ a₁ f'₁ f₁ h; simp only [recF_eq', abs_map, MvPFunctor.wDest'_wMk, h]
· intro x y z _e₁ _e₂ ih₁ ih₂; exact Eq.trans ih₁ ih₂
theorem wEquiv.abs' {α : TypeVec n} (x y : q.P.W α)
(h : MvQPF.abs (q.P.wDest' x) = MvQPF.abs (q.P.wDest' y)) :
WEquiv x y := by
revert h
apply q.P.w_cases _ x
intro a₀ f'₀ f₀
apply q.P.w_cases _ y
intro a₁ f'₁ f₁
apply WEquiv.abs
theorem wEquiv.refl {α : TypeVec n} (x : q.P.W α) : WEquiv x x := abs' x x rfl
theorem wEquiv.symm {α : TypeVec n} (x y : q.P.W α) : WEquiv x y → WEquiv y x := by
intro h; induction h with
| ind a f' f₀ f₁ _h ih => exact WEquiv.ind _ _ _ _ ih
| abs a₀ f'₀ f₀ a₁ f'₁ f₁ h => exact WEquiv.abs _ _ _ _ _ _ h.symm
| trans x y z _e₁ _e₂ ih₁ ih₂ => exact MvQPF.WEquiv.trans _ _ _ ih₂ ih₁
/-- maps every element of the W type to a canonical representative -/
def wrepr {α : TypeVec n} : q.P.W α → q.P.W α :=
recF (q.P.wMk' ∘ repr)
theorem wrepr_wMk {α : TypeVec n} (a : q.P.A) (f' : q.P.drop.B a ⟹ α)
(f : q.P.last.B a → q.P.W α) :
wrepr (q.P.wMk a f' f) =
q.P.wMk' (repr (abs (appendFun id wrepr <$$> ⟨a, q.P.appendContents f' f⟩))) := by
rw [wrepr, recF_eq', q.P.wDest'_wMk]; rfl
theorem wrepr_equiv {α : TypeVec n} (x : q.P.W α) : WEquiv (wrepr x) x := by
apply q.P.w_ind _ x; intro a f' f ih
apply WEquiv.trans _ (q.P.wMk' (appendFun id wrepr <$$> ⟨a, q.P.appendContents f' f⟩))
· apply wEquiv.abs'
rw [wrepr_wMk, q.P.wDest'_wMk', q.P.wDest'_wMk', abs_repr]
rw [q.P.map_eq, MvPFunctor.wMk', appendFun_comp_splitFun, id_comp]
apply WEquiv.ind; exact ih
theorem wEquiv_map {α β : TypeVec n} (g : α ⟹ β) (x y : q.P.W α) :
WEquiv x y → WEquiv (g <$$> x) (g <$$> y) := by
intro h; induction h with
| ind a f' f₀ f₁ h ih => rw [q.P.w_map_wMk, q.P.w_map_wMk]; apply WEquiv.ind; exact ih
| abs a₀ f'₀ f₀ a₁ f'₁ f₁ h =>
rw [q.P.w_map_wMk, q.P.w_map_wMk]; apply WEquiv.abs
change
abs (q.P.objAppend1 a₀ (g ⊚ f'₀) fun x => q.P.wMap g (f₀ x)) =
abs (q.P.objAppend1 a₁ (g ⊚ f'₁) fun x => q.P.wMap g (f₁ x))
rw [← q.P.map_objAppend1, ← q.P.map_objAppend1, abs_map, abs_map, h]
| trans x y z _ _ ih₁ ih₂ =>
apply MvQPF.WEquiv.trans
· apply ih₁
· apply ih₂
/-- Define the fixed point as the quotient of trees under the equivalence relation.
-/
def wSetoid (α : TypeVec n) : Setoid (q.P.W α) :=
⟨WEquiv, wEquiv.refl, wEquiv.symm _ _, WEquiv.trans _ _ _⟩
attribute [local instance] wSetoid
/-- Least fixed point of functor F. The result is a functor with one fewer parameters
than the input. For `F a b c` a ternary functor, `Fix F` is a binary functor such that
```lean
Fix F a b = F a b (Fix F a b)
```
-/
def Fix {n : ℕ} (F : TypeVec (n + 1) → Type*) [q : MvQPF F] (α : TypeVec n) :=
Quotient (wSetoid α : Setoid (q.P.W α))
/-- `Fix F` is a functor -/
def Fix.map {α β : TypeVec n} (g : α ⟹ β) : Fix F α → Fix F β :=
Quotient.lift (fun x : q.P.W α => ⟦q.P.wMap g x⟧) fun _a _b h => Quot.sound (wEquiv_map _ _ _ h)
instance Fix.mvfunctor : MvFunctor (Fix F) where map := Fix.map
variable {α : TypeVec.{u} n}
/-- Recursor for `Fix F` -/
def Fix.rec {β : Type u} (g : F (α ::: β) → β) : Fix F α → β :=
Quot.lift (recF g) (recF_eq_of_wEquiv α g)
/-- Access W-type underlying `Fix F` -/
def fixToW : Fix F α → q.P.W α :=
Quotient.lift wrepr (recF_eq_of_wEquiv α fun x => q.P.wMk' (repr x))
/-- Constructor for `Fix F` -/
def Fix.mk (x : F (append1 α (Fix F α))) : Fix F α :=
Quot.mk _ (q.P.wMk' (appendFun id fixToW <$$> repr x))
/-- Destructor for `Fix F` -/
def Fix.dest : Fix F α → F (append1 α (Fix F α)) :=
Fix.rec (MvFunctor.map (appendFun id Fix.mk))
theorem Fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (Fix F α))) :
Fix.rec g (Fix.mk x) = g (appendFun id (Fix.rec g) <$$> x) := by
have : recF g ∘ fixToW = Fix.rec g := by
apply funext
apply Quotient.ind
intro x
apply recF_eq_of_wEquiv
apply wrepr_equiv
conv =>
lhs
rw [Fix.rec, Fix.mk]
dsimp
rcases h : repr x with ⟨a, f⟩
rw [MvPFunctor.map_eq, recF_eq', ← MvPFunctor.map_eq, MvPFunctor.wDest'_wMk']
rw [← MvPFunctor.comp_map, abs_map, ← h, abs_repr, ← appendFun_comp, id_comp, this]
theorem Fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) :
Fix.mk (abs ⟨a, q.P.appendContents f' fun x => ⟦f x⟧⟩) = ⟦q.P.wMk a f' f⟧ := by
have : Fix.mk (abs ⟨a, q.P.appendContents f' fun x => ⟦f x⟧⟩) = ⟦wrepr (q.P.wMk a f' f)⟧ := by
apply Quot.sound; apply wEquiv.abs'
rw [MvPFunctor.wDest'_wMk', abs_map, abs_repr, ← abs_map, MvPFunctor.map_eq]
conv =>
rhs
rw [wrepr_wMk, q.P.wDest'_wMk', abs_repr, MvPFunctor.map_eq]
congr 2; rw [MvPFunctor.appendContents, MvPFunctor.appendContents]
rw [appendFun, appendFun, ← splitFun_comp, ← splitFun_comp]
rfl
rw [this]
apply Quot.sound
apply wrepr_equiv
theorem Fix.ind_rec {β : Type u} (g₁ g₂ : Fix F α → β)
(h :
∀ x : F (append1 α (Fix F α)),
appendFun id g₁ <$$> x = appendFun id g₂ <$$> x → g₁ (Fix.mk x) = g₂ (Fix.mk x)) :
∀ x, g₁ x = g₂ x := by
apply Quot.ind
intro x
apply q.P.w_ind _ x
intro a f' f ih
change g₁ ⟦q.P.wMk a f' f⟧ = g₂ ⟦q.P.wMk a f' f⟧
rw [← Fix.ind_aux a f' f]
apply h
rw [← abs_map, ← abs_map, MvPFunctor.map_eq, MvPFunctor.map_eq]
congr 2
rw [MvPFunctor.appendContents, appendFun, appendFun, ← splitFun_comp, ← splitFun_comp]
have : (g₁ ∘ fun x => ⟦f x⟧) = g₂ ∘ fun x => ⟦f x⟧ := by
ext x
exact ih x
rw [this]
theorem Fix.rec_unique {β : Type u} (g : F (append1 α β) → β) (h : Fix F α → β)
(hyp : ∀ x, h (Fix.mk x) = g (appendFun id h <$$> x)) : Fix.rec g = h := by
ext x
apply Fix.ind_rec
intro x hyp'
rw [hyp, ← hyp', Fix.rec_eq]
theorem Fix.mk_dest (x : Fix F α) : Fix.mk (Fix.dest x) = x := by
change (Fix.mk ∘ Fix.dest) x = x
apply Fix.ind_rec
intro x; dsimp
rw [Fix.dest, Fix.rec_eq, ← comp_map, ← appendFun_comp, id_comp]
intro h; rw [h]
change Fix.mk (appendFun id id <$$> x) = Fix.mk x
rw [appendFun_id_id, MvFunctor.id_map]
theorem Fix.dest_mk (x : F (append1 α (Fix F α))) : Fix.dest (Fix.mk x) = x := by
unfold Fix.dest
rw [Fix.rec_eq, ← Fix.dest, ← comp_map]
conv =>
rhs
rw [← MvFunctor.id_map x]
rw [← appendFun_comp, id_comp]
have : Fix.mk ∘ Fix.dest (F := F) (α := α) = _root_.id := by
ext (x : Fix F α)
apply Fix.mk_dest
rw [this, appendFun_id_id]
theorem Fix.ind {α : TypeVec n} (p : Fix F α → Prop)
(h : ∀ x : F (α.append1 (Fix F α)), LiftP (PredLast α p) x → p (Fix.mk x)) : ∀ x, p x := by
apply Quot.ind
intro x
apply q.P.w_ind _ x; intro a f' f ih
change p ⟦q.P.wMk a f' f⟧
rw [← Fix.ind_aux a f' f]
apply h
rw [MvQPF.liftP_iff]
refine ⟨_, _, rfl, ?_⟩
intro i j
cases i
· apply ih
· trivial
instance mvqpfFix : MvQPF (Fix F) where
P := q.P.wp
abs α := Quot.mk WEquiv α
repr α := fixToW α
abs_repr := by
intro α
apply Quot.ind
intro a
apply Quot.sound
apply wrepr_equiv
abs_map := by
intro α β g x
conv =>
rhs
dsimp [MvFunctor.map]
rfl
/-- Dependent recursor for `fix F` -/
def Fix.drec {β : Fix F α → Type u}
(g : ∀ x : F (α ::: Sigma β), β (Fix.mk <| (id ::: Sigma.fst) <$$> x)) (x : Fix F α) : β x :=
let y := @Fix.rec _ F _ α (Sigma β) (fun i => ⟨_, g i⟩) x
have : x = y.1 := by
symm
dsimp [y]
apply Fix.ind_rec _ id _ x
intro x' ih
rw [Fix.rec_eq]
dsimp
simp only [appendFun_id_id, MvFunctor.id_map] at ih
congr
conv =>
rhs
rw [← ih]
rw [MvFunctor.map_map, ← appendFun_comp, id_comp]
simp only [Function.comp_def]
cast (by rw [this]) y.2
end MvQPF |
.lake/packages/mathlib/Mathlib/Data/QPF/Univariate/Basic.lean | import Mathlib.Data.PFunctor.Univariate.M
/-!
# Quotients of Polynomial Functors
We assume the following:
* `P`: a polynomial functor
* `W`: its W-type
* `M`: its M-type
* `F`: a functor
We define:
* `q`: `QPF` data, representing `F` as a quotient of `P`
The main goal is to construct:
* `Fix`: the initial algebra with structure map `F Fix → Fix`.
* `Cofix`: the final coalgebra with structure map `Cofix → F Cofix`
We also show that the composition of qpfs is a qpf, and that the quotient of a qpf
is a qpf.
The present theory focuses on the univariate case for qpfs
## References
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial
Functors*][avigad-carneiro-hudon2019]
-/
universe u u' v
/-- Quotients of polynomial functors.
Roughly speaking, saying that `F` is a quotient of a polynomial functor means that for each `α`,
elements of `F α` are represented by pairs `⟨a, f⟩`, where `a` is the shape of the object and
`f` indexes the relevant elements of `α`, in a suitably natural manner.
-/
class QPF (F : Type u → Type v) extends Functor F where
P : PFunctor.{u, u'}
abs : ∀ {α}, P α → F α
repr : ∀ {α}, F α → P α
abs_repr : ∀ {α} (x : F α), abs (repr x) = x
abs_map : ∀ {α β} (f : α → β) (p : P α), abs (P.map f p) = f <$> abs p
namespace QPF
variable {F : Type u → Type v} [q : QPF F]
open Functor (Liftp Liftr)
/-
Show that every qpf is a lawful functor.
Note: every functor has a field, `map_const`, and `lawfulFunctor` has the defining
characterization. We can only propagate the assumption.
-/
theorem id_map {α : Type _} (x : F α) : id <$> x = x := by
rw [← abs_repr x]
obtain ⟨a, f⟩ := repr x
rw [← abs_map]
rfl
theorem comp_map {α β γ : Type _} (f : α → β) (g : β → γ) (x : F α) :
(g ∘ f) <$> x = g <$> f <$> x := by
rw [← abs_repr x]
obtain ⟨a, f⟩ := repr x
rw [← abs_map, ← abs_map, ← abs_map]
rfl
theorem lawfulFunctor
(h : ∀ α β : Type u, @Functor.mapConst F _ α _ = Functor.map ∘ Function.const β) :
LawfulFunctor F :=
{ map_const := @h
id_map := @id_map F _
comp_map := @comp_map F _ }
/-
Lifting predicates and relations
-/
section
open Functor
theorem liftp_iff {α : Type u} (p : α → Prop) (x : F α) :
Liftp p x ↔ ∃ a f, x = abs ⟨a, f⟩ ∧ ∀ i, p (f i) := by
constructor
· rintro ⟨y, hy⟩
rcases h : repr y with ⟨a, f⟩
use a, fun i => (f i).val
constructor
· rw [← hy, ← abs_repr y, h, ← abs_map]
rfl
intro i
apply (f i).property
rintro ⟨a, f, h₀, h₁⟩
use abs ⟨a, fun i => ⟨f i, h₁ i⟩⟩
rw [← abs_map, h₀]; rfl
theorem liftp_iff' {α : Type u} (p : α → Prop) (x : F α) :
Liftp p x ↔ ∃ u : q.P α, abs u = x ∧ ∀ i, p (u.snd i) := by
constructor
· rintro ⟨y, hy⟩
rcases h : repr y with ⟨a, f⟩
use ⟨a, fun i => (f i).val⟩
dsimp
constructor
· rw [← hy, ← abs_repr y, h, ← abs_map]
rfl
intro i
apply (f i).property
rintro ⟨⟨a, f⟩, h₀, h₁⟩; dsimp at *
use abs ⟨a, fun i => ⟨f i, h₁ i⟩⟩
rw [← abs_map, ← h₀]; rfl
theorem liftr_iff {α : Type u} (r : α → α → Prop) (x y : F α) :
Liftr r x y ↔ ∃ a f₀ f₁, x = abs ⟨a, f₀⟩ ∧ y = abs ⟨a, f₁⟩ ∧ ∀ i, r (f₀ i) (f₁ i) := by
constructor
· rintro ⟨u, xeq, yeq⟩
rcases h : repr u with ⟨a, f⟩
use a, fun i => (f i).val.fst, fun i => (f i).val.snd
constructor
· rw [← xeq, ← abs_repr u, h, ← abs_map]
rfl
constructor
· rw [← yeq, ← abs_repr u, h, ← abs_map]
rfl
intro i
exact (f i).property
rintro ⟨a, f₀, f₁, xeq, yeq, h⟩
use abs ⟨a, fun i => ⟨(f₀ i, f₁ i), h i⟩⟩
constructor
· rw [xeq, ← abs_map]
rfl
rw [yeq, ← abs_map]; rfl
end
/-
Think of trees in the `W` type corresponding to `P` as representatives of elements of the
least fixed point of `F`, and assign a canonical representative to each equivalence class
of trees.
-/
/-- does recursion on `q.P.W` using `g : F α → α` rather than `g : P α → α` -/
def recF {α : Type _} (g : F α → α) : q.P.W → α
| ⟨a, f⟩ => g (abs ⟨a, fun x => recF g (f x)⟩)
theorem recF_eq {α : Type _} (g : F α → α) (x : q.P.W) :
recF g x = g (abs (q.P.map (recF g) x.dest)) := by
cases x
rfl
theorem recF_eq' {α : Type _} (g : F α → α) (a : q.P.A) (f : q.P.B a → q.P.W) :
recF g ⟨a, f⟩ = g (abs (q.P.map (recF g) ⟨a, f⟩)) :=
rfl
/-- two trees are equivalent if their F-abstractions are -/
inductive Wequiv : q.P.W → q.P.W → Prop
| ind (a : q.P.A) (f f' : q.P.B a → q.P.W) : (∀ x, Wequiv (f x) (f' x)) → Wequiv ⟨a, f⟩ ⟨a, f'⟩
| abs (a : q.P.A) (f : q.P.B a → q.P.W) (a' : q.P.A) (f' : q.P.B a' → q.P.W) :
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → Wequiv ⟨a, f⟩ ⟨a', f'⟩
| trans (u v w : q.P.W) : Wequiv u v → Wequiv v w → Wequiv u w
/-- `recF` is insensitive to the representation -/
theorem recF_eq_of_Wequiv {α : Type u} (u : F α → α) (x y : q.P.W) :
Wequiv x y → recF u x = recF u y := by
intro h
induction h with
| ind a f f' _ ih => simp only [recF_eq', PFunctor.map_eq, Function.comp_def, ih]
| abs a f a' f' h => simp only [recF_eq', abs_map, h]
| trans x y z _ _ ih₁ ih₂ => exact Eq.trans ih₁ ih₂
theorem Wequiv.abs' (x y : q.P.W) (h : QPF.abs x.dest = QPF.abs y.dest) : Wequiv x y := by
cases x
cases y
apply Wequiv.abs
apply h
theorem Wequiv.refl (x : q.P.W) : Wequiv x x := by
obtain ⟨a, f⟩ := x
exact Wequiv.abs a f a f rfl
theorem Wequiv.symm (x y : q.P.W) : Wequiv x y → Wequiv y x := by
intro h
induction h with
| ind a f f' _ ih => exact Wequiv.ind _ _ _ ih
| abs a f a' f' h => exact Wequiv.abs _ _ _ _ h.symm
| trans x y z _ _ ih₁ ih₂ => exact QPF.Wequiv.trans _ _ _ ih₂ ih₁
/-- maps every element of the W type to a canonical representative -/
def Wrepr : q.P.W → q.P.W :=
recF (PFunctor.W.mk ∘ repr)
theorem Wrepr_equiv (x : q.P.W) : Wequiv (Wrepr x) x := by
induction x with | _ a f ih
apply Wequiv.trans
· change Wequiv (Wrepr ⟨a, f⟩) (PFunctor.W.mk (q.P.map Wrepr ⟨a, f⟩))
apply Wequiv.abs'
have : Wrepr ⟨a, f⟩ = PFunctor.W.mk (repr (abs (q.P.map Wrepr ⟨a, f⟩))) := rfl
rw [this, PFunctor.W.dest_mk, abs_repr]
rfl
apply Wequiv.ind; exact ih
/-- Define the fixed point as the quotient of trees under the equivalence relation `Wequiv`. -/
def Wsetoid : Setoid q.P.W :=
⟨Wequiv, @Wequiv.refl _ _, @Wequiv.symm _ _, @Wequiv.trans _ _⟩
attribute [local instance] Wsetoid
/-- inductive type defined as initial algebra of a Quotient of Polynomial Functor -/
def Fix (F : Type u → Type u) [q : QPF F] :=
Quotient (Wsetoid : Setoid q.P.W)
variable {F : Type u → Type u} [q : QPF F]
/-- recursor of a type defined by a qpf -/
def Fix.rec {α : Type _} (g : F α → α) : Fix F → α :=
Quot.lift (recF g) (recF_eq_of_Wequiv g)
/-- access the underlying W-type of a fixpoint data type -/
def fixToW : Fix F → q.P.W :=
Quotient.lift Wrepr (recF_eq_of_Wequiv fun x => @PFunctor.W.mk q.P (repr x))
/-- constructor of a type defined by a qpf -/
def Fix.mk (x : F (Fix F)) : Fix F :=
Quot.mk _ (PFunctor.W.mk (q.P.map fixToW (repr x)))
/-- destructor of a type defined by a qpf -/
def Fix.dest : Fix F → F (Fix F) :=
Fix.rec (Functor.map Fix.mk)
theorem Fix.rec_eq {α : Type _} (g : F α → α) (x : F (Fix F)) :
Fix.rec g (Fix.mk x) = g (Fix.rec g <$> x) := by
have : recF g ∘ fixToW = Fix.rec g := by
ext ⟨x⟩
apply recF_eq_of_Wequiv
rw [fixToW]
apply Wrepr_equiv
conv =>
lhs
rw [Fix.rec, Fix.mk]
dsimp
rcases h : repr x with ⟨a, f⟩
rw [PFunctor.map_eq, recF_eq, ← PFunctor.map_eq, PFunctor.W.dest_mk, PFunctor.map_map, abs_map,
← h, abs_repr, this]
theorem Fix.ind_aux (a : q.P.A) (f : q.P.B a → q.P.W) :
Fix.mk (abs ⟨a, fun x => ⟦f x⟧⟩) = ⟦⟨a, f⟩⟧ := by
have : Fix.mk (abs ⟨a, fun x => ⟦f x⟧⟩) = ⟦Wrepr ⟨a, f⟩⟧ := by
apply Quot.sound; apply Wequiv.abs'
rw [PFunctor.W.dest_mk, abs_map, abs_repr, ← abs_map, PFunctor.map_eq]
simp only [Wrepr, recF_eq, PFunctor.W.dest_mk, abs_repr, Function.comp]
rfl
rw [this]
apply Quot.sound
apply Wrepr_equiv
theorem Fix.ind_rec {α : Type u} (g₁ g₂ : Fix F → α)
(h : ∀ x : F (Fix F), g₁ <$> x = g₂ <$> x → g₁ (Fix.mk x) = g₂ (Fix.mk x)) :
∀ x, g₁ x = g₂ x := by
rintro ⟨x⟩
induction x with | _ a f ih
change g₁ ⟦⟨a, f⟩⟧ = g₂ ⟦⟨a, f⟩⟧
rw [← Fix.ind_aux a f]; apply h
rw [← abs_map, ← abs_map, PFunctor.map_eq, PFunctor.map_eq]
congr 2 with x
apply ih
theorem Fix.rec_unique {α : Type u} (g : F α → α) (h : Fix F → α)
(hyp : ∀ x, h (Fix.mk x) = g (h <$> x)) : Fix.rec g = h := by
ext x
apply Fix.ind_rec
intro x hyp'
rw [hyp, ← hyp', Fix.rec_eq]
theorem Fix.mk_dest (x : Fix F) : Fix.mk (Fix.dest x) = x := by
change (Fix.mk ∘ Fix.dest) x = id x
apply Fix.ind_rec (mk ∘ dest) id
intro x
rw [Function.comp_apply, id_eq, Fix.dest, Fix.rec_eq, id_map, comp_map]
intro h
rw [h]
theorem Fix.dest_mk (x : F (Fix F)) : Fix.dest (Fix.mk x) = x := by
unfold Fix.dest; rw [Fix.rec_eq, ← Fix.dest, ← comp_map]
conv =>
rhs
rw [← id_map x]
congr with x
apply Fix.mk_dest
theorem Fix.ind (p : Fix F → Prop) (h : ∀ x : F (Fix F), Liftp p x → p (Fix.mk x)) : ∀ x, p x := by
rintro ⟨x⟩
induction x with | _ a f ih
change p ⟦⟨a, f⟩⟧
rw [← Fix.ind_aux a f]
apply h
rw [liftp_iff]
refine ⟨_, _, rfl, ?_⟩
convert ih
end QPF
/-
Construct the final coalgebra to a qpf.
-/
namespace QPF
variable {F : Type u → Type u} [q : QPF F]
open Functor (Liftp Liftr)
/-- does recursion on `q.P.M` using `g : α → F α` rather than `g : α → P α` -/
def corecF {α : Type _} (g : α → F α) : α → q.P.M :=
PFunctor.M.corec fun x => repr (g x)
theorem corecF_eq {α : Type _} (g : α → F α) (x : α) :
PFunctor.M.dest (corecF g x) = q.P.map (corecF g) (repr (g x)) := by
rw [corecF, PFunctor.M.dest_corec]
-- Equivalence
/-- A pre-congruence on `q.P.M` *viewed as an F-coalgebra*. Not necessarily symmetric. -/
def IsPrecongr (r : q.P.M → q.P.M → Prop) : Prop :=
∀ ⦃x y⦄, r x y →
abs (q.P.map (Quot.mk r) (PFunctor.M.dest x)) = abs (q.P.map (Quot.mk r) (PFunctor.M.dest y))
/-- The maximal congruence on `q.P.M`. -/
def Mcongr : q.P.M → q.P.M → Prop := fun x y => ∃ r, IsPrecongr r ∧ r x y
/-- coinductive type defined as the final coalgebra of a qpf -/
def Cofix (F : Type u → Type u) [q : QPF F] :=
Quot (@Mcongr F q)
instance [Inhabited q.P.A] : Inhabited (Cofix F) :=
⟨Quot.mk _ default⟩
/-- corecursor for type defined by `Cofix` -/
def Cofix.corec {α : Type _} (g : α → F α) (x : α) : Cofix F :=
Quot.mk _ (corecF g x)
/-- destructor for type defined by `Cofix` -/
def Cofix.dest : Cofix F → F (Cofix F) :=
Quot.lift (fun x => Quot.mk Mcongr <$> abs (PFunctor.M.dest x))
(by
rintro x y ⟨r, pr, rxy⟩
dsimp
have : ∀ x y, r x y → Mcongr x y := by
intro x y h
exact ⟨r, pr, h⟩
rw [← Quot.factor_mk_eq _ _ this]
conv =>
lhs
rw [comp_map, ← abs_map, pr rxy, abs_map, ← comp_map])
theorem Cofix.dest_corec {α : Type u} (g : α → F α) (x : α) :
Cofix.dest (Cofix.corec g x) = Cofix.corec g <$> g x := by
conv =>
lhs
rw [Cofix.dest, Cofix.corec]
dsimp
rw [corecF_eq, abs_map, abs_repr, ← comp_map]; rfl
private theorem Cofix.bisim_aux (r : Cofix F → Cofix F → Prop) (h' : ∀ x, r x x)
(h : ∀ x y, r x y → Quot.mk r <$> Cofix.dest x = Quot.mk r <$> Cofix.dest y) :
∀ x y, r x y → x = y := by
rintro ⟨x⟩ ⟨y⟩ rxy
apply Quot.sound
let r' x y := r (Quot.mk _ x) (Quot.mk _ y)
have : IsPrecongr r' := by
intro a b r'ab
have h₀ :
Quot.mk r <$> Quot.mk Mcongr <$> abs (PFunctor.M.dest a) =
Quot.mk r <$> Quot.mk Mcongr <$> abs (PFunctor.M.dest b) :=
h _ _ r'ab
have h₁ : ∀ u v : q.P.M, Mcongr u v → Quot.mk r' u = Quot.mk r' v := by
intro u v cuv
apply Quot.sound
simp only [r']
rw [Quot.sound cuv]
apply h'
let f : Quot r → Quot r' :=
Quot.lift (Quot.lift (Quot.mk r') h₁) <| by
rintro ⟨c⟩ ⟨d⟩ rcd
exact Quot.sound rcd
have : f ∘ Quot.mk r ∘ Quot.mk Mcongr = Quot.mk r' := rfl
rw [← this, ← PFunctor.map_map _ _ f, ← PFunctor.map_map _ _ (Quot.mk r), abs_map, abs_map,
abs_map, h₀]
rw [← PFunctor.map_map _ _ f, ← PFunctor.map_map _ _ (Quot.mk r), abs_map, abs_map, abs_map]
exact ⟨r', this, rxy⟩
theorem Cofix.bisim_rel (r : Cofix F → Cofix F → Prop)
(h : ∀ x y, r x y → Quot.mk r <$> Cofix.dest x = Quot.mk r <$> Cofix.dest y) :
∀ x y, r x y → x = y := by
let r' (x y) := x = y ∨ r x y
intro x y rxy
apply Cofix.bisim_aux r'
· intro x
left
rfl
· intro x y r'xy
rcases r'xy with r'xy | r'xy
· rw [r'xy]
have : ∀ x y, r x y → r' x y := fun x y h => Or.inr h
rw [← Quot.factor_mk_eq _ _ this]
dsimp [r']
rw [@comp_map _ q _ _ _ (Quot.mk r), @comp_map _ q _ _ _ (Quot.mk r)]
rw [h _ _ r'xy]
right; exact rxy
theorem Cofix.bisim (r : Cofix F → Cofix F → Prop)
(h : ∀ x y, r x y → Liftr r (Cofix.dest x) (Cofix.dest y)) : ∀ x y, r x y → x = y := by
apply Cofix.bisim_rel
intro x y rxy
rcases (liftr_iff r _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩
rw [dxeq, dyeq, ← abs_map, ← abs_map, PFunctor.map_eq, PFunctor.map_eq]
congr 2 with i
apply Quot.sound
apply h'
theorem Cofix.bisim' {α : Type*} (Q : α → Prop) (u v : α → Cofix F)
(h : ∀ x, Q x → ∃ a f f', Cofix.dest (u x) = abs ⟨a, f⟩ ∧ Cofix.dest (v x) = abs ⟨a, f'⟩ ∧
∀ i, ∃ x', Q x' ∧ f i = u x' ∧ f' i = v x') :
∀ x, Q x → u x = v x := fun x Qx =>
let R := fun w z : Cofix F => ∃ x', Q x' ∧ w = u x' ∧ z = v x'
Cofix.bisim R
(fun x y ⟨x', Qx', xeq, yeq⟩ => by
rcases h x' Qx' with ⟨a, f, f', ux'eq, vx'eq, h'⟩
rw [liftr_iff]
exact ⟨a, f, f', xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, h'⟩)
_ _ ⟨x, Qx, rfl, rfl⟩
end QPF
/-
Composition of qpfs.
-/
namespace QPF
variable {F₂ : Type u → Type u} [q₂ : QPF F₂]
variable {F₁ : Type u → Type u} [q₁ : QPF F₁]
/-- composition of qpfs gives another qpf -/
def comp : QPF (Functor.Comp F₂ F₁) where
P := PFunctor.comp q₂.P q₁.P
abs {α} := by
dsimp [Functor.Comp]
intro p
exact abs ⟨p.1.1, fun x => abs ⟨p.1.2 x, fun y => p.2 ⟨x, y⟩⟩⟩
repr {α} := by
dsimp [Functor.Comp]
intro y
refine ⟨⟨(repr y).1, fun u => (repr ((repr y).2 u)).1⟩, ?_⟩
dsimp [PFunctor.comp]
intro x
exact (repr ((repr y).2 x.1)).snd x.2
abs_repr {α} := by
dsimp [Functor.Comp]
intro x
conv =>
rhs
rw [← abs_repr x]
obtain ⟨a, f⟩ := repr x
dsimp
congr with x
rcases h' : repr (f x) with ⟨b, g⟩
dsimp; rw [← h', abs_repr]
abs_map {α β} f := by
dsimp +unfoldPartialApp [Functor.Comp, PFunctor.comp]
intro p
obtain ⟨a, g⟩ := p; dsimp
obtain ⟨b, h⟩ := a; dsimp
symm
trans
· symm
apply abs_map
congr
rw [PFunctor.map_eq]
dsimp [Function.comp_def]
congr
ext x
rw [← abs_map]
rfl
end QPF
/-
Quotients.
We show that if `F` is a qpf and `G` is a suitable quotient of `F`, then `G` is a qpf.
-/
namespace QPF
variable {F : Type u → Type u} [q : QPF F]
variable {G : Type u → Type u} [Functor G]
variable {FG_abs : ∀ {α}, F α → G α}
variable {FG_repr : ∀ {α}, G α → F α}
/-- Given a qpf `F` and a well-behaved surjection `FG_abs` from `F α` to
functor `G α`, `G` is a qpf. We can consider `G` a quotient on `F` where
elements `x y : F α` are in the same equivalence class if
`FG_abs x = FG_abs y`. -/
def quotientQPF (FG_abs_repr : ∀ {α} (x : G α), FG_abs (FG_repr x) = x)
(FG_abs_map : ∀ {α β} (f : α → β) (x : F α), FG_abs (f <$> x) = f <$> FG_abs x) : QPF G where
P := q.P
abs {_} p := FG_abs (abs p)
repr {_} x := repr (FG_repr x)
abs_repr {α} x := by rw [abs_repr, FG_abs_repr]
abs_map {α β} f x := by rw [abs_map, FG_abs_map]
end QPF
/-
Support.
-/
namespace QPF
variable {F : Type u → Type u} [q : QPF F]
open Functor (Liftp Liftr supp)
open Set
theorem mem_supp {α : Type u} (x : F α) (u : α) :
u ∈ supp x ↔ ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ := by
rw [supp]; dsimp; constructor
· intro h a f haf
have : Liftp (fun u => u ∈ f '' univ) x := by
rw [liftp_iff]
exact ⟨a, f, haf.symm, fun i => mem_image_of_mem _ (mem_univ _)⟩
exact h this
intro h p; rw [liftp_iff]
rintro ⟨a, f, xeq, h'⟩
rcases h a f xeq.symm with ⟨i, _, hi⟩
rw [← hi]; apply h'
theorem supp_eq {α : Type u} (x : F α) :
supp x = { u | ∀ a f, abs ⟨a, f⟩ = x → u ∈ f '' univ } := by
ext
apply mem_supp
theorem has_good_supp_iff {α : Type u} (x : F α) :
(∀ p, Liftp p x ↔ ∀ u ∈ supp x, p u) ↔
∃ a f, abs ⟨a, f⟩ = x ∧ ∀ a' f', abs ⟨a', f'⟩ = x → f '' univ ⊆ f' '' univ := by
constructor
· intro h
have : Liftp (supp x) x := by rw [h]; intro u; exact id
rw [liftp_iff] at this
rcases this with ⟨a, f, xeq, h'⟩
refine ⟨a, f, xeq.symm, ?_⟩
intro a' f' h''
rintro u ⟨i, _, hfi⟩
have : u ∈ supp x := by rw [← hfi]; apply h'
exact (mem_supp x u).mp this _ _ h''
rintro ⟨a, f, xeq, h⟩ p; rw [liftp_iff]; constructor
· rintro ⟨a', f', xeq', h'⟩ u usuppx
rcases (mem_supp x u).mp usuppx a' f' xeq'.symm with ⟨i, _, f'ieq⟩
rw [← f'ieq]
apply h'
intro h'
refine ⟨a, f, xeq.symm, ?_⟩; intro i
apply h'; rw [mem_supp]
intro a' f' xeq'
apply h a' f' xeq'
apply mem_image_of_mem _ (mem_univ _)
/-- A qpf is said to be uniform if every polynomial functor
representing a single value all have the same range. -/
def IsUniform : Prop :=
∀ ⦃α : Type u⦄ (a a' : q.P.A) (f : q.P.B a → α) (f' : q.P.B a' → α),
abs ⟨a, f⟩ = abs ⟨a', f'⟩ → f '' univ = f' '' univ
/-- does `abs` preserve `Liftp`? -/
def LiftpPreservation : Prop :=
∀ ⦃α⦄ (p : α → Prop) (x : q.P α), Liftp p (abs x) ↔ Liftp p x
/-- does `abs` preserve `supp`? -/
def SuppPreservation : Prop :=
∀ ⦃α⦄ (x : q.P α), supp (abs x) = supp x
theorem supp_eq_of_isUniform (h : q.IsUniform) {α : Type u} (a : q.P.A) (f : q.P.B a → α) :
supp (abs ⟨a, f⟩) = f '' univ := by
ext u; rw [mem_supp]; constructor
· intro h'
apply h' _ _ rfl
intro h' a' f' e
rw [← h _ _ _ _ e.symm]; apply h'
theorem liftp_iff_of_isUniform (h : q.IsUniform) {α : Type u} (x : F α) (p : α → Prop) :
Liftp p x ↔ ∀ u ∈ supp x, p u := by
rw [liftp_iff, ← abs_repr x]
obtain ⟨a, f⟩ := repr x; constructor
· rintro ⟨a', f', abseq, hf⟩ u
rw [supp_eq_of_isUniform h, h _ _ _ _ abseq]
rintro ⟨i, _, hi⟩
rw [← hi]
apply hf
intro h'
refine ⟨a, f, rfl, fun i => h' _ ?_⟩
rw [supp_eq_of_isUniform h]
exact ⟨i, mem_univ i, rfl⟩
theorem supp_map (h : q.IsUniform) {α β : Type u} (g : α → β) (x : F α) :
supp (g <$> x) = g '' supp x := by
rw [← abs_repr x]; obtain ⟨a, f⟩ := repr x; rw [← abs_map, PFunctor.map_eq]
rw [supp_eq_of_isUniform h, supp_eq_of_isUniform h, image_comp]
theorem suppPreservation_iff_uniform : q.SuppPreservation ↔ q.IsUniform := by
constructor
· intro h α a a' f f' h'
rw [← PFunctor.supp_eq, ← PFunctor.supp_eq, ← h, h', h]
· rintro h α ⟨a, f⟩
rwa [supp_eq_of_isUniform, PFunctor.supp_eq]
theorem suppPreservation_iff_liftpPreservation : q.SuppPreservation ↔ q.LiftpPreservation := by
constructor <;> intro h
· rintro α p ⟨a, f⟩
have h' := h
rw [suppPreservation_iff_uniform] at h'
dsimp only [SuppPreservation, supp] at h
rw [liftp_iff_of_isUniform h', supp_eq_of_isUniform h', PFunctor.liftp_iff']
simp only [image_univ, mem_range, exists_imp]
constructor <;> intros <;> subst_vars <;> solve_by_elim
· rintro α ⟨a, f⟩
simp only [LiftpPreservation] at h
simp only [supp, h]
theorem liftpPreservation_iff_uniform : q.LiftpPreservation ↔ q.IsUniform := by
rw [← suppPreservation_iff_liftpPreservation, suppPreservation_iff_uniform]
end QPF |
.lake/packages/mathlib/Mathlib/Data/DList/Instances.lean | import Batteries.Data.DList.Lemmas
import Mathlib.Control.Traversable.Equiv
import Mathlib.Control.Traversable.Instances
/-!
# Traversable instance for DLists
This file provides the equivalence between `List α` and `DList α` and the traversable instance
for `DList`.
-/
open Function Equiv
namespace Batteries
variable (α : Type*)
/-- The natural equivalence between lists and difference lists, using
`DList.ofList` and `DList.toList`. -/
def DList.listEquivDList : List α ≃ DList α where
toFun := DList.ofList
invFun := DList.toList
left_inv _ := DList.toList_ofList _
right_inv _ := DList.ofList_toList _
instance : Traversable DList :=
Equiv.traversable DList.listEquivDList
instance : LawfulTraversable DList :=
Equiv.isLawfulTraversable DList.listEquivDList
instance {α} : Inhabited (DList α) :=
⟨DList.empty⟩
end Batteries |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Module.lean | import Mathlib.Algebra.GroupWithZero.Action.Pi
import Mathlib.Algebra.Module.LinearMap.Defs
import Mathlib.Algebra.Module.Pi
import Mathlib.Data.DFinsupp.Defs
/-!
# Group actions on `DFinsupp`
## Main results
* `DFinsupp.module`: pointwise scalar multiplication on `DFinsupp` gives a module structure
-/
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
namespace DFinsupp
section Algebra
/-- Dependent functions with finite support inherit a semiring action from an action on each
coordinate. -/
instance [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)] : SMulZeroClass γ (Π₀ i, β i) where
smul c v := v.mapRange (fun _ => (c • ·)) fun _ => smul_zero _
smul_zero _ := mapRange_zero _ _
theorem smul_apply [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)] (b : γ)
(v : Π₀ i, β i) (i : ι) : (b • v) i = b • v i :=
rfl
@[simp, norm_cast]
theorem coe_smul [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)] (b : γ)
(v : Π₀ i, β i) : ⇑(b • v) = b • ⇑v :=
rfl
instance smulCommClass {δ : Type*} [∀ i, Zero (β i)]
[∀ i, SMulZeroClass γ (β i)] [∀ i, SMulZeroClass δ (β i)] [∀ i, SMulCommClass γ δ (β i)] :
SMulCommClass γ δ (Π₀ i, β i) where
smul_comm r s m := ext fun i => by simp only [smul_apply, smul_comm r s (m i)]
instance isScalarTower {δ : Type*} [∀ i, Zero (β i)]
[∀ i, SMulZeroClass γ (β i)] [∀ i, SMulZeroClass δ (β i)] [SMul γ δ]
[∀ i, IsScalarTower γ δ (β i)] : IsScalarTower γ δ (Π₀ i, β i) where
smul_assoc r s m := ext fun i => by simp only [smul_apply, smul_assoc r s (m i)]
instance isCentralScalar [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)]
[∀ i, SMulZeroClass γᵐᵒᵖ (β i)] [∀ i, IsCentralScalar γ (β i)] :
IsCentralScalar γ (Π₀ i, β i) where
op_smul_eq_smul r m := ext fun i => by simp only [smul_apply, op_smul_eq_smul r (m i)]
/-- Dependent functions with finite support inherit a `DistribMulAction` structure from such a
structure on each coordinate. -/
instance distribMulAction [Monoid γ] [∀ i, AddMonoid (β i)] [∀ i, DistribMulAction γ (β i)] :
DistribMulAction γ (Π₀ i, β i) :=
Function.Injective.distribMulAction coeFnAddMonoidHom DFunLike.coe_injective coe_smul
/-- Dependent functions with finite support inherit a module structure from such a structure on
each coordinate. -/
instance module [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] :
Module γ (Π₀ i, β i) :=
{ inferInstanceAs (DistribMulAction γ (Π₀ i, β i)) with
zero_smul := fun c => ext fun i => by simp only [smul_apply, zero_smul, zero_apply]
add_smul := fun c x y => ext fun i => by simp only [add_apply, smul_apply, add_smul] }
end Algebra
variable (γ) in
/-- Coercion from a `DFinsupp` to a pi type is a `LinearMap`. -/
def coeFnLinearMap [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] :
(Π₀ i, β i) →ₗ[γ] ∀ i, β i where
toFun := (⇑)
map_add' := coe_add
map_smul' := coe_smul
@[simp]
lemma coeFnLinearMap_apply [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)]
(v : Π₀ i, β i) : coeFnLinearMap γ v = v :=
rfl
section FilterAndSubtypeDomain
@[simp]
theorem filter_smul [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)] (p : ι → Prop)
[DecidablePred p] (r : γ) (f : Π₀ i, β i) : (r • f).filter p = r • f.filter p := by
ext
simp [smul_apply, smul_ite]
variable (γ β)
/-- `DFinsupp.filter` as a `LinearMap`. -/
@[simps]
def filterLinearMap [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)] (p : ι → Prop)
[DecidablePred p] : (Π₀ i, β i) →ₗ[γ] Π₀ i, β i where
toFun := filter p
map_add' := filter_add p
map_smul' := filter_smul p
variable {γ β}
@[simp]
theorem subtypeDomain_smul [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)]
{p : ι → Prop} [DecidablePred p] (r : γ) (f : Π₀ i, β i) :
(r • f).subtypeDomain p = r • f.subtypeDomain p :=
DFunLike.coe_injective rfl
variable (γ β)
/-- `DFinsupp.subtypeDomain` as a `LinearMap`. -/
@[simps]
def subtypeDomainLinearMap [Semiring γ] [∀ i, AddCommMonoid (β i)] [∀ i, Module γ (β i)]
(p : ι → Prop) [DecidablePred p] : (Π₀ i, β i) →ₗ[γ] Π₀ i : Subtype p, β i where
toFun := subtypeDomain p
map_add' := subtypeDomain_add
map_smul' := subtypeDomain_smul
end FilterAndSubtypeDomain
section DecidableEq
variable [DecidableEq ι]
section
variable [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)]
@[simp]
theorem mk_smul {s : Finset ι} (c : γ) (x : ∀ i : (↑s : Set ι), β (i : ι)) :
mk s (c • x) = c • mk s x :=
ext fun i => by simp only [smul_apply, mk_apply]; split_ifs <;> [rfl; rw [smul_zero]]
@[simp]
theorem single_smul {i : ι} (c : γ) (x : β i) : single i (c • x) = c • single i x :=
ext fun i => by
simp only [smul_apply, single_apply]
split_ifs with h
· cases h; rfl
· rw [smul_zero]
end
theorem support_smul {γ : Type w} [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)]
[∀ (i : ι) (x : β i), Decidable (x ≠ 0)] (b : γ) (v : Π₀ i, β i) :
(b • v).support ⊆ v.support :=
support_mapRange
end DecidableEq
section Equiv
open Finset
variable {κ : Type*}
@[simp]
theorem comapDomain_smul [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)]
(h : κ → ι) (hh : Function.Injective h) (r : γ) (f : Π₀ i, β i) :
comapDomain h hh (r • f) = r • comapDomain h hh f := by
ext
rw [smul_apply, comapDomain_apply, smul_apply, comapDomain_apply]
@[simp]
theorem comapDomain'_smul [∀ i, Zero (β i)] [∀ i, SMulZeroClass γ (β i)]
(h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h) (r : γ) (f : Π₀ i, β i) :
comapDomain' h hh' (r • f) = r • comapDomain' h hh' f := by
ext
rw [smul_apply, comapDomain'_apply, smul_apply, comapDomain'_apply]
section SigmaCurry
variable {α : ι → Type*} {δ : ∀ i, α i → Type v}
instance distribMulAction₂ [Monoid γ] [∀ i j, AddMonoid (δ i j)]
[∀ i j, DistribMulAction γ (δ i j)] : DistribMulAction γ (Π₀ (i : ι) (j : α i), δ i j) :=
@DFinsupp.distribMulAction ι _ (fun i => Π₀ j, δ i j) _ _ _
end SigmaCurry
variable {α : Option ι → Type v}
theorem equivProdDFinsupp_smul [∀ i, Zero (α i)] [∀ i, SMulZeroClass γ (α i)]
(r : γ) (f : Π₀ i, α i) : equivProdDFinsupp (r • f) = r • equivProdDFinsupp f :=
Prod.ext (smul_apply _ _ _) (comapDomain_smul _ (Option.some_injective _) _ _)
end Equiv
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/FiniteInfinite.lean | import Mathlib.Data.DFinsupp.Defs
import Mathlib.Data.Fintype.Pi
/-!
# Finiteness and infiniteness of the `DFinsupp` type
## Main results
* `DFinsupp.fintype`: if the domain and codomain are finite, then `DFinsupp` is finite
* `DFinsupp.infinite_of_left`: if the domain is infinite, then `DFinsupp` is infinite
* `DFinsupp.infinite_of_exists_right`: if one fiber of the codomain is infinite,
then `DFinsupp` is infinite
-/
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
section FiniteInfinite
instance DFinsupp.fintype {ι : Sort _} {π : ι → Sort _} [DecidableEq ι] [∀ i, Zero (π i)]
[Fintype ι] [∀ i, Fintype (π i)] : Fintype (Π₀ i, π i) :=
Fintype.ofEquiv (∀ i, π i) DFinsupp.equivFunOnFintype.symm
instance DFinsupp.infinite_of_left {ι : Sort _} {π : ι → Sort _} [∀ i, Nontrivial (π i)]
[∀ i, Zero (π i)] [Infinite ι] : Infinite (Π₀ i, π i) := by
letI := Classical.decEq ι; choose m hm using fun i => exists_ne (0 : π i)
exact Infinite.of_injective _ (DFinsupp.single_left_injective hm)
/-- See `DFinsupp.infinite_of_right` for this in instance form, with the drawback that
it needs all `π i` to be infinite. -/
theorem DFinsupp.infinite_of_exists_right {ι : Sort _} {π : ι → Sort _} (i : ι) [Infinite (π i)]
[∀ i, Zero (π i)] : Infinite (Π₀ i, π i) :=
letI := Classical.decEq ι
Infinite.of_injective (fun j => DFinsupp.single i j) DFinsupp.single_injective
/-- See `DFinsupp.infinite_of_exists_right` for the case that only one `π ι` is infinite. -/
instance DFinsupp.infinite_of_right {ι : Sort _} {π : ι → Sort _} [∀ i, Infinite (π i)]
[∀ i, Zero (π i)] [Nonempty ι] : Infinite (Π₀ i, π i) :=
DFinsupp.infinite_of_exists_right (Classical.arbitrary ι)
end FiniteInfinite |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Interval.lean | import Mathlib.Data.Fintype.BigOperators
import Mathlib.Data.DFinsupp.BigOperators
import Mathlib.Data.DFinsupp.Order
import Mathlib.Order.Interval.Finset.Basic
import Mathlib.Algebra.Group.Pointwise.Finset.Basic
/-!
# Finite intervals of finitely supported functions
This file provides the `LocallyFiniteOrder` instance for `Π₀ i, α i` when `α` itself is locally
finite and calculates the cardinality of its finite intervals.
-/
open DFinsupp Finset
open Pointwise
variable {ι : Type*} {α : ι → Type*}
namespace Finset
variable [DecidableEq ι] [∀ i, Zero (α i)] {s : Finset ι} {f : Π₀ i, α i} {t : ∀ i, Finset (α i)}
/-- Finitely supported product of finsets. -/
def dfinsupp (s : Finset ι) (t : ∀ i, Finset (α i)) : Finset (Π₀ i, α i) :=
(s.pi t).map
⟨fun f => DFinsupp.mk s fun i => f i i.2, by
refine (mk_injective _).comp fun f g h => ?_
ext i hi
convert congr_fun h ⟨i, hi⟩⟩
@[simp]
theorem card_dfinsupp (s : Finset ι) (t : ∀ i, Finset (α i)) : #(s.dfinsupp t) = ∏ i ∈ s, #(t i) :=
(card_map _).trans <| card_pi _ _
variable [∀ i, DecidableEq (α i)]
theorem mem_dfinsupp_iff : f ∈ s.dfinsupp t ↔ f.support ⊆ s ∧ ∀ i ∈ s, f i ∈ t i := by
refine mem_map.trans ⟨?_, ?_⟩
· rintro ⟨f, hf, rfl⟩
rw [Function.Embedding.coeFn_mk]
refine ⟨support_mk_subset, fun i hi => ?_⟩
convert mem_pi.1 hf i hi
exact mk_of_mem hi
· refine fun h => ⟨fun i _ => f i, mem_pi.2 h.2, ?_⟩
ext i
dsimp
exact ite_eq_left_iff.2 fun hi => (notMem_support_iff.1 fun H => hi <| h.1 H).symm
/-- When `t` is supported on `s`, `f ∈ s.dfinsupp t` precisely means that `f` is pointwise in `t`.
-/
@[simp]
theorem mem_dfinsupp_iff_of_support_subset {t : Π₀ i, Finset (α i)} (ht : t.support ⊆ s) :
f ∈ s.dfinsupp t ↔ ∀ i, f i ∈ t i := by
refine mem_dfinsupp_iff.trans (forall_and.symm.trans <| forall_congr' fun i =>
⟨ fun h => ?_,
fun h => ⟨fun hi => ht <| mem_support_iff.2 fun H => mem_support_iff.1 hi ?_, fun _ => h⟩⟩)
· by_cases hi : i ∈ s
· exact h.2 hi
· rw [notMem_support_iff.1 (mt h.1 hi), notMem_support_iff.1 (notMem_mono ht hi)]
exact zero_mem_zero
· rwa [H, mem_zero] at h
end Finset
namespace DFinsupp
section BundledSingleton
variable [∀ i, Zero (α i)] {f : Π₀ i, α i} {i : ι} {a : α i}
/-- Pointwise `Finset.singleton` bundled as a `DFinsupp`. -/
def singleton (f : Π₀ i, α i) : Π₀ i, Finset (α i) where
toFun i := {f i}
support' := f.support'.map fun s => ⟨s.1, fun i => (s.prop i).imp id (congr_arg _)⟩
theorem mem_singleton_apply_iff : a ∈ f.singleton i ↔ a = f i :=
mem_singleton
end BundledSingleton
section BundledIcc
variable [∀ i, Zero (α i)] [∀ i, PartialOrder (α i)] [∀ i, LocallyFiniteOrder (α i)]
{f g : Π₀ i, α i} {i : ι} {a : α i}
/-- Pointwise `Finset.Icc` bundled as a `DFinsupp`. -/
def rangeIcc (f g : Π₀ i, α i) : Π₀ i, Finset (α i) where
toFun i := Icc (f i) (g i)
support' := f.support'.bind fun fs => g.support'.map fun gs =>
⟨ fs.1 + gs.1,
fun i => or_iff_not_imp_left.2 fun h => by
have hf : f i = 0 := (fs.prop i).resolve_left
(Multiset.notMem_mono (Multiset.Le.subset <| Multiset.le_add_right _ _) h)
have hg : g i = 0 := (gs.prop i).resolve_left
(Multiset.notMem_mono (Multiset.Le.subset <| Multiset.le_add_left _ _) h)
simp_rw [hf, hg]
exact Icc_self _⟩
@[simp]
theorem rangeIcc_apply (f g : Π₀ i, α i) (i : ι) : f.rangeIcc g i = Icc (f i) (g i) := rfl
theorem mem_rangeIcc_apply_iff : a ∈ f.rangeIcc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc
theorem support_rangeIcc_subset [DecidableEq ι] [∀ i, DecidableEq (α i)] :
(f.rangeIcc g).support ⊆ f.support ∪ g.support := by
refine fun x hx => ?_
by_contra h
refine notMem_support_iff.2 ?_ hx
rw [rangeIcc_apply, notMem_support_iff.1 (notMem_mono subset_union_left h),
notMem_support_iff.1 (notMem_mono subset_union_right h)]
exact Icc_self _
end BundledIcc
section Pi
variable [∀ i, Zero (α i)] [DecidableEq ι] [∀ i, DecidableEq (α i)]
/-- Given a finitely supported function `f : Π₀ i, Finset (α i)`, one can define the finset
`f.pi` of all finitely supported functions whose value at `i` is in `f i` for all `i`. -/
def pi (f : Π₀ i, Finset (α i)) : Finset (Π₀ i, α i) := f.support.dfinsupp f
@[simp]
theorem mem_pi {f : Π₀ i, Finset (α i)} {g : Π₀ i, α i} : g ∈ f.pi ↔ ∀ i, g i ∈ f i :=
mem_dfinsupp_iff_of_support_subset <| Subset.refl _
@[simp]
theorem card_pi (f : Π₀ i, Finset (α i)) : #f.pi = f.prod fun i ↦ #(f i) := by
rw [pi, card_dfinsupp]
exact Finset.prod_congr rfl fun i _ => by simp only [Pi.natCast_apply, Nat.cast_id]
end Pi
section PartialOrder
variable [DecidableEq ι] [∀ i, DecidableEq (α i)]
variable [∀ i, PartialOrder (α i)] [∀ i, Zero (α i)] [∀ i, LocallyFiniteOrder (α i)]
instance instLocallyFiniteOrder : LocallyFiniteOrder (Π₀ i, α i) :=
LocallyFiniteOrder.ofIcc (Π₀ i, α i)
(fun f g => (f.support ∪ g.support).dfinsupp <| f.rangeIcc g)
(fun f g x => by
refine (mem_dfinsupp_iff_of_support_subset <| support_rangeIcc_subset).trans ?_
simp_rw [mem_rangeIcc_apply_iff, forall_and]
rfl)
variable (f g : Π₀ i, α i)
theorem Icc_eq : Icc f g = (f.support ∪ g.support).dfinsupp (f.rangeIcc g) := rfl
lemma card_Icc : #(Icc f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) :=
card_dfinsupp _ _
lemma card_Ico : #(Ico f g) = (∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i))) - 1 := by
rw [card_Ico_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioc : #(Ioc f g) = (∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i))) - 1 := by
rw [card_Ioc_eq_card_Icc_sub_one, card_Icc]
lemma card_Ioo : #(Ioo f g) = (∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i))) - 2 := by
rw [card_Ioo_eq_card_Icc_sub_two, card_Icc]
end PartialOrder
section Lattice
variable [DecidableEq ι] [∀ i, DecidableEq (α i)] [∀ i, Lattice (α i)] [∀ i, Zero (α i)]
[∀ i, LocallyFiniteOrder (α i)] (f g : Π₀ i, α i)
lemma card_uIcc : #(uIcc f g) = ∏ i ∈ f.support ∪ g.support, #(uIcc (f i) (g i)) := by
rw [← support_inf_union_support_sup]; exact card_Icc _ _
end Lattice
section CanonicallyOrdered
variable [DecidableEq ι] [∀ i, DecidableEq (α i)]
variable [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)] [∀ i, CanonicallyOrderedAdd (α i)]
[∀ i, OrderBot (α i)] [∀ i, LocallyFiniteOrder (α i)]
variable (f : Π₀ i, α i)
lemma card_Iic : #(Iic f) = ∏ i ∈ f.support, #(Iic (f i)) := by
simp_rw [Iic_eq_Icc, card_Icc, DFinsupp.bot_eq_zero, support_zero, empty_union, zero_apply,
bot_eq_zero]
lemma card_Iio : #(Iio f) = (∏ i ∈ f.support, #(Iic (f i))) - 1 := by
rw [card_Iio_eq_card_Iic_sub_one, card_Iic]
end CanonicallyOrdered
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Lex.lean | import Mathlib.Algebra.Order.Group.PiLex
import Mathlib.Data.DFinsupp.Order
import Mathlib.Data.DFinsupp.NeLocus
import Mathlib.Order.WellFoundedSet
/-!
# Lexicographic order on finitely supported dependent functions
This file defines the lexicographic order on `DFinsupp`.
-/
variable {ι : Type*} {α : ι → Type*}
namespace DFinsupp
section Zero
variable [∀ i, Zero (α i)]
/-- `DFinsupp.Lex r s` is the lexicographic relation on `Π₀ i, α i`, where `ι` is ordered by `r`,
and `α i` is ordered by `s i`.
The type synonym `Lex (Π₀ i, α i)` has an order given by `DFinsupp.Lex (· < ·) (· < ·)`.
-/
protected def Lex (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop) (x y : Π₀ i, α i) : Prop :=
Pi.Lex r (s _) x y
theorem _root_.Pi.lex_eq_dfinsupp_lex {r : ι → ι → Prop} {s : ∀ i, α i → α i → Prop}
(a b : Π₀ i, α i) : Pi.Lex r (s _) (a : ∀ i, α i) b = DFinsupp.Lex r s a b :=
rfl
theorem lex_def {r : ι → ι → Prop} {s : ∀ i, α i → α i → Prop} {a b : Π₀ i, α i} :
DFinsupp.Lex r s a b ↔ ∃ j, (∀ d, r d j → a d = b d) ∧ s j (a j) (b j) :=
.rfl
instance [LT ι] [∀ i, LT (α i)] : LT (Lex (Π₀ i, α i)) :=
⟨fun f g ↦ DFinsupp.Lex (· < ·) (fun _ ↦ (· < ·)) (ofLex f) (ofLex g)⟩
theorem lex_lt_iff [LT ι] [∀ i, LT (α i)] {a b : Lex (Π₀ i, α i)} :
a < b ↔ ∃ i, (∀ j, j < i → a j = b j) ∧ a i < b i :=
.rfl
theorem lex_lt_of_lt_of_preorder [∀ i, Preorder (α i)] (r) [IsStrictOrder ι r] {x y : Π₀ i, α i}
(hlt : x < y) : ∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i := by
obtain ⟨hle, j, hlt⟩ := Pi.lt_def.1 hlt
classical
have : (x.neLocus y : Set ι).WellFoundedOn r := (x.neLocus y).finite_toSet.wellFoundedOn
obtain ⟨i, hi, hl⟩ := this.has_min { i | x i < y i } ⟨⟨j, mem_neLocus.2 hlt.ne⟩, hlt⟩
refine ⟨i, fun k hk ↦ ⟨hle k, ?_⟩, hi⟩
exact of_not_not fun h ↦ hl ⟨k, mem_neLocus.2 (ne_of_not_le h).symm⟩ ((hle k).lt_of_not_ge h) hk
theorem lex_lt_of_lt [∀ i, PartialOrder (α i)] (r) [IsStrictOrder ι r] {x y : Π₀ i, α i}
(hlt : x < y) : Pi.Lex r (· < ·) x y := by
simp_rw [Pi.Lex, le_antisymm_iff]
exact lex_lt_of_lt_of_preorder r hlt
variable [LinearOrder ι]
instance Lex.isStrictOrder [∀ i, PartialOrder (α i)] :
IsStrictOrder (Lex (Π₀ i, α i)) (· < ·) where
irrefl _ := lt_irrefl (α := Lex (∀ i, α i)) _
trans _ _ _ := lt_trans (α := Lex (∀ i, α i))
/-- The partial order on `DFinsupp`s obtained by the lexicographic ordering.
See `DFinsupp.Lex.linearOrder` for a proof that this partial order is in fact linear. -/
instance Lex.partialOrder [∀ i, PartialOrder (α i)] : PartialOrder (Lex (Π₀ i, α i)) where
lt := (· < ·)
le x y := ⇑(ofLex x) = ⇑(ofLex y) ∨ x < y
__ := PartialOrder.lift (fun x : Lex (Π₀ i, α i) ↦ toLex (⇑(ofLex x)))
(DFunLike.coe_injective (F := DFinsupp α))
section LinearOrder
variable [∀ i, LinearOrder (α i)]
/-- Auxiliary helper to case split computably. There is no need for this to be public, as it
can be written with `Or.by_cases` on `lt_trichotomy` once the instances below are constructed. -/
private def lt_trichotomy_rec {P : Lex (Π₀ i, α i) → Lex (Π₀ i, α i) → Sort*}
(h_lt : ∀ {f g}, toLex f < toLex g → P (toLex f) (toLex g))
(h_eq : ∀ {f g}, toLex f = toLex g → P (toLex f) (toLex g))
(h_gt : ∀ {f g}, toLex g < toLex f → P (toLex f) (toLex g)) : ∀ f g, P f g :=
Lex.rec fun f ↦ Lex.rec fun g ↦ match (motive := ∀ y, (f.neLocus g).min = y → _) _, rfl with
| ⊤, h => h_eq (neLocus_eq_empty.mp <| Finset.min_eq_top.mp h)
| (wit : ι), h => by
apply (mem_neLocus.mp <| Finset.mem_of_min h).lt_or_gt.by_cases <;> intro hwit
· exact h_lt ⟨wit, fun j hj ↦ notMem_neLocus.mp (Finset.notMem_of_lt_min hj h), hwit⟩
· exact h_gt ⟨wit, fun j hj ↦
notMem_neLocus.mp (Finset.notMem_of_lt_min hj <| by rwa [neLocus_comm]), hwit⟩
/-- The less-or-equal relation for the lexicographic ordering is decidable. -/
instance Lex.decidableLE : DecidableLE (Lex (Π₀ i, α i)) :=
lt_trichotomy_rec (fun h ↦ isTrue <| Or.inr h)
(fun h ↦ isTrue <| Or.inl <| congr_arg _ h)
fun h ↦ isFalse fun h' ↦ lt_irrefl _ (h.trans_le h')
/-- The less-than relation for the lexicographic ordering is decidable. -/
instance Lex.decidableLT : DecidableLT (Lex (Π₀ i, α i)) :=
lt_trichotomy_rec (fun h ↦ isTrue h) (fun h ↦ isFalse h.not_lt) fun h ↦ isFalse h.asymm
/-- The linear order on `DFinsupp`s obtained by the lexicographic ordering. -/
instance Lex.linearOrder : LinearOrder (Lex (Π₀ i, α i)) where
__ := Lex.partialOrder
le_total := lt_trichotomy_rec (fun h ↦ Or.inl h.le) (fun h ↦ Or.inl h.le) fun h ↦ Or.inr h.le
toDecidableLT := decidableLT
toDecidableLE := decidableLE
end LinearOrder
variable [∀ i, PartialOrder (α i)]
theorem toLex_monotone : Monotone (@toLex (Π₀ i, α i)) := by
intro a b h
refine le_of_lt_or_eq (or_iff_not_imp_right.2 fun hne ↦ ?_)
classical
exact ⟨Finset.min' _ (nonempty_neLocus_iff.2 hne),
fun j hj ↦ notMem_neLocus.1 fun h ↦ (Finset.min'_le _ _ h).not_gt hj,
(h _).lt_of_ne (mem_neLocus.1 <| Finset.min'_mem _ _)⟩
@[deprecated lex_lt_iff (since := "2025-10-12")]
theorem lt_of_forall_lt_of_lt (a b : Lex (Π₀ i, α i)) (i : ι) :
(∀ j < i, ofLex a j = ofLex b j) → ofLex a i < ofLex b i → a < b :=
fun h1 h2 ↦ ⟨i, h1, h2⟩
end Zero
section Covariants
variable [LinearOrder ι] [∀ i, AddMonoid (α i)] [∀ i, LinearOrder (α i)]
/-! We are about to sneak in a hypothesis that might appear to be too strong.
We assume `AddLeftStrictMono` (covariant with *strict* inequality `<`) also when proving the one
with the *weak* inequality `≤`. This is actually necessary: addition on `Lex (Π₀ i, α i)` may fail
to be monotone, when it is "just" monotone on `α i`. -/
section Left
variable [∀ i, AddLeftStrictMono (α i)]
instance Lex.addLeftStrictMono : AddLeftStrictMono (Lex (Π₀ i, α i)) :=
⟨fun _ _ _ ⟨a, lta, ha⟩ ↦ ⟨a, fun j ja ↦ congr_arg _ (lta j ja), by dsimp; gcongr⟩⟩
instance Lex.addLeftMono : AddLeftMono (Lex (Π₀ i, α i)) :=
addLeftMono_of_addLeftStrictMono _
end Left
section Right
variable [∀ i, AddRightStrictMono (α i)]
instance Lex.addRightStrictMono : AddRightStrictMono (Lex (Π₀ i, α i)) :=
⟨fun f _ _ ⟨a, lta, ha⟩ ↦
⟨a, fun j ja ↦ congr_arg (· + ofLex f j) (lta j ja), by dsimp; gcongr⟩⟩
instance Lex.addRightMono : AddRightMono (Lex (Π₀ i, α i)) :=
addRightMono_of_addRightStrictMono _
end Right
end Covariants
section OrderedAddMonoid
variable [LinearOrder ι]
instance Lex.orderBot [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)]
[∀ i, CanonicallyOrderedAdd (α i)] :
OrderBot (Lex (Π₀ i, α i)) where
bot := 0
bot_le _ := DFinsupp.toLex_monotone bot_le
instance Lex.isOrderedCancelAddMonoid [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)]
[∀ i, IsOrderedCancelAddMonoid (α i)] :
IsOrderedCancelAddMonoid (Lex (Π₀ i, α i)) where
add_le_add_left _ _ h _ := add_le_add_left (α := Lex (∀ i, α i)) h _
le_of_add_le_add_left _ _ _ := le_of_add_le_add_left (α := Lex (∀ i, α i))
instance Lex.isOrderedAddMonoid [∀ i, AddCommGroup (α i)] [∀ i, PartialOrder (α i)]
[∀ i, IsOrderedAddMonoid (α i)] :
IsOrderedAddMonoid (Lex (Π₀ i, α i)) where
add_le_add_left _ _ := add_le_add_left
end OrderedAddMonoid
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Sigma.lean | import Mathlib.Data.DFinsupp.Module
import Mathlib.Data.Fintype.Quotient
/-!
# `DFinsupp` on `Sigma` types
## Main definitions
* `DFinsupp.sigmaCurry`: turn a `DFinsupp` indexed by a `Sigma` type into a `DFinsupp` with two
parameters.
* `DFinsupp.sigmaUncurry`: turn a `DFinsupp` with two parameters into a `DFinsupp` indexed by a
`Sigma` type. Inverse of `DFinsupp.sigmaCurry`.
* `DFinsupp.sigmaCurryEquiv`: `DFinsupp.sigmaCurry` and `DFinsupp.sigmaUncurry` bundled into a
bijection.
-/
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
namespace DFinsupp
section Equiv
open Finset
variable {κ : Type*}
section SigmaCurry
variable {α : ι → Type*} {δ : ∀ i, α i → Type v}
variable [DecidableEq ι]
/-- The natural map between `Π₀ (i : Σ i, α i), δ i.1 i.2` and `Π₀ i (j : α i), δ i j`. -/
def sigmaCurry [∀ i j, Zero (δ i j)] (f : Π₀ (i : Σ _, _), δ i.1 i.2) :
Π₀ (i) (j), δ i j where
toFun := fun i ↦
{ toFun := fun j ↦ f ⟨i, j⟩,
support' := f.support'.map (fun ⟨m, hm⟩ ↦
⟨m.filterMap (fun ⟨i', j'⟩ ↦ if h : i' = i then some <| h.rec j' else none),
fun j ↦ (hm ⟨i, j⟩).imp_left (fun h ↦ (m.mem_filterMap _).mpr ⟨⟨i, j⟩, h, dif_pos rfl⟩)⟩) }
support' := f.support'.map (fun ⟨m, hm⟩ ↦
⟨m.map Sigma.fst, fun i ↦ Decidable.or_iff_not_imp_left.mpr (fun h ↦ DFinsupp.ext
(fun j ↦ (hm ⟨i, j⟩).resolve_left (fun H ↦ (Multiset.mem_map.not.mp h) ⟨⟨i, j⟩, H, rfl⟩)))⟩)
@[simp]
theorem sigmaCurry_apply [∀ i j, Zero (δ i j)] (f : Π₀ (i : Σ _, _), δ i.1 i.2) (i : ι) (j : α i) :
sigmaCurry f i j = f ⟨i, j⟩ :=
rfl
@[simp]
theorem sigmaCurry_zero [∀ i j, Zero (δ i j)] :
sigmaCurry (0 : Π₀ (i : Σ _, _), δ i.1 i.2) = 0 :=
rfl
@[simp]
theorem sigmaCurry_add [∀ i j, AddZeroClass (δ i j)] (f g : Π₀ (i : Σ _, _), δ i.1 i.2) :
sigmaCurry (f + g) = (sigmaCurry f + sigmaCurry g : Π₀ (i) (j), δ i j) := by
ext (i j)
rfl
@[simp]
theorem sigmaCurry_smul [Monoid γ] [∀ i j, AddMonoid (δ i j)] [∀ i j, DistribMulAction γ (δ i j)]
(r : γ) (f : Π₀ (i : Σ _, _), δ i.1 i.2) :
sigmaCurry (r • f) = (r • sigmaCurry f : Π₀ (i) (j), δ i j) := by
ext (i j)
rfl
@[simp]
theorem sigmaCurry_single [∀ i, DecidableEq (α i)] [∀ i j, Zero (δ i j)]
(ij : Σ i, α i) (x : δ ij.1 ij.2) :
sigmaCurry (single ij x) = single ij.1 (single ij.2 x : Π₀ j, δ ij.1 j) := by
obtain ⟨i, j⟩ := ij
ext i' j'
dsimp only
rw [sigmaCurry_apply]
obtain rfl | hi := eq_or_ne i i'
· rw [single_eq_same]
obtain rfl | hj := eq_or_ne j' j
· rw [single_eq_same, single_eq_same]
· rw [single_eq_of_ne, single_eq_of_ne hj]
simpa using hj
· simp [hi]
/-- The natural map between `Π₀ i (j : α i), δ i j` and `Π₀ (i : Σ i, α i), δ i.1 i.2`, inverse of
`curry`. -/
def sigmaUncurry [∀ i j, Zero (δ i j)] [DecidableEq ι] (f : Π₀ (i) (j), δ i j) :
Π₀ i : Σ _, _, δ i.1 i.2 where
toFun i := f i.1 i.2
support' :=
f.support'.bind fun s =>
(Trunc.finChoice (fun i : ↥s.val.toFinset => (f i).support')).map fun fs =>
⟨s.val.toFinset.attach.val.bind fun i => (fs i).val.map (Sigma.mk i.val), by
rintro ⟨i, a⟩
cases s.prop i with
| inl hi =>
cases (fs ⟨i, Multiset.mem_toFinset.mpr hi⟩).prop a with
| inl ha =>
left; rw [Multiset.mem_bind]
use ⟨i, Multiset.mem_toFinset.mpr hi⟩
constructor
case right => simp [ha]
case left => apply Multiset.mem_attach
| inr ha => right; simp [toFun_eq_coe (f i) ▸ ha]
| inr hi => right; simp [toFun_eq_coe f ▸ hi]⟩
@[simp]
theorem sigmaUncurry_apply [∀ i j, Zero (δ i j)]
(f : Π₀ (i) (j), δ i j) (i : ι) (j : α i) :
sigmaUncurry f ⟨i, j⟩ = f i j :=
rfl
@[simp]
theorem sigmaUncurry_zero [∀ i j, Zero (δ i j)] :
sigmaUncurry (0 : Π₀ (i) (j), δ i j) = 0 :=
rfl
@[simp]
theorem sigmaUncurry_add [∀ i j, AddZeroClass (δ i j)] (f g : Π₀ (i) (j), δ i j) :
sigmaUncurry (f + g) = sigmaUncurry f + sigmaUncurry g :=
DFunLike.coe_injective rfl
@[simp]
theorem sigmaUncurry_smul [Monoid γ] [∀ i j, AddMonoid (δ i j)]
[∀ i j, DistribMulAction γ (δ i j)]
(r : γ) (f : Π₀ (i) (j), δ i j) : sigmaUncurry (r • f) = r • sigmaUncurry f :=
DFunLike.coe_injective rfl
@[simp]
theorem sigmaUncurry_single [∀ i j, Zero (δ i j)] [∀ i, DecidableEq (α i)]
(i) (j : α i) (x : δ i j) :
sigmaUncurry (single i (single j x : Π₀ j : α i, δ i j)) = single ⟨i, j⟩ (by exact x) := by
ext ⟨i', j'⟩
dsimp only
rw [sigmaUncurry_apply]
obtain rfl | hi := eq_or_ne i i'
· rw [single_eq_same]
obtain rfl | hj := eq_or_ne j' j
· rw [single_eq_same, single_eq_same]
· rw [single_eq_of_ne hj, single_eq_of_ne]
simpa using hj
· simp [hi]
/-- The natural bijection between `Π₀ (i : Σ i, α i), δ i.1 i.2` and `Π₀ i (j : α i), δ i j`.
This is the dfinsupp version of `Equiv.piCurry`. -/
def sigmaCurryEquiv [∀ i j, Zero (δ i j)] [DecidableEq ι] :
(Π₀ i : Σ _, _, δ i.1 i.2) ≃ Π₀ (i) (j), δ i j where
toFun := sigmaCurry
invFun := sigmaUncurry
left_inv f := by
ext ⟨i, j⟩
rw [sigmaUncurry_apply, sigmaCurry_apply]
right_inv f := by
ext i j
rw [sigmaCurry_apply, sigmaUncurry_apply]
end SigmaCurry
end Equiv
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Order.lean | import Mathlib.Algebra.Order.Module.Defs
import Mathlib.Algebra.Order.Sub.Basic
import Mathlib.Data.DFinsupp.Module
/-!
# Pointwise order on finitely supported dependent functions
This file lifts order structures on the `α i` to `Π₀ i, α i`.
## Main declarations
* `DFinsupp.orderEmbeddingToFun`: The order embedding from finitely supported dependent functions
to functions.
-/
open Finset
variable {ι : Type*} {α : ι → Type*}
namespace DFinsupp
/-! ### Order structures -/
section Zero
variable [∀ i, Zero (α i)]
section LE
variable [∀ i, LE (α i)] {f g : Π₀ i, α i}
instance : LE (Π₀ i, α i) :=
⟨fun f g ↦ ∀ i, f i ≤ g i⟩
lemma le_def : f ≤ g ↔ ∀ i, f i ≤ g i := Iff.rfl
@[simp, norm_cast] lemma coe_le_coe : ⇑f ≤ g ↔ f ≤ g := Iff.rfl
/-- The order on `DFinsupp`s over a partial order embeds into the order on functions -/
def orderEmbeddingToFun : (Π₀ i, α i) ↪o ∀ i, α i where
toFun := DFunLike.coe
inj' := DFunLike.coe_injective
map_rel_iff' := Iff.rfl
@[simp, norm_cast]
lemma coe_orderEmbeddingToFun : ⇑(orderEmbeddingToFun (α := α)) = DFunLike.coe := rfl
theorem orderEmbeddingToFun_apply {f : Π₀ i, α i} {i : ι} :
orderEmbeddingToFun f i = f i :=
rfl
end LE
section Preorder
variable [∀ i, Preorder (α i)] {f g : Π₀ i, α i}
instance : Preorder (Π₀ i, α i) :=
{ (inferInstance : LE (DFinsupp α)) with
le_refl := fun _ _ ↦ le_rfl
le_trans := fun _ _ _ hfg hgh i ↦ (hfg i).trans (hgh i) }
lemma lt_def : f < g ↔ f ≤ g ∧ ∃ i, f i < g i := Pi.lt_def
@[simp, norm_cast] lemma coe_lt_coe : ⇑f < g ↔ f < g := Iff.rfl
lemma coe_mono : Monotone ((⇑) : (Π₀ i, α i) → ∀ i, α i) := fun _ _ ↦ id
lemma coe_strictMono : Monotone ((⇑) : (Π₀ i, α i) → ∀ i, α i) := fun _ _ ↦ id
end Preorder
instance [∀ i, PartialOrder (α i)] : PartialOrder (Π₀ i, α i) :=
{ (inferInstance : Preorder (DFinsupp α)) with
le_antisymm := fun _ _ hfg hgf ↦ ext fun i ↦ (hfg i).antisymm (hgf i) }
instance [∀ i, SemilatticeInf (α i)] : SemilatticeInf (Π₀ i, α i) :=
{ (inferInstance : PartialOrder (DFinsupp α)) with
inf := zipWith (fun _ ↦ (· ⊓ ·)) fun _ ↦ inf_idem _
inf_le_left := fun _ _ _ ↦ inf_le_left
inf_le_right := fun _ _ _ ↦ inf_le_right
le_inf := fun _ _ _ hf hg i ↦ le_inf (hf i) (hg i) }
@[simp, norm_cast]
lemma coe_inf [∀ i, SemilatticeInf (α i)] (f g : Π₀ i, α i) : f ⊓ g = ⇑f ⊓ g := rfl
theorem inf_apply [∀ i, SemilatticeInf (α i)] (f g : Π₀ i, α i) (i : ι) : (f ⊓ g) i = f i ⊓ g i :=
zipWith_apply _ _ _ _ _
instance [∀ i, SemilatticeSup (α i)] : SemilatticeSup (Π₀ i, α i) :=
{ (inferInstance : PartialOrder (DFinsupp α)) with
sup := zipWith (fun _ ↦ (· ⊔ ·)) fun _ ↦ sup_idem _
le_sup_left := fun _ _ _ ↦ le_sup_left
le_sup_right := fun _ _ _ ↦ le_sup_right
sup_le := fun _ _ _ hf hg i ↦ sup_le (hf i) (hg i) }
@[simp, norm_cast]
lemma coe_sup [∀ i, SemilatticeSup (α i)] (f g : Π₀ i, α i) : f ⊔ g = ⇑f ⊔ g := rfl
theorem sup_apply [∀ i, SemilatticeSup (α i)] (f g : Π₀ i, α i) (i : ι) : (f ⊔ g) i = f i ⊔ g i :=
zipWith_apply _ _ _ _ _
section Lattice
variable [∀ i, Lattice (α i)] (f g : Π₀ i, α i)
instance lattice : Lattice (Π₀ i, α i) :=
{ (inferInstance : SemilatticeInf (DFinsupp α)),
(inferInstance : SemilatticeSup (DFinsupp α)) with }
variable [DecidableEq ι] [∀ (i) (x : α i), Decidable (x ≠ 0)]
theorem support_inf_union_support_sup : (f ⊓ g).support ∪ (f ⊔ g).support = f.support ∪ g.support :=
coe_injective <| compl_injective <| by ext; simp [inf_eq_and_sup_eq_iff]
theorem support_sup_union_support_inf : (f ⊔ g).support ∪ (f ⊓ g).support = f.support ∪ g.support :=
(union_comm _ _).trans <| support_inf_union_support_sup _ _
end Lattice
end Zero
/-! ### Algebraic order structures -/
instance (α : ι → Type*) [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)]
[∀ i, IsOrderedAddMonoid (α i)] : IsOrderedAddMonoid (Π₀ i, α i) :=
{ add_le_add_left := fun _ _ h c i ↦ add_le_add_left (h i) (c i) }
instance (α : ι → Type*) [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)]
[∀ i, IsOrderedCancelAddMonoid (α i)] :
IsOrderedCancelAddMonoid (Π₀ i, α i) :=
{ le_of_add_le_add_left := fun _ _ _ H i ↦ le_of_add_le_add_left (H i) }
instance [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)] [∀ i, AddLeftReflectLE (α i)] :
AddLeftReflectLE (Π₀ i, α i) :=
⟨fun _ _ _ H i ↦ le_of_add_le_add_left (H i)⟩
section Module
variable {α : Type*} {β : ι → Type*} [Semiring α] [Preorder α] [∀ i, AddCommMonoid (β i)]
[∀ i, Preorder (β i)] [∀ i, Module α (β i)]
instance instPosSMulMono [∀ i, PosSMulMono α (β i)] : PosSMulMono α (Π₀ i, β i) :=
PosSMulMono.lift _ coe_le_coe coe_smul
instance instSMulPosMono [∀ i, SMulPosMono α (β i)] : SMulPosMono α (Π₀ i, β i) :=
SMulPosMono.lift _ coe_le_coe coe_smul coe_zero
instance instPosSMulReflectLE [∀ i, PosSMulReflectLE α (β i)] : PosSMulReflectLE α (Π₀ i, β i) :=
PosSMulReflectLE.lift _ coe_le_coe coe_smul
instance instSMulPosReflectLE [∀ i, SMulPosReflectLE α (β i)] : SMulPosReflectLE α (Π₀ i, β i) :=
SMulPosReflectLE.lift _ coe_le_coe coe_smul coe_zero
end Module
section Module
variable {α : Type*} {β : ι → Type*} [Semiring α] [PartialOrder α] [∀ i, AddCommMonoid (β i)]
[∀ i, PartialOrder (β i)] [∀ i, Module α (β i)]
instance instPosSMulStrictMono [∀ i, PosSMulStrictMono α (β i)] : PosSMulStrictMono α (Π₀ i, β i) :=
PosSMulStrictMono.lift _ coe_le_coe coe_smul
instance instSMulPosStrictMono [∀ i, SMulPosStrictMono α (β i)] : SMulPosStrictMono α (Π₀ i, β i) :=
SMulPosStrictMono.lift _ coe_le_coe coe_smul coe_zero
-- Note: There is no interesting instance for `PosSMulReflectLT α (Π₀ i, β i)` that's not already
-- implied by the other instances
instance instSMulPosReflectLT [∀ i, SMulPosReflectLT α (β i)] : SMulPosReflectLT α (Π₀ i, β i) :=
SMulPosReflectLT.lift _ coe_le_coe coe_smul coe_zero
end Module
section PartialOrder
variable (α) [∀ i, AddCommMonoid (α i)] [∀ i, PartialOrder (α i)] [∀ i, CanonicallyOrderedAdd (α i)]
instance : OrderBot (Π₀ i, α i) where
bot := 0
bot_le := by simp only [le_def, coe_zero, Pi.zero_apply, imp_true_iff, zero_le]
variable {α}
protected theorem bot_eq_zero : (⊥ : Π₀ i, α i) = 0 :=
rfl
@[simp]
theorem add_eq_zero_iff (f g : Π₀ i, α i) : f + g = 0 ↔ f = 0 ∧ g = 0 := by
simp [DFunLike.ext_iff, forall_and]
section LE
variable [DecidableEq ι]
section
variable [∀ (i) (x : α i), Decidable (x ≠ 0)] {f g : Π₀ i, α i} {s : Finset ι}
theorem le_iff' (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i :=
⟨fun h s _ ↦ h s, fun h s ↦
if H : s ∈ f.support then h s (hf H) else (notMem_support_iff.1 H).symm ▸ zero_le (g s)⟩
theorem le_iff : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i :=
le_iff' <| Subset.refl _
lemma support_monotone : Monotone (support (ι := ι) (β := α)) :=
fun f g h a ha ↦ by rw [mem_support_iff, ← pos_iff_ne_zero] at ha ⊢; exact ha.trans_le (h _)
lemma support_mono (hfg : f ≤ g) : f.support ⊆ g.support := support_monotone hfg
variable (α) in
instance decidableLE [∀ i, DecidableLE (α i)] : DecidableLE (Π₀ i, α i) :=
fun _ _ ↦ decidable_of_iff _ le_iff.symm
end
@[simp]
theorem single_le_iff {f : Π₀ i, α i} {i : ι} {a : α i} :
single i a ≤ f ↔ a ≤ f i := by
classical exact (le_iff' support_single_subset).trans <| by simp
end LE
variable (α) [∀ i, Sub (α i)] [∀ i, OrderedSub (α i)] {f g : Π₀ i, α i} {i : ι} {a b : α i}
/-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an
additive group. -/
instance tsub : Sub (Π₀ i, α i) :=
⟨zipWith (fun _ m n ↦ m - n) fun _ ↦ tsub_self 0⟩
variable {α}
theorem tsub_apply (f g : Π₀ i, α i) (i : ι) : (f - g) i = f i - g i :=
zipWith_apply _ _ _ _ _
@[simp, norm_cast]
theorem coe_tsub (f g : Π₀ i, α i) : ⇑(f - g) = f - g := by
ext i
exact tsub_apply f g i
variable (α)
instance : OrderedSub (Π₀ i, α i) :=
⟨fun _ _ _ ↦ forall_congr' fun _ ↦ tsub_le_iff_right⟩
instance [∀ i, AddLeftMono (α i)] : CanonicallyOrderedAdd (Π₀ i, α i) where
exists_add_of_le := by
intro f g h
exists g - f
ext i
exact (add_tsub_cancel_of_le <| h i).symm
le_add_self := fun _ _ _ ↦ le_add_self
le_self_add := fun _ _ _ ↦ le_self_add
variable {α} [DecidableEq ι]
@[simp]
theorem single_tsub : single i (a - b) = single i a - single i b := by
ext j
obtain rfl | h := eq_or_ne j i
· rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same]
· rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self]
variable [∀ (i) (x : α i), Decidable (x ≠ 0)]
theorem support_tsub : (f - g).support ⊆ f.support := by
simp +contextual only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff,
Ne, coe_tsub, Pi.sub_apply, not_imp_not, zero_le, imp_true_iff]
theorem subset_support_tsub : f.support \ g.support ⊆ (f - g).support := by
simp +contextual [subset_iff]
end PartialOrder
section LinearOrder
variable [∀ i, AddCommMonoid (α i)] [∀ i, LinearOrder (α i)] [∀ i, CanonicallyOrderedAdd (α i)]
[DecidableEq ι] {f g : Π₀ i, α i}
@[simp]
theorem support_inf : (f ⊓ g).support = f.support ∩ g.support := by
ext
simp only [inf_apply, mem_support_iff, Ne, Finset.mem_inter]
simp only [← nonpos_iff_eq_zero, min_le_iff, not_or]
@[simp]
theorem support_sup : (f ⊔ g).support = f.support ∪ g.support := by
ext
simp only [Finset.mem_union, mem_support_iff, sup_apply, Ne, ← nonpos_iff_eq_zero, sup_le_iff,
Classical.not_and_iff_not_or_not]
nonrec theorem disjoint_iff : Disjoint f g ↔ Disjoint f.support g.support := by
rw [disjoint_iff, disjoint_iff, DFinsupp.bot_eq_zero, ← DFinsupp.support_eq_empty,
DFinsupp.support_inf]
rfl
end LinearOrder
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Multiset.lean | import Mathlib.Data.DFinsupp.BigOperators
import Mathlib.Data.DFinsupp.Order
/-!
# Equivalence between `Multiset` and `ℕ`-valued finitely supported functions
This defines `DFinsupp.toMultiset` the equivalence between `Π₀ a : α, ℕ` and `Multiset α`, along
with `Multiset.toDFinsupp` the reverse equivalence.
-/
open Function
variable {α : Type*}
namespace DFinsupp
/-- Non-dependent special case of `DFinsupp.addZeroClass` to help typeclass search. -/
instance addZeroClass' {β} [AddZeroClass β] : AddZeroClass (Π₀ _ : α, β) :=
@DFinsupp.addZeroClass α (fun _ ↦ β) _
variable [DecidableEq α]
/-- A DFinsupp version of `Finsupp.toMultiset`. -/
def toMultiset : (Π₀ _ : α, ℕ) →+ Multiset α :=
DFinsupp.sumAddHom fun a : α ↦ Multiset.replicateAddMonoidHom a
@[simp]
theorem toMultiset_single (a : α) (n : ℕ) :
toMultiset (DFinsupp.single a n) = Multiset.replicate n a :=
DFinsupp.sumAddHom_single _ _ _
end DFinsupp
namespace Multiset
variable [DecidableEq α] {s t : Multiset α}
/-- A DFinsupp version of `Multiset.toFinsupp`. -/
def toDFinsupp : Multiset α →+ Π₀ _ : α, ℕ where
toFun s :=
{ toFun := fun n ↦ s.count n
support' := Trunc.mk ⟨s, fun i ↦ (em (i ∈ s)).imp_right Multiset.count_eq_zero_of_notMem⟩ }
map_zero' := rfl
map_add' _ _ := DFinsupp.ext fun _ ↦ Multiset.count_add _ _ _
@[simp]
theorem toDFinsupp_apply (s : Multiset α) (a : α) : Multiset.toDFinsupp s a = s.count a :=
rfl
@[simp]
theorem toDFinsupp_support (s : Multiset α) : s.toDFinsupp.support = s.toFinset :=
Finset.filter_true_of_mem fun _ hx ↦ count_ne_zero.mpr <| Multiset.mem_toFinset.1 hx
@[simp]
theorem toDFinsupp_replicate (a : α) (n : ℕ) :
toDFinsupp (Multiset.replicate n a) = DFinsupp.single a n := by
ext i
dsimp [toDFinsupp]
simp [count_replicate]
@[simp]
theorem toDFinsupp_singleton (a : α) : toDFinsupp {a} = DFinsupp.single a 1 := by
rw [← replicate_one, toDFinsupp_replicate]
/-- `Multiset.toDFinsupp` as an `AddEquiv`. -/
@[simps! apply symm_apply]
def equivDFinsupp : Multiset α ≃+ Π₀ _ : α, ℕ :=
AddMonoidHom.toAddEquiv Multiset.toDFinsupp DFinsupp.toMultiset (by ext; simp) (by ext; simp)
@[simp]
theorem toDFinsupp_toMultiset (s : Multiset α) : DFinsupp.toMultiset (Multiset.toDFinsupp s) = s :=
equivDFinsupp.symm_apply_apply s
theorem toDFinsupp_injective : Injective (toDFinsupp : Multiset α → Π₀ _a, ℕ) :=
equivDFinsupp.injective
@[simp]
theorem toDFinsupp_inj : toDFinsupp s = toDFinsupp t ↔ s = t :=
toDFinsupp_injective.eq_iff
@[simp]
theorem toDFinsupp_le_toDFinsupp : toDFinsupp s ≤ toDFinsupp t ↔ s ≤ t := by
simp [Multiset.le_iff_count, DFinsupp.le_def]
@[simp]
theorem toDFinsupp_lt_toDFinsupp : toDFinsupp s < toDFinsupp t ↔ s < t :=
lt_iff_lt_of_le_iff_le' toDFinsupp_le_toDFinsupp toDFinsupp_le_toDFinsupp
@[simp]
theorem toDFinsupp_inter (s t : Multiset α) : toDFinsupp (s ∩ t) = toDFinsupp s ⊓ toDFinsupp t := by
ext i; simp
@[simp]
theorem toDFinsupp_union (s t : Multiset α) : toDFinsupp (s ∪ t) = toDFinsupp s ⊔ toDFinsupp t := by
ext i; simp
end Multiset
namespace DFinsupp
variable [DecidableEq α] {f g : Π₀ _a : α, ℕ}
@[simp]
theorem toMultiset_toDFinsupp (f : Π₀ _ : α, ℕ) :
Multiset.toDFinsupp (DFinsupp.toMultiset f) = f :=
Multiset.equivDFinsupp.apply_symm_apply f
theorem toMultiset_injective : Injective (toMultiset : (Π₀ _a, ℕ) → Multiset α) :=
Multiset.equivDFinsupp.symm.injective
@[simp]
theorem toMultiset_inj : toMultiset f = toMultiset g ↔ f = g :=
toMultiset_injective.eq_iff
@[simp]
theorem toMultiset_le_toMultiset : toMultiset f ≤ toMultiset g ↔ f ≤ g := by
simp_rw [← Multiset.toDFinsupp_le_toDFinsupp, toMultiset_toDFinsupp]
@[simp]
theorem toMultiset_lt_toMultiset : toMultiset f < toMultiset g ↔ f < g := by
simp_rw [← Multiset.toDFinsupp_lt_toDFinsupp, toMultiset_toDFinsupp]
variable (f g)
@[simp]
theorem toMultiset_inf : toMultiset (f ⊓ g) = toMultiset f ∩ toMultiset g :=
Multiset.toDFinsupp_injective <| by simp
@[simp]
theorem toMultiset_sup : toMultiset (f ⊔ g) = toMultiset f ∪ toMultiset g :=
Multiset.toDFinsupp_injective <| by simp
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/WellFounded.lean | import Mathlib.Data.DFinsupp.Lex
import Mathlib.Order.Antisymmetrization
import Mathlib.Order.GameAdd
import Mathlib.SetTheory.Cardinal.Order
import Mathlib.Tactic.AdaptationNote
/-!
# Well-foundedness of the lexicographic and product orders on `DFinsupp` and `Pi`
The primary results are `DFinsupp.Lex.wellFounded` and the two variants that follow it,
which essentially say that if `(· > ·)` is a well order on `ι`, `(· < ·)` is well-founded on each
`α i`, and `0` is a bottom element in `α i`, then the lexicographic `(· < ·)` is well-founded
on `Π₀ i, α i`. The proof is modelled on the proof of `WellFounded.cutExpand`.
The results are used to prove `Pi.Lex.wellFounded` and two variants, which say that if
`ι` is finite and equipped with a linear order and `(· < ·)` is well-founded on each `α i`,
then the lexicographic `(· < ·)` is well-founded on `Π i, α i`, and the same is true for
`Π₀ i, α i` (`DFinsupp.Lex.wellFounded_of_finite`), because `DFinsupp` is order-isomorphic
to `pi` when `ι` is finite.
Finally, we deduce `DFinsupp.wellFoundedLT`, `Pi.wellFoundedLT`,
`DFinsupp.wellFoundedLT_of_finite` and variants, which concern the product order
rather than the lexicographic one. An order on `ι` is not required in these results,
but we deduce them from the well-foundedness of the lexicographic order by choosing
a well order on `ι` so that the product order `(· < ·)` becomes a subrelation
of the lexicographic `(· < ·)`.
All results are provided in two forms whenever possible: a general form where the relations
can be arbitrary (not the `(· < ·)` of a preorder, or not even transitive, etc.) and a specialized
form provided as `WellFoundedLT` instances where the `(d)Finsupp/pi` type (or their `Lex`
type synonyms) carries a natural `(· < ·)`.
Notice that the definition of `DFinsupp.Lex` says that `x < y` according to `DFinsupp.Lex r s`
iff there exists a coordinate `i : ι` such that `x i < y i` according to `s i`, and at all
`r`-smaller coordinates `j` (i.e. satisfying `r j i`), `x` remains unchanged relative to `y`;
in other words, coordinates `j` such that `¬ r j i` and `j ≠ i` are exactly where changes
can happen arbitrarily. This explains the appearance of `rᶜ ⊓ (≠)` in
`dfinsupp.acc_single` and `dfinsupp.well_founded`. When `r` is trichotomous (e.g. the `(· < ·)`
of a linear order), `¬ r j i ∧ j ≠ i` implies `r i j`, so it suffices to require `r.swap`
to be well-founded.
-/
variable {ι : Type*} {α : ι → Type*}
namespace DFinsupp
open Relation Prod
section Zero
variable [∀ i, Zero (α i)] (r : ι → ι → Prop) (s : ∀ i, α i → α i → Prop)
/-- This key lemma says that if a finitely supported dependent function `x₀` is obtained by merging
two such functions `x₁` and `x₂`, and if we evolve `x₀` down the `DFinsupp.Lex` relation one
step and get `x`, we can always evolve one of `x₁` and `x₂` down the `DFinsupp.Lex` relation
one step while keeping the other unchanged, and merge them back (possibly in a different way)
to get back `x`. In other words, the two parts evolve essentially independently under
`DFinsupp.Lex`. This is used to show that a function `x` is accessible if
`DFinsupp.single i (x i)` is accessible for each `i` in the (finite) support of `x`
(`DFinsupp.Lex.acc_of_single`). -/
theorem lex_fibration [∀ (i) (s : Set ι), Decidable (i ∈ s)] :
Fibration (InvImage (GameAdd (DFinsupp.Lex r s) (DFinsupp.Lex r s)) snd) (DFinsupp.Lex r s)
fun x => piecewise x.2.1 x.2.2 x.1 := by
rintro ⟨p, x₁, x₂⟩ x ⟨i, hr, hs⟩
simp_rw [piecewise_apply] at hs hr
split_ifs at hs with hp
· refine ⟨⟨{ j | r j i → j ∈ p }, piecewise x₁ x { j | r j i }, x₂⟩,
.fst ⟨i, fun j hj ↦ ?_, ?_⟩, ?_⟩ <;> simp only [piecewise_apply, Set.mem_setOf_eq]
· simp only [if_pos hj]
· split_ifs with hi
· rwa [hr i hi, if_pos hp] at hs
· assumption
· ext1 j
simp only [piecewise_apply, Set.mem_setOf_eq]
split_ifs with h₁ h₂ <;> try rfl
· rw [hr j h₂, if_pos (h₁ h₂)]
· rw [Classical.not_imp] at h₁
rw [hr j h₁.1, if_neg h₁.2]
· refine ⟨⟨{ j | r j i ∧ j ∈ p }, x₁, piecewise x₂ x { j | r j i }⟩,
.snd ⟨i, fun j hj ↦ ?_, ?_⟩, ?_⟩ <;> simp only [piecewise_apply, Set.mem_setOf_eq]
· exact if_pos hj
· split_ifs with hi
· rwa [hr i hi, if_neg hp] at hs
· assumption
· ext1 j
simp only [piecewise_apply, Set.mem_setOf_eq]
split_ifs with h₁ h₂ <;> try rfl
· rw [hr j h₁.1, if_pos h₁.2]
· rw [hr j h₂, if_neg]
simpa [h₂] using h₁
variable {r s}
theorem Lex.acc_of_single_erase [DecidableEq ι] {x : Π₀ i, α i} (i : ι)
(hs : Acc (DFinsupp.Lex r s) <| single i (x i)) (hu : Acc (DFinsupp.Lex r s) <| x.erase i) :
Acc (DFinsupp.Lex r s) x := by
classical
convert ← @Acc.of_fibration _ _ _ _ _ (lex_fibration r s) ⟨{i}, _⟩
(InvImage.accessible snd <| hs.prod_gameAdd hu)
convert piecewise_single_erase x i
theorem Lex.acc_zero (hbot : ∀ ⦃i a⦄, ¬s i a 0) : Acc (DFinsupp.Lex r s) 0 :=
Acc.intro 0 fun _ ⟨_, _, h⟩ => (hbot h).elim
theorem Lex.acc_of_single (hbot : ∀ ⦃i a⦄, ¬s i a 0) [DecidableEq ι]
[∀ (i) (x : α i), Decidable (x ≠ 0)] (x : Π₀ i, α i) :
(∀ i ∈ x.support, Acc (DFinsupp.Lex r s) <| single i (x i)) → Acc (DFinsupp.Lex r s) x := by
generalize ht : x.support = t; revert x
classical
induction t using Finset.induction with
| empty =>
intro x ht
rw [support_eq_empty.1 ht]
exact fun _ => Lex.acc_zero hbot
| insert b t hb ih =>
refine fun x ht h => Lex.acc_of_single_erase b (h b <| t.mem_insert_self b) ?_
refine ih _ (by rw [support_erase, ht, Finset.erase_insert hb]) fun a ha => ?_
rw [erase_ne (ha.ne_of_notMem hb)]
exact h a (Finset.mem_insert_of_mem ha)
theorem Lex.acc_single (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i))
[DecidableEq ι] {i : ι} (hi : Acc (rᶜ ⊓ (· ≠ ·)) i) :
∀ a, Acc (DFinsupp.Lex r s) (single i a) := by
induction hi with | _ i _ ih
refine fun a => WellFounded.induction (hs i)
(C := fun x ↦ Acc (DFinsupp.Lex r s) (single i x)) a fun a ha ↦ ?_
refine Acc.intro _ fun x ↦ ?_
rintro ⟨k, hr, hs⟩
rw [single_apply] at hs
split_ifs at hs with hik
swap
· exact (hbot hs).elim
subst hik
classical
refine Lex.acc_of_single hbot x fun j hj ↦ ?_
obtain rfl | hij := eq_or_ne j i
· exact ha _ hs
by_cases h : r j i
· rw [hr j h, single_eq_of_ne hij, single_zero]
exact Lex.acc_zero hbot
· exact ih _ ⟨h, hij⟩ _
theorem Lex.acc (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i))
[DecidableEq ι] [∀ (i) (x : α i), Decidable (x ≠ 0)] (x : Π₀ i, α i)
(h : ∀ i ∈ x.support, Acc (rᶜ ⊓ (· ≠ ·)) i) : Acc (DFinsupp.Lex r s) x :=
Lex.acc_of_single hbot x fun i hi => Lex.acc_single hbot hs (h i hi) _
theorem Lex.wellFounded (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i))
(hr : WellFounded <| rᶜ ⊓ (· ≠ ·)) : WellFounded (DFinsupp.Lex r s) :=
⟨fun x => by classical exact Lex.acc hbot hs x fun i _ => hr.apply i⟩
theorem Lex.wellFounded' (hbot : ∀ ⦃i a⦄, ¬s i a 0) (hs : ∀ i, WellFounded (s i))
[IsTrichotomous ι r] (hr : WellFounded (Function.swap r)) :
WellFounded (DFinsupp.Lex r s) :=
Lex.wellFounded hbot hs <| Subrelation.wf
(fun {i j} h => ((@IsTrichotomous.trichotomous ι r _ i j).resolve_left h.1).resolve_left h.2) hr
end Zero
instance Lex.wellFoundedLT [LT ι] [IsTrichotomous ι (· < ·)] [hι : WellFoundedGT ι]
[∀ i, AddMonoid (α i)] [∀ i, PartialOrder (α i)] [∀ i, CanonicallyOrderedAdd (α i)]
[hα : ∀ i, WellFoundedLT (α i)] :
WellFoundedLT (Lex (Π₀ i, α i)) :=
⟨Lex.wellFounded' (fun _ a => (zero_le a).not_gt) (fun i => (hα i).wf) hι.wf⟩
end DFinsupp
open DFinsupp
variable (r : ι → ι → Prop) {s : ∀ i, α i → α i → Prop}
theorem Pi.Lex.wellFounded [IsStrictTotalOrder ι r] [Finite ι] (hs : ∀ i, WellFounded (s i)) :
WellFounded (Pi.Lex r (fun {i} ↦ s i)) := by
obtain h | ⟨⟨x⟩⟩ := isEmpty_or_nonempty (∀ i, α i)
· convert emptyWf.wf
letI : ∀ i, Zero (α i) := fun i => ⟨(hs i).min ⊤ ⟨x i, trivial⟩⟩
haveI := IsTrans.swap r; haveI := IsIrrefl.swap r; haveI := Fintype.ofFinite ι
refine InvImage.wf equivFunOnFintype.symm (Lex.wellFounded' (fun i a => ?_) hs ?_)
exacts [(hs i).not_lt_min ⊤ _ trivial, Finite.wellFounded_of_trans_of_irrefl (Function.swap r)]
instance Pi.Lex.wellFoundedLT [LinearOrder ι] [Finite ι] [∀ i, LT (α i)]
[hwf : ∀ i, WellFoundedLT (α i)] : WellFoundedLT (Lex (∀ i, α i)) :=
⟨Pi.Lex.wellFounded (· < ·) fun i => (hwf i).1⟩
instance Function.Lex.wellFoundedLT {α} [LinearOrder ι] [Finite ι] [LT α] [WellFoundedLT α] :
WellFoundedLT (Lex (ι → α)) :=
Pi.Lex.wellFoundedLT
theorem DFinsupp.Lex.wellFounded_of_finite [IsStrictTotalOrder ι r] [Finite ι] [∀ i, Zero (α i)]
(hs : ∀ i, WellFounded (s i)) : WellFounded (DFinsupp.Lex r s) :=
have := Fintype.ofFinite ι
InvImage.wf equivFunOnFintype (Pi.Lex.wellFounded r hs)
instance DFinsupp.Lex.wellFoundedLT_of_finite [LinearOrder ι] [Finite ι] [∀ i, Zero (α i)]
[∀ i, LT (α i)] [hwf : ∀ i, WellFoundedLT (α i)] : WellFoundedLT (Lex (Π₀ i, α i)) :=
⟨DFinsupp.Lex.wellFounded_of_finite (· < ·) fun i => (hwf i).1⟩
protected theorem DFinsupp.wellFoundedLT [∀ i, Zero (α i)] [∀ i, Preorder (α i)]
[∀ i, WellFoundedLT (α i)] (hbot : ∀ ⦃i⦄ ⦃a : α i⦄, ¬a < 0) : WellFoundedLT (Π₀ i, α i) :=
⟨by
set β := fun i ↦ Antisymmetrization (α i) (· ≤ ·)
set e : (i : ι) → α i → β i := fun i ↦ toAntisymmetrization (· ≤ ·)
let _ : ∀ i, Zero (β i) := fun i ↦ ⟨e i 0⟩
have : WellFounded (DFinsupp.Lex (Function.swap <| @WellOrderingRel ι)
(fun _ ↦ (· < ·) : (i : ι) → β i → β i → Prop)) := by
have := IsTrichotomous.swap (@WellOrderingRel ι)
refine Lex.wellFounded' ?_ (fun i ↦ IsWellFounded.wf) ?_
· rintro i ⟨a⟩
apply hbot
· simp +unfoldPartialApp only [Function.swap]
exact IsWellFounded.wf
refine Subrelation.wf (fun h => ?_) <| InvImage.wf (mapRange e fun _ ↦ rfl) this
have := IsStrictOrder.swap (@WellOrderingRel ι)
obtain ⟨i, he, hl⟩ := lex_lt_of_lt_of_preorder (Function.swap WellOrderingRel) h
exact ⟨i, fun j hj ↦ Quot.sound (he j hj), hl⟩⟩
instance DFinsupp.wellFoundedLT'
[∀ i, AddMonoid (α i)] [∀ i, PartialOrder (α i)] [∀ i, CanonicallyOrderedAdd (α i)]
[∀ i, WellFoundedLT (α i)] : WellFoundedLT (Π₀ i, α i) :=
DFinsupp.wellFoundedLT fun _i a => (zero_le a).not_gt
instance Pi.wellFoundedLT [Finite ι] [∀ i, Preorder (α i)] [hw : ∀ i, WellFoundedLT (α i)] :
WellFoundedLT (∀ i, α i) :=
⟨by
obtain h | ⟨⟨x⟩⟩ := isEmpty_or_nonempty (∀ i, α i)
· convert emptyWf.wf
letI : ∀ i, Zero (α i) := fun i => ⟨(hw i).wf.min ⊤ ⟨x i, trivial⟩⟩
haveI := Fintype.ofFinite ι
refine InvImage.wf equivFunOnFintype.symm (DFinsupp.wellFoundedLT fun i a => ?_).wf
exact (hw i).wf.not_lt_min ⊤ _ trivial⟩
instance Function.wellFoundedLT {α} [Finite ι] [Preorder α] [WellFoundedLT α] :
WellFoundedLT (ι → α) :=
Pi.wellFoundedLT
instance DFinsupp.wellFoundedLT_of_finite [Finite ι] [∀ i, Zero (α i)] [∀ i, Preorder (α i)]
[∀ i, WellFoundedLT (α i)] : WellFoundedLT (Π₀ i, α i) :=
have := Fintype.ofFinite ι
⟨InvImage.wf equivFunOnFintype Pi.wellFoundedLT.wf⟩ |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Ext.lean | import Mathlib.Algebra.Group.Submonoid.Basic
import Mathlib.Data.DFinsupp.Defs
/-!
# Extensionality principles for `DFinsupp`
## Main results
* `DFinsupp.addHom_ext`, `DFinsupp.addHom_ext'`: if two additive homomorphisms from `Π₀ i, β i`
are equal on each `single a b`, then they are equal.
-/
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
namespace DFinsupp
section DecidableEq
variable [DecidableEq ι]
section AddMonoid
variable [∀ i, AddZeroClass (β i)]
@[simp]
theorem add_closure_iUnion_range_single :
AddSubmonoid.closure (⋃ i : ι, Set.range (single i : β i → Π₀ i, β i)) = ⊤ :=
top_unique fun x _ => by
apply DFinsupp.induction x
· exact AddSubmonoid.zero_mem _
exact fun a b f _ _ hf =>
AddSubmonoid.add_mem _
(AddSubmonoid.subset_closure <| Set.mem_iUnion.2 ⟨a, Set.mem_range_self _⟩) hf
/-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then
they are equal. -/
theorem addHom_ext {γ : Type w} [AddZeroClass γ] ⦃f g : (Π₀ i, β i) →+ γ⦄
(H : ∀ (i : ι) (y : β i), f (single i y) = g (single i y)) : f = g := by
refine AddMonoidHom.eq_of_eqOn_denseM add_closure_iUnion_range_single fun f hf => ?_
simp only [Set.mem_iUnion, Set.mem_range] at hf
rcases hf with ⟨x, y, rfl⟩
apply H
/-- If two additive homomorphisms from `Π₀ i, β i` are equal on each `single a b`, then
they are equal.
See note [partially-applied ext lemmas]. -/
@[ext]
theorem addHom_ext' {γ : Type w} [AddZeroClass γ] ⦃f g : (Π₀ i, β i) →+ γ⦄
(H : ∀ x, f.comp (singleAddHom β x) = g.comp (singleAddHom β x)) : f = g :=
addHom_ext fun x => DFunLike.congr_fun (H x)
end AddMonoid
end DecidableEq
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Notation.lean | import Mathlib.Data.DFinsupp.Defs
import Mathlib.Data.Finsupp.Notation
/-!
# Notation for `DFinsupp`
This file extends the existing `fun₀ | 3 => a | 7 => b` notation to work for `DFinsupp`,
which desugars to `DFinsupp.update` and `DFinsupp.single`,
in the same way that `{a, b}` desugars to `insert` and `singleton`.
Note that this syntax is for `Finsupp` by default, but works for `DFinsupp` if the expected type
is correct.
-/
namespace DFinsupp
open Lean Parser Term
namespace Internal
open Finsupp.Internal
/-- `DFinsupp` elaborator for `single₀`. -/
@[term_elab Finsupp.Internal.stxSingle₀]
def elabSingle₀ : Elab.Term.TermElab
| `(term| single₀ $i $x) => fun ty? => do
Elab.Term.tryPostponeIfNoneOrMVar ty?
let some ty := ty? | Elab.throwUnsupportedSyntax
let_expr DFinsupp _ _ _ := ← Meta.withReducible (Meta.whnf ty) | Elab.throwUnsupportedSyntax
Elab.Term.elabTerm (← `(DFinsupp.single $i $x)) ty?
| _ => fun _ => Elab.throwUnsupportedSyntax
/-- `DFinsupp` elaborator for `update₀`. -/
@[term_elab Finsupp.Internal.stxUpdate₀]
def elabUpdate₀ : Elab.Term.TermElab
| `(term| update₀ $f $i $x) => fun ty? => do
Elab.Term.tryPostponeIfNoneOrMVar ty?
let some ty := ty? | Elab.throwUnsupportedSyntax
let_expr DFinsupp _ _ _ := ← Meta.withReducible (Meta.whnf ty) | Elab.throwUnsupportedSyntax
Elab.Term.elabTerm (← `(DFinsupp.update $f $i $x)) ty?
| _ => fun _ => Elab.throwUnsupportedSyntax
end Internal
/-- Unexpander for the `fun₀ | i => x` notation. -/
@[app_unexpander DFinsupp.single]
def singleUnexpander : Lean.PrettyPrinter.Unexpander
| `($_ $pat $val) => `(fun₀ | $pat => $val)
| _ => throw ()
/-- Unexpander for the `fun₀ | i => x` notation. -/
@[app_unexpander DFinsupp.update]
def updateUnexpander : Lean.PrettyPrinter.Unexpander
| `($_ $f $pat $val) => match f with
| `(fun₀ $xs:matchAlt*) => `(fun₀ $xs:matchAlt* | $pat => $val)
| _ => throw ()
| _ => throw ()
/-- Display `DFinsupp` using `fun₀` notation. -/
unsafe instance {α : Type*} {β : α → Type*} [Repr α] [∀ i, Repr (β i)] [∀ i, Zero (β i)] :
Repr (Π₀ a, β a) where
reprPrec f p :=
let vals :=
((f.support'.unquot.val.map fun i => (repr i, repr (f i))).filter
(fun p => toString p.2 != "0")).unquot
let vals_dedup := vals.foldl (fun xs x => x :: xs.eraseP (toString ·.1 == toString x.1)) []
if vals.length = 0 then
"0"
else
let ret : Std.Format := f!"fun₀" ++ .nest 2 (
.group (.join <| vals_dedup.map fun a =>
.line ++ .group (f!"| {a.1} =>" ++ .line ++ a.2)))
if p ≥ leadPrec then Format.paren ret else ret
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Defs.lean | import Mathlib.Data.Set.Finite.Basic
import Mathlib.Algebra.Group.InjSurj
import Mathlib.Algebra.Group.Equiv.Defs
import Mathlib.Algebra.Group.Pi.Basic
import Mathlib.Algebra.Notation.Prod
import Mathlib.Algebra.Group.Basic
/-!
# Dependent functions with finite support
For a non-dependent version see `Mathlib/Data/Finsupp/Defs.lean`.
## Notation
This file introduces the notation `Π₀ a, β a` as notation for `DFinsupp β`, mirroring the `α →₀ β`
notation used for `Finsupp`. This works for nested binders too, with `Π₀ a b, γ a b` as notation
for `DFinsupp (fun a ↦ DFinsupp (γ a))`.
## Implementation notes
The support is internally represented (in the primed `DFinsupp.support'`) as a `Multiset` that
represents a superset of the true support of the function, quotiented by the always-true relation so
that this does not impact equality. This approach has computational benefits over storing a
`Finset`; it allows us to add together two finitely-supported functions without
having to evaluate the resulting function to recompute its support (which would required
decidability of `b = 0` for `b : β i`).
The true support of the function can still be recovered with `DFinsupp.support`; but these
decidability obligations are now postponed to when the support is actually needed. As a consequence,
there are two ways to sum a `DFinsupp`: with `DFinsupp.sum` which works over an arbitrary function
but requires recomputation of the support and therefore a `Decidable` argument; and with
`DFinsupp.sumAddHom` which requires an additive morphism, using its properties to show that
summing over a superset of the support is sufficient.
`Finsupp` takes an altogether different approach here; it uses `Classical.Decidable` and declares
the `Add` instance as noncomputable. This design difference is independent of the fact that
`DFinsupp` is dependently-typed and `Finsupp` is not; in future, we may want to align these two
definitions, or introduce two more definitions for the other combinations of decisions.
-/
assert_not_exists Finset.prod Submonoid
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
variable (β) in
/-- A dependent function `Π i, β i` with finite support, with notation `Π₀ i, β i`.
Note that `DFinsupp.support` is the preferred API for accessing the support of the function,
`DFinsupp.support'` is an implementation detail that aids computability; see the implementation
notes in this file for more information. -/
structure DFinsupp [∀ i, Zero (β i)] : Type max u v where mk' ::
/-- The underlying function of a dependent function with finite support (aka `DFinsupp`). -/
toFun : ∀ i, β i
/-- The support of a dependent function with finite support (aka `DFinsupp`). -/
support' : Trunc { s : Multiset ι // ∀ i, i ∈ s ∨ toFun i = 0 }
/-- `Π₀ i, β i` denotes the type of dependent functions with finite support `DFinsupp β`. -/
notation3 "Π₀ "(...)", "r:(scoped f => DFinsupp f) => r
namespace DFinsupp
section Basic
variable [∀ i, Zero (β i)] [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)]
instance instDFunLike : DFunLike (Π₀ i, β i) ι β :=
⟨fun f => f.toFun, fun ⟨f₁, s₁⟩ ⟨f₂, s₁⟩ ↦ fun (h : f₁ = f₂) ↦ by
subst h
congr
subsingleton ⟩
@[simp]
theorem toFun_eq_coe (f : Π₀ i, β i) : f.toFun = f :=
rfl
@[ext]
theorem ext {f g : Π₀ i, β i} (h : ∀ i, f i = g i) : f = g :=
DFunLike.ext _ _ h
lemma ne_iff {f g : Π₀ i, β i} : f ≠ g ↔ ∃ i, f i ≠ g i := DFunLike.ne_iff
instance : Zero (Π₀ i, β i) :=
⟨⟨0, Trunc.mk <| ⟨∅, fun _ => Or.inr rfl⟩⟩⟩
instance : Inhabited (Π₀ i, β i) :=
⟨0⟩
@[simp, norm_cast] lemma coe_mk' (f : ∀ i, β i) (s) : ⇑(⟨f, s⟩ : Π₀ i, β i) = f := rfl
@[simp, norm_cast] lemma coe_zero : ⇑(0 : Π₀ i, β i) = 0 := rfl
theorem zero_apply (i : ι) : (0 : Π₀ i, β i) i = 0 :=
rfl
/-- The composition of `f : β₁ → β₂` and `g : Π₀ i, β₁ i` is
`mapRange f hf g : Π₀ i, β₂ i`, well defined when `f 0 = 0`.
This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself
bundled:
* `DFinsupp.mapRange.addMonoidHom`
* `DFinsupp.mapRange.addEquiv`
* `dfinsupp.mapRange.linearMap`
* `dfinsupp.mapRange.linearEquiv`
-/
def mapRange (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (x : Π₀ i, β₁ i) : Π₀ i, β₂ i :=
⟨fun i => f i (x i),
x.support'.map fun s => ⟨s.1, fun i => (s.2 i).imp_right fun h : x i = 0 => by
rw [← hf i, ← h]⟩⟩
@[simp]
theorem mapRange_apply (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) (g : Π₀ i, β₁ i) (i : ι) :
mapRange f hf g i = f i (g i) :=
rfl
@[simp]
theorem mapRange_id (h : ∀ i, id (0 : β₁ i) = 0 := fun _ => rfl) (g : Π₀ i : ι, β₁ i) :
mapRange (fun i => (id : β₁ i → β₁ i)) h g = g := by
ext
rfl
theorem mapRange_comp (f : ∀ i, β₁ i → β₂ i) (f₂ : ∀ i, β i → β₁ i) (hf : ∀ i, f i 0 = 0)
(hf₂ : ∀ i, f₂ i 0 = 0) (h : ∀ i, (f i ∘ f₂ i) 0 = 0) (g : Π₀ i : ι, β i) :
mapRange (fun i => f i ∘ f₂ i) h g = mapRange f hf (mapRange f₂ hf₂ g) := by
ext
simp only [mapRange_apply]; rfl
@[simp]
theorem mapRange_zero (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) :
mapRange f hf (0 : Π₀ i, β₁ i) = 0 := by
ext
simp only [mapRange_apply, coe_zero, Pi.zero_apply, hf]
/-- Let `f i` be a binary operation `β₁ i → β₂ i → β i` such that `f i 0 0 = 0`.
Then `zipWith f hf` is a binary operation `Π₀ i, β₁ i → Π₀ i, β₂ i → Π₀ i, β i`. -/
def zipWith (f : ∀ i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (x : Π₀ i, β₁ i) (y : Π₀ i, β₂ i) :
Π₀ i, β i :=
⟨fun i => f i (x i) (y i), by
refine x.support'.bind fun xs => ?_
refine y.support'.map fun ys => ?_
refine ⟨xs + ys, fun i => ?_⟩
obtain h1 | (h1 : x i = 0) := xs.prop i
· left
rw [Multiset.mem_add]
left
exact h1
obtain h2 | (h2 : y i = 0) := ys.prop i
· left
rw [Multiset.mem_add]
right
exact h2
right; rw [← hf, ← h1, ← h2]⟩
@[simp]
theorem zipWith_apply (f : ∀ i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0) (g₁ : Π₀ i, β₁ i)
(g₂ : Π₀ i, β₂ i) (i : ι) : zipWith f hf g₁ g₂ i = f i (g₁ i) (g₂ i) :=
rfl
section Piecewise
variable (x y : Π₀ i, β i) (s : Set ι) [∀ i, Decidable (i ∈ s)]
/-- `x.piecewise y s` is the finitely supported function equal to `x` on the set `s`,
and to `y` on its complement. -/
def piecewise : Π₀ i, β i :=
zipWith (fun i x y => if i ∈ s then x else y) (fun _ => ite_self 0) x y
theorem piecewise_apply (i : ι) : x.piecewise y s i = if i ∈ s then x i else y i :=
rfl
@[simp, norm_cast]
theorem coe_piecewise : ⇑(x.piecewise y s) = s.piecewise x y :=
rfl
end Piecewise
end Basic
section Algebra
instance [∀ i, AddZeroClass (β i)] : Add (Π₀ i, β i) :=
⟨zipWith (fun _ => (· + ·)) fun _ => add_zero 0⟩
theorem add_apply [∀ i, AddZeroClass (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) :
(g₁ + g₂) i = g₁ i + g₂ i :=
rfl
@[simp, norm_cast]
theorem coe_add [∀ i, AddZeroClass (β i)] (g₁ g₂ : Π₀ i, β i) : ⇑(g₁ + g₂) = g₁ + g₂ :=
rfl
instance addZeroClass [∀ i, AddZeroClass (β i)] : AddZeroClass (Π₀ i, β i) :=
DFunLike.coe_injective.addZeroClass _ coe_zero coe_add
instance instIsLeftCancelAdd [∀ i, AddZeroClass (β i)] [∀ i, IsLeftCancelAdd (β i)] :
IsLeftCancelAdd (Π₀ i, β i) where
add_left_cancel _ _ _ h := ext fun x => add_left_cancel <| DFunLike.congr_fun h x
instance instIsRightCancelAdd [∀ i, AddZeroClass (β i)] [∀ i, IsRightCancelAdd (β i)] :
IsRightCancelAdd (Π₀ i, β i) where
add_right_cancel _ _ _ h := ext fun x => add_right_cancel <| DFunLike.congr_fun h x
instance instIsCancelAdd [∀ i, AddZeroClass (β i)] [∀ i, IsCancelAdd (β i)] :
IsCancelAdd (Π₀ i, β i) where
/-- Note the general `SMul` instance doesn't apply as `ℕ` is not distributive
unless `β i`'s addition is commutative. -/
instance hasNatScalar [∀ i, AddMonoid (β i)] : SMul ℕ (Π₀ i, β i) :=
⟨fun c v => v.mapRange (fun _ => (c • ·)) fun _ => nsmul_zero _⟩
theorem nsmul_apply [∀ i, AddMonoid (β i)] (b : ℕ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • v i :=
rfl
@[simp, norm_cast]
theorem coe_nsmul [∀ i, AddMonoid (β i)] (b : ℕ) (v : Π₀ i, β i) : ⇑(b • v) = b • ⇑v :=
rfl
instance [∀ i, AddMonoid (β i)] : AddMonoid (Π₀ i, β i) :=
DFunLike.coe_injective.addMonoid _ coe_zero coe_add fun _ _ => coe_nsmul _ _
/-- Coercion from a `DFinsupp` to a pi type is an `AddMonoidHom`. -/
def coeFnAddMonoidHom [∀ i, AddZeroClass (β i)] : (Π₀ i, β i) →+ ∀ i, β i where
toFun := (⇑)
map_zero' := coe_zero
map_add' := coe_add
@[simp]
lemma coeFnAddMonoidHom_apply [∀ i, AddZeroClass (β i)] (v : Π₀ i, β i) : coeFnAddMonoidHom v = v :=
rfl
instance addCommMonoid [∀ i, AddCommMonoid (β i)] : AddCommMonoid (Π₀ i, β i) :=
DFunLike.coe_injective.addCommMonoid _ coe_zero coe_add fun _ _ => coe_nsmul _ _
instance [∀ i, AddGroup (β i)] : Neg (Π₀ i, β i) :=
⟨fun f => f.mapRange (fun _ => Neg.neg) fun _ => neg_zero⟩
theorem neg_apply [∀ i, AddGroup (β i)] (g : Π₀ i, β i) (i : ι) : (-g) i = -g i :=
rfl
@[simp, norm_cast] lemma coe_neg [∀ i, AddGroup (β i)] (g : Π₀ i, β i) : ⇑(-g) = -g := rfl
instance [∀ i, AddGroup (β i)] : Sub (Π₀ i, β i) :=
⟨zipWith (fun _ => Sub.sub) fun _ => sub_zero 0⟩
theorem sub_apply [∀ i, AddGroup (β i)] (g₁ g₂ : Π₀ i, β i) (i : ι) : (g₁ - g₂) i = g₁ i - g₂ i :=
rfl
@[simp, norm_cast]
theorem coe_sub [∀ i, AddGroup (β i)] (g₁ g₂ : Π₀ i, β i) : ⇑(g₁ - g₂) = g₁ - g₂ :=
rfl
/-- Note the general `SMul` instance doesn't apply as `ℤ` is not distributive
unless `β i`'s addition is commutative. -/
instance hasIntScalar [∀ i, AddGroup (β i)] : SMul ℤ (Π₀ i, β i) :=
⟨fun c v => v.mapRange (fun _ => (c • ·)) fun _ => zsmul_zero _⟩
theorem zsmul_apply [∀ i, AddGroup (β i)] (b : ℤ) (v : Π₀ i, β i) (i : ι) : (b • v) i = b • v i :=
rfl
@[simp, norm_cast]
theorem coe_zsmul [∀ i, AddGroup (β i)] (b : ℤ) (v : Π₀ i, β i) : ⇑(b • v) = b • ⇑v :=
rfl
instance [∀ i, AddGroup (β i)] : AddGroup (Π₀ i, β i) :=
DFunLike.coe_injective.addGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_nsmul _ _)
fun _ _ => coe_zsmul _ _
instance addCommGroup [∀ i, AddCommGroup (β i)] : AddCommGroup (Π₀ i, β i) :=
DFunLike.coe_injective.addCommGroup _ coe_zero coe_add coe_neg coe_sub (fun _ _ => coe_nsmul _ _)
fun _ _ => coe_zsmul _ _
end Algebra
section FilterAndSubtypeDomain
/-- `Filter p f` is the function which is `f i` if `p i` is true and 0 otherwise. -/
def filter [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] (x : Π₀ i, β i) : Π₀ i, β i :=
⟨fun i => if p i then x i else 0,
x.support'.map fun xs =>
⟨xs.1, fun i => (xs.prop i).imp_right fun H : x i = 0 => by simp only [H, ite_self]⟩⟩
@[simp]
theorem filter_apply [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] (i : ι) (f : Π₀ i, β i) :
f.filter p i = if p i then f i else 0 :=
rfl
theorem filter_apply_pos [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] (f : Π₀ i, β i) {i : ι}
(h : p i) : f.filter p i = f i := by simp only [filter_apply, if_pos h]
theorem filter_apply_neg [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] (f : Π₀ i, β i) {i : ι}
(h : ¬p i) : f.filter p i = 0 := by simp only [filter_apply, if_neg h]
theorem filter_pos_add_filter_neg [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i) (p : ι → Prop)
[DecidablePred p] : (f.filter p + f.filter fun i => ¬p i) = f :=
ext fun i => by
simp only [add_apply, filter_apply]; split_ifs <;> simp only [add_zero, zero_add]
@[simp]
theorem filter_zero [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] :
(0 : Π₀ i, β i).filter p = 0 := by
ext
simp
@[simp]
theorem filter_add [∀ i, AddZeroClass (β i)] (p : ι → Prop) [DecidablePred p] (f g : Π₀ i, β i) :
(f + g).filter p = f.filter p + g.filter p := by
ext
simp [ite_add_zero]
variable (γ β)
/-- `DFinsupp.filter` as an `AddMonoidHom`. -/
@[simps]
def filterAddMonoidHom [∀ i, AddZeroClass (β i)] (p : ι → Prop) [DecidablePred p] :
(Π₀ i, β i) →+ Π₀ i, β i where
toFun := filter p
map_zero' := filter_zero p
map_add' := filter_add p
variable {γ β}
@[simp]
theorem filter_neg [∀ i, AddGroup (β i)] (p : ι → Prop) [DecidablePred p] (f : Π₀ i, β i) :
(-f).filter p = -f.filter p :=
(filterAddMonoidHom β p).map_neg f
@[simp]
theorem filter_sub [∀ i, AddGroup (β i)] (p : ι → Prop) [DecidablePred p] (f g : Π₀ i, β i) :
(f - g).filter p = f.filter p - g.filter p :=
(filterAddMonoidHom β p).map_sub f g
/-- `subtypeDomain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtypeDomain [∀ i, Zero (β i)] (p : ι → Prop) [DecidablePred p] (x : Π₀ i, β i) :
Π₀ i : Subtype p, β i :=
⟨fun i => x (i : ι),
x.support'.map fun xs =>
⟨(Multiset.filter p xs.1).attach.map fun j => ⟨j.1, (Multiset.mem_filter.1 j.2).2⟩, fun i =>
(xs.prop i).imp_left fun H =>
Multiset.mem_map.2
⟨⟨i, Multiset.mem_filter.2 ⟨H, i.2⟩⟩, Multiset.mem_attach _ _, Subtype.eta _ _⟩⟩⟩
@[simp]
theorem subtypeDomain_zero [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] :
subtypeDomain p (0 : Π₀ i, β i) = 0 :=
rfl
@[simp]
theorem subtypeDomain_apply [∀ i, Zero (β i)] {p : ι → Prop} [DecidablePred p] {i : Subtype p}
{v : Π₀ i, β i} : (subtypeDomain p v) i = v i :=
rfl
@[simp]
theorem subtypeDomain_add [∀ i, AddZeroClass (β i)] {p : ι → Prop} [DecidablePred p]
(v v' : Π₀ i, β i) : (v + v').subtypeDomain p = v.subtypeDomain p + v'.subtypeDomain p :=
DFunLike.coe_injective rfl
variable (γ β)
/-- `subtypeDomain` but as an `AddMonoidHom`. -/
@[simps]
def subtypeDomainAddMonoidHom [∀ i, AddZeroClass (β i)] (p : ι → Prop) [DecidablePred p] :
(Π₀ i : ι, β i) →+ Π₀ i : Subtype p, β i where
toFun := subtypeDomain p
map_zero' := subtypeDomain_zero
map_add' := subtypeDomain_add
variable {γ β}
@[simp]
theorem subtypeDomain_neg [∀ i, AddGroup (β i)] {p : ι → Prop} [DecidablePred p] {v : Π₀ i, β i} :
(-v).subtypeDomain p = -v.subtypeDomain p :=
DFunLike.coe_injective rfl
@[simp]
theorem subtypeDomain_sub [∀ i, AddGroup (β i)] {p : ι → Prop} [DecidablePred p]
{v v' : Π₀ i, β i} : (v - v').subtypeDomain p = v.subtypeDomain p - v'.subtypeDomain p :=
DFunLike.coe_injective rfl
end FilterAndSubtypeDomain
section Basic
variable [∀ i, Zero (β i)]
theorem finite_support (f : Π₀ i, β i) : Set.Finite { i | f i ≠ 0 } :=
Trunc.induction_on f.support' fun xs ↦
xs.1.finite_toSet.subset fun i H ↦ ((xs.prop i).resolve_right H)
section DecidableEq
variable [DecidableEq ι]
/-- Create an element of `Π₀ i, β i` from a finset `s` and a function `x`
defined on this `Finset`. -/
def mk (s : Finset ι) (x : ∀ i : (↑s : Set ι), β (i : ι)) : Π₀ i, β i :=
⟨fun i => if H : i ∈ s then x ⟨i, H⟩ else 0,
Trunc.mk ⟨s.1, fun i => if H : i ∈ s then Or.inl H else Or.inr <| dif_neg H⟩⟩
variable {s : Finset ι} {x : ∀ i : (↑s : Set ι), β i} {i : ι}
@[simp]
theorem mk_apply : (mk s x : ∀ i, β i) i = if H : i ∈ s then x ⟨i, H⟩ else 0 :=
rfl
theorem mk_of_mem (hi : i ∈ s) : (mk s x : ∀ i, β i) i = x ⟨i, hi⟩ :=
dif_pos hi
theorem mk_of_notMem (hi : i ∉ s) : (mk s x : ∀ i, β i) i = 0 :=
dif_neg hi
@[deprecated (since := "2025-05-23")] alias mk_of_not_mem := mk_of_notMem
theorem mk_injective (s : Finset ι) : Function.Injective (@mk ι β _ _ s) := by
intro x y H
ext i
have h1 : (mk s x : ∀ i, β i) i = (mk s y : ∀ i, β i) i := by rw [H]
obtain ⟨i, hi : i ∈ s⟩ := i
dsimp only [mk_apply, Subtype.coe_mk] at h1
simpa only [dif_pos hi] using h1
end DecidableEq
instance unique [∀ i, Subsingleton (β i)] : Unique (Π₀ i, β i) :=
DFunLike.coe_injective.unique
instance uniqueOfIsEmpty [IsEmpty ι] : Unique (Π₀ i, β i) :=
DFunLike.coe_injective.unique
/-- Given `Fintype ι`, `equivFunOnFintype` is the `Equiv` between `Π₀ i, β i` and `Π i, β i`.
(All dependent functions on a finite type are finitely supported.) -/
@[simps apply]
def equivFunOnFintype [Fintype ι] : (Π₀ i, β i) ≃ ∀ i, β i where
toFun := (⇑)
invFun f := ⟨f, Trunc.mk ⟨Finset.univ.1, fun _ => Or.inl <| Finset.mem_univ_val _⟩⟩
left_inv _ := DFunLike.coe_injective rfl
@[simp]
theorem equivFunOnFintype_symm_coe [Fintype ι] (f : Π₀ i, β i) : equivFunOnFintype.symm f = f :=
Equiv.symm_apply_apply _ _
variable [DecidableEq ι]
/-- The function `single i b : Π₀ i, β i` sends `i` to `b`
and all other points to `0`. -/
def single (i : ι) (b : β i) : Π₀ i, β i :=
⟨Pi.single i b,
Trunc.mk ⟨{i}, fun j => (Decidable.eq_or_ne j i).imp (by simp) fun h => Pi.single_eq_of_ne h _⟩⟩
theorem single_eq_pi_single {i b} : ⇑(single i b : Π₀ i, β i) = Pi.single i b :=
rfl
@[simp]
theorem single_apply {i i' b} :
(single i b : Π₀ i, β i) i' = if h : i = i' then Eq.recOn h b else 0 := by
rw [single_eq_pi_single, Pi.single, Function.update]
simp [@eq_comm _ i i']
@[simp]
theorem single_zero (i) : (single i 0 : Π₀ i, β i) = 0 :=
DFunLike.coe_injective <| Pi.single_zero _
theorem single_eq_same {i b} : (single i b : Π₀ i, β i) i = b := by
simp only [single_apply, dite_eq_ite, ite_true]
theorem single_eq_of_ne {i i' b} (h : i' ≠ i) : (single i b : Π₀ i, β i) i' = 0 := by
simp only [single_apply, @eq_comm _ i i', dif_neg h]
theorem single_injective {i} : Function.Injective (single i : β i → Π₀ i, β i) := fun _ _ H =>
Pi.single_injective i <| DFunLike.coe_injective.eq_iff.mpr H
/-- Like `Finsupp.single_eq_single_iff`, but with a `HEq` due to dependent types -/
theorem single_eq_single_iff (i j : ι) (xi : β i) (xj : β j) :
DFinsupp.single i xi = DFinsupp.single j xj ↔ i = j ∧ xi ≍ xj ∨ xi = 0 ∧ xj = 0 := by
constructor
· intro h
by_cases hij : i = j
· subst hij
exact Or.inl ⟨rfl, heq_of_eq (DFinsupp.single_injective h)⟩
· have h_coe : ⇑(DFinsupp.single i xi) = DFinsupp.single j xj := congr_arg (⇑) h
have hci := congr_fun h_coe i
have hcj := congr_fun h_coe j
rw [DFinsupp.single_eq_same] at hci hcj
rw [DFinsupp.single_eq_of_ne hij] at hci
rw [DFinsupp.single_eq_of_ne (Ne.symm hij)] at hcj
exact Or.inr ⟨hci, hcj.symm⟩
· rintro (⟨rfl, hxi⟩ | ⟨hi, hj⟩)
· rw [eq_of_heq hxi]
· rw [hi, hj, DFinsupp.single_zero, DFinsupp.single_zero]
/-- `DFinsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see
`DFinsupp.single_injective` -/
theorem single_left_injective {b : ∀ i : ι, β i} (h : ∀ i, b i ≠ 0) :
Function.Injective (fun i => single i (b i) : ι → Π₀ i, β i) := fun _ _ H =>
(((single_eq_single_iff _ _ _ _).mp H).resolve_right fun hb => h _ hb.1).left
@[simp]
theorem single_eq_zero {i : ι} {xi : β i} : single i xi = 0 ↔ xi = 0 := by
rw [← single_zero i, single_eq_single_iff]
simp
theorem single_ne_zero {i : ι} {xi : β i} : single i xi ≠ 0 ↔ xi ≠ 0 :=
single_eq_zero.not
theorem filter_single (p : ι → Prop) [DecidablePred p] (i : ι) (x : β i) :
(single i x).filter p = if p i then single i x else 0 := by
ext j
have := apply_ite (fun x : Π₀ i, β i => x j) (p i) (single i x) 0
dsimp at this
rw [filter_apply, this]
obtain rfl | hij := Decidable.eq_or_ne j i
· rfl
· rw [single_eq_of_ne hij, ite_self, ite_self]
@[simp]
theorem filter_single_pos {p : ι → Prop} [DecidablePred p] (i : ι) (x : β i) (h : p i) :
(single i x).filter p = single i x := by rw [filter_single, if_pos h]
@[simp]
theorem filter_single_neg {p : ι → Prop} [DecidablePred p] (i : ι) (x : β i) (h : ¬p i) :
(single i x).filter p = 0 := by rw [filter_single, if_neg h]
/-- Equality of sigma types is sufficient (but not necessary) to show equality of `DFinsupp`s. -/
theorem single_eq_of_sigma_eq {i j} {xi : β i} {xj : β j} (h : (⟨i, xi⟩ : Sigma β) = ⟨j, xj⟩) :
DFinsupp.single i xi = DFinsupp.single j xj := by
cases h
rfl
@[simp]
theorem equivFunOnFintype_single [Fintype ι] (i : ι) (m : β i) :
(@DFinsupp.equivFunOnFintype ι β _ _) (DFinsupp.single i m) = Pi.single i m := rfl
@[simp]
theorem equivFunOnFintype_symm_single [Fintype ι] (i : ι) (m : β i) :
(@DFinsupp.equivFunOnFintype ι β _ _).symm (Pi.single i m) = DFinsupp.single i m := by
ext i'
simp only [← single_eq_pi_single, equivFunOnFintype_symm_coe]
section SingleAndZipWith
variable [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)]
@[simp]
theorem zipWith_single_single (f : ∀ i, β₁ i → β₂ i → β i) (hf : ∀ i, f i 0 0 = 0)
{i} (b₁ : β₁ i) (b₂ : β₂ i) :
zipWith f hf (single i b₁) (single i b₂) = single i (f i b₁ b₂) := by
ext j
rw [zipWith_apply]
obtain rfl | hij := Decidable.eq_or_ne j i
· rw [single_eq_same, single_eq_same, single_eq_same]
· rw [single_eq_of_ne hij, single_eq_of_ne hij, single_eq_of_ne hij, hf]
end SingleAndZipWith
/-- Redefine `f i` to be `0`. -/
def erase (i : ι) (x : Π₀ i, β i) : Π₀ i, β i :=
⟨fun j ↦ if j = i then 0 else x.1 j,
x.support'.map fun xs ↦ ⟨xs.1, fun j ↦ (xs.prop j).imp_right (by simp only [·, ite_self])⟩⟩
@[simp]
theorem erase_apply {i j : ι} {f : Π₀ i, β i} : (f.erase i) j = if j = i then 0 else f j :=
rfl
theorem erase_same {i : ι} {f : Π₀ i, β i} : (f.erase i) i = 0 := by simp
theorem erase_ne {i i' : ι} {f : Π₀ i, β i} (h : i' ≠ i) : (f.erase i) i' = f i' := by simp [h]
theorem piecewise_single_erase (x : Π₀ i, β i) (i : ι) :
(single i (x i)).piecewise (x.erase i) {i} = x := by
ext j; rw [piecewise_apply]; split_ifs with h
· rw [(id h : j = i), single_eq_same]
· exact erase_ne h
theorem erase_eq_sub_single {β : ι → Type*} [∀ i, AddGroup (β i)] (f : Π₀ i, β i) (i : ι) :
f.erase i = f - single i (f i) := by
ext j
rcases eq_or_ne j i with (rfl | h)
· simp
· simp [erase_ne h, single_eq_of_ne h]
@[simp]
theorem erase_zero (i : ι) : erase i (0 : Π₀ i, β i) = 0 :=
ext fun _ => ite_self _
@[simp]
theorem filter_ne_eq_erase (f : Π₀ i, β i) (i : ι) : f.filter (· ≠ i) = f.erase i := by
ext1 j
simp only [DFinsupp.filter_apply, DFinsupp.erase_apply, ite_not]
@[simp]
theorem filter_ne_eq_erase' (f : Π₀ i, β i) (i : ι) : f.filter (i ≠ ·) = f.erase i := by
rw [← filter_ne_eq_erase f i]
congr with j
exact ne_comm
theorem erase_single (j : ι) (i : ι) (x : β i) :
(single i x).erase j = if i = j then 0 else single i x := by
rw [← filter_ne_eq_erase, filter_single, ite_not]
@[simp]
theorem erase_single_same (i : ι) (x : β i) : (single i x).erase i = 0 := by
rw [erase_single, if_pos rfl]
@[simp]
theorem erase_single_ne {i j : ι} (x : β i) (h : i ≠ j) : (single i x).erase j = single i x := by
rw [erase_single, if_neg h]
section Update
variable (f : Π₀ i, β i) (i) (b : β i)
/-- Replace the value of a `Π₀ i, β i` at a given point `i : ι` by a given value `b : β i`.
If `b = 0`, this amounts to removing `i` from the support.
Otherwise, `i` is added to it.
This is the (dependent) finitely-supported version of `Function.update`. -/
def update : Π₀ i, β i :=
⟨Function.update f i b,
f.support'.map fun s =>
⟨i ::ₘ s.1, fun j => by
rcases eq_or_ne i j with (rfl | hi)
· simp
· obtain hj | (hj : f j = 0) := s.prop j
· exact Or.inl (Multiset.mem_cons_of_mem hj)
· exact Or.inr ((Function.update_of_ne hi.symm b _).trans hj)⟩⟩
variable (j : ι)
@[simp, norm_cast] lemma coe_update : (f.update i b : ∀ i : ι, β i) = Function.update f i b := rfl
@[simp]
theorem update_self : f.update i (f i) = f := by
ext
simp
@[simp]
theorem update_eq_erase : f.update i 0 = f.erase i := by
ext j
rcases eq_or_ne i j with (rfl | hi)
· simp
· simp [hi.symm]
theorem update_eq_single_add_erase {β : ι → Type*} [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i)
(i : ι) (b : β i) : f.update i b = single i b + f.erase i := by
ext j
rcases eq_or_ne i j with (rfl | h)
· simp
· simp [h, h.symm]
theorem update_eq_erase_add_single {β : ι → Type*} [∀ i, AddZeroClass (β i)] (f : Π₀ i, β i)
(i : ι) (b : β i) : f.update i b = f.erase i + single i b := by
ext j
rcases eq_or_ne i j with (rfl | h)
· simp
· simp [h, h.symm]
theorem update_eq_sub_add_single {β : ι → Type*} [∀ i, AddGroup (β i)] (f : Π₀ i, β i) (i : ι)
(b : β i) : f.update i b = f - single i (f i) + single i b := by
rw [update_eq_erase_add_single f i b, erase_eq_sub_single f i]
end Update
end Basic
section DecidableEq
variable [DecidableEq ι]
section AddMonoid
variable [∀ i, AddZeroClass (β i)]
@[simp]
theorem single_add (i : ι) (b₁ b₂ : β i) : single i (b₁ + b₂) = single i b₁ + single i b₂ :=
(zipWith_single_single (fun _ => (· + ·)) _ b₁ b₂).symm
@[simp]
theorem erase_add (i : ι) (f₁ f₂ : Π₀ i, β i) : erase i (f₁ + f₂) = erase i f₁ + erase i f₂ :=
ext fun _ => by simp [ite_zero_add]
variable (β)
/-- `DFinsupp.single` as an `AddMonoidHom`. -/
@[simps]
def singleAddHom (i : ι) : β i →+ Π₀ i, β i where
toFun := single i
map_zero' := single_zero i
map_add' := single_add i
/-- `DFinsupp.erase` as an `AddMonoidHom`. -/
@[simps]
def eraseAddHom (i : ι) : (Π₀ i, β i) →+ Π₀ i, β i where
toFun := erase i
map_zero' := erase_zero i
map_add' := erase_add i
variable {β}
@[simp]
theorem single_neg {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (x : β i) :
single i (-x) = -single i x :=
(singleAddHom β i).map_neg x
@[simp]
theorem single_sub {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (x y : β i) :
single i (x - y) = single i x - single i y :=
(singleAddHom β i).map_sub x y
@[simp]
theorem erase_neg {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (f : Π₀ i, β i) :
(-f).erase i = -f.erase i :=
(eraseAddHom β i).map_neg f
@[simp]
theorem erase_sub {β : ι → Type v} [∀ i, AddGroup (β i)] (i : ι) (f g : Π₀ i, β i) :
(f - g).erase i = f.erase i - g.erase i :=
(eraseAddHom β i).map_sub f g
theorem single_add_erase (i : ι) (f : Π₀ i, β i) : single i (f i) + f.erase i = f :=
ext fun i' =>
if h : i = i' then by
subst h; simp only [add_apply, single_apply, erase_apply, add_zero, dite_eq_ite, if_true]
else by
simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (Ne.symm h), zero_add]
theorem erase_add_single (i : ι) (f : Π₀ i, β i) : f.erase i + single i (f i) = f :=
ext fun i' =>
if h : i = i' then by
subst h; simp only [add_apply, single_apply, erase_apply, zero_add, dite_eq_ite, if_true]
else by
simp only [add_apply, single_apply, erase_apply, dif_neg h, if_neg (Ne.symm h), add_zero]
protected theorem induction {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0)
(ha : ∀ (i b) (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (single i b + f)) : p f := by
obtain ⟨f, s⟩ := f
induction s using Trunc.induction_on with | _ s
obtain ⟨s, H⟩ := s
induction s using Multiset.induction_on generalizing f with
| empty =>
have : f = 0 := funext fun i => (H i).resolve_left (Multiset.notMem_zero _)
subst this
exact h0
| cons i s ih => ?_
have H2 : p (erase i ⟨f, Trunc.mk ⟨i ::ₘ s, H⟩⟩) := by
dsimp only [erase, Trunc.map, Trunc.bind, Trunc.liftOn, Trunc.lift_mk,
Function.comp, Subtype.coe_mk]
have H2 : ∀ j, j ∈ s ∨ ite (j = i) 0 (f j) = 0 := by
intro j
rcases H j with H2 | H2
· rcases Multiset.mem_cons.1 H2 with H3 | H3
· right; exact if_pos H3
· left; exact H3
right
split_ifs <;> [rfl; exact H2]
have H3 : ∀ aux, (⟨fun j : ι => ite (j = i) 0 (f j), Trunc.mk ⟨i ::ₘ s, aux⟩⟩ : Π₀ i, β i) =
⟨fun j : ι => ite (j = i) 0 (f j), Trunc.mk ⟨s, H2⟩⟩ :=
fun _ ↦ ext fun _ => rfl
rw [H3]
apply ih
have H3 : single i _ + _ = (⟨f, Trunc.mk ⟨i ::ₘ s, H⟩⟩ : Π₀ i, β i) := single_add_erase _ _
rw [← H3]
change p (single i (f i) + _)
rcases Classical.em (f i = 0) with h | h
· rw [h, single_zero, zero_add]
exact H2
refine ha _ _ _ ?_ h H2
rw [erase_same]
theorem induction₂ {p : (Π₀ i, β i) → Prop} (f : Π₀ i, β i) (h0 : p 0)
(ha : ∀ (i b) (f : Π₀ i, β i), f i = 0 → b ≠ 0 → p f → p (f + single i b)) : p f :=
DFinsupp.induction f h0 fun i b f h1 h2 h3 =>
have h4 : f + single i b = single i b + f := by
ext j; by_cases H : i = j
· subst H
simp [h1]
· simp [H]
Eq.recOn h4 <| ha i b f h1 h2 h3
end AddMonoid
@[simp]
theorem mk_add [∀ i, AddZeroClass (β i)] {s : Finset ι} {x y : ∀ i : (↑s : Set ι), β i} :
mk s (x + y) = mk s x + mk s y :=
ext fun i => by simp only [add_apply, mk_apply]; split_ifs <;> [rfl; rw [zero_add]]
@[simp]
theorem mk_zero [∀ i, Zero (β i)] {s : Finset ι} : mk s (0 : ∀ i : (↑s : Set ι), β i.1) = 0 :=
ext fun i => by simp only [mk_apply]; split_ifs <;> rfl
@[simp]
theorem mk_neg [∀ i, AddGroup (β i)] {s : Finset ι} {x : ∀ i : (↑s : Set ι), β i.1} :
mk s (-x) = -mk s x :=
ext fun i => by simp only [neg_apply, mk_apply]; split_ifs <;> [rfl; rw [neg_zero]]
@[simp]
theorem mk_sub [∀ i, AddGroup (β i)] {s : Finset ι} {x y : ∀ i : (↑s : Set ι), β i.1} :
mk s (x - y) = mk s x - mk s y :=
ext fun i => by simp only [sub_apply, mk_apply]; split_ifs <;> [rfl; rw [sub_zero]]
/-- If `s` is a subset of `ι` then `mk_addGroupHom s` is the canonical additive
group homomorphism from $\prod_{i\in s}\beta_i$ to $\prod_{\mathtt{i : \iota}}\beta_i$. -/
def mkAddGroupHom [∀ i, AddGroup (β i)] (s : Finset ι) :
(∀ i : (s : Set ι), β ↑i) →+ Π₀ i : ι, β i where
toFun := mk s
map_zero' := mk_zero
map_add' _ _ := mk_add
section SupportBasic
variable [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
/-- Set `{i | f x ≠ 0}` as a `Finset`. -/
def support (f : Π₀ i, β i) : Finset ι :=
(f.support'.lift fun xs => (Multiset.toFinset xs.1).filter fun i => f i ≠ 0) <| by
rintro ⟨sx, hx⟩ ⟨sy, hy⟩
dsimp only [Subtype.coe_mk, toFun_eq_coe] at *
ext i; constructor
· intro H
rcases Finset.mem_filter.1 H with ⟨_, h⟩
exact Finset.mem_filter.2 ⟨Multiset.mem_toFinset.2 <| (hy i).resolve_right h, h⟩
· intro H
rcases Finset.mem_filter.1 H with ⟨_, h⟩
exact Finset.mem_filter.2 ⟨Multiset.mem_toFinset.2 <| (hx i).resolve_right h, h⟩
@[simp]
theorem support_mk_subset {s : Finset ι} {x : ∀ i : (↑s : Set ι), β i.1} : (mk s x).support ⊆ s :=
fun _ H => Multiset.mem_toFinset.1 (Finset.mem_filter.1 H).1
@[simp]
theorem support_mk'_subset {f : ∀ i, β i} {s : Multiset ι} {h} :
(mk' f <| Trunc.mk ⟨s, h⟩).support ⊆ s.toFinset := fun i H =>
Multiset.mem_toFinset.1 <| by simpa using (Finset.mem_filter.1 H).1
@[simp]
theorem mem_support_toFun (f : Π₀ i, β i) (i) : i ∈ f.support ↔ f i ≠ 0 := by
obtain ⟨f, s⟩ := f
induction s using Trunc.induction_on with | _ s
dsimp only [support, Trunc.lift_mk]
rw [Finset.mem_filter, Multiset.mem_toFinset, coe_mk']
exact and_iff_right_of_imp (s.prop i).resolve_right
theorem eq_mk_support (f : Π₀ i, β i) : f = mk f.support fun i => f i := by aesop
/-- Equivalence between dependent functions with finite support `s : Finset ι` and functions
`∀ i, {x : β i // x ≠ 0}`. -/
@[simps]
def subtypeSupportEqEquiv (s : Finset ι) :
{f : Π₀ i, β i // f.support = s} ≃ ∀ i : s, {x : β i // x ≠ 0} where
toFun | ⟨f, hf⟩ => fun ⟨i, hi⟩ ↦ ⟨f i, (f.mem_support_toFun i).1 <| hf.symm ▸ hi⟩
invFun f := ⟨mk s fun i ↦ (f i).1, Finset.ext fun i ↦ by
-- TODO: `simp` fails to use `(f _).2` inside `∃ _, _`
calc
i ∈ support (mk s fun i ↦ (f i).1) ↔ ∃ h : i ∈ s, (f ⟨i, h⟩).1 ≠ 0 := by simp
_ ↔ ∃ _ : i ∈ s, True := exists_congr fun h ↦ (iff_true _).mpr (f _).2
_ ↔ i ∈ s := by simp⟩
left_inv := by
rintro ⟨f, rfl⟩
ext i
simpa using Eq.symm
right_inv f := by
ext1
simp
/-- Equivalence between all dependent finitely supported functions `f : Π₀ i, β i` and type
of pairs `⟨s : Finset ι, f : ∀ i : s, {x : β i // x ≠ 0}⟩`. -/
@[simps! apply_fst apply_snd_coe]
def sigmaFinsetFunEquiv : (Π₀ i, β i) ≃ Σ s : Finset ι, ∀ i : s, {x : β i // x ≠ 0} :=
(Equiv.sigmaFiberEquiv DFinsupp.support).symm.trans (.sigmaCongrRight subtypeSupportEqEquiv)
@[simp]
theorem support_zero : (0 : Π₀ i, β i).support = ∅ :=
rfl
theorem mem_support_iff {f : Π₀ i, β i} {i : ι} : i ∈ f.support ↔ f i ≠ 0 :=
f.mem_support_toFun _
theorem notMem_support_iff {f : Π₀ i, β i} {i : ι} : i ∉ f.support ↔ f i = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[deprecated (since := "2025-05-23")] alias not_mem_support_iff := notMem_support_iff
@[simp]
theorem support_eq_empty {f : Π₀ i, β i} : f.support = ∅ ↔ f = 0 :=
⟨fun H => ext <| by simpa [Finset.ext_iff] using H, by simp +contextual⟩
instance decidableZero [∀ (i) (x : β i), Decidable (x = 0)] (f : Π₀ i, β i) : Decidable (f = 0) :=
f.support'.recOnSubsingleton <| fun s =>
decidable_of_iff (∀ i ∈ s.val, f i = 0) <| by
constructor
case mpr => rintro rfl _ _; rfl
case mp =>
intro hs₁; ext i
-- This instance prevent consuming `DecidableEq ι` in the next `by_cases`.
letI := Classical.propDecidable
by_cases hs₂ : i ∈ s.val
case pos => exact hs₁ _ hs₂
case neg => exact (s.prop i).resolve_left hs₂
theorem support_subset_iff {s : Set ι} {f : Π₀ i, β i} : ↑f.support ⊆ s ↔ ∀ i ∉ s, f i = 0 := by
simpa [Set.subset_def] using forall_congr' fun i => not_imp_comm
theorem support_single_ne_zero {i : ι} {b : β i} (hb : b ≠ 0) : (single i b).support = {i} := by
ext j; by_cases h : i = j
· subst h
simp [hb]
simp [Ne.symm h, h]
theorem support_single_subset {i : ι} {b : β i} : (single i b).support ⊆ {i} :=
support_mk'_subset
section MapRangeAndZipWith
variable [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)]
theorem mapRange_def [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] {f : ∀ i, β₁ i → β₂ i}
{hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} :
mapRange f hf g = mk g.support fun i => f i.1 (g i.1) := by
ext i
by_cases h : g i ≠ 0 <;> simp at h <;> simp [h, hf]
@[simp]
theorem mapRange_single {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {i : ι} {b : β₁ i} :
mapRange f hf (single i b) = single i (f i b) :=
DFinsupp.ext fun i' => by
by_cases h : i = i'
· subst i'
simp
· simp [h, hf]
omit [DecidableEq ι] in
theorem mapRange_injective (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) :
Function.Injective (mapRange f hf) ↔ ∀ i, Function.Injective (f i) := by
classical exact ⟨fun h i x y eq ↦ single_injective (@h (single i x) (single i y) <| by
simpa using congr_arg _ eq), fun h _ _ eq ↦ DFinsupp.ext fun i ↦ h i congr($eq i)⟩
omit [DecidableEq ι] in
theorem mapRange_surjective (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0) :
Function.Surjective (mapRange f hf) ↔ ∀ i, Function.Surjective (f i) := by
classical
refine ⟨fun h i u ↦ ?_, fun h x ↦ ?_⟩
· obtain ⟨x, hx⟩ := h (single i u)
exact ⟨x i, by simpa using congr($hx i)⟩
· obtain ⟨x, s, hs⟩ := x
have (i : ι) : ∃ u : β₁ i, f i u = x i ∧ (x i = 0 → u = 0) :=
(eq_or_ne (x i) 0).elim
(fun h ↦ ⟨0, (hf i).trans h.symm, fun _ ↦ rfl⟩)
(fun h' ↦ by
obtain ⟨u, hu⟩ := h i (x i)
exact ⟨u, hu, fun h'' ↦ (h' h'').elim⟩)
choose y hy using this
refine ⟨⟨y, Trunc.mk ⟨s, fun i ↦ ?_⟩⟩, ext fun i ↦ ?_⟩
· exact (hs i).imp_right (hy i).2
· simp [(hy i).1]
variable [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i) (x : β₂ i), Decidable (x ≠ 0)]
theorem support_mapRange {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} :
(mapRange f hf g).support ⊆ g.support := by simp [mapRange_def]
theorem zipWith_def {ι : Type u} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
[dec : DecidableEq ι] [∀ i : ι, Zero (β i)] [∀ i : ι, Zero (β₁ i)] [∀ i : ι, Zero (β₂ i)]
[∀ (i : ι) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i : ι) (x : β₂ i), Decidable (x ≠ 0)]
{f : ∀ i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i} {g₂ : Π₀ i, β₂ i} :
zipWith f hf g₁ g₂ = mk (g₁.support ∪ g₂.support) fun i => f i.1 (g₁ i.1) (g₂ i.1) := by
ext i
by_cases h1 : g₁ i ≠ 0 <;> by_cases h2 : g₂ i ≠ 0 <;> simp only [not_not, Ne] at h1 h2 <;>
simp [h1, h2, hf]
theorem support_zipWith {f : ∀ i, β₁ i → β₂ i → β i} {hf : ∀ i, f i 0 0 = 0} {g₁ : Π₀ i, β₁ i}
{g₂ : Π₀ i, β₂ i} : (zipWith f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by
simp [zipWith_def]
end MapRangeAndZipWith
theorem erase_def (i : ι) (f : Π₀ i, β i) : f.erase i = mk (f.support.erase i) fun j => f j.1 := by
ext j
by_cases h1 : j = i <;> by_cases h2 : f j ≠ 0 <;> simp at h2 <;> simp [h1, h2]
@[simp]
theorem support_erase (i : ι) (f : Π₀ i, β i) : (f.erase i).support = f.support.erase i := by
ext
simp
theorem support_update_ne_zero (f : Π₀ i, β i) (i : ι) {b : β i} (h : b ≠ 0) :
support (f.update i b) = insert i f.support := by
ext j
rcases eq_or_ne i j with (rfl | hi)
· simp [h]
· simp [hi.symm]
theorem support_update (f : Π₀ i, β i) (i : ι) (b : β i) [Decidable (b = 0)] :
support (f.update i b) = if b = 0 then support (f.erase i) else insert i f.support := by
ext j
split_ifs with hb
· subst hb
simp [update_eq_erase, support_erase]
· rw [support_update_ne_zero f _ hb]
section FilterAndSubtypeDomain
variable {p : ι → Prop} [DecidablePred p]
theorem filter_def (f : Π₀ i, β i) : f.filter p = mk (f.support.filter p) fun i => f i.1 := by
ext i; by_cases h1 : p i <;> by_cases h2 : f i ≠ 0 <;> simp at h2 <;> simp [h1, h2]
@[simp]
theorem support_filter (f : Π₀ i, β i) : (f.filter p).support = {x ∈ f.support | p x} := by
ext i; by_cases h : p i <;> simp [h]
theorem subtypeDomain_def (f : Π₀ i, β i) :
f.subtypeDomain p = mk (f.support.subtype p) fun i => f i := by
ext i; by_cases h2 : f i ≠ 0 <;> try simp at h2; simp [h2]
@[simp]
theorem support_subtypeDomain {f : Π₀ i, β i} :
(subtypeDomain p f).support = f.support.subtype p := by
ext i
simp
end FilterAndSubtypeDomain
end SupportBasic
theorem support_add [∀ i, AddZeroClass (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
{g₁ g₂ : Π₀ i, β i} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zipWith
@[simp]
theorem support_neg [∀ i, AddGroup (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] {f : Π₀ i, β i} :
support (-f) = support f := by ext i; simp
instance [∀ i, Zero (β i)] [∀ i, DecidableEq (β i)] : DecidableEq (Π₀ i, β i) := fun f g =>
decidable_of_iff (f.support = g.support ∧ ∀ i ∈ f.support, f i = g i)
⟨fun ⟨h₁, h₂⟩ => ext fun i => if h : i ∈ f.support then h₂ i h else by
have hf : f i = 0 := by rwa [mem_support_iff, not_not] at h
have hg : g i = 0 := by rwa [h₁, mem_support_iff, not_not] at h
rw [hf, hg],
by rintro rfl; simp⟩
end DecidableEq
section Equiv
open Finset
variable {κ : Type*}
/-- Reindexing (and possibly removing) terms of a dfinsupp. -/
noncomputable def comapDomain [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h)
(f : Π₀ i, β i) : Π₀ k, β (h k) where
toFun x := f (h x)
support' :=
f.support'.map fun s =>
⟨(s.1.finite_toSet.preimage hh.injOn).toFinset.val, fun x =>
(s.prop (h x)).imp_left fun hx => (Set.Finite.mem_toFinset _).mpr <| hx⟩
@[simp]
theorem comapDomain_apply [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h) (f : Π₀ i, β i)
(k : κ) : comapDomain h hh f k = f (h k) :=
rfl
@[simp]
theorem comapDomain_zero [∀ i, Zero (β i)] (h : κ → ι) (hh : Function.Injective h) :
comapDomain h hh (0 : Π₀ i, β i) = 0 := by
ext
rw [zero_apply, comapDomain_apply, zero_apply]
@[simp]
theorem comapDomain_add [∀ i, AddZeroClass (β i)] (h : κ → ι) (hh : Function.Injective h)
(f g : Π₀ i, β i) : comapDomain h hh (f + g) = comapDomain h hh f + comapDomain h hh g := by
ext
rw [add_apply, comapDomain_apply, comapDomain_apply, comapDomain_apply, add_apply]
@[simp]
theorem comapDomain_single [DecidableEq ι] [DecidableEq κ] [∀ i, Zero (β i)] (h : κ → ι)
(hh : Function.Injective h) (k : κ) (x : β (h k)) :
comapDomain h hh (single (h k) x) = single k x := by
ext i
rw [comapDomain_apply]
obtain rfl | hik := Decidable.eq_or_ne i k
· rw [single_eq_same, single_eq_same]
· rw [single_eq_of_ne hik, single_eq_of_ne (hh.ne hik)]
/-- A computable version of comap_domain when an explicit left inverse is provided. -/
def comapDomain' [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ} (hh' : Function.LeftInverse h' h)
(f : Π₀ i, β i) : Π₀ k, β (h k) where
toFun x := f (h x)
support' :=
f.support'.map fun s =>
⟨Multiset.map h' s.1, fun x =>
(s.prop (h x)).imp_left fun hx => Multiset.mem_map.mpr ⟨_, hx, hh' _⟩⟩
@[simp]
theorem comapDomain'_apply [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ}
(hh' : Function.LeftInverse h' h) (f : Π₀ i, β i) (k : κ) : comapDomain' h hh' f k = f (h k) :=
rfl
@[simp]
theorem comapDomain'_zero [∀ i, Zero (β i)] (h : κ → ι) {h' : ι → κ}
(hh' : Function.LeftInverse h' h) : comapDomain' h hh' (0 : Π₀ i, β i) = 0 := by
ext
rw [zero_apply, comapDomain'_apply, zero_apply]
@[simp]
theorem comapDomain'_add [∀ i, AddZeroClass (β i)] (h : κ → ι) {h' : ι → κ}
(hh' : Function.LeftInverse h' h) (f g : Π₀ i, β i) :
comapDomain' h hh' (f + g) = comapDomain' h hh' f + comapDomain' h hh' g := by
ext
rw [add_apply, comapDomain'_apply, comapDomain'_apply, comapDomain'_apply, add_apply]
@[simp]
theorem comapDomain'_single [DecidableEq ι] [DecidableEq κ] [∀ i, Zero (β i)] (h : κ → ι)
{h' : ι → κ} (hh' : Function.LeftInverse h' h) (k : κ) (x : β (h k)) :
comapDomain' h hh' (single (h k) x) = single k x := by
ext i
rw [comapDomain'_apply]
obtain rfl | hik := Decidable.eq_or_ne i k
· rw [single_eq_same, single_eq_same]
· rw [single_eq_of_ne hik, single_eq_of_ne (hh'.injective.ne hik)]
/-- Reindexing terms of a dfinsupp.
This is the dfinsupp version of `Equiv.piCongrLeft'`. -/
@[simps apply]
def equivCongrLeft [∀ i, Zero (β i)] (h : ι ≃ κ) : (Π₀ i, β i) ≃ Π₀ k, β (h.symm k) where
toFun := comapDomain' h.symm h.right_inv
invFun f :=
mapRange (fun i => Equiv.cast <| congr_arg β <| h.symm_apply_apply i)
(fun i => (Equiv.cast_eq_iff_heq _).mpr <| by rw [Equiv.symm_apply_apply])
(@comapDomain' _ _ _ _ h _ h.left_inv f)
left_inv f := by
ext i
rw [mapRange_apply, comapDomain'_apply, comapDomain'_apply, Equiv.cast_eq_iff_heq,
h.symm_apply_apply]
right_inv f := by
ext k
rw [comapDomain'_apply, mapRange_apply, comapDomain'_apply, Equiv.cast_eq_iff_heq,
h.apply_symm_apply]
section SigmaCurry
variable {α : ι → Type*} {δ : ∀ i, α i → Type v}
instance hasAdd₂ [∀ i j, AddZeroClass (δ i j)] : Add (Π₀ (i : ι) (j : α i), δ i j) :=
inferInstance
instance addZeroClass₂ [∀ i j, AddZeroClass (δ i j)] : AddZeroClass (Π₀ (i : ι) (j : α i), δ i j) :=
inferInstance
instance addMonoid₂ [∀ i j, AddMonoid (δ i j)] : AddMonoid (Π₀ (i : ι) (j : α i), δ i j) :=
inferInstance
end SigmaCurry
variable {α : Option ι → Type v}
/-- Adds a term to a dfinsupp, making a dfinsupp indexed by an `Option`.
This is the dfinsupp version of `Option.rec`. -/
def extendWith [∀ i, Zero (α i)] (a : α none) (f : Π₀ i, α (some i)) : Π₀ i, α i where
toFun := fun i ↦ match i with | none => a | some _ => f _
support' :=
f.support'.map fun s =>
⟨none ::ₘ Multiset.map some s.1, fun i =>
Option.rec (Or.inl <| Multiset.mem_cons_self _ _)
(fun i =>
(s.prop i).imp_left fun h => Multiset.mem_cons_of_mem <| Multiset.mem_map_of_mem _ h)
i⟩
@[simp]
theorem extendWith_none [∀ i, Zero (α i)] (f : Π₀ i, α (some i)) (a : α none) :
f.extendWith a none = a :=
rfl
@[simp]
theorem extendWith_some [∀ i, Zero (α i)] (f : Π₀ i, α (some i)) (a : α none) (i : ι) :
f.extendWith a (some i) = f i :=
rfl
@[simp]
theorem extendWith_single_zero [DecidableEq ι] [∀ i, Zero (α i)] (i : ι) (x : α (some i)) :
(single i x).extendWith 0 = single (some i) x := by
ext (_ | j)
· rw [extendWith_none, single_eq_of_ne (Option.some_ne_none _).symm]
· rw [extendWith_some]
obtain rfl | hij := Decidable.eq_or_ne j i
· rw [single_eq_same, single_eq_same]
· rw [single_eq_of_ne hij, single_eq_of_ne ((Option.some_injective _).ne hij)]
@[simp]
theorem extendWith_zero [DecidableEq ι] [∀ i, Zero (α i)] (x : α none) :
(0 : Π₀ i, α (some i)).extendWith x = single none x := by
ext (_ | j)
· rw [extendWith_none, single_eq_same]
· rw [extendWith_some, single_eq_of_ne (Option.some_ne_none _), zero_apply]
/-- Bijection obtained by separating the term of index `none` of a dfinsupp over `Option ι`.
This is the dfinsupp version of `Equiv.piOptionEquivProd`. -/
@[simps]
noncomputable def equivProdDFinsupp [∀ i, Zero (α i)] :
(Π₀ i, α i) ≃ α none × Π₀ i, α (some i) where
toFun f := (f none, comapDomain some (Option.some_injective _) f)
invFun f := f.2.extendWith f.1
left_inv f := by
ext i; obtain - | i := i
· rw [extendWith_none]
· rw [extendWith_some, comapDomain_apply]
right_inv x := by
dsimp only
ext
· exact extendWith_none x.snd _
· rw [comapDomain_apply, extendWith_some]
theorem equivProdDFinsupp_add [∀ i, AddZeroClass (α i)] (f g : Π₀ i, α i) :
equivProdDFinsupp (f + g) = equivProdDFinsupp f + equivProdDFinsupp g :=
Prod.ext (add_apply _ _ _) (comapDomain_add _ (Option.some_injective _) _ _)
end Equiv
/-! ### Bundled versions of `DFinsupp.mapRange`
The names should match the equivalent bundled `Finsupp.mapRange` definitions.
-/
section MapRange
variable [∀ i, AddZeroClass (β i)] [∀ i, AddZeroClass (β₁ i)] [∀ i, AddZeroClass (β₂ i)]
theorem mapRange_add (f : ∀ i, β₁ i → β₂ i) (hf : ∀ i, f i 0 = 0)
(hf' : ∀ i x y, f i (x + y) = f i x + f i y) (g₁ g₂ : Π₀ i, β₁ i) :
mapRange f hf (g₁ + g₂) = mapRange f hf g₁ + mapRange f hf g₂ := by
ext
simp only [mapRange_apply f, coe_add, Pi.add_apply, hf']
/-- `DFinsupp.mapRange` as an `AddMonoidHom`. -/
@[simps apply]
def mapRange.addMonoidHom (f : ∀ i, β₁ i →+ β₂ i) : (Π₀ i, β₁ i) →+ Π₀ i, β₂ i where
toFun := mapRange (fun i x => f i x) fun i => (f i).map_zero
map_zero' := mapRange_zero _ _
map_add' := mapRange_add _ (fun i => (f i).map_zero) fun i => (f i).map_add
@[simp]
theorem mapRange.addMonoidHom_id :
(mapRange.addMonoidHom fun i => AddMonoidHom.id (β₂ i)) = AddMonoidHom.id _ :=
AddMonoidHom.ext mapRange_id
theorem mapRange.addMonoidHom_comp (f : ∀ i, β₁ i →+ β₂ i) (f₂ : ∀ i, β i →+ β₁ i) :
(mapRange.addMonoidHom fun i => (f i).comp (f₂ i)) =
(mapRange.addMonoidHom f).comp (mapRange.addMonoidHom f₂) := by
refine AddMonoidHom.ext <| mapRange_comp (fun i x => f i x) (fun i x => f₂ i x) ?_ ?_ ?_
· intros; apply map_zero
· intros; apply map_zero
· intros; dsimp; simp only [map_zero]
/-- `DFinsupp.mapRange.addMonoidHom` as an `AddEquiv`. -/
@[simps apply]
def mapRange.addEquiv (e : ∀ i, β₁ i ≃+ β₂ i) : (Π₀ i, β₁ i) ≃+ Π₀ i, β₂ i :=
{ mapRange.addMonoidHom fun i =>
(e i).toAddMonoidHom with
toFun := mapRange (fun i x => e i x) fun i => (e i).map_zero
invFun := mapRange (fun i x => (e i).symm x) fun i => (e i).symm.map_zero
left_inv := fun x => by
rw [← mapRange_comp] <;>
· simp_rw [AddEquiv.symm_comp_self]
simp
right_inv := fun x => by
rw [← mapRange_comp] <;>
· simp_rw [AddEquiv.self_comp_symm]
simp }
@[simp]
theorem mapRange.addEquiv_refl :
(mapRange.addEquiv fun i => AddEquiv.refl (β₁ i)) = AddEquiv.refl _ :=
AddEquiv.ext mapRange_id
theorem mapRange.addEquiv_trans (f : ∀ i, β i ≃+ β₁ i) (f₂ : ∀ i, β₁ i ≃+ β₂ i) :
(mapRange.addEquiv fun i => (f i).trans (f₂ i)) =
(mapRange.addEquiv f).trans (mapRange.addEquiv f₂) := by
ext
simp
@[simp]
theorem mapRange.addEquiv_symm (e : ∀ i, β₁ i ≃+ β₂ i) :
(mapRange.addEquiv e).symm = mapRange.addEquiv fun i => (e i).symm :=
rfl
end MapRange
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Submonoid.lean | import Mathlib.Algebra.Group.Submonoid.BigOperators
import Mathlib.Algebra.Group.Submonoid.Membership
import Mathlib.Data.DFinsupp.BigOperators
import Mathlib.Order.ConditionallyCompleteLattice.Basic
/-!
# `DFinsupp` and submonoids
This file mainly concerns the interaction between submonoids and products/sums of `DFinsupp`s.
## Main results
* `AddSubmonoid.mem_iSup_iff_exists_dfinsupp`: elements of the supremum of additive commutative
monoids can be given by taking finite sums of elements of each monoid.
* `AddSubmonoid.mem_bsupr_iff_exists_dfinsupp`: elements of the supremum of additive commutative
monoids can be given by taking finite sums of elements of each monoid.
-/
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
open DFinsupp
variable [DecidableEq ι]
@[to_additive]
theorem dfinsuppProd_mem [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[CommMonoid γ] {S : Type*} [SetLike S γ] [SubmonoidClass S γ]
(s : S) (f : Π₀ i, β i) (g : ∀ i, β i → γ)
(h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : f.prod g ∈ s :=
prod_mem fun _ hi => h _ <| mem_support_iff.1 hi
theorem dfinsuppSumAddHom_mem [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] {S : Type*}
[SetLike S γ] [AddSubmonoidClass S γ] (s : S) (f : Π₀ i, β i) (g : ∀ i, β i →+ γ)
(h : ∀ c, f c ≠ 0 → g c (f c) ∈ s) : DFinsupp.sumAddHom g f ∈ s := by
classical
rw [DFinsupp.sumAddHom_apply]
exact dfinsuppSum_mem s f (g ·) h
/-- The supremum of a family of commutative additive submonoids is equal to the range of
`DFinsupp.sumAddHom`; that is, every element in the `iSup` can be produced from taking a finite
number of non-zero elements of `S i`, coercing them to `γ`, and summing them. -/
theorem AddSubmonoid.iSup_eq_mrange_dfinsuppSumAddHom
[AddCommMonoid γ] (S : ι → AddSubmonoid γ) :
iSup S = AddMonoidHom.mrange (DFinsupp.sumAddHom fun i => (S i).subtype) := by
apply le_antisymm
· apply iSup_le _
intro i y hy
exact ⟨DFinsupp.single i ⟨y, hy⟩, DFinsupp.sumAddHom_single _ _ _⟩
· rintro x ⟨v, rfl⟩
exact dfinsuppSumAddHom_mem _ v _ fun i _ => (le_iSup S i : S i ≤ _) (v i).prop
/-- The bounded supremum of a family of commutative additive submonoids is equal to the range of
`DFinsupp.sumAddHom` composed with `DFinsupp.filterAddMonoidHom`; that is, every element in the
bounded `iSup` can be produced from taking a finite number of non-zero elements from the `S i` that
satisfy `p i`, coercing them to `γ`, and summing them. -/
theorem AddSubmonoid.bsupr_eq_mrange_dfinsuppSumAddHom (p : ι → Prop) [DecidablePred p]
[AddCommMonoid γ] (S : ι → AddSubmonoid γ) :
⨆ (i) (_ : p i), S i =
AddMonoidHom.mrange ((sumAddHom fun i => (S i).subtype).comp (filterAddMonoidHom _ p)) := by
apply le_antisymm
· refine iSup₂_le fun i hi y hy => ⟨DFinsupp.single i ⟨y, hy⟩, ?_⟩
rw [AddMonoidHom.comp_apply, filterAddMonoidHom_apply, filter_single_pos _ _ hi]
exact sumAddHom_single _ _ _
· rintro x ⟨v, rfl⟩
refine dfinsuppSumAddHom_mem _ _ _ fun i _ => ?_
refine AddSubmonoid.mem_iSup_of_mem i ?_
by_cases hp : p i
· simp [hp]
· simp [hp]
theorem AddSubmonoid.mem_iSup_iff_exists_dfinsupp [AddCommMonoid γ] (S : ι → AddSubmonoid γ)
(x : γ) : x ∈ iSup S ↔ ∃ f : Π₀ i, S i, DFinsupp.sumAddHom (fun i => (S i).subtype) f = x :=
SetLike.ext_iff.mp (AddSubmonoid.iSup_eq_mrange_dfinsuppSumAddHom S) x
/-- A variant of `AddSubmonoid.mem_iSup_iff_exists_dfinsupp` with the RHS fully unfolded. -/
theorem AddSubmonoid.mem_iSup_iff_exists_dfinsupp' [AddCommMonoid γ] (S : ι → AddSubmonoid γ)
[∀ (i) (x : S i), Decidable (x ≠ 0)] (x : γ) :
x ∈ iSup S ↔ ∃ f : Π₀ i, S i, (f.sum fun _ xi => ↑xi) = x := by
rw [AddSubmonoid.mem_iSup_iff_exists_dfinsupp]
simp_rw [sumAddHom_apply]
rfl
theorem AddSubmonoid.mem_bsupr_iff_exists_dfinsupp (p : ι → Prop) [DecidablePred p]
[AddCommMonoid γ] (S : ι → AddSubmonoid γ) (x : γ) :
(x ∈ ⨆ (i) (_ : p i), S i) ↔
∃ f : Π₀ i, S i, DFinsupp.sumAddHom (fun i => (S i).subtype) (f.filter p) = x :=
SetLike.ext_iff.mp (AddSubmonoid.bsupr_eq_mrange_dfinsuppSumAddHom p S) x |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Small.lean | import Mathlib.Data.Finsupp.ToDFinsupp
import Mathlib.Data.DFinsupp.Defs
import Mathlib.Logic.Small.Basic
/-!
# Smallness of the `DFinsupp` type
Let `π : ι → Type v`. If `ι` and all the `π i` are `w`-small, this provides a `Small.{w}`
instance on `DFinsupp π`.
As an application, `σ →₀ R` has a `Small.{v}` instance if `σ` and `R` have one.
-/
universe u v w
variable {ι : Type u} {π : ι → Type v} [∀ i, Zero (π i)]
section Small
instance DFinsupp.small [Small.{w} ι] [∀ (i : ι), Small.{w} (π i)] :
Small.{w} (DFinsupp π) :=
small_of_injective (f := fun x j ↦ x j) (fun f f' eq ↦ by ext j; exact congr_fun eq j)
instance Finsupp.small {σ : Type*} {R : Type*} [Zero R]
[Small.{u} R] [Small.{u} σ] :
Small.{u} (σ →₀ R) := by
classical
exact small_map finsuppEquivDFinsupp
end Small |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/BigOperators.lean | import Mathlib.Algebra.BigOperators.GroupWithZero.Action
import Mathlib.Data.DFinsupp.Ext
/-!
# Dependent functions with finite support
For a non-dependent version see `Mathlib/Data/Finsupp/Defs.lean`.
## Notation
This file introduces the notation `Π₀ a, β a` as notation for `DFinsupp β`, mirroring the `α →₀ β`
notation used for `Finsupp`. This works for nested binders too, with `Π₀ a b, γ a b` as notation
for `DFinsupp (fun a ↦ DFinsupp (γ a))`.
## Implementation notes
The support is internally represented (in the primed `DFinsupp.support'`) as a `Multiset` that
represents a superset of the true support of the function, quotiented by the always-true relation so
that this does not impact equality. This approach has computational benefits over storing a
`Finset`; it allows us to add together two finitely-supported functions without
having to evaluate the resulting function to recompute its support (which would required
decidability of `b = 0` for `b : β i`).
The true support of the function can still be recovered with `DFinsupp.support`; but these
decidability obligations are now postponed to when the support is actually needed. As a consequence,
there are two ways to sum a `DFinsupp`: with `DFinsupp.sum` which works over an arbitrary function
but requires recomputation of the support and therefore a `Decidable` argument; and with
`DFinsupp.sumAddHom` which requires an additive morphism, using its properties to show that
summing over a superset of the support is sufficient.
`Finsupp` takes an altogether different approach here; it uses `Classical.Decidable` and declares
the `Add` instance as noncomputable. This design difference is independent of the fact that
`DFinsupp` is dependently-typed and `Finsupp` is not; in future, we may want to align these two
definitions, or introduce two more definitions for the other combinations of decisions.
-/
universe u u₁ u₂ v v₁ v₂ v₃ w x y l
variable {ι : Type u} {γ : Type w} {β : ι → Type v} {β₁ : ι → Type v₁} {β₂ : ι → Type v₂}
namespace DFinsupp
section Algebra
/-- Evaluation at a point is an `AddMonoidHom`. This is the finitely-supported version of
`Pi.evalAddMonoidHom`. -/
def evalAddMonoidHom [∀ i, AddZeroClass (β i)] (i : ι) : (Π₀ i, β i) →+ β i :=
(Pi.evalAddMonoidHom β i).comp coeFnAddMonoidHom
@[simp, norm_cast]
theorem coe_finset_sum {α} [∀ i, AddCommMonoid (β i)] (s : Finset α) (g : α → Π₀ i, β i) :
⇑(∑ a ∈ s, g a) = ∑ a ∈ s, ⇑(g a) :=
map_sum coeFnAddMonoidHom g s
@[simp]
theorem finset_sum_apply {α} [∀ i, AddCommMonoid (β i)] (s : Finset α) (g : α → Π₀ i, β i) (i : ι) :
(∑ a ∈ s, g a) i = ∑ a ∈ s, g a i :=
map_sum (evalAddMonoidHom i) g s
end Algebra
section ProdAndSum
variable [DecidableEq ι]
/-- `DFinsupp.prod f g` is the product of `g i (f i)` over the support of `f`. -/
@[to_additive /-- `sum f g` is the sum of `g i (f i)` over the support of `f`. -/]
def prod [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] (f : Π₀ i, β i)
(g : ∀ i, β i → γ) : γ :=
∏ i ∈ f.support, g i (f i)
@[to_additive (attr := simp)]
theorem _root_.map_dfinsuppProd
{R S H : Type*} [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[CommMonoid R] [CommMonoid S] [FunLike H R S] [MonoidHomClass H R S] (h : H) (f : Π₀ i, β i)
(g : ∀ i, β i → R) : h (f.prod g) = f.prod fun a b => h (g a b) :=
map_prod _ _ _
@[to_additive]
theorem prod_mapRange_index {β₁ : ι → Type v₁} {β₂ : ι → Type v₂} [∀ i, Zero (β₁ i)]
[∀ i, Zero (β₂ i)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ (i) (x : β₂ i), Decidable (x ≠ 0)]
[CommMonoid γ] {f : ∀ i, β₁ i → β₂ i} {hf : ∀ i, f i 0 = 0} {g : Π₀ i, β₁ i} {h : ∀ i, β₂ i → γ}
(h0 : ∀ i, h i 0 = 1) : (mapRange f hf g).prod h = g.prod fun i b => h i (f i b) := by
rw [mapRange_def]
refine (Finset.prod_subset support_mk_subset ?_).trans ?_
· intro i h1 h2
simp only [mem_support_toFun, ne_eq] at h1
simp only [Finset.coe_sort_coe, mem_support_toFun, mk_apply, ne_eq, h1, not_false_iff,
dite_eq_ite, ite_true, not_not] at h2
simp [h2, h0]
· refine Finset.prod_congr rfl ?_
intro i h1
simp only [mem_support_toFun, ne_eq] at h1
simp [h1]
@[to_additive]
theorem prod_zero_index [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[CommMonoid γ] {h : ∀ i, β i → γ} : (0 : Π₀ i, β i).prod h = 1 :=
rfl
@[to_additive]
theorem prod_single_index [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ]
{i : ι} {b : β i} {h : ∀ i, β i → γ} (h_zero : h i 0 = 1) : (single i b).prod h = h i b := by
by_cases h : b ≠ 0
· simp [DFinsupp.prod, support_single_ne_zero h]
· rw [not_not] at h
simp [h, h_zero]
rfl
@[to_additive]
theorem prod_neg_index [∀ i, AddGroup (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ]
{g : Π₀ i, β i} {h : ∀ i, β i → γ} (h0 : ∀ i, h i 0 = 1) :
(-g).prod h = g.prod fun i b => h i (-b) :=
prod_mapRange_index h0
@[to_additive]
theorem prod_comm {ι₁ ι₂ : Sort _} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} [DecidableEq ι₁]
[DecidableEq ι₂] [∀ i, Zero (β₁ i)] [∀ i, Zero (β₂ i)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)]
[∀ (i) (x : β₂ i), Decidable (x ≠ 0)] [CommMonoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i)
(h : ∀ i, β₁ i → ∀ i, β₂ i → γ) :
(f₁.prod fun i₁ x₁ => f₂.prod fun i₂ x₂ => h i₁ x₁ i₂ x₂) =
f₂.prod fun i₂ x₂ => f₁.prod fun i₁ x₁ => h i₁ x₁ i₂ x₂ :=
Finset.prod_comm
@[simp]
theorem sum_apply {ι} {β : ι → Type v} {ι₁ : Type u₁} [DecidableEq ι₁] {β₁ : ι₁ → Type v₁}
[∀ i₁, Zero (β₁ i₁)] [∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)]
{f : Π₀ i₁, β₁ i₁} {g : ∀ i₁, β₁ i₁ → Π₀ i, β i} {i₂ : ι} :
(f.sum g) i₂ = f.sum fun i₁ b => g i₁ b i₂ :=
map_sum (evalAddMonoidHom i₂) _ f.support
theorem support_sum {ι₁ : Type u₁} [DecidableEq ι₁] {β₁ : ι₁ → Type v₁} [∀ i₁, Zero (β₁ i₁)]
[∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)]
[∀ (i) (x : β i), Decidable (x ≠ 0)] {f : Π₀ i₁, β₁ i₁} {g : ∀ i₁, β₁ i₁ → Π₀ i, β i} :
(f.sum g).support ⊆ f.support.biUnion fun i => (g i (f i)).support := by
have :
∀ i₁ : ι,
(f.sum fun (i : ι₁) (b : β₁ i) => (g i b) i₁) ≠ 0 → ∃ i : ι₁, f i ≠ 0 ∧ ¬(g i (f i)) i₁ = 0 :=
fun i₁ h =>
let ⟨i, hi, Ne⟩ := Finset.exists_ne_zero_of_sum_ne_zero h
⟨i, mem_support_iff.1 hi, Ne⟩
simpa [Finset.subset_iff, mem_support_iff, Finset.mem_biUnion, sum_apply] using this
@[to_additive (attr := simp)]
theorem prod_one [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ]
{f : Π₀ i, β i} : (f.prod fun _ _ => (1 : γ)) = 1 :=
Finset.prod_const_one
@[to_additive (attr := simp)]
theorem prod_mul [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ]
{f : Π₀ i, β i} {h₁ h₂ : ∀ i, β i → γ} :
(f.prod fun i b => h₁ i b * h₂ i b) = f.prod h₁ * f.prod h₂ :=
Finset.prod_mul_distrib
@[to_additive (attr := simp)]
theorem prod_inv [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[DivisionCommMonoid γ] {f : Π₀ i, β i} {h : ∀ i, β i → γ} :
(f.prod fun i b => (h i b)⁻¹) = (f.prod h)⁻¹ :=
(map_prod (invMonoidHom : γ →* γ) _ f.support).symm
@[to_additive]
theorem prod_eq_one [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ]
{f : Π₀ i, β i} {h : ∀ i, β i → γ} (hyp : ∀ i, h i (f i) = 1) : f.prod h = 1 :=
Finset.prod_eq_one fun i _ => hyp i
theorem smul_sum {α : Type*} [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[AddCommMonoid γ] [DistribSMul α γ] {f : Π₀ i, β i} {h : ∀ i, β i → γ} {c : α} :
c • f.sum h = f.sum fun a b => c • h a b :=
Finset.smul_sum
@[to_additive]
theorem prod_add_index [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[CommMonoid γ] {f g : Π₀ i, β i} {h : ∀ i, β i → γ} (h_zero : ∀ i, h i 0 = 1)
(h_add : ∀ i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) : (f + g).prod h = f.prod h * g.prod h :=
have f_eq : (∏ i ∈ f.support ∪ g.support, h i (f i)) = f.prod h :=
(Finset.prod_subset Finset.subset_union_left <| by
simp +contextual [h_zero]).symm
have g_eq : (∏ i ∈ f.support ∪ g.support, h i (g i)) = g.prod h :=
(Finset.prod_subset Finset.subset_union_right <| by
simp +contextual [h_zero]).symm
calc
(∏ i ∈ (f + g).support, h i ((f + g) i)) = ∏ i ∈ f.support ∪ g.support, h i ((f + g) i) :=
Finset.prod_subset support_add <| by
simp +contextual [h_zero]
_ = (∏ i ∈ f.support ∪ g.support, h i (f i)) * ∏ i ∈ f.support ∪ g.support, h i (g i) := by
{ simp [h_add, Finset.prod_mul_distrib] }
_ = _ := by rw [f_eq, g_eq]
@[to_additive (attr := simp)]
theorem prod_eq_prod_fintype [Fintype ι] [∀ i, Zero (β i)] [∀ (i : ι) (x : β i), Decidable (x ≠ 0)]
[CommMonoid γ] (v : Π₀ i, β i) {f : ∀ i, β i → γ} (hf : ∀ i, f i 0 = 1) :
v.prod f = ∏ i, f i (DFinsupp.equivFunOnFintype v i) := by
suffices (∏ i ∈ v.support, f i (v i)) = ∏ i, f i (v i) by simp [DFinsupp.prod, this]
apply Finset.prod_subset v.support.subset_univ
intro i _ hi
rw [mem_support_iff, not_not] at hi
rw [hi, hf]
section CommMonoidWithZero
variable [Π i, Zero (β i)] [CommMonoidWithZero γ] [Nontrivial γ] [NoZeroDivisors γ]
[Π i, DecidableEq (β i)] {f : Π₀ i, β i} {g : Π i, β i → γ}
@[simp]
lemma prod_eq_zero_iff : f.prod g = 0 ↔ ∃ i ∈ f.support, g i (f i) = 0 := Finset.prod_eq_zero_iff
lemma prod_ne_zero_iff : f.prod g ≠ 0 ↔ ∀ i ∈ f.support, g i (f i) ≠ 0 := Finset.prod_ne_zero_iff
end CommMonoidWithZero
/--
When summing over an `ZeroHom`, the decidability assumption is not needed, and the result is
also an `ZeroHom`.
-/
def sumZeroHom [∀ i, Zero (β i)] [AddCommMonoid γ] (φ : ∀ i, ZeroHom (β i) γ) :
ZeroHom (Π₀ i, β i) γ where
toFun f :=
(f.support'.lift fun s => ∑ i ∈ Multiset.toFinset s.1, φ i (f i)) <| by
rintro ⟨sx, hx⟩ ⟨sy, hy⟩
dsimp only [Subtype.coe_mk, toFun_eq_coe] at *
have H1 : sx.toFinset ∩ sy.toFinset ⊆ sx.toFinset := Finset.inter_subset_left
have H2 : sx.toFinset ∩ sy.toFinset ⊆ sy.toFinset := Finset.inter_subset_right
refine
(Finset.sum_subset H1 ?_).symm.trans
((Finset.sum_congr rfl ?_).trans (Finset.sum_subset H2 ?_))
· intro i H1 H2
rw [Finset.mem_inter] at H2
simp only [Multiset.mem_toFinset] at H1 H2
convert map_zero (φ i)
exact (hy i).resolve_left (mt (And.intro H1) H2)
· intro i _
rfl
· intro i H1 H2
rw [Finset.mem_inter] at H2
simp only [Multiset.mem_toFinset] at H1 H2
convert map_zero (φ i)
exact (hx i).resolve_left (mt (fun H3 => And.intro H3 H1) H2)
map_zero' := by
simp only [toFun_eq_coe, coe_zero, Pi.zero_apply, map_zero, Finset.sum_const_zero]; rfl
@[simp]
theorem sumZeroHom_single [∀ i, Zero (β i)] [AddCommMonoid γ] (φ : ∀ i, ZeroHom (β i) γ) (i)
(x : β i) : sumZeroHom φ (single i x) = φ i x := by
dsimp [sumZeroHom, single, Trunc.lift_mk]
rw [Multiset.toFinset_singleton, Finset.sum_singleton, Pi.single_eq_same]
@[simp]
theorem sumZeroHom_piSingle [∀ i, Zero (β i)] [AddCommMonoid γ] (i) (φ : ZeroHom (β i) γ) :
sumZeroHom (Pi.single i φ) = φ.comp { toFun := (· i), map_zero' := rfl} := by
ext ⟨f, sf, hf⟩
change (∑ i ∈ _, _) = _
dsimp
rw [Finset.sum_eq_single i (fun j _ hji => ?_) (fun hi => ?_), Pi.single_eq_same]
· simp [hji]
· simp [(hf i).resolve_left (by simpa using hi)]
/-- While we didn't need decidable instances to define it, we do to reduce it to a sum -/
theorem sumZeroHom_apply [∀ i, AddZeroClass (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[AddCommMonoid γ] (φ : ∀ i, ZeroHom (β i) γ) (f : Π₀ i, β i) :
sumZeroHom φ f = f.sum fun x => φ x := by
rcases f with ⟨f, s, hf⟩
change (∑ i ∈ _, _) = ∑ i ∈ _ with _, _
rw [Finset.sum_filter, Finset.sum_congr rfl]
intro i _
dsimp only [coe_mk', Subtype.coe_mk] at *
split_ifs with h
· rfl
· rw [not_not.mp h, map_zero]
/--
When summing over an `AddMonoidHom`, the decidability assumption is not needed, and the result is
also an `AddMonoidHom`.
-/
@[simps toZeroHom]
def sumAddHom [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (φ : ∀ i, β i →+ γ) :
(Π₀ i, β i) →+ γ where
__ := sumZeroHom fun i => φ i |>.toZeroHom
map_add' := by
rintro ⟨f, sf, hf⟩ ⟨g, sg, hg⟩
change (∑ i ∈ _, _) = (∑ i ∈ _, _) + ∑ i ∈ _, _
simp only [AddMonoidHom.toZeroHom_coe, coe_add, coe_mk', Pi.add_apply, map_add,
Finset.sum_add_distrib]
congr 1
· refine (Finset.sum_subset ?_ ?_).symm
· intro i
simp only [Multiset.mem_toFinset, Multiset.mem_add]
exact Or.inl
· intro i _ H2
simp only [Multiset.mem_toFinset] at H2
rw [(hf i).resolve_left H2, AddMonoidHom.map_zero]
· refine (Finset.sum_subset ?_ ?_).symm
· intro i
simp only [Multiset.mem_toFinset, Multiset.mem_add]
exact Or.inr
· intro i _ H2
simp only [Multiset.mem_toFinset] at H2
rw [(hg i).resolve_left H2, AddMonoidHom.map_zero]
@[simp]
theorem sumAddHom_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (φ : ∀ i, β i →+ γ) (i)
(x : β i) : sumAddHom φ (single i x) = φ i x := sumZeroHom_single _ _ _
@[simp]
theorem sumAddHom_piSingle [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (i) (φ : β i →+ γ) :
sumAddHom (Pi.single i φ) = φ.comp (evalAddMonoidHom i) :=
AddMonoidHom.toZeroHom_injective <| by
convert sumZeroHom_piSingle i φ.toZeroHom using 1
rw [DFinsupp.sumAddHom_toZeroHom]
conv_lhs =>
enter [1, i]
rw [Pi.apply_single (fun i (x : β i →+ γ) => x.toZeroHom) (fun _ => rfl)]
@[simp]
theorem sumAddHom_comp_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (f : ∀ i, β i →+ γ)
(i : ι) : (sumAddHom f).comp (singleAddHom β i) = f i :=
AddMonoidHom.ext fun x => sumAddHom_single f i x
/-- While we didn't need decidable instances to define it, we do to reduce it to a sum -/
theorem sumAddHom_apply [∀ i, AddZeroClass (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[AddCommMonoid γ] (φ : ∀ i, β i →+ γ) (f : Π₀ i, β i) : sumAddHom φ f = f.sum fun x => φ x :=
sumZeroHom_apply _ _
theorem sumAddHom_comm {ι₁ ι₂ : Sort _} {β₁ : ι₁ → Type*} {β₂ : ι₂ → Type*} {γ : Type*}
[DecidableEq ι₁] [DecidableEq ι₂] [∀ i, AddZeroClass (β₁ i)] [∀ i, AddZeroClass (β₂ i)]
[AddCommMonoid γ] (f₁ : Π₀ i, β₁ i) (f₂ : Π₀ i, β₂ i) (h : ∀ i j, β₁ i →+ β₂ j →+ γ) :
sumAddHom (fun i₂ => sumAddHom (fun i₁ => h i₁ i₂) f₁) f₂ =
sumAddHom (fun i₁ => sumAddHom (fun i₂ => (h i₁ i₂).flip) f₂) f₁ := by
obtain ⟨⟨f₁, s₁, h₁⟩, ⟨f₂, s₂, h₂⟩⟩ := f₁, f₂
simpa [sumAddHom, sumZeroHom, AddMonoidHom.finset_sum_apply, AddMonoidHom.coe_mk,
AddMonoidHom.flip_apply, Trunc.lift, toFun_eq_coe, ZeroHom.coe_mk, coe_mk']
using Finset.sum_comm
/-- The `DFinsupp` version of `Finsupp.liftAddHom` -/
@[simps apply symm_apply]
def liftAddHom [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] :
(∀ i, β i →+ γ) ≃+ ((Π₀ i, β i) →+ γ) where
toFun := sumAddHom
invFun F i := F.comp (singleAddHom β i)
left_inv x := by ext; simp
right_inv ψ := by ext; simp
map_add' F G := by ext; simp
/-- The `DFinsupp` version of `Finsupp.liftAddHom_singleAddHom` -/
theorem liftAddHom_singleAddHom [∀ i, AddCommMonoid (β i)] :
liftAddHom (singleAddHom β) = AddMonoidHom.id (Π₀ i, β i) :=
liftAddHom.toEquiv.apply_eq_iff_eq_symm_apply.2 rfl
/-- The `DFinsupp` version of `Finsupp.liftAddHom_apply_single` -/
theorem liftAddHom_apply_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (f : ∀ i, β i →+ γ)
(i : ι) (x : β i) : liftAddHom f (single i x) = f i x := by simp
/-- The `DFinsupp` version of `Finsupp.liftAddHom_comp_single` -/
theorem liftAddHom_comp_single [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (f : ∀ i, β i →+ γ)
(i : ι) : (liftAddHom f).comp (singleAddHom β i) = f i := by simp
/-- The `DFinsupp` version of `Finsupp.comp_liftAddHom` -/
theorem comp_liftAddHom {δ : Type*} [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] [AddCommMonoid δ]
(g : γ →+ δ) (f : ∀ i, β i →+ γ) :
g.comp (liftAddHom f) = liftAddHom fun a => g.comp (f a) :=
liftAddHom.symm_apply_eq.1 <|
funext fun a => by
rw [liftAddHom_symm_apply, AddMonoidHom.comp_assoc, liftAddHom_comp_single]
@[simp]
theorem sumAddHom_zero [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] :
(sumAddHom fun i => (0 : β i →+ γ)) = 0 :=
map_zero liftAddHom
@[simp]
theorem sumAddHom_add [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] (g : ∀ i, β i →+ γ)
(h : ∀ i, β i →+ γ) : (sumAddHom fun i => g i + h i) = sumAddHom g + sumAddHom h :=
map_add liftAddHom _ _
@[simp]
theorem sumAddHom_singleAddHom [∀ i, AddCommMonoid (β i)] :
sumAddHom (singleAddHom β) = AddMonoidHom.id _ :=
liftAddHom_singleAddHom
theorem comp_sumAddHom {δ : Type*} [∀ i, AddZeroClass (β i)] [AddCommMonoid γ] [AddCommMonoid δ]
(g : γ →+ δ) (f : ∀ i, β i →+ γ) : g.comp (sumAddHom f) = sumAddHom fun a => g.comp (f a) :=
comp_liftAddHom _ _
theorem sum_sub_index [∀ i, AddGroup (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] [AddCommGroup γ]
{f g : Π₀ i, β i} {h : ∀ i, β i → γ} (h_sub : ∀ i b₁ b₂, h i (b₁ - b₂) = h i b₁ - h i b₂) :
(f - g).sum h = f.sum h - g.sum h := by
have := (liftAddHom fun a => AddMonoidHom.ofMapSub (h a) (h_sub a)).map_sub f g
rw [liftAddHom_apply, sumAddHom_apply, sumAddHom_apply, sumAddHom_apply] at this
exact this
@[to_additive]
theorem prod_finset_sum_index {γ : Type w} {α : Type x} [∀ i, AddCommMonoid (β i)]
[∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {s : Finset α} {g : α → Π₀ i, β i}
{h : ∀ i, β i → γ} (h_zero : ∀ i, h i 0 = 1)
(h_add : ∀ i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
(∏ i ∈ s, (g i).prod h) = (∑ i ∈ s, g i).prod h := by
classical
exact Finset.induction_on s (by simp [prod_zero_index])
(by simp +contextual [prod_add_index, h_zero, h_add])
@[to_additive]
theorem prod_sum_index {ι₁ : Type u₁} [DecidableEq ι₁] {β₁ : ι₁ → Type v₁} [∀ i₁, Zero (β₁ i₁)]
[∀ (i) (x : β₁ i), Decidable (x ≠ 0)] [∀ i, AddCommMonoid (β i)]
[∀ (i) (x : β i), Decidable (x ≠ 0)] [CommMonoid γ] {f : Π₀ i₁, β₁ i₁}
{g : ∀ i₁, β₁ i₁ → Π₀ i, β i} {h : ∀ i, β i → γ} (h_zero : ∀ i, h i 0 = 1)
(h_add : ∀ i b₁ b₂, h i (b₁ + b₂) = h i b₁ * h i b₂) :
(f.sum g).prod h = f.prod fun i b => (g i b).prod h :=
(prod_finset_sum_index h_zero h_add).symm
@[simp]
theorem sum_single [∀ i, AddCommMonoid (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)] {f : Π₀ i, β i} :
f.sum single = f := by
have := DFunLike.congr_fun (liftAddHom_singleAddHom (β := β)) f
rw [liftAddHom_apply, sumAddHom_apply] at this
exact this
@[to_additive]
theorem prod_subtypeDomain_index [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
[CommMonoid γ] {v : Π₀ i, β i} {p : ι → Prop} [DecidablePred p] {h : ∀ i, β i → γ}
(hp : ∀ x ∈ v.support, p x) : (v.subtypeDomain p).prod (fun i b => h i b) = v.prod h := by
refine Finset.prod_bij (fun p _ ↦ p) ?_ ?_ ?_ ?_ <;> aesop
theorem subtypeDomain_sum {ι} {β : ι → Type v} [∀ i, AddCommMonoid (β i)] {s : Finset γ}
{h : γ → Π₀ i, β i} {p : ι → Prop} [DecidablePred p] :
(∑ c ∈ s, h c).subtypeDomain p = ∑ c ∈ s, (h c).subtypeDomain p :=
map_sum (subtypeDomainAddMonoidHom β p) _ s
theorem subtypeDomain_finsupp_sum {ι} {β : ι → Type v} {δ : γ → Type x} [DecidableEq γ]
[∀ c, Zero (δ c)] [∀ (c) (x : δ c), Decidable (x ≠ 0)]
[∀ i, AddCommMonoid (β i)] {p : ι → Prop} [DecidablePred p]
{s : Π₀ c, δ c} {h : ∀ c, δ c → Π₀ i, β i} :
(s.sum h).subtypeDomain p = s.sum fun c d => (h c d).subtypeDomain p :=
subtypeDomain_sum
end ProdAndSum
end DFinsupp
/-! ### Product and sum lemmas for bundled morphisms.
In this section, we provide analogues of `AddMonoidHom.map_sum`, `AddMonoidHom.coe_finset_sum`,
and `AddMonoidHom.finset_sum_apply` for `DFinsupp.sum` and `DFinsupp.sumAddHom` instead of
`Finset.sum`.
We provide these for `AddMonoidHom`, `MonoidHom`, `RingHom`, `AddEquiv`, and `MulEquiv`.
Lemmas for `LinearMap` and `LinearEquiv` are in another file.
-/
section
variable [DecidableEq ι]
namespace MonoidHom
variable {R S : Type*}
variable [∀ i, Zero (β i)] [∀ (i) (x : β i), Decidable (x ≠ 0)]
@[to_additive (attr := simp, norm_cast)]
theorem coe_dfinsuppProd [MulOneClass R] [CommMonoid S] (f : Π₀ i, β i) (g : ∀ i, β i → R →* S) :
⇑(f.prod g) = f.prod fun a b => ⇑(g a b) :=
coe_finset_prod _ _
@[to_additive]
theorem dfinsuppProd_apply [MulOneClass R] [CommMonoid S] (f : Π₀ i, β i) (g : ∀ i, β i → R →* S)
(r : R) : (f.prod g) r = f.prod fun a b => (g a b) r :=
finset_prod_apply _ _ _
end MonoidHom
/-! The above lemmas, repeated for `DFinsupp.sumAddHom`. -/
namespace AddMonoidHom
variable {R S : Type*}
open DFinsupp
@[simp]
theorem map_dfinsuppSumAddHom [AddCommMonoid R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)]
(h : R →+ S) (f : Π₀ i, β i) (g : ∀ i, β i →+ R) :
h (sumAddHom g f) = sumAddHom (fun i => h.comp (g i)) f :=
DFunLike.congr_fun (comp_liftAddHom h g) f
theorem dfinsuppSumAddHom_apply [AddZeroClass R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)]
(f : Π₀ i, β i) (g : ∀ i, β i →+ R →+ S) (r : R) :
(sumAddHom g f) r = sumAddHom (fun i => (eval r).comp (g i)) f :=
map_dfinsuppSumAddHom (eval r) f g
@[simp, norm_cast]
theorem coe_dfinsuppSumAddHom [AddZeroClass R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)]
(f : Π₀ i, β i) (g : ∀ i, β i →+ R →+ S) :
⇑(sumAddHom g f) = sumAddHom (fun i => (coeFn R S).comp (g i)) f :=
map_dfinsuppSumAddHom (coeFn R S) f g
end AddMonoidHom
namespace RingHom
variable {R S : Type*}
open DFinsupp
@[simp]
theorem map_dfinsuppSumAddHom [NonAssocSemiring R] [NonAssocSemiring S] [∀ i, AddZeroClass (β i)]
(h : R →+* S) (f : Π₀ i, β i) (g : ∀ i, β i →+ R) :
h (sumAddHom g f) = sumAddHom (fun i => h.toAddMonoidHom.comp (g i)) f :=
DFunLike.congr_fun (comp_liftAddHom h.toAddMonoidHom g) f
end RingHom
namespace AddEquiv
variable {R S : Type*}
open DFinsupp
@[simp]
theorem map_dfinsuppSumAddHom [AddCommMonoid R] [AddCommMonoid S] [∀ i, AddZeroClass (β i)]
(h : R ≃+ S) (f : Π₀ i, β i) (g : ∀ i, β i →+ R) :
h (sumAddHom g f) = sumAddHom (fun i => h.toAddMonoidHom.comp (g i)) f :=
DFunLike.congr_fun (comp_liftAddHom h.toAddMonoidHom g) f
end AddEquiv
end |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/NeLocus.lean | import Mathlib.Data.DFinsupp.Defs
/-!
# Locus of unequal values of finitely supported dependent functions
Let `N : α → Type*` be a type family, assume that `N a` has a `0` for all `a : α` and let
`f g : Π₀ a, N a` be finitely supported dependent functions.
## Main definition
* `DFinsupp.neLocus f g : Finset α`, the finite subset of `α` where `f` and `g` differ.
In the case in which `N a` is an additive group for all `a`, `DFinsupp.neLocus f g` coincides with
`DFinsupp.support (f - g)`.
-/
variable {α : Type*} {N : α → Type*}
namespace DFinsupp
variable [DecidableEq α]
section NHasZero
variable [∀ a, DecidableEq (N a)] [∀ a, Zero (N a)] (f g : Π₀ a, N a)
/-- Given two finitely supported functions `f g : α →₀ N`, `Finsupp.neLocus f g` is the `Finset`
where `f` and `g` differ. This generalizes `(f - g).support` to situations without subtraction. -/
def neLocus (f g : Π₀ a, N a) : Finset α :=
(f.support ∪ g.support).filter fun x ↦ f x ≠ g x
@[simp]
theorem mem_neLocus {f g : Π₀ a, N a} {a : α} : a ∈ f.neLocus g ↔ f a ≠ g a := by
simpa only [neLocus, Finset.mem_filter, Finset.mem_union, mem_support_iff,
and_iff_right_iff_imp] using Ne.ne_or_ne _
theorem notMem_neLocus {f g : Π₀ a, N a} {a : α} : a ∉ f.neLocus g ↔ f a = g a :=
mem_neLocus.not.trans not_ne_iff
@[deprecated (since := "2025-05-23")] alias not_mem_neLocus := notMem_neLocus
@[simp]
theorem coe_neLocus : ↑(f.neLocus g) = { x | f x ≠ g x } :=
Set.ext fun _x ↦ mem_neLocus
@[simp]
theorem neLocus_eq_empty {f g : Π₀ a, N a} : f.neLocus g = ∅ ↔ f = g :=
⟨fun h ↦
ext fun a ↦ not_not.mp (mem_neLocus.not.mp (Finset.eq_empty_iff_forall_notMem.mp h a)),
fun h ↦ h ▸ by simp only [neLocus, Ne, not_true, Finset.filter_false]⟩
@[simp]
theorem nonempty_neLocus_iff {f g : Π₀ a, N a} : (f.neLocus g).Nonempty ↔ f ≠ g :=
Finset.nonempty_iff_ne_empty.trans neLocus_eq_empty.not
theorem neLocus_comm : f.neLocus g = g.neLocus f := by
simp_rw [neLocus, Finset.union_comm, ne_comm]
@[simp]
theorem neLocus_zero_right : f.neLocus 0 = f.support := by
ext
rw [mem_neLocus, mem_support_iff, coe_zero, Pi.zero_apply]
@[simp]
theorem neLocus_zero_left : (0 : Π₀ a, N a).neLocus f = f.support :=
(neLocus_comm _ _).trans (neLocus_zero_right _)
end NHasZero
section NeLocusAndMaps
variable {M P : α → Type*} [∀ a, Zero (N a)] [∀ a, Zero (M a)] [∀ a, Zero (P a)]
theorem subset_mapRange_neLocus [∀ a, DecidableEq (N a)] [∀ a, DecidableEq (M a)] (f g : Π₀ a, N a)
{F : ∀ a, N a → M a} (F0 : ∀ a, F a 0 = 0) :
(f.mapRange F F0).neLocus (g.mapRange F F0) ⊆ f.neLocus g := fun a ↦ by
simpa only [mem_neLocus, mapRange_apply, not_imp_not] using congr_arg (F a)
theorem zipWith_neLocus_eq_left [∀ a, DecidableEq (N a)] [∀ a, DecidableEq (P a)]
{F : ∀ a, M a → N a → P a} (F0 : ∀ a, F a 0 0 = 0) (f : Π₀ a, M a) (g₁ g₂ : Π₀ a, N a)
(hF : ∀ a f, Function.Injective fun g ↦ F a f g) :
(zipWith F F0 f g₁).neLocus (zipWith F F0 f g₂) = g₁.neLocus g₂ := by
ext a
simpa only [mem_neLocus] using (hF a _).ne_iff
theorem zipWith_neLocus_eq_right [∀ a, DecidableEq (M a)] [∀ a, DecidableEq (P a)]
{F : ∀ a, M a → N a → P a} (F0 : ∀ a, F a 0 0 = 0) (f₁ f₂ : Π₀ a, M a) (g : Π₀ a, N a)
(hF : ∀ a g, Function.Injective fun f ↦ F a f g) :
(zipWith F F0 f₁ g).neLocus (zipWith F F0 f₂ g) = f₁.neLocus f₂ := by
ext a
simpa only [mem_neLocus] using (hF a _).ne_iff
theorem mapRange_neLocus_eq [∀ a, DecidableEq (N a)] [∀ a, DecidableEq (M a)] (f g : Π₀ a, N a)
{F : ∀ a, N a → M a} (F0 : ∀ a, F a 0 = 0) (hF : ∀ a, Function.Injective (F a)) :
(f.mapRange F F0).neLocus (g.mapRange F F0) = f.neLocus g := by
ext a
simpa only [mem_neLocus] using (hF a).ne_iff
end NeLocusAndMaps
variable [∀ a, DecidableEq (N a)]
@[simp]
theorem neLocus_add_left [∀ a, AddLeftCancelMonoid (N a)] (f g h : Π₀ a, N a) :
(f + g).neLocus (f + h) = g.neLocus h :=
zipWith_neLocus_eq_left _ _ _ _ fun _a ↦ add_right_injective
@[simp]
theorem neLocus_add_right [∀ a, AddRightCancelMonoid (N a)] (f g h : Π₀ a, N a) :
(f + h).neLocus (g + h) = f.neLocus g :=
zipWith_neLocus_eq_right _ _ _ _ fun _a ↦ add_left_injective
section AddGroup
variable [∀ a, AddGroup (N a)] (f f₁ f₂ g g₁ g₂ : Π₀ a, N a)
@[simp]
theorem neLocus_neg_neg : neLocus (-f) (-g) = f.neLocus g :=
mapRange_neLocus_eq _ _ (fun _a ↦ neg_zero) fun _a ↦ neg_injective
theorem neLocus_neg : neLocus (-f) g = f.neLocus (-g) := by rw [← neLocus_neg_neg, neg_neg]
theorem neLocus_eq_support_sub : f.neLocus g = (f - g).support := by
rw [← @neLocus_add_right α N _ _ _ _ _ (-g), add_neg_cancel, neLocus_zero_right, sub_eq_add_neg]
@[simp]
theorem neLocus_sub_left : neLocus (f - g₁) (f - g₂) = neLocus g₁ g₂ := by
simp only [sub_eq_add_neg, @neLocus_add_left α N _ _ _, neLocus_neg_neg]
@[simp]
theorem neLocus_sub_right : neLocus (f₁ - g) (f₂ - g) = neLocus f₁ f₂ := by
simpa only [sub_eq_add_neg] using @neLocus_add_right α N _ _ _ _ _ _
@[simp]
theorem neLocus_self_add_right : neLocus f (f + g) = g.support := by
rw [← neLocus_zero_left, ← @neLocus_add_left α N _ _ _ f 0 g, add_zero]
@[simp]
theorem neLocus_self_add_left : neLocus (f + g) f = g.support := by
rw [neLocus_comm, neLocus_self_add_right]
@[simp]
theorem neLocus_self_sub_right : neLocus f (f - g) = g.support := by
rw [sub_eq_add_neg, neLocus_self_add_right, support_neg]
@[simp]
theorem neLocus_self_sub_left : neLocus (f - g) f = g.support := by
rw [neLocus_comm, neLocus_self_sub_right]
end AddGroup
end DFinsupp |
.lake/packages/mathlib/Mathlib/Data/DFinsupp/Encodable.lean | import Mathlib.Data.DFinsupp.Defs
import Mathlib.Logic.Encodable.Pi
/-!
# `Encodable` and `Countable` instances for `Π₀ i, α i`
In this file we provide instances for `Encodable (Π₀ i, α i)` and `Countable (Π₀ i, α i)`.
-/
variable {ι : Type*} {α : ι → Type*} [∀ i, Zero (α i)]
instance [Encodable ι] [∀ i, Encodable (α i)] [∀ i (x : α i), Decidable (x ≠ 0)] :
Encodable (Π₀ i, α i) :=
letI : DecidableEq ι := Encodable.decidableEqOfEncodable _
letI : ∀ s : Finset ι, Encodable (∀ i : s, {x : α i // x ≠ 0}) := fun _ ↦
.ofEquiv _ <| .piCongrLeft' _ Encodable.fintypeEquivFin
.ofEquiv _ DFinsupp.sigmaFinsetFunEquiv
instance [Countable ι] [∀ i, Countable (α i)] : Countable (Π₀ i, α i) := by
classical
let _ := Encodable.ofCountable ι
let _ := fun i ↦ Encodable.ofCountable (α i)
infer_instance |
.lake/packages/mathlib/Mathlib/Data/Fin/SuccPred.lean | import Mathlib.Data.Fin.Basic
import Mathlib.Logic.Equiv.Set
/-!
# Successors and predecessor operations of `Fin n`
This file contains a number of definitions and lemmas
related to `Fin.succ`, `Fin.pred`, and related operations on `Fin n`.
## Main definitions
* `finCongr` : `Fin.cast` as an `Equiv`, equivalence between `Fin n` and `Fin m` when `n = m`;
* `Fin.succAbove` : embeds `Fin n` into `Fin (n + 1)` skipping `p`.
* `Fin.predAbove` : the (partial) inverse of `Fin.succAbove`.
-/
assert_not_exists Monoid Finset
open Fin Nat Function
attribute [simp] Fin.succ_ne_zero Fin.castSucc_lt_last
namespace Fin
variable {n m : ℕ}
section Succ
/-!
### succ and casts into larger Fin types
-/
lemma succ_injective (n : ℕ) : Injective (@Fin.succ n) := fun a b ↦ by simp [Fin.ext_iff]
@[simp]
theorem exists_succ_eq {x : Fin (n + 1)} : (∃ y, Fin.succ y = x) ↔ x ≠ 0 :=
⟨fun ⟨_, hy⟩ => hy ▸ succ_ne_zero _, x.cases (fun h => h.irrefl.elim) (fun _ _ => ⟨_, rfl⟩)⟩
theorem exists_succ_eq_of_ne_zero {x : Fin (n + 1)} (h : x ≠ 0) :
∃ y, Fin.succ y = x := exists_succ_eq.mpr h
@[simp]
theorem succ_zero_eq_one' [NeZero n] : Fin.succ (0 : Fin n) = 1 := by
cases n
· exact (NeZero.ne 0 rfl).elim
· rfl
theorem one_pos' [NeZero n] : (0 : Fin (n + 1)) < 1 := succ_zero_eq_one' (n := n) ▸ succ_pos _
theorem zero_ne_one' [NeZero n] : (0 : Fin (n + 1)) ≠ 1 := Fin.ne_of_lt one_pos'
/--
The `Fin.succ_one_eq_two` in `Lean` only applies in `Fin (n+2)`.
This one instead uses a `NeZero n` typeclass hypothesis.
-/
@[simp]
theorem succ_one_eq_two' [NeZero n] : Fin.succ (1 : Fin (n + 1)) = 2 := by
cases n
· exact (NeZero.ne 0 rfl).elim
· rfl
-- Version of `succ_one_eq_two` to be used by `dsimp`.
-- Note the `'` swapped around due to a move to std4.
/--
The `Fin.le_zero_iff` in `Lean` only applies in `Fin (n+1)`.
This one instead uses a `NeZero n` typeclass hypothesis.
-/
@[simp]
theorem le_zero_iff' {n : ℕ} [NeZero n] {k : Fin n} : k ≤ 0 ↔ k = 0 :=
⟨fun h => Fin.ext <| by rw [Nat.eq_zero_of_le_zero h]; rfl, by rintro rfl; exact Nat.le_refl _⟩
-- TODO: Move to Batteries
@[simp] lemma castLE_inj {hmn : m ≤ n} {a b : Fin m} : castLE hmn a = castLE hmn b ↔ a = b := by
simp [Fin.ext_iff]
@[simp] lemma castAdd_inj {a b : Fin m} : castAdd n a = castAdd n b ↔ a = b := by simp [Fin.ext_iff]
attribute [simp] castSucc_inj
lemma castLE_injective (hmn : m ≤ n) : Injective (castLE hmn) :=
fun _ _ hab ↦ Fin.ext (congr_arg val hab :)
lemma castAdd_injective (m n : ℕ) : Injective (@Fin.castAdd m n) := castLE_injective _
lemma castSucc_injective (n : ℕ) : Injective (@Fin.castSucc n) := castAdd_injective _ _
@[simp] lemma castLE_castSucc {n m} (i : Fin n) (h : n + 1 ≤ m) :
i.castSucc.castLE h = i.castLE (Nat.le_of_succ_le h) :=
rfl
@[simp] lemma castLE_comp_castSucc {n m} (h : n + 1 ≤ m) :
Fin.castLE h ∘ Fin.castSucc = Fin.castLE (Nat.le_of_succ_le h) :=
rfl
@[simp] lemma castLE_rfl (n : ℕ) : Fin.castLE (le_refl n) = id :=
rfl
@[simp]
theorem range_castLE {n k : ℕ} (h : n ≤ k) : Set.range (castLE h) = { i : Fin k | (i : ℕ) < n } :=
Set.ext fun x => ⟨fun ⟨y, hy⟩ => hy ▸ y.2, fun hx => ⟨⟨x, hx⟩, rfl⟩⟩
@[simp]
theorem coe_of_injective_castLE_symm {n k : ℕ} (h : n ≤ k) (i : Fin k) (hi) :
((Equiv.ofInjective _ (castLE_injective h)).symm ⟨i, hi⟩ : ℕ) = i := by
rw [← coe_castLE h]
exact congr_arg Fin.val (Equiv.apply_ofInjective_symm _ _)
theorem leftInverse_cast (eq : n = m) : LeftInverse (Fin.cast eq.symm) (Fin.cast eq) :=
fun _ => rfl
theorem rightInverse_cast (eq : n = m) : RightInverse (Fin.cast eq.symm) (Fin.cast eq) :=
fun _ => rfl
@[simp]
theorem cast_inj (eq : n = m) {a b : Fin n} : a.cast eq = b.cast eq ↔ a = b := by
simp [← val_inj]
@[simp]
theorem cast_lt_cast (eq : n = m) {a b : Fin n} : a.cast eq < b.cast eq ↔ a < b :=
Iff.rfl
@[simp]
theorem cast_le_cast (eq : n = m) {a b : Fin n} : a.cast eq ≤ b.cast eq ↔ a ≤ b :=
Iff.rfl
/-- The 'identity' equivalence between `Fin m` and `Fin n` when `m = n`. -/
@[simps]
def _root_.finCongr (eq : n = m) : Fin n ≃ Fin m where
toFun := Fin.cast eq
invFun := Fin.cast eq.symm
left_inv := leftInverse_cast eq
right_inv := rightInverse_cast eq
@[simp] lemma _root_.finCongr_apply_mk (h : m = n) (k : ℕ) (hk : k < m) :
finCongr h ⟨k, hk⟩ = ⟨k, h ▸ hk⟩ := rfl
@[simp]
lemma _root_.finCongr_refl (h : n = n := rfl) : finCongr h = Equiv.refl (Fin n) := by ext; simp
@[simp] lemma _root_.finCongr_symm (h : m = n) : (finCongr h).symm = finCongr h.symm := rfl
@[simp] lemma _root_.finCongr_apply_coe (h : m = n) (k : Fin m) : (finCongr h k : ℕ) = k := rfl
lemma _root_.finCongr_symm_apply_coe (h : m = n) (k : Fin n) : ((finCongr h).symm k : ℕ) = k := rfl
/-- While in many cases `finCongr` is better than `Equiv.cast`/`cast`, sometimes we want to apply
a generic theorem about `cast`. -/
lemma _root_.finCongr_eq_equivCast (h : n = m) : finCongr h = .cast (h ▸ rfl) := by subst h; simp
/-- While in many cases `Fin.cast` is better than `Equiv.cast`/`cast`, sometimes we want to apply
a generic theorem about `cast`. -/
theorem cast_eq_cast (h : n = m) : (Fin.cast h : Fin n → Fin m) = _root_.cast (h ▸ rfl) := by
subst h
ext
rfl
theorem castSucc_le_succ {n} (i : Fin n) : i.castSucc ≤ i.succ := Nat.le_succ i
@[simp] theorem castSucc_le_castSucc_iff {a b : Fin n} : castSucc a ≤ castSucc b ↔ a ≤ b := .rfl
@[simp] theorem succ_le_castSucc_iff {a b : Fin n} : succ a ≤ castSucc b ↔ a < b := by
rw [le_castSucc_iff, succ_lt_succ_iff]
@[simp] theorem castSucc_lt_succ_iff {a b : Fin n} : castSucc a < succ b ↔ a ≤ b := by
rw [castSucc_lt_iff_succ_le, succ_le_succ_iff]
theorem le_of_castSucc_lt_of_succ_lt {a b : Fin (n + 1)} {i : Fin n}
(hl : castSucc i < a) (hu : b < succ i) : b < a := by
simp [Fin.lt_def, -val_fin_lt] at *; cutsat
theorem castSucc_lt_or_lt_succ (p : Fin (n + 1)) (i : Fin n) : castSucc i < p ∨ p < i.succ := by
simpa [Fin.lt_def, -val_fin_lt] using by cutsat
theorem succ_le_or_le_castSucc (p : Fin (n + 1)) (i : Fin n) : succ i ≤ p ∨ p ≤ i.castSucc := by
rw [le_castSucc_iff, ← castSucc_lt_iff_succ_le]
exact p.castSucc_lt_or_lt_succ i
theorem eq_castSucc_of_ne_last {x : Fin (n + 1)} (h : x ≠ (last _)) :
∃ y, Fin.castSucc y = x := exists_castSucc_eq.mpr h
theorem forall_fin_succ' {P : Fin (n + 1) → Prop} :
(∀ i, P i) ↔ (∀ i : Fin n, P i.castSucc) ∧ P (.last _) :=
⟨fun H => ⟨fun _ => H _, H _⟩, fun ⟨H0, H1⟩ i => Fin.lastCases H1 H0 i⟩
-- to match `Fin.eq_zero_or_eq_succ`
theorem eq_castSucc_or_eq_last {n : Nat} (i : Fin (n + 1)) :
(∃ j : Fin n, i = j.castSucc) ∨ i = last n := i.lastCases (Or.inr rfl) (Or.inl ⟨·, rfl⟩)
@[simp]
theorem castSucc_ne_last {n : ℕ} (i : Fin n) : i.castSucc ≠ .last n :=
Fin.ne_of_lt i.castSucc_lt_last
theorem exists_fin_succ' {P : Fin (n + 1) → Prop} :
(∃ i, P i) ↔ (∃ i : Fin n, P i.castSucc) ∨ P (.last _) :=
⟨fun ⟨i, h⟩ => Fin.lastCases Or.inr (fun i hi => Or.inl ⟨i, hi⟩) i h,
fun h => h.elim (fun ⟨i, hi⟩ => ⟨i.castSucc, hi⟩) (fun h => ⟨.last _, h⟩)⟩
/--
The `Fin.castSucc_zero` in `Lean` only applies in `Fin (n+1)`.
This one instead uses a `NeZero n` typeclass hypothesis.
-/
@[simp]
theorem castSucc_zero' [NeZero n] : castSucc (0 : Fin n) = 0 := rfl
@[simp]
theorem castSucc_pos_iff [NeZero n] {i : Fin n} : 0 < castSucc i ↔ 0 < i := by simp [← val_pos_iff]
/-- `castSucc i` is positive when `i` is positive.
The `Fin.castSucc_pos` in `Lean` only applies in `Fin (n+1)`.
This one instead uses a `NeZero n` typeclass hypothesis. -/
alias ⟨_, castSucc_pos'⟩ := castSucc_pos_iff
@[deprecated Fin.castSucc_eq_zero_iff (since := "2025-05-13")]
theorem castSucc_eq_zero_iff' [NeZero n] (a : Fin n) : castSucc a = 0 ↔ a = 0 :=
Fin.ext_iff.trans <| (Fin.ext_iff.trans <| by simp).symm
@[deprecated Fin.castSucc_ne_zero_iff (since := "2025-05-13")]
theorem castSucc_ne_zero_iff' [NeZero n] (a : Fin n) : castSucc a ≠ 0 ↔ a ≠ 0 :=
not_iff_not.mpr <| castSucc_eq_zero_iff
theorem castSucc_ne_zero_of_lt {p i : Fin n} (h : p < i) : castSucc i ≠ 0 := by
cases n
· exact i.elim0
· rw [castSucc_ne_zero_iff, Ne, Fin.ext_iff]
exact ((zero_le _).trans_lt h).ne'
theorem succ_ne_last_iff (a : Fin (n + 1)) : succ a ≠ last (n + 1) ↔ a ≠ last n :=
not_iff_not.mpr <| succ_eq_last_succ
theorem succ_ne_last_of_lt {p i : Fin n} (h : i < p) : succ i ≠ last n := by
cases n
· exact i.elim0
· rw [succ_ne_last_iff, Ne, Fin.ext_iff]
exact ((le_last _).trans_lt' h).ne
open Fin.NatCast in
@[norm_cast, simp]
theorem coe_eq_castSucc {a : Fin n} : ((a : Nat) : Fin (n + 1)) = castSucc a := by
ext
exact val_cast_of_lt (Nat.lt.step a.is_lt)
open Fin.NatCast in
theorem coe_succ_lt_iff_lt {n : ℕ} {j k : Fin n} : (j : Fin (n + 1)) < k ↔ j < k := by
simp only [coe_eq_castSucc, castSucc_lt_castSucc_iff]
@[simp]
theorem range_castSucc {n : ℕ} : Set.range (castSucc : Fin n → Fin n.succ) =
({ i | (i : ℕ) < n } : Set (Fin n.succ)) := range_castLE (by cutsat)
@[simp]
theorem coe_of_injective_castSucc_symm {n : ℕ} (i : Fin n.succ) (hi) :
((Equiv.ofInjective castSucc (castSucc_injective _)).symm ⟨i, hi⟩ : ℕ) = i := by
rw [← coe_castSucc]
exact congr_arg val (Equiv.apply_ofInjective_symm _ _)
theorem castSucc_castAdd (i : Fin n) : castSucc (castAdd m i) = castAdd (m + 1) i := rfl
theorem succ_castAdd (i : Fin n) : succ (castAdd m i) =
if h : i.succ = last _ then natAdd n (0 : Fin (m + 1))
else castAdd (m + 1) ⟨i.1 + 1, lt_of_le_of_ne i.2 (Fin.val_ne_iff.mpr h)⟩ := by
split_ifs with h
exacts [Fin.ext (congr_arg Fin.val h :), rfl]
theorem succ_natAdd (i : Fin m) : succ (natAdd n i) = natAdd n (succ i) := rfl
end Succ
section Pred
/-!
### pred
-/
theorem pred_one' [NeZero n] (h := (zero_ne_one' (n := n)).symm) :
Fin.pred (1 : Fin (n + 1)) h = 0 := by
simp_rw [Fin.ext_iff, coe_pred, val_one', val_zero, Nat.sub_eq_zero_iff_le, Nat.mod_le]
theorem pred_last (h := Fin.ext_iff.not.2 last_pos'.ne') :
pred (last (n + 1)) h = last n := by simp_rw [← succ_last, pred_succ]
theorem pred_lt_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : pred i hi < j ↔ i < succ j := by
rw [← succ_lt_succ_iff, succ_pred]
theorem lt_pred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : j < pred i hi ↔ succ j < i := by
rw [← succ_lt_succ_iff, succ_pred]
theorem pred_le_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : pred i hi ≤ j ↔ i ≤ succ j := by
rw [← succ_le_succ_iff, succ_pred]
theorem le_pred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ 0) : j ≤ pred i hi ↔ succ j ≤ i := by
rw [← succ_le_succ_iff, succ_pred]
theorem castSucc_pred_eq_pred_castSucc {a : Fin (n + 1)} (ha : a ≠ 0) :
(a.pred ha).castSucc = (castSucc a).pred (castSucc_ne_zero_iff.mpr ha) := rfl
theorem castSucc_pred_add_one_eq {a : Fin (n + 1)} (ha : a ≠ 0) :
(a.pred ha).castSucc + 1 = a := by
simp
theorem le_pred_castSucc_iff {a b : Fin (n + 1)} (ha : castSucc a ≠ 0) :
b ≤ (castSucc a).pred ha ↔ b < a := by
rw [le_pred_iff, succ_le_castSucc_iff]
theorem pred_castSucc_lt_iff {a b : Fin (n + 1)} (ha : castSucc a ≠ 0) :
(castSucc a).pred ha < b ↔ a ≤ b := by
rw [pred_lt_iff, castSucc_lt_succ_iff]
theorem pred_castSucc_lt {a : Fin (n + 1)} (ha : castSucc a ≠ 0) :
(castSucc a).pred ha < a := by rw [pred_castSucc_lt_iff, le_def]
theorem le_castSucc_pred_iff {a b : Fin (n + 1)} (ha : a ≠ 0) :
b ≤ castSucc (a.pred ha) ↔ b < a := by
rw [castSucc_pred_eq_pred_castSucc, le_pred_castSucc_iff]
theorem castSucc_pred_lt_iff {a b : Fin (n + 1)} (ha : a ≠ 0) :
castSucc (a.pred ha) < b ↔ a ≤ b := by
rw [castSucc_pred_eq_pred_castSucc, pred_castSucc_lt_iff]
theorem castSucc_pred_lt {a : Fin (n + 1)} (ha : a ≠ 0) :
castSucc (a.pred ha) < a := by rw [castSucc_pred_lt_iff, le_def]
end Pred
section CastPred
/-- `castPred i` sends `i : Fin (n + 1)` to `Fin n` as long as i ≠ last n. -/
@[inline] def castPred (i : Fin (n + 1)) (h : i ≠ last n) : Fin n := castLT i (val_lt_last h)
@[simp]
lemma castLT_eq_castPred (i : Fin (n + 1)) (h : i < last _) (h' := Fin.ext_iff.not.2 h.ne) :
castLT i h = castPred i h' := rfl
@[simp]
lemma coe_castPred (i : Fin (n + 1)) (h : i ≠ last _) : (castPred i h : ℕ) = i := rfl
@[simp]
theorem castPred_castSucc {i : Fin n} (h' := Fin.ext_iff.not.2 (castSucc_lt_last i).ne) :
castPred (castSucc i) h' = i := rfl
@[simp]
theorem castSucc_castPred (i : Fin (n + 1)) (h : i ≠ last n) :
castSucc (i.castPred h) = i := by
rcases exists_castSucc_eq.mpr h with ⟨y, rfl⟩
rw [castPred_castSucc]
theorem castPred_eq_iff_eq_castSucc (i : Fin (n + 1)) (hi : i ≠ last _) (j : Fin n) :
castPred i hi = j ↔ i = castSucc j :=
⟨fun h => by rw [← h, castSucc_castPred], fun h => by simp_rw [h, castPred_castSucc]⟩
@[simp]
theorem castPred_mk (i : ℕ) (h₁ : i < n) (h₂ := h₁.trans (Nat.lt_succ_self _))
(h₃ : ⟨i, h₂⟩ ≠ last _ := (ne_iff_vne _ _).mpr (val_last _ ▸ h₁.ne)) :
castPred ⟨i, h₂⟩ h₃ = ⟨i, h₁⟩ := rfl
@[simp]
theorem castPred_le_castPred_iff {i j : Fin (n + 1)} {hi : i ≠ last n} {hj : j ≠ last n} :
castPred i hi ≤ castPred j hj ↔ i ≤ j := Iff.rfl
/-- A version of the right-to-left implication of `castPred_le_castPred_iff`
that deduces `i ≠ last n` from `i ≤ j` and `j ≠ last n`. -/
@[gcongr]
theorem castPred_le_castPred {i j : Fin (n + 1)} (h : i ≤ j) (hj : j ≠ last n) :
castPred i (by rw [← lt_last_iff_ne_last] at hj ⊢; exact Fin.lt_of_le_of_lt h hj) ≤
castPred j hj :=
h
@[simp]
theorem castPred_lt_castPred_iff {i j : Fin (n + 1)} {hi : i ≠ last n} {hj : j ≠ last n} :
castPred i hi < castPred j hj ↔ i < j := Iff.rfl
/-- A version of the right-to-left implication of `castPred_lt_castPred_iff`
that deduces `i ≠ last n` from `i < j`. -/
@[gcongr]
theorem castPred_lt_castPred {i j : Fin (n + 1)} (h : i < j) (hj : j ≠ last n) :
castPred i (ne_last_of_lt h) < castPred j hj := h
theorem castPred_lt_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) :
castPred i hi < j ↔ i < castSucc j := by
rw [← castSucc_lt_castSucc_iff, castSucc_castPred]
theorem lt_castPred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) :
j < castPred i hi ↔ castSucc j < i := by
rw [← castSucc_lt_castSucc_iff, castSucc_castPred]
theorem castPred_le_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) :
castPred i hi ≤ j ↔ i ≤ castSucc j := by
rw [← castSucc_le_castSucc_iff, castSucc_castPred]
theorem le_castPred_iff {j : Fin n} {i : Fin (n + 1)} (hi : i ≠ last n) :
j ≤ castPred i hi ↔ castSucc j ≤ i := by
rw [← castSucc_le_castSucc_iff, castSucc_castPred]
@[simp]
theorem castPred_inj {i j : Fin (n + 1)} {hi : i ≠ last n} {hj : j ≠ last n} :
castPred i hi = castPred j hj ↔ i = j := by
simp_rw [Fin.ext_iff, le_antisymm_iff, ← le_def, castPred_le_castPred_iff]
@[simp]
theorem castPred_zero [NeZero n] :
castPred (0 : Fin (n + 1)) (Fin.ext_iff.not.2 last_pos'.ne) = 0 := rfl
@[deprecated (since := "2025-05-11")]
alias castPred_zero' := castPred_zero
@[simp]
theorem castPred_eq_zero [NeZero n] {i : Fin (n + 1)} (h : i ≠ last n) :
Fin.castPred i h = 0 ↔ i = 0 := by
rw [← castPred_zero, castPred_inj]
theorem castPred_ne_zero [NeZero n] {i : Fin (n + 1)} (h₁ : i ≠ last n) (h₂ : i ≠ 0) :
castPred i h₁ ≠ 0 :=
(castPred_eq_zero h₁).not.mpr h₂
@[simp]
theorem castPred_one [NeZero n] :
castPred (1 : Fin (n + 2)) (Fin.ext_iff.not.2 one_lt_last.ne) = 1 := by
cases n
· exact subsingleton_one.elim _ 1
· rfl
theorem succ_castPred_eq_castPred_succ {a : Fin (n + 1)} (ha : a ≠ last n)
(ha' := a.succ_ne_last_iff.mpr ha) :
(a.castPred ha).succ = (succ a).castPred ha' := rfl
theorem succ_castPred_eq_add_one {a : Fin (n + 1)} (ha : a ≠ last n) :
(a.castPred ha).succ = a + 1 := by
cases a using lastCases
· exact (ha rfl).elim
· rw [castPred_castSucc, coeSucc_eq_succ]
theorem castpred_succ_le_iff {a b : Fin (n + 1)} (ha : succ a ≠ last (n + 1)) :
(succ a).castPred ha ≤ b ↔ a < b := by
rw [castPred_le_iff, succ_le_castSucc_iff]
theorem lt_castPred_succ_iff {a b : Fin (n + 1)} (ha : succ a ≠ last (n + 1)) :
b < (succ a).castPred ha ↔ b ≤ a := by
rw [lt_castPred_iff, castSucc_lt_succ_iff]
theorem lt_castPred_succ {a : Fin (n + 1)} (ha : succ a ≠ last (n + 1)) :
a < (succ a).castPred ha := by rw [lt_castPred_succ_iff, le_def]
theorem succ_castPred_le_iff {a b : Fin (n + 1)} (ha : a ≠ last n) :
succ (a.castPred ha) ≤ b ↔ a < b := by
rw [succ_castPred_eq_castPred_succ ha, castpred_succ_le_iff]
theorem lt_succ_castPred_iff {a b : Fin (n + 1)} (ha : a ≠ last n) :
b < succ (a.castPred ha) ↔ b ≤ a := by
rw [succ_castPred_eq_castPred_succ ha, lt_castPred_succ_iff]
theorem lt_succ_castPred {a : Fin (n + 1)} (ha : a ≠ last n) :
a < succ (a.castPred ha) := by rw [lt_succ_castPred_iff, le_def]
theorem castPred_le_pred_iff {a b : Fin (n + 1)} (ha : a ≠ last n) (hb : b ≠ 0) :
castPred a ha ≤ pred b hb ↔ a < b := by
rw [le_pred_iff, succ_castPred_le_iff]
theorem pred_lt_castPred_iff {a b : Fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ last n) :
pred a ha < castPred b hb ↔ a ≤ b := by
rw [lt_castPred_iff, castSucc_pred_lt_iff ha]
theorem pred_lt_castPred {a : Fin (n + 1)} (h₁ : a ≠ 0) (h₂ : a ≠ last n) :
pred a h₁ < castPred a h₂ := by
rw [pred_lt_castPred_iff, le_def]
end CastPred
section SuccAbove
variable {p : Fin (n + 1)} {i j : Fin n}
/-- `succAbove p i` embeds `Fin n` into `Fin (n + 1)` with a hole around `p`. -/
def succAbove (p : Fin (n + 1)) (i : Fin n) : Fin (n + 1) :=
if castSucc i < p then i.castSucc else i.succ
/-- Embedding `i : Fin n` into `Fin (n + 1)` with a hole around `p : Fin (n + 1)`
embeds `i` by `castSucc` when the resulting `i.castSucc < p`. -/
lemma succAbove_of_castSucc_lt (p : Fin (n + 1)) (i : Fin n) (h : castSucc i < p) :
p.succAbove i = castSucc i := if_pos h
lemma succAbove_of_succ_le (p : Fin (n + 1)) (i : Fin n) (h : succ i ≤ p) :
p.succAbove i = castSucc i :=
succAbove_of_castSucc_lt _ _ (castSucc_lt_iff_succ_le.mpr h)
/-- Embedding `i : Fin n` into `Fin (n + 1)` with a hole around `p : Fin (n + 1)`
embeds `i` by `succ` when the resulting `p < i.succ`. -/
lemma succAbove_of_le_castSucc (p : Fin (n + 1)) (i : Fin n) (h : p ≤ castSucc i) :
p.succAbove i = i.succ := if_neg (Fin.not_lt.2 h)
lemma succAbove_of_lt_succ (p : Fin (n + 1)) (i : Fin n) (h : p < succ i) :
p.succAbove i = succ i := succAbove_of_le_castSucc _ _ (le_castSucc_iff.mpr h)
lemma succAbove_succ_of_lt (p i : Fin n) (h : p < i) : succAbove p.succ i = i.succ :=
succAbove_of_lt_succ _ _ (succ_lt_succ_iff.mpr h)
lemma succAbove_succ_of_le (p i : Fin n) (h : i ≤ p) : succAbove p.succ i = i.castSucc :=
succAbove_of_succ_le _ _ (succ_le_succ_iff.mpr h)
@[simp] lemma succAbove_succ_self (j : Fin n) : j.succ.succAbove j = j.castSucc :=
succAbove_succ_of_le _ _ Fin.le_rfl
lemma succAbove_castSucc_of_lt (p i : Fin n) (h : i < p) : succAbove p.castSucc i = i.castSucc :=
succAbove_of_castSucc_lt _ _ (castSucc_lt_castSucc_iff.2 h)
lemma succAbove_castSucc_of_le (p i : Fin n) (h : p ≤ i) : succAbove p.castSucc i = i.succ :=
succAbove_of_le_castSucc _ _ (castSucc_le_castSucc_iff.2 h)
@[simp] lemma succAbove_castSucc_self (j : Fin n) : succAbove j.castSucc j = j.succ :=
succAbove_castSucc_of_le _ _ Fin.le_rfl
lemma succAbove_pred_of_lt (p i : Fin (n + 1)) (h : p < i) :
succAbove p (i.pred (Fin.ne_of_gt <| Fin.lt_of_le_of_lt p.zero_le h)) = i := by
rw [succAbove_of_lt_succ _ _ (succ_pred _ _ ▸ h), succ_pred]
lemma succAbove_pred_of_le (p i : Fin (n + 1)) (h : i ≤ p) (hi : i ≠ 0) :
succAbove p (i.pred hi) = (i.pred hi).castSucc := succAbove_of_succ_le _ _ (succ_pred _ _ ▸ h)
@[simp] lemma succAbove_pred_self (p : Fin (n + 1)) (h : p ≠ 0) :
succAbove p (p.pred h) = (p.pred h).castSucc := succAbove_pred_of_le _ _ Fin.le_rfl h
lemma succAbove_castPred_of_lt (p i : Fin (n + 1)) (h : i < p) :
succAbove p (i.castPred (Fin.ne_of_lt <| Nat.lt_of_lt_of_le h p.le_last)) = i := by
rw [succAbove_of_castSucc_lt _ _ (castSucc_castPred _ _ ▸ h), castSucc_castPred]
lemma succAbove_castPred_of_le (p i : Fin (n + 1)) (h : p ≤ i) (hi : i ≠ last n) :
succAbove p (i.castPred hi) = (i.castPred hi).succ :=
succAbove_of_le_castSucc _ _ (castSucc_castPred _ _ ▸ h)
lemma succAbove_castPred_self (p : Fin (n + 1)) (h : p ≠ last n) :
succAbove p (p.castPred h) = (p.castPred h).succ := succAbove_castPred_of_le _ _ Fin.le_rfl h
/-- Embedding `i : Fin n` into `Fin (n + 1)` with a hole around `p : Fin (n + 1)`
never results in `p` itself -/
@[simp]
lemma succAbove_ne (p : Fin (n + 1)) (i : Fin n) : p.succAbove i ≠ p := by
rcases p.castSucc_lt_or_lt_succ i with (h | h)
· rw [succAbove_of_castSucc_lt _ _ h]
exact Fin.ne_of_lt h
· rw [succAbove_of_lt_succ _ _ h]
exact Fin.ne_of_gt h
@[simp]
lemma ne_succAbove (p : Fin (n + 1)) (i : Fin n) : p ≠ p.succAbove i := (succAbove_ne _ _).symm
/-- Given a fixed pivot `p : Fin (n + 1)`, `p.succAbove` is injective. -/
lemma succAbove_right_injective : Injective p.succAbove := by
rintro i j hij
unfold succAbove at hij
split_ifs at hij with hi hj hj
· exact castSucc_injective _ hij
· rw [hij] at hi
cases hj <| Nat.lt_trans j.castSucc_lt_succ hi
· rw [← hij] at hj
cases hi <| Nat.lt_trans i.castSucc_lt_succ hj
· exact succ_injective _ hij
/-- Given a fixed pivot `p : Fin (n + 1)`, `p.succAbove` is injective. -/
lemma succAbove_right_inj : p.succAbove i = p.succAbove j ↔ i = j :=
succAbove_right_injective.eq_iff
@[simp]
lemma succAbove_ne_zero_zero [NeZero n] {a : Fin (n + 1)} (ha : a ≠ 0) : a.succAbove 0 = 0 := by
rw [Fin.succAbove_of_castSucc_lt]
· exact castSucc_zero'
· exact Fin.pos_iff_ne_zero.2 ha
lemma succAbove_eq_zero_iff [NeZero n] {a : Fin (n + 1)} {b : Fin n} (ha : a ≠ 0) :
a.succAbove b = 0 ↔ b = 0 := by
rw [← succAbove_ne_zero_zero ha, succAbove_right_inj]
lemma succAbove_ne_zero [NeZero n] {a : Fin (n + 1)} {b : Fin n} (ha : a ≠ 0) (hb : b ≠ 0) :
a.succAbove b ≠ 0 := mt (succAbove_eq_zero_iff ha).mp hb
/-- Embedding `Fin n` into `Fin (n + 1)` with a hole around zero embeds by `succ`. -/
@[simp] lemma succAbove_zero : succAbove (0 : Fin (n + 1)) = Fin.succ := rfl
lemma succAbove_zero_apply (i : Fin n) : succAbove 0 i = succ i := by rw [succAbove_zero]
@[simp] lemma succAbove_ne_last_last {a : Fin (n + 2)} (h : a ≠ last (n + 1)) :
a.succAbove (last n) = last (n + 1) := by
rw [succAbove_of_lt_succ _ _ (succ_last _ ▸ lt_last_iff_ne_last.2 h), succ_last]
lemma succAbove_eq_last_iff {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ last _) :
a.succAbove b = last _ ↔ b = last _ := by
rw [← succAbove_ne_last_last ha, succAbove_right_inj]
lemma succAbove_ne_last {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ last _) (hb : b ≠ last _) :
a.succAbove b ≠ last _ := mt (succAbove_eq_last_iff ha).mp hb
/-- Embedding `Fin n` into `Fin (n + 1)` with a hole around `last n` embeds by `castSucc`. -/
@[simp] lemma succAbove_last : succAbove (last n) = castSucc := by
ext; simp only [succAbove_of_castSucc_lt, castSucc_lt_last]
lemma succAbove_last_apply (i : Fin n) : succAbove (last n) i = castSucc i := by rw [succAbove_last]
/-- Embedding `i : Fin n` into `Fin (n + 1)` using a pivot `p` that is greater
results in a value that is less than `p`. -/
lemma succAbove_lt_iff_castSucc_lt (p : Fin (n + 1)) (i : Fin n) :
p.succAbove i < p ↔ castSucc i < p := by
rcases castSucc_lt_or_lt_succ p i with H | H
· rwa [iff_true_right H, succAbove_of_castSucc_lt _ _ H]
· rw [castSucc_lt_iff_succ_le, iff_false_right (Fin.not_le.2 H), succAbove_of_lt_succ _ _ H]
exact Fin.not_lt.2 <| Fin.le_of_lt H
lemma succAbove_lt_iff_succ_le (p : Fin (n + 1)) (i : Fin n) :
p.succAbove i < p ↔ succ i ≤ p := by
rw [succAbove_lt_iff_castSucc_lt, castSucc_lt_iff_succ_le]
/-- Embedding `i : Fin n` into `Fin (n + 1)` using a pivot `p` that is lesser
results in a value that is greater than `p`. -/
lemma lt_succAbove_iff_le_castSucc (p : Fin (n + 1)) (i : Fin n) :
p < p.succAbove i ↔ p ≤ castSucc i := by
rcases castSucc_lt_or_lt_succ p i with H | H
· rw [iff_false_right (Fin.not_le.2 H), succAbove_of_castSucc_lt _ _ H]
exact Fin.not_lt.2 <| Fin.le_of_lt H
· rwa [succAbove_of_lt_succ _ _ H, iff_true_left H, le_castSucc_iff]
lemma lt_succAbove_iff_lt_castSucc (p : Fin (n + 1)) (i : Fin n) :
p < p.succAbove i ↔ p < succ i := by rw [lt_succAbove_iff_le_castSucc, le_castSucc_iff]
/-- Embedding a positive `Fin n` results in a positive `Fin (n + 1)` -/
lemma succAbove_pos [NeZero n] (p : Fin (n + 1)) (i : Fin n) (h : 0 < i) : 0 < p.succAbove i := by
by_cases H : castSucc i < p
· simpa [succAbove_of_castSucc_lt _ _ H] using castSucc_pos' h
· simp [succAbove_of_le_castSucc _ _ (Fin.not_lt.1 H)]
lemma castPred_succAbove (x : Fin n) (y : Fin (n + 1)) (h : castSucc x < y)
(h' := Fin.ne_last_of_lt <| (succAbove_lt_iff_castSucc_lt ..).2 h) :
(y.succAbove x).castPred h' = x := by
rw [castPred_eq_iff_eq_castSucc, succAbove_of_castSucc_lt _ _ h]
lemma pred_succAbove (x : Fin n) (y : Fin (n + 1)) (h : y ≤ castSucc x)
(h' := Fin.ne_zero_of_lt <| (lt_succAbove_iff_le_castSucc ..).2 h) :
(y.succAbove x).pred h' = x := by simp only [succAbove_of_le_castSucc _ _ h, pred_succ]
lemma exists_succAbove_eq {x y : Fin (n + 1)} (h : x ≠ y) : ∃ z, y.succAbove z = x := by
obtain hxy | hyx := Fin.lt_or_lt_of_ne h
exacts [⟨_, succAbove_castPred_of_lt _ _ hxy⟩, ⟨_, succAbove_pred_of_lt _ _ hyx⟩]
@[simp] lemma exists_succAbove_eq_iff {x y : Fin (n + 1)} : (∃ z, x.succAbove z = y) ↔ y ≠ x :=
⟨by rintro ⟨y, rfl⟩; exact succAbove_ne _ _, exists_succAbove_eq⟩
/-- The range of `p.succAbove` is everything except `p`. -/
@[simp] lemma range_succAbove (p : Fin (n + 1)) : Set.range p.succAbove = {p}ᶜ :=
Set.ext fun _ => exists_succAbove_eq_iff
@[simp] lemma range_succ (n : ℕ) : Set.range (Fin.succ : Fin n → Fin (n + 1)) = {0}ᶜ := by
rw [← succAbove_zero, range_succAbove]
/-- `succAbove` is injective at the pivot -/
lemma succAbove_left_injective : Injective (@succAbove n) := fun _ _ h => by
simpa [range_succAbove] using congr_arg (fun f : Fin n → Fin (n + 1) => (Set.range f)ᶜ) h
/-- `succAbove` is injective at the pivot -/
@[simp] lemma succAbove_left_inj {x y : Fin (n + 1)} : x.succAbove = y.succAbove ↔ x = y :=
succAbove_left_injective.eq_iff
@[simp] lemma zero_succAbove {n : ℕ} (i : Fin n) : (0 : Fin (n + 1)).succAbove i = i.succ := rfl
lemma succ_succAbove_zero {n : ℕ} [NeZero n] (i : Fin n) : succAbove i.succ 0 = 0 := by simp
/-- `succ` commutes with `succAbove`. -/
@[simp] lemma succ_succAbove_succ {n : ℕ} (i : Fin (n + 1)) (j : Fin n) :
i.succ.succAbove j.succ = (i.succAbove j).succ := by
obtain h | h := i.lt_or_ge (succ j)
· rw [succAbove_of_lt_succ _ _ h, succAbove_succ_of_lt _ _ h]
· rwa [succAbove_of_castSucc_lt _ _ h, succAbove_succ_of_le, succ_castSucc]
/-- `castSucc` commutes with `succAbove`. -/
@[simp]
lemma castSucc_succAbove_castSucc {n : ℕ} {i : Fin (n + 1)} {j : Fin n} :
i.castSucc.succAbove j.castSucc = (i.succAbove j).castSucc := by
rcases i.le_or_gt (castSucc j) with (h | h)
· rw [succAbove_of_le_castSucc _ _ h, succAbove_castSucc_of_le _ _ h, succ_castSucc]
· rw [succAbove_of_castSucc_lt _ _ h, succAbove_castSucc_of_lt _ _ h]
/-- `pred` commutes with `succAbove`. -/
lemma pred_succAbove_pred {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ 0) (hb : b ≠ 0)
(hk := succAbove_ne_zero ha hb) :
(a.pred ha).succAbove (b.pred hb) = (a.succAbove b).pred hk := by
simp_rw [← succ_inj (b := pred (succAbove a b) hk), ← succ_succAbove_succ, succ_pred]
/-- `castPred` commutes with `succAbove`. -/
lemma castPred_succAbove_castPred {a : Fin (n + 2)} {b : Fin (n + 1)} (ha : a ≠ last (n + 1))
(hb : b ≠ last n) (hk := succAbove_ne_last ha hb) :
(a.castPred ha).succAbove (b.castPred hb) = (a.succAbove b).castPred hk := by
simp_rw [← castSucc_inj (b := (a.succAbove b).castPred hk), ← castSucc_succAbove_castSucc,
castSucc_castPred]
lemma one_succAbove_zero {n : ℕ} : (1 : Fin (n + 2)).succAbove 0 = 0 := rfl
/-- By moving `succ` to the outside of this expression, we create opportunities for further
simplification using `succAbove_zero` or `succ_succAbove_zero`. -/
@[simp] lemma succ_succAbove_one {n : ℕ} [NeZero n] (i : Fin (n + 1)) :
i.succ.succAbove 1 = (i.succAbove 0).succ := by
rw [← succ_zero_eq_one']
exact succ_succAbove_succ i 0
@[simp] lemma one_succAbove_succ {n : ℕ} (j : Fin n) :
(1 : Fin (n + 2)).succAbove j.succ = j.succ.succ := by
have := succ_succAbove_succ 0 j; rwa [succ_zero_eq_one, zero_succAbove] at this
@[simp] lemma one_succAbove_one {n : ℕ} : (1 : Fin (n + 3)).succAbove 1 = 2 := by
simpa only [succ_zero_eq_one, val_zero, zero_succAbove, succ_one_eq_two]
using succ_succAbove_succ (0 : Fin (n + 2)) (0 : Fin (n + 1))
end SuccAbove
section PredAbove
/-- `predAbove p i` surjects `i : Fin (n+1)` into `Fin n` by subtracting one if `p < i`. -/
def predAbove (p : Fin n) (i : Fin (n + 1)) : Fin n :=
if h : castSucc p < i
then pred i (Fin.ne_zero_of_lt h)
else castPred i (Fin.ne_of_lt <| Fin.lt_of_le_of_lt (Fin.not_lt.1 h) (castSucc_lt_last _))
lemma predAbove_of_le_castSucc (p : Fin n) (i : Fin (n + 1)) (h : i ≤ castSucc p) :
p.predAbove i = i.castPred (Fin.ne_of_lt <| Fin.lt_of_le_of_lt h <| castSucc_lt_last _) :=
dif_neg <| Fin.not_lt.2 h
lemma predAbove_of_lt_succ (p : Fin n) (i : Fin (n + 1)) (h : i < succ p) :
p.predAbove i = i.castPred (Fin.ne_last_of_lt h) :=
predAbove_of_le_castSucc _ _ (le_castSucc_iff.mpr h)
lemma predAbove_of_castSucc_lt (p : Fin n) (i : Fin (n + 1)) (h : castSucc p < i) :
p.predAbove i = i.pred (Fin.ne_zero_of_lt h) := dif_pos h
lemma predAbove_of_succ_le (p : Fin n) (i : Fin (n + 1)) (h : succ p ≤ i) :
p.predAbove i = i.pred (Fin.ne_of_gt <| Fin.lt_of_lt_of_le (succ_pos _) h) :=
predAbove_of_castSucc_lt _ _ (castSucc_lt_iff_succ_le.mpr h)
lemma predAbove_succ_of_lt (p i : Fin n) (h : i < p) :
p.predAbove (succ i) = (i.succ).castPred (succ_ne_last_of_lt h) := by
rw [predAbove_of_lt_succ _ _ (succ_lt_succ_iff.mpr h)]
lemma predAbove_succ_of_le (p i : Fin n) (h : p ≤ i) : p.predAbove (succ i) = i := by
rw [predAbove_of_succ_le _ _ (succ_le_succ_iff.mpr h), pred_succ]
@[simp] lemma predAbove_succ_self (p : Fin n) : p.predAbove (succ p) = p :=
predAbove_succ_of_le _ _ Fin.le_rfl
lemma predAbove_castSucc_of_lt (p i : Fin n) (h : p < i) :
p.predAbove (castSucc i) = i.castSucc.pred (castSucc_ne_zero_of_lt h) := by
rw [predAbove_of_castSucc_lt _ _ (castSucc_lt_castSucc_iff.2 h)]
lemma predAbove_castSucc_of_le (p i : Fin n) (h : i ≤ p) : p.predAbove (castSucc i) = i := by
rw [predAbove_of_le_castSucc _ _ (castSucc_le_castSucc_iff.mpr h), castPred_castSucc]
@[simp] lemma predAbove_castSucc_self (p : Fin n) : p.predAbove (castSucc p) = p :=
predAbove_castSucc_of_le _ _ Fin.le_rfl
lemma predAbove_pred_of_lt (p i : Fin (n + 1)) (h : i < p) :
(pred p (Fin.ne_zero_of_lt h)).predAbove i = castPred i (Fin.ne_last_of_lt h) := by
rw [predAbove_of_lt_succ _ _ (succ_pred _ _ ▸ h)]
lemma predAbove_pred_of_le (p i : Fin (n + 1)) (h : p ≤ i) (hp : p ≠ 0) :
(pred p hp).predAbove i =
pred i (Fin.ne_of_gt <| Fin.lt_of_lt_of_le (Fin.pos_iff_ne_zero.2 hp) h) := by
rw [predAbove_of_succ_le _ _ (succ_pred _ _ ▸ h)]
lemma predAbove_pred_self (p : Fin (n + 1)) (hp : p ≠ 0) : (pred p hp).predAbove p = pred p hp :=
predAbove_pred_of_le _ _ Fin.le_rfl hp
lemma predAbove_castPred_of_lt (p i : Fin (n + 1)) (h : p < i) :
(castPred p (Fin.ne_last_of_lt h)).predAbove i = pred i (Fin.ne_zero_of_lt h) := by
rw [predAbove_of_castSucc_lt _ _ (castSucc_castPred _ _ ▸ h)]
lemma predAbove_castPred_of_le (p i : Fin (n + 1)) (h : i ≤ p) (hp : p ≠ last n) :
(castPred p hp).predAbove i =
castPred i (Fin.ne_of_lt <| Fin.lt_of_le_of_lt h <| Fin.lt_last_iff_ne_last.2 hp) := by
rw [predAbove_of_le_castSucc _ _ (castSucc_castPred _ _ ▸ h)]
lemma predAbove_castPred_self (p : Fin (n + 1)) (hp : p ≠ last n) :
(castPred p hp).predAbove p = castPred p hp := predAbove_castPred_of_le _ _ Fin.le_rfl hp
@[simp] lemma predAbove_right_zero [NeZero n] {i : Fin n} : predAbove (i : Fin n) 0 = 0 := by
cases n
· exact i.elim0
· rw [predAbove_of_le_castSucc _ _ (zero_le _), castPred_zero]
lemma predAbove_zero_succ [NeZero n] {i : Fin n} : predAbove 0 i.succ = i := by
rw [predAbove_succ_of_le _ _ (Fin.zero_le _)]
@[simp] lemma predAbove_zero_of_ne_zero [NeZero n] {i : Fin (n + 1)} (hi : i ≠ 0) :
predAbove 0 i = i.pred hi := by
obtain ⟨y, rfl⟩ := exists_succ_eq.2 hi
exact predAbove_zero_succ
lemma succ_predAbove_zero [NeZero n] {j : Fin (n + 1)} (h : j ≠ 0) : succ (predAbove 0 j) = j := by
simp [h]
lemma predAbove_zero [NeZero n] {i : Fin (n + 1)} :
predAbove (0 : Fin n) i = if hi : i = 0 then 0 else i.pred hi := by
split_ifs with hi
· rw [hi, predAbove_right_zero]
· rw [predAbove_zero_of_ne_zero hi]
@[simp] lemma predAbove_right_last {i : Fin (n + 1)} : predAbove i (last (n + 1)) = last n := by
rw [predAbove_of_castSucc_lt _ _ (castSucc_lt_last _), pred_last]
lemma predAbove_last_castSucc {i : Fin (n + 1)} : predAbove (last n) (i.castSucc) = i := by
rw [predAbove_of_le_castSucc _ _ (castSucc_le_castSucc_iff.mpr (le_last _)), castPred_castSucc]
@[simp] lemma predAbove_last_of_ne_last {i : Fin (n + 2)} (hi : i ≠ last (n + 1)) :
predAbove (last n) i = castPred i hi := by
rw [← exists_castSucc_eq] at hi
rcases hi with ⟨y, rfl⟩
exact predAbove_last_castSucc
lemma predAbove_last_apply {i : Fin (n + 2)} :
predAbove (last n) i = if hi : i = last _ then last _ else i.castPred hi := by
split_ifs with hi
· rw [hi, predAbove_right_last]
· rw [predAbove_last_of_ne_last hi]
lemma predAbove_surjective {n : ℕ} (p : Fin n) :
Function.Surjective p.predAbove := by
intro i
by_cases hi : i ≤ p
· exact ⟨i.castSucc, predAbove_castSucc_of_le p i hi⟩
· rw [Fin.not_le] at hi
exact ⟨i.succ, predAbove_succ_of_le p i (Fin.le_of_lt hi)⟩
/-- Sending `Fin (n+1)` to `Fin n` by subtracting one from anything above `p`
then back to `Fin (n+1)` with a gap around `p` is the identity away from `p`. -/
@[simp]
lemma succAbove_predAbove {p : Fin n} {i : Fin (n + 1)} (h : i ≠ castSucc p) :
p.castSucc.succAbove (p.predAbove i) = i := by
obtain h | h := Fin.lt_or_lt_of_ne h
· rw [predAbove_of_le_castSucc _ _ (Fin.le_of_lt h), succAbove_castPred_of_lt _ _ h]
· rw [predAbove_of_castSucc_lt _ _ h, succAbove_pred_of_lt _ _ h]
/-- Sending `Fin (n+1)` to `Fin n` by subtracting one from anything above `p`
then back to `Fin (n+1)` with a gap around `p.succ` is the identity away from `p.succ`. -/
@[simp]
lemma succ_succAbove_predAbove {n : ℕ} {p : Fin n} {i : Fin (n + 1)} (h : i ≠ p.succ) :
p.succ.succAbove (p.predAbove i) = i := by
obtain h | h := Fin.lt_or_lt_of_ne h
· rw [predAbove_of_le_castSucc _ _ (le_castSucc_iff.2 h),
succAbove_castPred_of_lt _ _ h]
· rw [predAbove_of_castSucc_lt _ _ (Fin.lt_of_le_of_lt (p.castSucc_le_succ) h),
succAbove_pred_of_lt _ _ h]
/-- Sending `Fin n` into `Fin (n + 1)` with a gap at `p`
then back to `Fin n` by subtracting one from anything above `p` is the identity. -/
@[simp]
lemma predAbove_succAbove (p : Fin n) (i : Fin n) : p.predAbove ((castSucc p).succAbove i) = i := by
obtain h | h := p.le_or_gt i
· rw [succAbove_castSucc_of_le _ _ h, predAbove_succ_of_le _ _ h]
· rw [succAbove_castSucc_of_lt _ _ h, predAbove_castSucc_of_le _ _ <| Fin.le_of_lt h]
/-- `succ` commutes with `predAbove`. -/
@[simp] lemma succ_predAbove_succ (a : Fin n) (b : Fin (n + 1)) :
a.succ.predAbove b.succ = (a.predAbove b).succ := by
obtain h | h := Fin.le_or_gt (succ a) b
· rw [predAbove_of_castSucc_lt _ _ h, predAbove_succ_of_le _ _ h, succ_pred]
· rw [predAbove_of_lt_succ _ _ h, predAbove_succ_of_lt _ _ h, succ_castPred_eq_castPred_succ]
/-- `castSucc` commutes with `predAbove`. -/
@[simp] lemma castSucc_predAbove_castSucc {n : ℕ} (a : Fin n) (b : Fin (n + 1)) :
a.castSucc.predAbove b.castSucc = (a.predAbove b).castSucc := by
obtain h | h := a.castSucc.lt_or_ge b
· rw [predAbove_of_castSucc_lt _ _ h, predAbove_castSucc_of_lt _ _ h,
castSucc_pred_eq_pred_castSucc]
· rw [predAbove_of_le_castSucc _ _ h, predAbove_castSucc_of_le _ _ h, castSucc_castPred]
theorem predAbove_predAbove_succAbove {n : ℕ} (i : Fin (n + 1)) (j : Fin n) :
(j.predAbove i).predAbove (i.succAbove j) = j := by
cases j.castSucc.lt_or_le i with
| inl h =>
rw [predAbove_of_castSucc_lt _ _ h, succAbove_of_castSucc_lt _ _ h, predAbove_of_le_castSucc,
castPred_castSucc]
rwa [le_castSucc_iff, succ_pred]
| inr h =>
rw [predAbove_of_le_castSucc _ _ h, succAbove_of_le_castSucc _ _ h, predAbove_of_castSucc_lt,
pred_succ]
rwa [castSucc_castPred, ← le_castSucc_iff]
theorem succAbove_succAbove_predAbove {n : ℕ} (i : Fin (n + 1)) (j : Fin n) :
(i.succAbove j).succAbove (j.predAbove i) = i := by
cases Fin.lt_or_le j.castSucc i with
| inl h => rw [succAbove_of_castSucc_lt _ _ h, succAbove_predAbove (Fin.ne_of_gt h)]
| inr h =>
rw [succAbove_of_le_castSucc _ _ h,
succ_succAbove_predAbove (Fin.ne_of_lt <| le_castSucc_iff.mp h)]
/-- Given `i : Fin (n + 2)` and `j : Fin (n + 1)`,
there are two ways to represent the order embedding `Fin n → Fin (n + 2)`
leaving holes at `i` and `i.succAbove j`.
One is `i.succAbove ∘ j.succAbove`.
It corresponds to embedding `Fin n` to `Fin (n + 1)` leaving a hole at `j`,
then embedding the result to `Fin (n + 2)` leaving a hole at `i`.
The other one is `(i.succAbove j).succAbove ∘ (j.predAbove i).succAbove`.
It corresponds to swapping the roles of `i` and `j`.
This lemma says that these two ways are equal.
It is used in `Fin.removeNth_removeNth_eq_swap`
to show that two ways of removing 2 elements from a sequence give the same answer.
-/
theorem succAbove_succAbove_succAbove_predAbove {n : ℕ}
(i : Fin (n + 2)) (j : Fin (n + 1)) (k : Fin n) :
(i.succAbove j).succAbove ((j.predAbove i).succAbove k) = i.succAbove (j.succAbove k) := by
/- While it is possible to give a "morally correct" proof
by saying that both functions are strictly monotone and have the same range `{i, i.succAbove j}ᶜ`,
we give a direct proof by case analysis to avoid extra dependencies. -/
ext
simp? [succAbove, predAbove, lt_def, apply_dite Fin.val, apply_ite Fin.val] says
simp only [succAbove, predAbove, lt_def, coe_castSucc, apply_dite Fin.val, coe_pred,
coe_castPred, dite_eq_ite, apply_ite Fin.val, val_succ]
split_ifs <;> omega
end PredAbove
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/VecNotation.lean | import Mathlib.Data.Fin.Tuple.Basic
/-!
# Matrix and vector notation
This file defines notation for vectors and matrices. Given `a b c d : α`,
the notation allows us to write `![a, b, c, d] : Fin 4 → α`.
Nesting vectors gives coefficients of a matrix, so `![![a, b], ![c, d]] : Fin 2 → Fin 2 → α`.
In later files we introduce `!![a, b; c, d]` as notation for `Matrix.of ![![a, b], ![c, d]]`.
## Main definitions
* `vecEmpty` is the empty vector (or `0` by `n` matrix) `![]`
* `vecCons` prepends an entry to a vector, so `![a, b]` is `vecCons a (vecCons b vecEmpty)`
## Implementation notes
The `simp` lemmas require that one of the arguments is of the form `vecCons _ _`.
This ensures `simp` works with entries only when (some) entries are already given.
In other words, this notation will only appear in the output of `simp` if it
already appears in the input.
## Notation
The main new notation is `![a, b]`, which gets expanded to `vecCons a (vecCons b vecEmpty)`.
## Examples
Examples of usage can be found in the `MathlibTest/matrix.lean` file.
-/
namespace Matrix
universe u
variable {α : Type u}
section MatrixNotation
/-- `![]` is the vector with no entries. -/
def vecEmpty : Fin 0 → α :=
Fin.elim0
/-- `vecCons h t` prepends an entry `h` to a vector `t`.
The inverse functions are `vecHead` and `vecTail`.
The notation `![a, b, ...]` expands to `vecCons a (vecCons b ...)`.
-/
def vecCons {n : ℕ} (h : α) (t : Fin n → α) : Fin n.succ → α :=
Fin.cons h t
/-- `![...]` notation is used to construct a vector `Fin n → α` using `Matrix.vecEmpty` and
`Matrix.vecCons`.
For instance, `![a, b, c] : Fin 3` is syntax for `vecCons a (vecCons b (vecCons c vecEmpty))`.
Note that this should not be used as syntax for `Matrix` as it generates a term with the wrong type.
The `!![a, b; c, d]` syntax (provided by `Matrix.matrixNotation`) should be used instead.
-/
syntax (name := vecNotation) "![" term,* "]" : term
macro_rules
| `(![$term:term, $terms:term,*]) => `(vecCons $term ![$terms,*])
| `(![$term:term]) => `(vecCons $term ![])
| `(![]) => `(vecEmpty)
/-- Unexpander for the `![x, y, ...]` notation. -/
@[app_unexpander vecCons]
def vecConsUnexpander : Lean.PrettyPrinter.Unexpander
| `($_ $term ![$term2, $terms,*]) => `(![$term, $term2, $terms,*])
| `($_ $term ![$term2]) => `(![$term, $term2])
| `($_ $term ![]) => `(![$term])
| _ => throw ()
/-- Unexpander for the `![]` notation. -/
@[app_unexpander vecEmpty]
def vecEmptyUnexpander : Lean.PrettyPrinter.Unexpander
| `($_:ident) => `(![])
| _ => throw ()
/-- `vecHead v` gives the first entry of the vector `v` -/
def vecHead {n : ℕ} (v : Fin n.succ → α) : α :=
v 0
/-- `vecTail v` gives a vector consisting of all entries of `v` except the first -/
def vecTail {n : ℕ} (v : Fin n.succ → α) : Fin n → α :=
v ∘ Fin.succ
variable {m n : ℕ}
/-- Use `![...]` notation for displaying a vector `Fin n → α`, for example:
```
#eval ![1, 2] + ![3, 4] -- ![4, 6]
```
-/
instance _root_.PiFin.hasRepr [Repr α] : Repr (Fin n → α) where
reprPrec f _ :=
Std.Format.bracket "![" (Std.Format.joinSep
((List.finRange n).map fun n => repr (f n)) ("," ++ Std.Format.line)) "]"
end MatrixNotation
variable {m n o : ℕ}
theorem empty_eq (v : Fin 0 → α) : v = ![] :=
Subsingleton.elim _ _
section Val
@[simp]
theorem head_fin_const (a : α) : (vecHead fun _ : Fin (n + 1) => a) = a :=
rfl
@[simp]
theorem cons_val_zero (x : α) (u : Fin m → α) : vecCons x u 0 = x :=
rfl
theorem cons_val_zero' (h : 0 < m.succ) (x : α) (u : Fin m → α) : vecCons x u ⟨0, h⟩ = x :=
rfl
@[simp]
theorem cons_val_succ (x : α) (u : Fin m → α) (i : Fin m) : vecCons x u i.succ = u i := by
simp [vecCons]
@[simp]
theorem cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : Fin m → α) :
vecCons x u ⟨i.succ, h⟩ = u ⟨i, Nat.lt_of_succ_lt_succ h⟩ := by
simp only [vecCons, Fin.cons, Fin.cases_succ']
section simprocs
open Lean Qq
/-- Parses a chain of `Matrix.vecCons` calls into elements, leaving everything else in the tail.
`let ⟨xs, tailn, tail⟩ ← matchVecConsPrefix n e` decomposes `e : Fin n → _` in the form
`vecCons x₀ <| ... <| vecCons xₙ <| tail` where `tail : Fin tailn → _`. -/
partial def matchVecConsPrefix (n : Q(Nat)) (e : Expr) : MetaM <| List Expr × Q(Nat) × Expr := do
match_expr ← Meta.whnfR e with
| Matrix.vecCons _ n x xs => do
let (elems, n', tail) ← matchVecConsPrefix n xs
return (x :: elems, n', tail)
| _ =>
return ([], n, e)
open Qq in
/-- A simproc that handles terms of the form `Matrix.vecCons a f i` where `i` is a numeric literal.
In practice, this is most effective at handling `![a, b, c] i`-style terms. -/
dsimproc cons_val (Matrix.vecCons _ _ _) := fun e => do
let_expr Matrix.vecCons α en x xs' ei := ← Meta.whnfR e | return .continue
let some i := ei.int? | return .continue
let (xs, etailn, tail) ← matchVecConsPrefix en xs'
let xs := x :: xs
-- Determine if the tail is a numeral or only an offset.
let (tailn, variadic, etailn) ← do
let etailn_whnf : Q(ℕ) ← Meta.whnfD etailn
if let Expr.lit (.natVal length) := etailn_whnf then
pure (length, false, q(OfNat.ofNat $etailn_whnf))
else if let some ((base : Q(ℕ)), offset) ← (Meta.isOffset? etailn_whnf).run then
let offset_e : Q(ℕ) := mkNatLit offset
pure (offset, true, q($base + $offset))
else
pure (0, true, etailn)
-- Wrap the index if possible, and abort if not
let wrapped_i ←
if variadic then
-- can't wrap as we don't know the length
unless 0 ≤ i ∧ i < xs.length + tailn do return .continue
pure i.toNat
else
pure (i % (xs.length + tailn)).toNat
if h : wrapped_i < xs.length then
return .continue xs[wrapped_i]
else
-- Within the `tail`
let _ ← synthInstanceQ q(NeZero $etailn)
have i_lit : Q(ℕ) := mkRawNatLit (wrapped_i - xs.length)
return .continue (.some <| .app tail q(OfNat.ofNat $i_lit : Fin $etailn))
end simprocs
@[simp]
theorem head_cons (x : α) (u : Fin m → α) : vecHead (vecCons x u) = x :=
rfl
@[simp]
theorem tail_cons (x : α) (u : Fin m → α) : vecTail (vecCons x u) = u := by
ext
simp [vecTail]
theorem empty_val' {n' : Type*} (j : n') : (fun i => (![] : Fin 0 → n' → α) i j) = ![] :=
empty_eq _
@[simp]
theorem cons_head_tail (u : Fin m.succ → α) : vecCons (vecHead u) (vecTail u) = u :=
Fin.cons_self_tail _
@[simp]
theorem range_cons (x : α) (u : Fin n → α) : Set.range (vecCons x u) = {x} ∪ Set.range u :=
Set.ext fun y => by simp [Fin.exists_fin_succ, eq_comm]
@[simp]
theorem range_empty (u : Fin 0 → α) : Set.range u = ∅ :=
Set.range_eq_empty _
theorem range_cons_empty (x : α) (u : Fin 0 → α) : Set.range (Matrix.vecCons x u) = {x} := by
rw [range_cons, range_empty, Set.union_empty]
-- simp can prove this (up to commutativity)
theorem range_cons_cons_empty (x y : α) (u : Fin 0 → α) :
Set.range (vecCons x <| vecCons y u) = {x, y} := by
rw [range_cons, range_cons_empty, Set.singleton_union]
theorem vecCons_const (a : α) : (vecCons a fun _ : Fin n => a) = fun _ => a :=
funext <| Fin.forall_iff_succ.2 ⟨rfl, cons_val_succ _ _⟩
theorem vec_single_eq_const (a : α) : ![a] = fun _ => a :=
let _ : Unique (Fin 1) := inferInstance
funext <| Unique.forall_iff.2 rfl
/-- `![a, b, ...] 1` is equal to `b`.
The simplifier needs a special lemma for length `≥ 2`, in addition to
`cons_val_succ`, because `1 : Fin 1 = 0 : Fin 1`.
-/
@[simp]
theorem cons_val_one (x : α) (u : Fin m.succ → α) : vecCons x u 1 = u 0 :=
rfl
theorem cons_val_two (x : α) (u : Fin m.succ.succ → α) : vecCons x u 2 = vecHead (vecTail u) := rfl
lemma cons_val_three (x : α) (u : Fin m.succ.succ.succ → α) :
vecCons x u 3 = vecHead (vecTail (vecTail u)) :=
rfl
lemma cons_val_four (x : α) (u : Fin m.succ.succ.succ.succ → α) :
vecCons x u 4 = vecHead (vecTail (vecTail (vecTail u))) :=
rfl
@[simp]
theorem cons_val_fin_one (x : α) (u : Fin 0 → α) : ∀ (i : Fin 1), vecCons x u i = x := by
rw [Fin.forall_fin_one]
rfl
theorem cons_fin_one (x : α) (u : Fin 0 → α) : vecCons x u = fun _ => x :=
funext (cons_val_fin_one x u)
@[simp]
theorem vecCons_inj {x y : α} {u v : Fin n → α} : vecCons x u = vecCons y v ↔ x = y ∧ u = v :=
Fin.cons_inj
open Lean Qq in
/-- `mkVecLiteralQ ![x, y, z]` produces the term `q(![$x, $y, $z])`. -/
def _root_.PiFin.mkLiteralQ {u : Level} {α : Q(Type u)} {n : ℕ} (elems : Fin n → Q($α)) :
Q(Fin $n → $α) :=
loop 0 q(vecEmpty)
where
/-- The core logic of `loop` is that `loop 0 ![] = ![a 0, a 1, a 2] = loop 1 ![a 2]`, where
recursion starts from the end. In this example, on the right-hand side, the variable `rest := 1`
tracks the length of the current generated notation `![a 2]`, and the last used index is
`n - rest` (`= 3 - 1 = 2`). -/
loop (i : ℕ) (rest : Q(Fin $i → $α)) : Q(Fin $n → $α) :=
if h : i < n then
loop (i + 1) q(vecCons $(elems (Fin.rev ⟨i, h⟩)) $rest)
else
rest
open Lean Qq in
protected instance _root_.PiFin.toExpr [ToLevel.{u}] [ToExpr α] (n : ℕ) : ToExpr (Fin n → α) :=
have lu := toLevel.{u}
have eα : Q(Type $lu) := toTypeExpr α
let toTypeExpr := q(Fin $n → $eα)
{ toTypeExpr, toExpr v := PiFin.mkLiteralQ fun i => show Q($eα) from toExpr (v i) }
/-! ### `bit0` and `bit1` indices
The following definitions and `simp` lemmas are used to allow
numeral-indexed element of a vector given with matrix notation to
be extracted by `simp` in Lean 3 (even when the numeral is larger than the
number of elements in the vector, which is taken modulo that number
of elements by virtue of the semantics of `bit0` and `bit1` and of
addition on `Fin n`).
-/
/-- `vecAppend ho u v` appends two vectors of lengths `m` and `n` to produce
one of length `o = m + n`. This is a variant of `Fin.append` with an additional `ho` argument,
which provides control of definitional equality for the vector length.
This turns out to be helpful when providing simp lemmas to reduce `![a, b, c] n`, and also means
that `vecAppend ho u v 0` is valid. `Fin.append u v 0` is not valid in this case because there is
no `Zero (Fin (m + n))` instance. -/
def vecAppend {α : Type*} {o : ℕ} (ho : o = m + n) (u : Fin m → α) (v : Fin n → α) : Fin o → α :=
Fin.append u v ∘ Fin.cast ho
theorem vecAppend_eq_ite {α : Type*} {o : ℕ} (ho : o = m + n) (u : Fin m → α) (v : Fin n → α) :
vecAppend ho u v = fun i : Fin o =>
if h : (i : ℕ) < m then u ⟨i, h⟩ else v ⟨(i : ℕ) - m, by cutsat⟩ := by
ext i
rw [vecAppend, Fin.append, Function.comp_apply, Fin.addCases]
congr with hi
simp only [eq_rec_constant]
rfl
@[simp]
theorem vecAppend_apply_zero {α : Type*} {o : ℕ} (ho : o + 1 = m + 1 + n) (u : Fin (m + 1) → α)
(v : Fin n → α) : vecAppend ho u v 0 = u 0 :=
dif_pos _
@[simp]
theorem empty_vecAppend (v : Fin n → α) : vecAppend n.zero_add.symm ![] v = v := by
ext
simp [vecAppend_eq_ite]
@[simp]
theorem vecAppend_empty (v : Fin n → α) : vecAppend rfl v ![] = v := by
ext
simp [vecAppend_eq_ite]
@[simp]
theorem cons_vecAppend (ho : o + 1 = m + 1 + n) (x : α) (u : Fin m → α) (v : Fin n → α) :
vecAppend ho (vecCons x u) v = vecCons x (vecAppend (by cutsat) u v) := by
ext i
simp_rw [vecAppend_eq_ite]
split_ifs with h
· rcases i with ⟨⟨⟩ | i, hi⟩
· simp
· simp only [Nat.add_lt_add_iff_right] at h
simp [h]
· rcases i with ⟨⟨⟩ | i, hi⟩
· simp at h
· rw [not_lt, Fin.val_mk, Nat.add_le_add_iff_right] at h
simp [not_lt.2 h]
/-- `vecAlt0 v` gives a vector with half the length of `v`, with
only alternate elements (even-numbered). -/
def vecAlt0 (hm : m = n + n) (v : Fin m → α) (k : Fin n) : α := v ⟨(k : ℕ) + k, by cutsat⟩
/-- `vecAlt1 v` gives a vector with half the length of `v`, with
only alternate elements (odd-numbered). -/
def vecAlt1 (hm : m = n + n) (v : Fin m → α) (k : Fin n) : α :=
v ⟨(k : ℕ) + k + 1, hm.symm ▸ Nat.add_succ_lt_add k.2 k.2⟩
section bits
theorem vecAlt0_vecAppend (v : Fin n → α) :
vecAlt0 rfl (vecAppend rfl v v) = v ∘ (fun n ↦ n + n) := by
ext i
simp_rw [Function.comp, vecAlt0, vecAppend_eq_ite]
split_ifs with h <;> congr
· rw [Fin.val_mk] at h
exact (Nat.mod_eq_of_lt h).symm
· rw [Fin.val_mk, not_lt] at h
simp only [Nat.mod_eq_sub_mod h]
refine (Nat.mod_eq_of_lt ?_).symm
cutsat
theorem vecAlt1_vecAppend (v : Fin (n + 1) → α) :
vecAlt1 rfl (vecAppend rfl v v) = v ∘ (fun n ↦ (n + n) + 1) := by
ext i
simp_rw [Function.comp, vecAlt1, vecAppend_eq_ite]
cases n with
| zero =>
obtain ⟨i, hi⟩ := i
simp only [Nat.zero_add, Nat.lt_one_iff] at hi; subst i; rfl
| succ n =>
split_ifs with h <;> congr
· simp [Nat.mod_eq_of_lt, h]
· rw [Fin.val_mk, not_lt] at h
simp only [Nat.mod_add_mod,
Nat.mod_eq_sub_mod h, show 1 % (n + 2) = 1 from Nat.mod_eq_of_lt (by cutsat)]
refine (Nat.mod_eq_of_lt ?_).symm
cutsat
@[simp]
theorem vecHead_vecAlt0 (hm : m + 2 = n + 1 + (n + 1)) (v : Fin (m + 2) → α) :
vecHead (vecAlt0 hm v) = v 0 :=
rfl
@[simp]
theorem vecHead_vecAlt1 (hm : m + 2 = n + 1 + (n + 1)) (v : Fin (m + 2) → α) :
vecHead (vecAlt1 hm v) = v 1 := by simp [vecHead, vecAlt1]
theorem cons_vec_bit0_eq_alt0 (x : α) (u : Fin n → α) (i : Fin (n + 1)) :
vecCons x u (i + i) = vecAlt0 rfl (vecAppend rfl (vecCons x u) (vecCons x u)) i := by
rw [vecAlt0_vecAppend]; rfl
theorem cons_vec_bit1_eq_alt1 (x : α) (u : Fin n → α) (i : Fin (n + 1)) :
vecCons x u ((i + i) + 1) = vecAlt1 rfl (vecAppend rfl (vecCons x u) (vecCons x u)) i := by
rw [vecAlt1_vecAppend]; rfl
end bits
@[simp]
theorem cons_vecAlt0 (h : m + 1 + 1 = n + 1 + (n + 1)) (x y : α) (u : Fin m → α) :
vecAlt0 h (vecCons x (vecCons y u)) = vecCons x (vecAlt0 (by cutsat) u) := by
ext i
simp_rw [vecAlt0]
rcases i with ⟨⟨⟩ | i, hi⟩
· rfl
· simp only [← Nat.add_assoc, Nat.add_right_comm, cons_val_succ',
vecAlt0]
@[simp]
theorem empty_vecAlt0 (α) {h} : vecAlt0 h (![] : Fin 0 → α) = ![] := by
simp [eq_iff_true_of_subsingleton]
@[simp]
theorem cons_vecAlt1 (h : m + 1 + 1 = n + 1 + (n + 1)) (x y : α) (u : Fin m → α) :
vecAlt1 h (vecCons x (vecCons y u)) = vecCons y (vecAlt1 (by cutsat) u) := by
ext i
simp_rw [vecAlt1]
rcases i with ⟨⟨⟩ | i, hi⟩
· rfl
· simp [vecAlt1, Nat.add_right_comm, ← Nat.add_assoc]
@[simp]
theorem empty_vecAlt1 (α) {h} : vecAlt1 h (![] : Fin 0 → α) = ![] := by
simp [eq_iff_true_of_subsingleton]
end Val
lemma const_fin1_eq (x : α) : (fun _ : Fin 1 => x) = ![x] :=
(cons_fin_one x _).symm
end Matrix |
.lake/packages/mathlib/Mathlib/Data/Fin/FlagRange.lean | import Mathlib.Order.Fin.Basic
import Mathlib.Order.Preorder.Chain
/-!
# Range of `f : Fin (n + 1) → α` as a `Flag`
Let `f : Fin (n + 1) → α` be an `(n + 1)`-tuple `(f₀, …, fₙ)` such that
- `f₀ = ⊥` and `fₙ = ⊤`;
- `fₖ₊₁` weakly covers `fₖ` for all `0 ≤ k < n`;
this means that `fₖ ≤ fₖ₊₁` and there is no `c` such that `fₖ<c<fₖ₊₁`.
Then the range of `f` is a maximal chain.
We formulate this result in terms of `IsMaxChain` and `Flag`.
-/
open Set
variable {α : Type*} [PartialOrder α] [BoundedOrder α] {n : ℕ} {f : Fin (n + 1) → α}
/-- Let `f : Fin (n + 1) → α` be an `(n + 1)`-tuple `(f₀, …, fₙ)` such that
- `f₀ = ⊥` and `fₙ = ⊤`;
- `fₖ₊₁` weakly covers `fₖ` for all `0 ≤ k < n`;
this means that `fₖ ≤ fₖ₊₁` and there is no `c` such that `fₖ<c<fₖ₊₁`.
Then the range of `f` is a maximal chain. -/
theorem IsMaxChain.range_fin_of_covBy (h0 : f 0 = ⊥) (hlast : f (.last n) = ⊤)
(hcovBy : ∀ k : Fin n, f k.castSucc ⩿ f k.succ) :
IsMaxChain (· ≤ ·) (range f) := by
have hmono : Monotone f := Fin.monotone_iff_le_succ.2 fun k ↦ (hcovBy k).1
refine ⟨hmono.isChain_range, fun t htc hbt ↦ hbt.antisymm fun x hx ↦ ?_⟩
rw [mem_range]; by_contra! h
suffices ∀ k, f k < x by simpa [hlast] using this (.last _)
intro k
induction k using Fin.induction with
| zero => simpa [h0, bot_lt_iff_ne_bot] using (h 0).symm
| succ k ihk =>
rw [range_subset_iff] at hbt
exact (htc.lt_of_le (hbt k.succ) hx (h _)).resolve_right ((hcovBy k).2 ihk)
/-- Let `f : Fin (n + 1) → α` be an `(n + 1)`-tuple `(f₀, …, fₙ)` such that
- `f₀ = ⊥` and `fₙ = ⊤`;
- `fₖ₊₁` weakly covers `fₖ` for all `0 ≤ k < n`;
this means that `fₖ ≤ fₖ₊₁` and there is no `c` such that `fₖ<c<fₖ₊₁`.
Then the range of `f` is a `Flag α`. -/
@[simps]
def Flag.rangeFin (f : Fin (n + 1) → α) (h0 : f 0 = ⊥) (hlast : f (.last n) = ⊤)
(hcovBy : ∀ k : Fin n, f k.castSucc ⩿ f k.succ) : Flag α where
carrier := range f
Chain' := (IsMaxChain.range_fin_of_covBy h0 hlast hcovBy).1
max_chain' := (IsMaxChain.range_fin_of_covBy h0 hlast hcovBy).2
@[simp] theorem Flag.mem_rangeFin {x h0 hlast hcovBy} :
x ∈ rangeFin f h0 hlast hcovBy ↔ ∃ k, f k = x :=
Iff.rfl |
.lake/packages/mathlib/Mathlib/Data/Fin/SuccPredOrder.lean | import Mathlib.Order.Fin.Basic
import Mathlib.Order.SuccPred.Basic
/-!
# `SuccOrder` and `PredOrder` of `Fin n`
In this file, we show that `Fin n` is both a `SuccOrder` and a `PredOrder`. Note that they are
also archimedean, but this is derived from the general instance for well-orderings as opposed
to a specific `Fin` instance.
-/
namespace Fin
instance : ∀ {n : ℕ}, SuccOrder (Fin n)
| 0 => by constructor <;> intro a <;> exact elim0 a
| n + 1 =>
SuccOrder.ofCore (Fin.lastCases (Fin.last n) Fin.succ)
(fun {i} hi j ↦ by
obtain ⟨i, rfl⟩ := Fin.eq_castSucc_of_ne_last (by simpa using hi)
simp [castSucc_lt_iff_succ_le])
(fun i hi ↦ by
obtain rfl : i = Fin.last n := by simpa using hi
simp)
lemma orderSucc_eq {n : ℕ} :
Order.succ = Fin.lastCases (Fin.last n) Fin.succ := rfl
lemma orderSucc_apply {n : ℕ} (i : Fin (n + 1)) :
Order.succ i = Fin.lastCases (Fin.last n) Fin.succ i := rfl
@[simp]
lemma orderSucc_last (n : ℕ) :
Order.succ (Fin.last n) = Fin.last n := by
simp [orderSucc_apply]
@[simp]
lemma orderSucc_castSucc {n : ℕ} (i : Fin n) :
Order.succ i.castSucc = i.succ := by
simp [orderSucc_apply]
instance : ∀ {n : ℕ}, PredOrder (Fin n)
| 0 => by constructor <;> first | intro a; exact elim0 a
| n + 1 =>
PredOrder.ofCore
(Fin.cases 0 Fin.castSucc)
(fun {i} hi j ↦ by
obtain ⟨i, rfl⟩ := Fin.eq_succ_of_ne_zero (by simpa using hi)
simp [le_castSucc_iff])
(fun i hi ↦ by
obtain rfl : i = 0 := by simpa using hi
rfl)
lemma orderPred_eq {n : ℕ} :
Order.succ = Fin.lastCases (Fin.last n) Fin.succ := rfl
lemma orderPred_apply {n : ℕ} (i : Fin (n + 1)) :
Order.pred i = Fin.cases 0 Fin.castSucc i := rfl
@[simp]
lemma orderPred_zero (n : ℕ) :
Order.pred (0 : Fin (n + 1)) = 0 :=
rfl
@[simp]
lemma orderPred_succ {n : ℕ} (i : Fin n) :
Order.pred i.succ = i.castSucc :=
rfl
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Basic.lean | import Mathlib.Data.Int.DivMod
import Mathlib.Order.Lattice
import Mathlib.Tactic.Common
import Batteries.Data.Fin.Basic
/-!
# The finite type with `n` elements
`Fin n` is the type whose elements are natural numbers smaller than `n`.
This file expands on the development in the core library.
## Main definitions
* `finZeroElim` : Elimination principle for the empty set `Fin 0`, generalizes `Fin.elim0`.
Further definitions and eliminators can be found in `Init.Data.Fin.Lemmas`
* `Fin.equivSubtype` : Equivalence between `Fin n` and `{ i // i < n }`.
-/
assert_not_exists Monoid Finset
open Fin Nat Function
attribute [simp] Fin.succ_ne_zero Fin.castSucc_lt_last
/-- Elimination principle for the empty set `Fin 0`, dependent version. -/
def finZeroElim {α : Fin 0 → Sort*} (x : Fin 0) : α x :=
x.elim0
namespace Fin
@[simp] theorem mk_eq_one {n a : Nat} {ha : a < n + 2} :
(⟨a, ha⟩ : Fin (n + 2)) = 1 ↔ a = 1 :=
mk.inj_iff
@[simp] theorem one_eq_mk {n a : Nat} {ha : a < n + 2} :
1 = (⟨a, ha⟩ : Fin (n + 2)) ↔ a = 1 := by
simp [eq_comm]
instance {n : ℕ} : CanLift ℕ (Fin n) Fin.val (· < n) where
prf k hk := ⟨⟨k, hk⟩, rfl⟩
/-- A dependent variant of `Fin.elim0`. -/
def rec0 {α : Fin 0 → Sort*} (i : Fin 0) : α i := absurd i.2 (Nat.not_lt_zero _)
variable {n m : ℕ}
theorem val_injective : Function.Injective (@Fin.val n) :=
@Fin.eq_of_val_eq n
/-- If you actually have an element of `Fin n`, then the `n` is always positive -/
lemma size_positive : Fin n → 0 < n := Fin.pos
lemma size_positive' [Nonempty (Fin n)] : 0 < n :=
‹Nonempty (Fin n)›.elim Fin.pos
protected theorem prop (a : Fin n) : a.val < n :=
a.2
lemma lt_last_iff_ne_last {a : Fin (n + 1)} : a < last n ↔ a ≠ last n := by
simp [Fin.lt_iff_le_and_ne, le_last]
lemma ne_zero_of_lt {a b : Fin (n + 1)} (hab : a < b) : b ≠ 0 :=
Fin.ne_of_gt <| Fin.lt_of_le_of_lt a.zero_le hab
lemma ne_last_of_lt {a b : Fin (n + 1)} (hab : a < b) : a ≠ last n :=
Fin.ne_of_lt <| Fin.lt_of_lt_of_le hab b.le_last
/-- Equivalence between `Fin n` and `{ i // i < n }`. -/
@[simps apply symm_apply]
def equivSubtype : Fin n ≃ { i // i < n } where
toFun a := ⟨a.1, a.2⟩
invFun a := ⟨a.1, a.2⟩
section coe
/-!
### coercions and constructions
-/
theorem val_eq_val (a b : Fin n) : (a : ℕ) = b ↔ a = b :=
Fin.ext_iff.symm
theorem ne_iff_vne (a b : Fin n) : a ≠ b ↔ a.1 ≠ b.1 :=
Fin.ext_iff.not
theorem mk_eq_mk {a h a' h'} : @mk n a h = @mk n a' h' ↔ a = a' :=
Fin.ext_iff
/-- Assume `k = l`. If two functions defined on `Fin k` and `Fin l` are equal on each element,
then they coincide (in the heq sense). -/
protected theorem heq_fun_iff {α : Sort*} {k l : ℕ} (h : k = l) {f : Fin k → α} {g : Fin l → α} :
f ≍ g ↔ ∀ i : Fin k, f i = g ⟨(i : ℕ), h ▸ i.2⟩ := by
subst h
simp [funext_iff]
/-- Assume `k = l` and `k' = l'`.
If two functions `Fin k → Fin k' → α` and `Fin l → Fin l' → α` are equal on each pair,
then they coincide (in the heq sense). -/
protected theorem heq_fun₂_iff {α : Sort*} {k l k' l' : ℕ} (h : k = l) (h' : k' = l')
{f : Fin k → Fin k' → α} {g : Fin l → Fin l' → α} :
f ≍ g ↔ ∀ (i : Fin k) (j : Fin k'), f i j = g ⟨(i : ℕ), h ▸ i.2⟩ ⟨(j : ℕ), h' ▸ j.2⟩ := by
subst h
subst h'
simp [funext_iff]
/-- Two elements of `Fin k` and `Fin l` are heq iff their values in `ℕ` coincide. This requires
`k = l`. For the left implication without this assumption, see `val_eq_val_of_heq`. -/
protected theorem heq_ext_iff {k l : ℕ} (h : k = l) {i : Fin k} {j : Fin l} :
i ≍ j ↔ (i : ℕ) = (j : ℕ) := by
subst h
simp [val_eq_val]
end coe
section Order
/-!
### order
-/
/-- `Fin.lt_or_ge` is an alias of `Fin.lt_or_le`.
It is preferred since it follows the mathlib naming convention. -/
protected alias lt_or_ge := Fin.lt_or_le
/-- `Fin.le_or_gt` is an alias of `Fin.le_or_lt`.
It is preferred since it follows the mathlib naming convention. -/
protected alias le_or_gt := Fin.le_or_lt
theorem le_iff_val_le_val {a b : Fin n} : a ≤ b ↔ (a : ℕ) ≤ b :=
Iff.rfl
/-- `a < b` as natural numbers if and only if `a < b` in `Fin n`. -/
@[norm_cast, simp]
theorem val_fin_lt {n : ℕ} {a b : Fin n} : (a : ℕ) < (b : ℕ) ↔ a < b :=
Iff.rfl
/-- `a ≤ b` as natural numbers if and only if `a ≤ b` in `Fin n`. -/
@[norm_cast, simp]
theorem val_fin_le {n : ℕ} {a b : Fin n} : (a : ℕ) ≤ (b : ℕ) ↔ a ≤ b :=
Iff.rfl
theorem min_val {a : Fin n} : min (a : ℕ) n = a := by simp
theorem max_val {a : Fin n} : max (a : ℕ) n = n := by simp
/-- Use the ordering on `Fin n` for checking recursive definitions.
For example, the following definition is not accepted by the termination checker,
unless we declare the `WellFoundedRelation` instance:
```lean
def factorial {n : ℕ} : Fin n → ℕ
| ⟨0, _⟩ := 1
| ⟨i + 1, hi⟩ := (i + 1) * factorial ⟨i, i.lt_succ_self.trans hi⟩
```
-/
instance {n : ℕ} : WellFoundedRelation (Fin n) :=
measure (val : Fin n → ℕ)
/-- `Fin.mk_zero` in `Lean` only applies in `Fin (n + 1)`.
This one instead uses a `NeZero n` typeclass hypothesis.
-/
@[simp]
theorem mk_zero' (n : ℕ) [NeZero n] : (⟨0, pos_of_neZero n⟩ : Fin n) = 0 := rfl
@[deprecated Fin.zero_le (since := "2025-05-13")]
protected theorem zero_le' [NeZero n] (a : Fin n) : 0 ≤ a :=
Nat.zero_le a.val
@[simp, norm_cast]
theorem val_pos_iff [NeZero n] {a : Fin n} : 0 < a.val ↔ 0 < a := by
rw [← val_fin_lt, val_zero]
/--
The `Fin.pos_iff_ne_zero` in `Lean` only applies in `Fin (n+1)`.
This one instead uses a `NeZero n` typeclass hypothesis.
-/
theorem pos_iff_ne_zero' [NeZero n] (a : Fin n) : 0 < a ↔ a ≠ 0 := by
rw [← val_pos_iff, Nat.pos_iff_ne_zero, val_ne_zero_iff]
@[simp] lemma cast_eq_self (a : Fin n) : a.cast rfl = a := rfl
@[simp] theorem cast_eq_zero {k l : ℕ} [NeZero k] [NeZero l]
(h : k = l) (x : Fin k) : Fin.cast h x = 0 ↔ x = 0 := by
simp [← val_eq_zero_iff]
lemma cast_injective {k l : ℕ} (h : k = l) : Injective (Fin.cast h) :=
fun a b hab ↦ by simpa [← val_eq_val] using hab
theorem last_pos' [NeZero n] : 0 < last n := n.pos_of_neZero
theorem one_lt_last [NeZero n] : 1 < last (n + 1) := by
rw [lt_iff_val_lt_val, val_one, val_last, Nat.lt_add_left_iff_pos, Nat.pos_iff_ne_zero]
exact NeZero.ne n
end Order
/-! ### Coercions to `ℤ` and the `fin_omega` tactic. -/
open Int
theorem coe_int_sub_eq_ite {n : Nat} (u v : Fin n) :
((u - v : Fin n) : Int) = if v ≤ u then (u - v : Int) else (u - v : Int) + n := by
rw [Fin.sub_def]
split
· rw [natCast_emod, Int.emod_eq_sub_self_emod, Int.emod_eq_of_lt] <;> omega
· rw [natCast_emod, Int.emod_eq_of_lt] <;> omega
theorem coe_int_sub_eq_mod {n : Nat} (u v : Fin n) :
((u - v : Fin n) : Int) = ((u : Int) - (v : Int)) % n := by
rw [coe_int_sub_eq_ite]
split
· rw [Int.emod_eq_of_lt] <;> omega
· rw [Int.emod_eq_add_self_emod, Int.emod_eq_of_lt] <;> omega
theorem coe_int_add_eq_ite {n : Nat} (u v : Fin n) :
((u + v : Fin n) : Int) = if (u + v : ℕ) < n then (u + v : Int) else (u + v : Int) - n := by
rw [Fin.add_def]
split
· rw [natCast_emod, Int.emod_eq_of_lt] <;> omega
· rw [natCast_emod, Int.emod_eq_sub_self_emod, Int.emod_eq_of_lt] <;> omega
theorem coe_int_add_eq_mod {n : Nat} (u v : Fin n) :
((u + v : Fin n) : Int) = ((u : Int) + (v : Int)) % n := by
omega
-- Write `a + b` as `if (a + b : ℕ) < n then (a + b : ℤ) else (a + b : ℤ) - n` and
-- similarly `a - b` as `if (b : ℕ) ≤ a then (a - b : ℤ) else (a - b : ℤ) + n`.
attribute [fin_omega] coe_int_sub_eq_ite coe_int_add_eq_ite
-- Rewrite inequalities in `Fin` to inequalities in `ℕ`
attribute [fin_omega] Fin.lt_iff_val_lt_val Fin.le_iff_val_le_val
-- Rewrite `1 : Fin (n + 2)` to `1 : ℤ`
attribute [fin_omega] val_one
/--
Preprocessor for `omega` to handle inequalities in `Fin`.
Note that this involves a lot of case splitting, so may be slow.
-/
-- Further adjustment to the simp set can probably make this more powerful.
-- Please experiment and PR updates!
macro "fin_omega" : tactic => `(tactic|
{ try simp only [fin_omega, ← Int.ofNat_lt, ← Int.ofNat_le] at *
omega })
section Add
/-!
### addition, numerals, and coercion from Nat
-/
theorem val_one' (n : ℕ) [NeZero n] : ((1 : Fin n) : ℕ) = 1 % n :=
rfl
theorem nontrivial_iff_two_le : Nontrivial (Fin n) ↔ 2 ≤ n := by
simp [← not_subsingleton_iff_nontrivial, subsingleton_iff_le_one]; cutsat
instance instNontrivial [n.AtLeastTwo] : Nontrivial (Fin n) :=
nontrivial_iff_two_le.2 Nat.AtLeastTwo.one_lt
/-- If working with more than two elements, we can always pick a third distinct from two existing
elements. -/
theorem exists_ne_and_ne_of_two_lt (i j : Fin n) (h : 2 < n) : ∃ k, k ≠ i ∧ k ≠ j := by
have : NeZero n := ⟨by cutsat⟩
rcases i with ⟨i, hi⟩
rcases j with ⟨j, hj⟩
simp_rw [← Fin.val_ne_iff]
by_cases h0 : 0 ≠ i ∧ 0 ≠ j
· exact ⟨0, h0⟩
· by_cases h1 : 1 ≠ i ∧ 1 ≠ j
· exact ⟨⟨1, by cutsat⟩, h1⟩
· refine ⟨⟨2, by cutsat⟩, ?_⟩
dsimp only
cutsat
section Monoid
instance inhabitedFinOneAdd (n : ℕ) : Inhabited (Fin (1 + n)) :=
haveI : NeZero (1 + n) := by rw [Nat.add_comm]; infer_instance
inferInstance
@[simp]
theorem default_eq_zero (n : ℕ) [NeZero n] : (default : Fin n) = 0 :=
rfl
end Monoid
theorem val_add_eq_ite {n : ℕ} (a b : Fin n) :
(↑(a + b) : ℕ) = if n ≤ a + b then a + b - n else a + b := by
rw [Fin.val_add, Nat.add_mod_eq_ite, Nat.mod_eq_of_lt (show ↑a < n from a.2),
Nat.mod_eq_of_lt (show ↑b < n from b.2)]
theorem val_add_eq_of_add_lt {n : ℕ} {a b : Fin n} (huv : a.val + b.val < n) :
(a + b).val = a.val + b.val := by
rw [val_add]
simp [Nat.mod_eq_of_lt huv]
lemma intCast_val_sub_eq_sub_add_ite {n : ℕ} (a b : Fin n) :
((a - b).val : ℤ) = a.val - b.val + if b ≤ a then 0 else n := by
split <;> fin_omega
lemma sub_val_lt_sub {n : ℕ} {i j : Fin n} (hij : i ≤ j) : (j - i).val < n - i.val := by
simp [sub_val_of_le hij, Nat.sub_lt_sub_right hij j.isLt]
lemma castLT_sub_nezero {n : ℕ} {i j : Fin n} (hij : i < j) :
letI : NeZero (n - i.1) := neZero_iff.mpr (by cutsat)
(j - i).castLT (sub_val_lt_sub (Fin.le_of_lt hij)) ≠ 0 := by
refine Ne.symm (ne_of_val_ne ?_)
simpa [coe_sub_iff_le.mpr (Fin.le_of_lt hij)] using by cutsat
lemma one_le_of_ne_zero {n : ℕ} [NeZero n] {k : Fin n} (hk : k ≠ 0) : 1 ≤ k := by
obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne n)
cases n with
| zero => simp only [Fin.isValue, Fin.zero_le]
| succ n => rwa [Fin.le_iff_val_le_val, Fin.val_one, Nat.one_le_iff_ne_zero, val_ne_zero_iff]
lemma val_sub_one_of_ne_zero [NeZero n] {i : Fin n} (hi : i ≠ 0) : (i - 1).val = i - 1 := by
obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero (NeZero.ne n)
rw [Fin.sub_val_of_le (one_le_of_ne_zero hi), Fin.val_one', Nat.mod_eq_of_lt
(Nat.succ_le_iff.mpr (nontrivial_iff_two_le.mp <| nontrivial_of_ne i 0 hi))]
section OfNatCoe
-- We allow the coercion from `Nat` to `Fin` in this section.
open Fin.NatCast
@[simp]
theorem ofNat_eq_cast (n : ℕ) [NeZero n] (a : ℕ) : Fin.ofNat n a = (a : Fin n) :=
rfl
@[deprecated ofNat_eq_cast (since := "2025-05-30")]
alias ofNat'_eq_cast := ofNat_eq_cast
@[simp] lemma val_natCast (a n : ℕ) [NeZero n] : (a : Fin n).val = a % n := rfl
/-- Converting an in-range number to `Fin (n + 1)` produces a result
whose value is the original number. -/
theorem val_cast_of_lt {n : ℕ} [NeZero n] {a : ℕ} (h : a < n) : (a : Fin n).val = a :=
Nat.mod_eq_of_lt h
/-- If `n` is non-zero, converting the value of a `Fin n` to `Fin n` results
in the same value. -/
@[simp, norm_cast] theorem cast_val_eq_self {n : ℕ} [NeZero n] (a : Fin n) : (a.val : Fin n) = a :=
Fin.ext <| val_cast_of_lt a.isLt
-- This is a special case of `CharP.cast_eq_zero` that doesn't require typeclass search
@[simp high] lemma natCast_self (n : ℕ) [NeZero n] : (n : Fin n) = 0 := by ext; simp
@[simp] lemma natCast_eq_zero {a n : ℕ} [NeZero n] : (a : Fin n) = 0 ↔ n ∣ a := by
simp [Fin.ext_iff, Nat.dvd_iff_mod_eq_zero]
@[simp]
theorem natCast_eq_last (n) : (n : Fin (n + 1)) = Fin.last n := by ext; simp
theorem natCast_eq_mk {m n : ℕ} (h : m < n) : have : NeZero n := ⟨Nat.ne_zero_of_lt h⟩
(m : Fin n) = Fin.mk m h :=
Fin.val_inj.mp (Nat.mod_eq_of_lt h)
theorem one_eq_mk_of_lt {n : ℕ} (h : 1 < n) : have : NeZero n := ⟨Nat.ne_zero_of_lt h⟩
1 = Fin.mk 1 h :=
Fin.val_inj.mp (Nat.mod_eq_of_lt h)
theorem le_val_last (i : Fin (n + 1)) : i ≤ n := by
rw [Fin.natCast_eq_last]
exact Fin.le_last i
variable {a b : ℕ}
lemma natCast_le_natCast (han : a ≤ n) (hbn : b ≤ n) : (a : Fin (n + 1)) ≤ b ↔ a ≤ b := by
rw [← Nat.lt_succ_iff] at han hbn
simp [le_iff_val_le_val, -val_fin_le, Nat.mod_eq_of_lt, han, hbn]
lemma natCast_lt_natCast (han : a ≤ n) (hbn : b ≤ n) : (a : Fin (n + 1)) < b ↔ a < b := by
rw [← Nat.lt_succ_iff] at han hbn; simp [lt_iff_val_lt_val, Nat.mod_eq_of_lt, han, hbn]
lemma natCast_mono (hbn : b ≤ n) (hab : a ≤ b) : (a : Fin (n + 1)) ≤ b :=
(natCast_le_natCast (hab.trans hbn) hbn).2 hab
lemma natCast_strictMono (hbn : b ≤ n) (hab : a < b) : (a : Fin (n + 1)) < b :=
(natCast_lt_natCast (hab.le.trans hbn) hbn).2 hab
@[simp]
lemma castLE_natCast {m n : ℕ} [NeZero m] (h : m ≤ n) (a : ℕ) :
letI : NeZero n := ⟨Nat.pos_iff_ne_zero.mp (lt_of_lt_of_le m.pos_of_neZero h)⟩
Fin.castLE h (a.cast : Fin m) = (a % m : ℕ) := by
ext
simp only [coe_castLE, val_natCast]
rw [Nat.mod_eq_of_lt (a := a % m) (lt_of_lt_of_le (Nat.mod_lt _ m.pos_of_neZero) h)]
end OfNatCoe
end Add
section DivMod
theorem modNat_rev (i : Fin (m * n)) : i.rev.modNat = i.modNat.rev := by
ext
have H₁ : i % n + 1 ≤ n := i.modNat.is_lt
have H₂ : i / n < m := i.divNat.is_lt
simp only [val_rev]
calc
(m * n - (i + 1)) % n = (m * n - ((i / n) * n + i % n + 1)) % n := by rw [Nat.div_add_mod']
_ = ((m - i / n - 1) * n + (n - (i % n + 1))) % n := by
rw [Nat.mul_sub_right_distrib, Nat.one_mul, Nat.sub_add_sub_cancel _ H₁,
Nat.mul_sub_right_distrib, Nat.sub_sub, Nat.add_assoc]
exact Nat.le_mul_of_pos_left _ <| Nat.le_sub_of_add_le' H₂
_ = n - (i % n + 1) := by
rw [Nat.mul_comm, Nat.mul_add_mod, Nat.mod_eq_of_lt]; exact i.modNat.rev.is_lt
end DivMod
section Rec
/-!
### recursion and induction principles
-/
end Rec
open scoped Relator in
theorem liftFun_iff_succ {α : Type*} (r : α → α → Prop) [IsTrans α r] {f : Fin (n + 1) → α} :
((· < ·) ⇒ r) f f ↔ ∀ i : Fin n, r (f (castSucc i)) (f i.succ) := by
constructor
· intro H i
exact H i.castSucc_lt_succ
· refine fun H i => Fin.induction (fun h ↦ ?_) ?_
· simp at h
· intro j ihj hij
rw [← le_castSucc_iff] at hij
obtain hij | hij := (le_def.1 hij).eq_or_lt
· obtain rfl := Fin.ext hij
exact H _
· exact _root_.trans (ihj hij) (H j)
section AddGroup
theorem eq_zero (n : Fin 1) : n = 0 := Subsingleton.elim _ _
lemma eq_one_of_ne_zero (i : Fin 2) (hi : i ≠ 0) : i = 1 := by fin_omega
@[deprecated (since := "2025-04-27")]
alias eq_one_of_neq_zero := eq_one_of_ne_zero
@[simp]
theorem coe_neg_one : ↑(-1 : Fin (n + 1)) = n := by
cases n
· simp
rw [Fin.coe_neg, Fin.val_one, Nat.add_one_sub_one, Nat.mod_eq_of_lt]
constructor
theorem last_sub (i : Fin (n + 1)) : last n - i = Fin.rev i :=
Fin.ext <| by rw [coe_sub_iff_le.2 i.le_last, val_last, val_rev, Nat.succ_sub_succ_eq_sub]
theorem add_one_le_of_lt {n : ℕ} {a b : Fin (n + 1)} (h : a < b) : a + 1 ≤ b := by
cases n <;> fin_omega
theorem exists_eq_add_of_le {n : ℕ} {a b : Fin n} (h : a ≤ b) : ∃ k ≤ b, b = a + k := by
obtain ⟨k, hk⟩ : ∃ k : ℕ, (b : ℕ) = a + k := Nat.exists_eq_add_of_le h
have hkb : k ≤ b := by omega
refine ⟨⟨k, hkb.trans_lt b.is_lt⟩, hkb, ?_⟩
simp [Fin.ext_iff, Fin.val_add, ← hk, Nat.mod_eq_of_lt b.is_lt]
theorem exists_eq_add_of_lt {n : ℕ} {a b : Fin (n + 1)} (h : a < b) :
∃ k < b, k + 1 ≤ b ∧ b = a + k + 1 := by
cases n
· cutsat
obtain ⟨k, hk⟩ : ∃ k : ℕ, (b : ℕ) = a + k + 1 := Nat.exists_eq_add_of_lt h
have hkb : k < b := by omega
refine ⟨⟨k, hkb.trans b.is_lt⟩, hkb, by fin_omega, ?_⟩
simp [Fin.ext_iff, Fin.val_add, ← hk, Nat.mod_eq_of_lt b.is_lt]
lemma pos_of_ne_zero {n : ℕ} {a : Fin (n + 1)} (h : a ≠ 0) : 0 < a :=
Nat.pos_of_ne_zero (val_ne_of_ne h)
lemma sub_succ_le_sub_of_le {n : ℕ} {u v : Fin (n + 2)} (h : u < v) : v - (u + 1) < v - u := by
fin_omega
end AddGroup
open Fin.NatCast in
@[simp]
theorem coe_natCast_eq_mod (m n : ℕ) [NeZero m] :
((n : Fin m) : ℕ) = n % m :=
rfl
@[simp]
theorem coe_ofNat_eq_mod (m n : ℕ) [NeZero m] :
((ofNat(n) : Fin m) : ℕ) = ofNat(n) % m :=
rfl
theorem val_add_one_of_lt' {n : ℕ} [NeZero n] {i : Fin n} (h : i + 1 < n) :
(i + 1).val = i.val + 1 := by
simpa [add_def] using Nat.mod_eq_of_lt (by cutsat)
instance [NeZero n] [NeZero ofNat(m)] : NeZero (ofNat(m) : Fin (n + ofNat(m))) := by
suffices m % (n + m) = m by simpa [neZero_iff, Fin.ext_iff, OfNat.ofNat, this] using NeZero.ne m
apply Nat.mod_eq_of_lt
simpa using zero_lt_of_ne_zero (NeZero.ne n)
section Mul
/-!
### mul
-/
@[deprecated (since := "2025-10-06")] alias mul_one' := Fin.mul_one
@[deprecated (since := "2025-10-06")] alias one_mul' := Fin.one_mul
@[deprecated (since := "2025-10-06")] alias mul_zero' := Fin.mul_zero
@[deprecated (since := "2025-10-06")] alias zero_mul' := Fin.zero_mul
end Mul
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Pigeonhole.lean | import Mathlib.Data.Fintype.Card
/-!
# Pigeonhole-like results for Fin
This adapts Pigeonhole-like results from `Mathlib.Data.Fintype.Card` to the setting where the map
has the type `f : Fin m → Fin n`.
-/
namespace Fin
variable {m n : ℕ}
/--
If we have an injective map from `Fin m` to `Fin n`, then `m ≤ n`.
See also `Fintype.card_le_of_injective` for the generalisation to arbitrary finite types.
-/
theorem le_of_injective (f : Fin m → Fin n) (hf : f.Injective) : m ≤ n := by
simpa using Fintype.card_le_of_injective f hf
/--
If we have an embedding from `Fin m` to `Fin n`, then `m ≤ n`.
See also `Fintype.card_le_of_embedding` for the generalisation to arbitrary finite types.
-/
theorem le_of_embedding (f : Fin m ↪ Fin n) : m ≤ n := by
simpa using Fintype.card_le_of_embedding f
/--
If we have an injective map from `Fin m` to `Fin n` whose image does not contain everything,
then `m < n`. See also `Fintype.card_lt_of_injective_of_notMem` for the generalisation to
arbitrary finite types.
-/
theorem lt_of_injective_of_notMem (f : Fin m → Fin n) (hf : f.Injective) {b : Fin n}
(hb : b ∉ Set.range f) : m < n := by
simpa using Fintype.card_lt_of_injective_of_notMem f hf hb
/--
If we have a surjective map from `Fin m` to `Fin n`, then `m ≥ n`.
See also `Fintype.card_le_of_surjective` for the generalisation to arbitrary finite types.
-/
theorem le_of_surjective (f : Fin m → Fin n) (hf : Function.Surjective f) : n ≤ m := by
simpa using Fintype.card_le_of_surjective f hf
/--
Any map from `Fin m` reaches at most `m` different values.
See also `Fintype.card_range_le` for the generalisation to an arbitrary finite type.
-/
theorem card_range_le {α : Type*} [Fintype α] [DecidableEq α] (f : Fin m → α) :
Fintype.card (Set.range f) ≤ m := by
simpa using Fintype.card_range_le f
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Embedding.lean | import Mathlib.Data.Fin.SuccPred
import Mathlib.Logic.Embedding.Basic
/-!
# Embeddings of `Fin n`
`Fin n` is the type whose elements are natural numbers smaller than `n`.
This file defines embeddings between `Fin n` and other types,
## Main definitions
* `Fin.valEmbedding` : coercion to natural numbers as an `Embedding`;
* `Fin.succEmb` : `Fin.succ` as an `Embedding`;
* `Fin.castLEEmb h` : `Fin.castLE` as an `Embedding`, embed `Fin n` into `Fin m`, `h : n ≤ m`;
* `Fin.castAddEmb m` : `Fin.castAdd` as an `Embedding`, embed `Fin n` into `Fin (n+m)`;
* `Fin.castSuccEmb` : `Fin.castSucc` as an `Embedding`, embed `Fin n` into `Fin (n+1)`;
* `Fin.addNatEmb m i` : `Fin.addNat` as an `Embedding`, add `m` on `i` on the right,
generalizes `Fin.succ`;
* `Fin.natAddEmb n i` : `Fin.natAdd` as an `Embedding`, adds `n` on `i` on the left;
-/
assert_not_exists Monoid Finset
open Fin Nat Function
namespace Fin
variable {n m : ℕ}
section Order
/-!
### order
-/
/-- The inclusion map `Fin n → ℕ` is an embedding. -/
@[simps -fullyApplied apply]
def valEmbedding : Fin n ↪ ℕ :=
⟨val, val_injective⟩
@[simp]
theorem equivSubtype_symm_trans_valEmbedding :
equivSubtype.symm.toEmbedding.trans valEmbedding = Embedding.subtype (· < n) :=
rfl
end Order
section Succ
/-!
### succ and casts into larger Fin types
-/
/-- `Fin.succ` as an `Embedding` -/
def succEmb (n : ℕ) : Fin n ↪ Fin (n + 1) where
toFun := succ
inj' := succ_injective _
@[simp]
theorem coe_succEmb : ⇑(succEmb n) = Fin.succ :=
rfl
attribute [simp] castSucc_inj
/-- `Fin.castLE` as an `Embedding`, `castLEEmb h i` embeds `i` into a larger `Fin` type. -/
@[simps apply]
def castLEEmb (h : n ≤ m) : Fin n ↪ Fin m where
toFun := castLE h
inj' := castLE_injective _
@[simp, norm_cast] lemma coe_castLEEmb {m n} (hmn : m ≤ n) : castLEEmb hmn = castLE hmn := rfl
/- The next proof can be golfed a lot using `Fintype.card`.
It is written this way to define `ENat.card` and `Nat.card` without a `Fintype` dependency
(not done yet). -/
lemma nonempty_embedding_iff : Nonempty (Fin n ↪ Fin m) ↔ n ≤ m := by
refine ⟨fun h ↦ ?_, fun h ↦ ⟨castLEEmb h⟩⟩
induction n generalizing m with
| zero => exact m.zero_le
| succ n ihn =>
obtain ⟨e⟩ := h
rcases exists_eq_succ_of_ne_zero (pos_iff_nonempty.2 (Nonempty.map e inferInstance)).ne'
with ⟨m, rfl⟩
refine Nat.succ_le_succ <| ihn ⟨?_⟩
refine ⟨fun i ↦ (e.setValue 0 0 i.succ).pred (mt e.setValue_eq_iff.1 i.succ_ne_zero),
fun i j h ↦ ?_⟩
simpa only [pred_inj, EmbeddingLike.apply_eq_iff_eq, succ_inj] using h
lemma equiv_iff_eq : Nonempty (Fin m ≃ Fin n) ↔ m = n :=
⟨fun ⟨e⟩ ↦ le_antisymm (nonempty_embedding_iff.1 ⟨e⟩) (nonempty_embedding_iff.1 ⟨e.symm⟩),
fun h ↦ h ▸ ⟨.refl _⟩⟩
/-- `Fin.castAdd` as an `Embedding`, `castAddEmb m i` embeds `i : Fin n` in `Fin (n+m)`.
See also `Fin.natAddEmb` and `Fin.addNatEmb`. -/
def castAddEmb (m) : Fin n ↪ Fin (n + m) := castLEEmb (le_add_right n m)
@[simp]
lemma coe_castAddEmb (m) : (castAddEmb m : Fin n → Fin (n + m)) = castAdd m := rfl
lemma castAddEmb_apply (m) (i : Fin n) : castAddEmb m i = castAdd m i := rfl
/-- `Fin.castSucc` as an `Embedding`, `castSuccEmb i` embeds `i : Fin n` in `Fin (n+1)`. -/
def castSuccEmb : Fin n ↪ Fin (n + 1) := castAddEmb _
@[simp, norm_cast] lemma coe_castSuccEmb : (castSuccEmb : Fin n → Fin (n + 1)) = Fin.castSucc := rfl
lemma castSuccEmb_apply (i : Fin n) : castSuccEmb i = i.castSucc := rfl
/-- `Fin.addNat` as an `Embedding`, `addNatEmb m i` adds `m` to `i`, generalizes `Fin.succ`. -/
@[simps! apply]
def addNatEmb (m) : Fin n ↪ Fin (n + m) where
toFun := (addNat · m)
inj' a b := by simp [Fin.ext_iff]
/-- `Fin.natAdd` as an `Embedding`, `natAddEmb n i` adds `n` to `i` "on the left". -/
@[simps! apply]
def natAddEmb (n) {m} : Fin m ↪ Fin (n + m) where
toFun := natAdd n
inj' a b := by simp [Fin.ext_iff]
end Succ
section SuccAbove
variable {p : Fin (n + 1)}
/-- `Fin.succAbove p` as an `Embedding`. -/
@[simps!]
def succAboveEmb (p : Fin (n + 1)) : Fin n ↪ Fin (n + 1) := ⟨p.succAbove, succAbove_right_injective⟩
@[simp, norm_cast] lemma coe_succAboveEmb (p : Fin (n + 1)) : p.succAboveEmb = p.succAbove := rfl
/-- `Fin.natAdd_castLEEmb` as an `Embedding` from `Fin n` to `Fin m`, by appending the former
at the end of the latter.
`natAdd_castLEEmb hmn i` maps `i : Fin m` to `i + (m - n) : Fin n` by adding `m - n` to `i` -/
@[simps!]
def natAdd_castLEEmb (hmn : n ≤ m) : Fin n ↪ Fin m :=
(addNatEmb (m - n)).trans (finCongr (by cutsat)).toEmbedding
lemma range_natAdd_castLEEmb {n m : ℕ} (hmn : n ≤ m) :
Set.range (natAdd_castLEEmb hmn) = {i | m - n ≤ i.1} := by
simp only [natAdd_castLEEmb, Nat.sub_le_iff_le_add]
ext y
exact ⟨fun ⟨x, hx⟩ ↦ by simp [← hx]; cutsat,
fun xin ↦ ⟨subNat (m - n) (y.cast (Nat.add_sub_of_le hmn).symm)
(Nat.sub_le_of_le_add xin), by simp⟩⟩
end SuccAbove
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Rev.lean | import Mathlib.Data.Fin.SuccPred
/-!
# Reverse on `Fin n`
This file contains lemmas about `Fin.rev : Fin n → Fin n` which maps `i` to `n - 1 - i`.
## Definitions
* `Fin.revPerm : Equiv.Perm (Fin n)` : `Fin.rev` as an `Equiv.Perm`, the antitone involution given
by `i ↦ n-(i+1)`
-/
assert_not_exists Monoid Fintype
open Fin Nat Function
namespace Fin
variable {n m : ℕ}
theorem rev_involutive : Involutive (rev : Fin n → Fin n) := rev_rev
/-- `Fin.rev` as an `Equiv.Perm`, the antitone involution `Fin n → Fin n` given by
`i ↦ n-(i+1)`. -/
@[simps! apply symm_apply]
def revPerm : Equiv.Perm (Fin n) :=
Involutive.toPerm rev rev_involutive
theorem rev_injective : Injective (@rev n) :=
rev_involutive.injective
theorem rev_surjective : Surjective (@rev n) :=
rev_involutive.surjective
theorem rev_bijective : Bijective (@rev n) :=
rev_involutive.bijective
@[simp]
theorem revPerm_symm : (@revPerm n).symm = revPerm :=
rfl
theorem cast_rev (i : Fin n) (h : n = m) :
i.rev.cast h = (i.cast h).rev := by
subst h; simp
theorem rev_eq_iff {i j : Fin n} : rev i = j ↔ i = rev j := by
rw [← rev_inj, rev_rev]
theorem rev_ne_iff {i j : Fin n} : rev i ≠ j ↔ i ≠ rev j := rev_eq_iff.not
theorem rev_lt_iff {i j : Fin n} : rev i < j ↔ rev j < i := by
rw [← rev_lt_rev, rev_rev]
theorem rev_le_iff {i j : Fin n} : rev i ≤ j ↔ rev j ≤ i := by
rw [← rev_le_rev, rev_rev]
theorem lt_rev_iff {i j : Fin n} : i < rev j ↔ j < rev i := by
rw [← rev_lt_rev, rev_rev]
theorem le_rev_iff {i j : Fin n} : i ≤ rev j ↔ j ≤ rev i := by
rw [← rev_le_rev, rev_rev]
theorem val_rev_zero [NeZero n] : ((rev 0 : Fin n) : ℕ) = n.pred := rfl
theorem rev_pred {i : Fin (n + 1)} (h : i ≠ 0) (h' := rev_ne_iff.mpr ((rev_last _).symm ▸ h)) :
rev (pred i h) = castPred (rev i) h' := by
rw [← castSucc_inj, castSucc_castPred, ← rev_succ, succ_pred]
theorem rev_castPred {i : Fin (n + 1)}
(h : i ≠ last n) (h' := rev_ne_iff.mpr ((rev_zero _).symm ▸ h)) :
rev (castPred i h) = pred (rev i) h' := by
rw [← succ_inj, succ_pred, ← rev_castSucc, castSucc_castPred]
lemma succAbove_rev_left (p : Fin (n + 1)) (i : Fin n) :
p.rev.succAbove i = (p.succAbove i.rev).rev := by
obtain h | h := (rev p).succ_le_or_le_castSucc i
· rw [succAbove_of_succ_le _ _ h,
succAbove_of_le_castSucc _ _ (rev_succ _ ▸ (le_rev_iff.mpr h)), rev_succ, rev_rev]
· rw [succAbove_of_le_castSucc _ _ h,
succAbove_of_succ_le _ _ (rev_castSucc _ ▸ (rev_le_iff.mpr h)), rev_castSucc, rev_rev]
lemma succAbove_rev_right (p : Fin (n + 1)) (i : Fin n) :
p.succAbove i.rev = (p.rev.succAbove i).rev := by rw [succAbove_rev_left, rev_rev]
/-- `rev` commutes with `succAbove`. -/
lemma rev_succAbove (p : Fin (n + 1)) (i : Fin n) :
rev (succAbove p i) = succAbove (rev p) (rev i) := by
rw [succAbove_rev_left, rev_rev]
lemma predAbove_rev_left (p : Fin n) (i : Fin (n + 1)) :
p.rev.predAbove i = (p.predAbove i.rev).rev := by
obtain h | h := (rev i).succ_le_or_le_castSucc p
· rw [predAbove_of_succ_le _ _ h, rev_pred,
predAbove_of_le_castSucc _ _ (rev_succ _ ▸ (le_rev_iff.mpr h)), castPred_inj, rev_rev]
· rw [predAbove_of_le_castSucc _ _ h, rev_castPred,
predAbove_of_succ_le _ _ (rev_castSucc _ ▸ (rev_le_iff.mpr h)), pred_inj, rev_rev]
lemma predAbove_rev_right (p : Fin n) (i : Fin (n + 1)) :
p.predAbove i.rev = (p.rev.predAbove i).rev := by rw [predAbove_rev_left, rev_rev]
/-- `rev` commutes with `predAbove`. -/
lemma rev_predAbove {n : ℕ} (p : Fin n) (i : Fin (n + 1)) :
(predAbove p i).rev = predAbove p.rev i.rev := by rw [predAbove_rev_left, rev_rev]
lemma add_rev_cast (j : Fin (n + 1)) : j.1 + j.rev.1 = n := by
obtain ⟨j, hj⟩ := j
simp [Nat.add_sub_cancel' <| le_of_lt_succ hj]
lemma rev_add_cast (j : Fin (n + 1)) : j.rev.1 + j.1 = n := by
rw [Nat.add_comm, j.add_rev_cast]
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Parity.lean | import Mathlib.Algebra.Ring.Parity
import Mathlib.Data.Fin.Basic
import Mathlib.Data.ZMod.Defs
/-!
# Parity in `Fin n`
In this file we prove that an element `k : Fin n` is even in `Fin n`
iff `n` is odd or `Fin.val k` is even.
We also prove a lemma about parity of `Fin.succAbove i j + Fin.predAbove j i`
which can be used to prove `d ∘ d = 0` for de Rham cohomologies.
-/
open Fin
namespace Fin
open Fin.CommRing
variable {n : ℕ} {k : Fin n}
theorem even_succAbove_add_predAbove (i : Fin (n + 1)) (j : Fin n) :
Even (i.succAbove j + j.predAbove i : ℕ) ↔ Odd (i + j : ℕ) := by
rcases lt_or_ge j.castSucc i with hji | hij
· have : 1 ≤ (i : ℕ) := (Nat.zero_le j).trans_lt hji
simp [succAbove_of_castSucc_lt _ _ hji, predAbove_of_castSucc_lt _ _ hji, this, iff_comm,
parity_simps]
· simp [succAbove_of_le_castSucc _ _ hij, predAbove_of_le_castSucc _ _ hij,
← Nat.not_even_iff_odd, not_iff, not_iff_comm, parity_simps]
lemma neg_one_pow_succAbove_add_predAbove {R : Type*} [Monoid R] [HasDistribNeg R]
(i : Fin (n + 1)) (j : Fin n) :
(-1 : R) ^ (i.succAbove j + j.predAbove i : ℕ) = -(-1) ^ (i + j : ℕ) := by
rw [← neg_one_mul (_ ^ _), ← pow_succ', neg_one_pow_congr]
rw [even_succAbove_add_predAbove, Nat.even_add_one, Nat.not_even_iff_odd]
lemma even_of_val (h : Even k.val) : Even k := by
have : NeZero n := ⟨k.pos.ne'⟩
rw [← Fin.cast_val_eq_self k]
exact h.natCast
lemma odd_of_val [NeZero n] (h : Odd k.val) : Odd k := by
rw [← Fin.cast_val_eq_self k]
exact h.natCast
lemma even_of_odd (hn : Odd n) (k : Fin n) : Even k := by
have : NeZero n := ⟨k.pos.ne'⟩
rcases k.val.even_or_odd with hk | hk
· exact even_of_val hk
· simpa using (hk.add_odd hn).natCast (α := Fin n)
lemma odd_of_odd [NeZero n] (hn : Odd n) (k : Fin n) : Odd k := by
rcases k.val.even_or_odd with hk | hk
· simpa using (Even.add_odd hk hn).natCast (R := Fin n)
· exact odd_of_val hk
lemma even_iff_of_even (hn : Even n) : Even k ↔ Even k.val := by
rcases hn with ⟨n, rfl⟩
refine ⟨?_, even_of_val⟩
rintro ⟨l, rfl⟩
rw [val_add_eq_ite]
split_ifs with h <;> simp [Nat.even_sub, *]
lemma odd_iff_of_even [NeZero n] (hn : Even n) : Odd k ↔ Odd k.val := by
rcases hn with ⟨n, rfl⟩
refine ⟨?_, odd_of_val⟩
rintro ⟨l, rfl⟩
rw [val_add, val_mul, coe_ofNat_eq_mod, coe_ofNat_eq_mod]
simp only [Nat.mod_mul_mod, Nat.add_mod_mod, Nat.mod_add_mod, Nat.odd_iff]
rw [Nat.mod_mod_of_dvd _ ⟨n, (two_mul n).symm⟩, ← Nat.odd_iff, Nat.odd_add_one,
Nat.not_odd_iff_even]
simp
/-- In `Fin n`, all elements are even for odd `n`,
otherwise an element is even iff its `Fin.val` value is even. -/
lemma even_iff : Even k ↔ (Odd n ∨ Even k.val) := by
refine ⟨fun hk ↦ ?_, or_imp.mpr ⟨(even_of_odd · k), even_of_val⟩⟩
rw [← Nat.not_even_iff_odd, ← imp_iff_not_or]
exact fun hn ↦ (even_iff_of_even hn).mp hk
lemma even_iff_imp : Even k ↔ (Even n → Even k.val) := by
rw [imp_iff_not_or, Nat.not_even_iff_odd]
exact even_iff
/-- In `Fin n`, all elements are odd for odd `n`,
otherwise an element is odd iff its `Fin.val` value is odd. -/
lemma odd_iff [NeZero n] : Odd k ↔ Odd n ∨ Odd k.val := by
refine ⟨fun hk ↦ ?_, or_imp.mpr ⟨(odd_of_odd · k), odd_of_val⟩⟩
rw [← Nat.not_even_iff_odd, ← imp_iff_not_or]
exact fun hn ↦ (odd_iff_of_even hn).mp hk
lemma odd_iff_imp [NeZero n] : Odd k ↔ (Even n → Odd k.val) := by
rw [imp_iff_not_or, Nat.not_even_iff_odd]
exact odd_iff
lemma even_iff_mod_of_even (hn : Even n) : Even k ↔ k.val % 2 = 0 := by
rw [even_iff_of_even hn]
exact Nat.even_iff
lemma odd_iff_mod_of_even [NeZero n] (hn : Even n) : Odd k ↔ k.val % 2 = 1 := by
rw [odd_iff_of_even hn]
exact Nat.odd_iff
lemma not_odd_iff_even_of_even [NeZero n] (hn : Even n) : ¬Odd k ↔ Even k := by
rw [even_iff_of_even hn, odd_iff_of_even hn]
exact Nat.not_odd_iff_even
lemma not_even_iff_odd_of_even [NeZero n] (hn : Even n) : ¬Even k ↔ Odd k := by
rw [even_iff_of_even hn, odd_iff_of_even hn]
exact Nat.not_even_iff_odd
lemma odd_add_one_iff_even [NeZero n] : Odd (k + 1) ↔ Even k :=
⟨fun ⟨k, hk⟩ ↦ add_right_cancel hk ▸ even_two_mul k, Even.add_one⟩
lemma even_add_one_iff_odd [NeZero n] : Even (k + 1) ↔ Odd k :=
⟨fun ⟨k, hk⟩ ↦ eq_sub_iff_add_eq.mpr hk ▸ (Even.add_self k).sub_odd odd_one, Odd.add_one⟩
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Fin2.lean | import Mathlib.Data.Finset.Image
import Mathlib.Data.Fintype.Defs
import Mathlib.Data.Nat.Notation
import Mathlib.Logic.Function.Basic
/-!
# Inductive type variant of `Fin`
`Fin` is defined as a subtype of `ℕ`. This file defines an equivalent type, `Fin2`, which is
defined inductively. This is useful for its induction principle and different definitional
equalities.
## Main declarations
* `Fin2 n`: Inductive type variant of `Fin n`. `fz` corresponds to `0` and `fs n` corresponds to
`n`.
* `Fin2.toNat`, `Fin2.optOfNat`, `Fin2.ofNat'`: Conversions to and from `ℕ`. `ofNat' m` takes a
proof that `m < n` through the class `Fin2.IsLT`.
* `Fin2.add k`: Takes `i : Fin2 n` to `i + k : Fin2 (n + k)`.
* `Fin2.left`: Embeds `Fin2 n` into `Fin2 (n + k)`.
* `Fin2.insertPerm a`: Permutation of `Fin2 n` which cycles `0, ..., a - 1` and leaves
`a, ..., n - 1` unchanged.
* `Fin2.remapLeft f`: Function `Fin2 (m + k) → Fin2 (n + k)` by applying `f : Fin m → Fin n` to
`0, ..., m - 1` and sending `m + i` to `n + i`.
-/
open Nat
universe u
/-- An alternate definition of `Fin n` defined as an inductive type instead of a subtype of `ℕ`. -/
inductive Fin2 : ℕ → Type
/-- `0` as a member of `Fin (n + 1)` (`Fin 0` is empty) -/
| fz {n} : Fin2 (n + 1)
/-- `n` as a member of `Fin (n + 1)` -/
| fs {n} : Fin2 n → Fin2 (n + 1)
namespace Fin2
/-- Define a dependent function on `Fin2 (succ n)` by giving its value at
zero (`H1`) and by giving a dependent function on the rest (`H2`). -/
@[elab_as_elim]
protected def cases' {n} {C : Fin2 (succ n) → Sort u} (H1 : C fz) (H2 : ∀ n, C (fs n)) :
∀ i : Fin2 (succ n), C i
| fz => H1
| fs n => H2 n
/-- Ex falso. The dependent eliminator for the empty `Fin2 0` type. -/
def elim0 {C : Fin2 0 → Sort u} : ∀ i : Fin2 0, C i := nofun
/-- Converts a `Fin2` into a natural. -/
def toNat : ∀ {n}, Fin2 n → ℕ
| _, @fz _ => 0
| _, @fs _ i => succ (toNat i)
/-- Converts a natural into a `Fin2` if it is in range -/
def optOfNat : ∀ {n}, ℕ → Option (Fin2 n)
| 0, _ => none
| succ _, 0 => some fz
| succ m, succ k => fs <$> @optOfNat m k
/-- `i + k : Fin2 (n + k)` when `i : Fin2 n` and `k : ℕ` -/
def add {n} (i : Fin2 n) : ∀ k, Fin2 (n + k)
| 0 => i
| succ k => fs (add i k)
/-- `left k` is the embedding `Fin2 n → Fin2 (k + n)` -/
def left (k) : ∀ {n}, Fin2 n → Fin2 (k + n)
| _, @fz _ => fz
| _, @fs _ i => fs (left k i)
/-- `insertPerm a` is a permutation of `Fin2 n` with the following properties:
* `insertPerm a i = i+1` if `i < a`
* `insertPerm a a = 0`
* `insertPerm a i = i` if `i > a` -/
def insertPerm : ∀ {n}, Fin2 n → Fin2 n → Fin2 n
| _, @fz _, @fz _ => fz
| _, @fz _, @fs _ j => fs j
| _, @fs (succ _) _, @fz _ => fs fz
| _, @fs (succ _) i, @fs _ j =>
match insertPerm i j with
| fz => fz
| fs k => fs (fs k)
/-- `remapLeft f k : Fin2 (m + k) → Fin2 (n + k)` applies the function
`f : Fin2 m → Fin2 n` to inputs less than `m`, and leaves the right part
on the right (that is, `remapLeft f k (m + i) = n + i`). -/
def remapLeft {m n} (f : Fin2 m → Fin2 n) : ∀ k, Fin2 (m + k) → Fin2 (n + k)
| 0, i => f i
| _k + 1, @fz _ => fz
| _k + 1, @fs _ i => fs (remapLeft f _ i)
/-- This is a simple type class inference prover for proof obligations
of the form `m < n` where `m n : ℕ`. -/
class IsLT (m n : ℕ) : Prop where
/-- The unique field of `Fin2.IsLT`, a proof that `m < n`. -/
h : m < n
instance IsLT.zero (n) : IsLT 0 (succ n) :=
⟨succ_pos _⟩
instance IsLT.succ (m n) [l : IsLT m n] : IsLT (succ m) (succ n) :=
⟨succ_lt_succ l.h⟩
/-- Use type class inference to infer the boundedness proof, so that we can directly convert a
`Nat` into a `Fin2 n`. This supports notation like `&1 : Fin 3`. -/
def ofNat' : ∀ {n} (m) [IsLT m n], Fin2 n
| 0, _, h => absurd h.h (Nat.not_lt_zero _)
| succ _, 0, _ => fz
| succ n, succ m, h => fs (@ofNat' n m ⟨lt_of_succ_lt_succ h.h⟩)
/-- `castSucc i` embeds `i : Fin2 n` in `Fin2 (n+1)`. -/
def castSucc {n} : Fin2 n → Fin2 (n + 1)
| fz => fz
| fs k => fs <| castSucc k
/-- The greatest value of `Fin2 (n+1)`. -/
def last : {n : Nat} → Fin2 (n + 1)
| 0 => fz
| n + 1 => fs (@last n)
/-- Maps `0` to `n-1`, `1` to `n-2`, ..., `n-1` to `0`. -/
def rev {n : Nat} : Fin2 n → Fin2 n
| .fz => last
| .fs i => i.rev.castSucc
@[simp] lemma rev_last {n} : rev (@last n) = fz := by
induction n <;> simp_all [rev, castSucc, last]
@[simp] lemma rev_castSucc {n} (i : Fin2 n) : rev (castSucc i) = fs (rev i) := by
induction i <;> simp_all [rev, castSucc, last]
@[simp] lemma rev_rev {n} (i : Fin2 n) : i.rev.rev = i := by
induction i <;> simp_all [rev]
theorem rev_involutive {n} : Function.Involutive (@rev n) := rev_rev
@[inherit_doc] local prefix:arg "&" => ofNat'
instance : Inhabited (Fin2 1) :=
⟨fz⟩
instance instFintype : ∀ n, Fintype (Fin2 n)
| 0 => ⟨∅, Fin2.elim0⟩
| n + 1 =>
let ⟨elems, compl⟩ := instFintype n
{ elems := elems.map ⟨Fin2.fs, @fs.inj _⟩ |>.cons .fz (by simp)
complete := by rintro (_ | i) <;> simp [compl] }
/-- Converts a `Fin2` into a `Fin`. -/
def toFin {n : Nat} (i : Fin2 n) : Fin n :=
match i with
| fz => 0
| fs i => i.toFin.succ
@[simp]
theorem toFin_fz (n : Nat) : toFin (@fz n) = 0 := rfl
@[simp]
theorem toFin_fs {n : Nat} (i : Fin2 n) : toFin (fs i) = (toFin i).succ := rfl
/-- Converts a `Fin` into a `Fin2`. -/
def ofFin {n : Nat} (i : Fin n) : Fin2 n :=
i.succRec (fun _ => fz) (fun _ _ => fs)
@[simp]
theorem ofFin_zero (n : Nat) : ofFin 0 = @fz n := rfl
@[simp]
theorem ofFin_succ {n : Nat} (i : Fin n) : ofFin i.succ = fs (ofFin i) := rfl
@[simp]
theorem toFin_ofFin {n : Nat} (i : Fin n) : toFin (ofFin i) = i :=
i.succRec (fun _ => rfl) (fun _ _ ih => congrArg Fin.succ ih)
@[simp]
theorem ofFin_toFin {n : Nat} (i : Fin2 n) : ofFin (toFin i) = i := by
induction i with
| fz => rfl
| fs _ ih => exact congrArg fs ih
/-- `Fin2` is equivalent to the usual encoding of `Fin` as a subtype of `ℕ`. -/
@[simps]
def equivFin (n : Nat) : Fin2 n ≃ Fin n where
toFun := toFin
invFun := ofFin
left_inv := ofFin_toFin
right_inv := toFin_ofFin
end Fin2 |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/BubbleSortInduction.lean | import Mathlib.Data.Fin.Tuple.Sort
import Mathlib.Order.WellFounded
import Mathlib.Order.PiLex
import Mathlib.Data.Finite.Prod
/-!
# "Bubble sort" induction
We implement the following induction principle `Tuple.bubble_sort_induction`
on tuples with values in a linear order `α`.
Let `f : Fin n → α` and let `P` be a predicate on `Fin n → α`. Then we can show that
`f ∘ sort f` satisfies `P` if `f` satisfies `P`, and whenever some `g : Fin n → α`
satisfies `P` and `g i > g j` for some `i < j`, then `g ∘ swap i j` also satisfies `P`.
We deduce it from a stronger variant `Tuple.bubble_sort_induction'`, which
requires the assumption only for `g` that are permutations of `f`.
The latter is proved by well-founded induction via `WellFounded.induction_bot'`
with respect to the lexicographic ordering on the finite set of all permutations of `f`.
-/
namespace Tuple
/-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P`
if `f` satisfies `P` and `P` is preserved on permutations of `f` when swapping two
antitone values. -/
theorem bubble_sort_induction' {n : ℕ} {α : Type*} [LinearOrder α] {f : Fin n → α}
{P : (Fin n → α) → Prop} (hf : P f)
(h : ∀ (σ : Equiv.Perm (Fin n)) (i j : Fin n),
i < j → (f ∘ σ) j < (f ∘ σ) i → P (f ∘ σ) → P (f ∘ σ ∘ Equiv.swap i j)) :
P (f ∘ sort f) := by
letI := @Preorder.lift _ (Lex (Fin n → α)) _ fun σ : Equiv.Perm (Fin n) => toLex (f ∘ σ)
refine
@WellFounded.induction_bot' _ _ _ (IsWellFounded.wf : WellFounded (· < ·))
(Equiv.refl _) (sort f) P (fun σ => f ∘ σ) (fun σ hσ hfσ => ?_) hf
obtain ⟨i, j, hij₁, hij₂⟩ := antitone_pair_of_not_sorted' hσ
exact ⟨σ * Equiv.swap i j, Pi.lex_desc hij₁.le hij₂, h σ i j hij₁ hij₂ hfσ⟩
/-- *Bubble sort induction*: Prove that the sorted version of `f` has some property `P`
if `f` satisfies `P` and `P` is preserved when swapping two antitone values. -/
theorem bubble_sort_induction {n : ℕ} {α : Type*} [LinearOrder α] {f : Fin n → α}
{P : (Fin n → α) → Prop} (hf : P f)
(h : ∀ (g : Fin n → α) (i j : Fin n), i < j → g j < g i → P g → P (g ∘ Equiv.swap i j)) :
P (f ∘ sort f) :=
bubble_sort_induction' hf fun _ => h _
end Tuple |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Curry.lean | import Mathlib.Data.Fin.Tuple.Basic
import Mathlib.Logic.Equiv.Fin.Basic
import Mathlib.Logic.Function.OfArity
/-!
# Currying and uncurrying of n-ary functions
A function of `n` arguments can either be written as `f a₁ a₂ ⋯ aₙ` or `f' ![a₁, a₂, ⋯, aₙ]`.
This file provides the currying and uncurrying operations that convert between the two, as
n-ary generalizations of the binary `curry` and `uncurry`.
## Main definitions
* `Function.OfArity.uncurry`: convert an `n`-ary function to a function from `Fin n → α`.
* `Function.OfArity.curry`: convert a function from `Fin n → α` to an `n`-ary function.
* `Function.FromTypes.uncurry`: convert an `p`-ary heterogeneous function to a
function from `(i : Fin n) → p i`.
* `Function.FromTypes.curry`: convert a function from `(i : Fin n) → p i` to a
`p`-ary heterogeneous function.
-/
universe u v w w'
namespace Function.FromTypes
open Matrix (vecCons vecHead vecTail vecEmpty)
/-- Uncurry all the arguments of `Function.FromTypes p τ` to get
a function from a tuple.
Note this can be used on raw functions if used. -/
def uncurry : {n : ℕ} → {p : Fin n → Type u} → {τ : Type u} →
(f : Function.FromTypes p τ) → ((i : Fin n) → p i) → τ
| 0 , _, _, f => fun _ => f
| _ + 1, _, _, f => fun args => (f (args 0)).uncurry (args ∘' Fin.succ)
/-- Curry all the arguments of `Function.FromTypes p τ` to get a function from a tuple. -/
def curry : {n : ℕ} → {p : Fin n → Type u} → {τ : Type u} →
(((i : Fin n) → p i) → τ) → Function.FromTypes p τ
| 0 , _, _, f => f isEmptyElim
| _ + 1, _, _, f => fun a => curry (fun args => f (Fin.cons a args))
@[simp]
theorem uncurry_apply_cons {n : ℕ} {α} {p : Fin n → Type u} {τ : Type u}
(f : Function.FromTypes (vecCons α p) τ) (a : α) (args : (i : Fin n) → p i) :
uncurry f (Fin.cons a args) = @uncurry _ p _ (f a) args := rfl
@[simp low]
theorem uncurry_apply_succ {n : ℕ} {p : Fin (n + 1) → Type u} {τ : Type u}
(f : Function.FromTypes p τ) (args : (i : Fin (n + 1)) → p i) :
uncurry f args = uncurry (f (args 0)) (Fin.tail args) := rfl
@[simp]
theorem curry_apply_cons {n : ℕ} {α} {p : Fin n → Type u} {τ : Type u}
(f : ((i : Fin (n + 1)) → (vecCons α p) i) → τ) (a : α) :
curry f a = @curry _ p _ (f ∘' Fin.cons a) := rfl
@[simp low]
theorem curry_apply_succ {n : ℕ} {p : Fin (n + 1) → Type u} {τ : Type u}
(f : ((i : Fin (n + 1)) → p i) → τ) (a : p 0) :
curry f a = curry (f ∘ Fin.cons a) := rfl
variable {n : ℕ} {p : Fin n → Type u} {τ : Type u}
@[simp]
theorem curry_uncurry (f : Function.FromTypes p τ) : curry (uncurry f) = f := by
induction n with
| zero => rfl
| succ n ih => exact funext (ih <| f ·)
@[simp]
theorem uncurry_curry (f : ((i : Fin n) → p i) → τ) :
uncurry (curry f) = f := by
ext args
induction n with
| zero => exact congrArg f (Subsingleton.allEq _ _)
| succ n ih => exact Eq.trans (ih _ _) (congrArg f (Fin.cons_self_tail args))
/-- `Equiv.curry` for `p`-ary heterogeneous functions. -/
@[simps]
def curryEquiv (p : Fin n → Type u) : (((i : Fin n) → p i) → τ) ≃ FromTypes p τ where
toFun := curry
invFun := uncurry
left_inv := uncurry_curry
right_inv := curry_uncurry
lemma curry_two_eq_curry {p : Fin 2 → Type u} {τ : Type u}
(f : ((i : Fin 2) → p i) → τ) :
curry f = Function.curry (f ∘ (piFinTwoEquiv p).symm) := rfl
lemma uncurry_two_eq_uncurry (p : Fin 2 → Type u) (τ : Type u)
(f : Function.FromTypes p τ) :
uncurry f = Function.uncurry f ∘ piFinTwoEquiv p := rfl
end Function.FromTypes
namespace Function.OfArity
variable {α β : Type u}
/-- Uncurry all the arguments of `Function.OfArity α n` to get a function from a tuple.
Note this can be used on raw functions if used. -/
def uncurry {n} (f : Function.OfArity α β n) : (Fin n → α) → β := FromTypes.uncurry f
/-- Curry all the arguments of `Function.OfArity α β n` to get a function from a tuple. -/
def curry {n} (f : (Fin n → α) → β) : Function.OfArity α β n := FromTypes.curry f
@[simp]
theorem curry_uncurry {n} (f : Function.OfArity α β n) :
curry (uncurry f) = f := FromTypes.curry_uncurry f
@[simp]
theorem uncurry_curry {n} (f : (Fin n → α) → β) :
uncurry (curry f) = f := FromTypes.uncurry_curry f
/-- `Equiv.curry` for n-ary functions. -/
@[simps!]
def curryEquiv (n : ℕ) : ((Fin n → α) → β) ≃ OfArity α β n :=
FromTypes.curryEquiv _
lemma curry_two_eq_curry {α β : Type u} (f : ((i : Fin 2) → α) → β) :
curry f = Function.curry (f ∘ (finTwoArrowEquiv α).symm) :=
FromTypes.curry_two_eq_curry f
lemma uncurry_two_eq_uncurry {α β : Type u} (f : OfArity α β 2) :
uncurry f = Function.uncurry f ∘ (finTwoArrowEquiv α) :=
FromTypes.uncurry_two_eq_uncurry _ _ f
end Function.OfArity |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Reflection.lean | import Mathlib.Data.Fin.VecNotation
import Mathlib.Algebra.BigOperators.Fin
/-!
# Lemmas for tuples `Fin m → α`
This file contains alternative definitions of common operators on vectors which expand
definitionally to the expected expression when evaluated on `![]` notation.
This allows "proof by reflection", where we prove `f = ![f 0, f 1]` by defining
`FinVec.etaExpand f` to be equal to the RHS definitionally, and then prove that
`f = etaExpand f`.
The definitions in this file should normally not be used directly; the intent is for the
corresponding `*_eq` lemmas to be used in a place where they are definitionally unfolded.
## Main definitions
* `FinVec.seq`
* `FinVec.map`
* `FinVec.sum`
* `FinVec.etaExpand`
-/
assert_not_exists Field
namespace FinVec
variable {m : ℕ} {α β : Type*}
/-- Evaluate `FinVec.seq f v = ![(f 0) (v 0), (f 1) (v 1), ...]` -/
def seq : ∀ {m}, (Fin m → α → β) → (Fin m → α) → Fin m → β
| 0, _, _ => ![]
| _ + 1, f, v => Matrix.vecCons (f 0 (v 0)) (seq (Matrix.vecTail f) (Matrix.vecTail v))
@[simp]
theorem seq_eq : ∀ {m} (f : Fin m → α → β) (v : Fin m → α), seq f v = fun i => f i (v i)
| 0, _, _ => Subsingleton.elim _ _
| n + 1, f, v =>
funext fun i => by
simp_rw [seq, seq_eq]
refine i.cases ?_ fun i => ?_
· rfl
· rw [Matrix.cons_val_succ]
rfl
example {f₁ f₂ : α → β} (a₁ a₂ : α) : seq ![f₁, f₂] ![a₁, a₂] = ![f₁ a₁, f₂ a₂] := rfl
/-- `FinVec.map f v = ![f (v 0), f (v 1), ...]` -/
def map (f : α → β) {m} : (Fin m → α) → Fin m → β :=
seq fun _ => f
/-- This can be used to prove
```lean
example {f : α → β} (a₁ a₂ : α) : f ∘ ![a₁, a₂] = ![f a₁, f a₂] :=
(map_eq _ _).symm
```
-/
@[simp]
theorem map_eq (f : α → β) {m} (v : Fin m → α) : map f v = f ∘ v :=
seq_eq _ _
example {f : α → β} (a₁ a₂ : α) : f ∘ ![a₁, a₂] = ![f a₁, f a₂] :=
(map_eq _ _).symm
/-- Expand `v` to `![v 0, v 1, ...]` -/
def etaExpand {m} (v : Fin m → α) : Fin m → α :=
map id v
/-- This can be used to prove
```lean
example (a : Fin 2 → α) : a = ![a 0, a 1] :=
(etaExpand_eq _).symm
```
-/
@[simp]
theorem etaExpand_eq {m} (v : Fin m → α) : etaExpand v = v :=
map_eq id v
example (a : Fin 2 → α) : a = ![a 0, a 1] :=
(etaExpand_eq _).symm
/-- `∀` with better defeq for `∀ x : Fin m → α, P x`. -/
def Forall : ∀ {m} (_ : (Fin m → α) → Prop), Prop
| 0, P => P ![]
| _ + 1, P => ∀ x : α, Forall fun v => P (Matrix.vecCons x v)
/-- This can be used to prove
```lean
example (P : (Fin 2 → α) → Prop) : (∀ f, P f) ↔ ∀ a₀ a₁, P ![a₀, a₁] :=
(forall_iff _).symm
```
-/
@[simp]
theorem forall_iff : ∀ {m} (P : (Fin m → α) → Prop), Forall P ↔ ∀ x, P x
| 0, P => by
simp only [Forall, Fin.forall_fin_zero_pi]
rfl
| .succ n, P => by simp only [Forall, forall_iff, Fin.forall_fin_succ_pi, Matrix.vecCons]
example (P : (Fin 2 → α) → Prop) : (∀ f, P f) ↔ ∀ a₀ a₁, P ![a₀, a₁] :=
(forall_iff _).symm
/-- `∃` with better defeq for `∃ x : Fin m → α, P x`. -/
def Exists : ∀ {m} (_ : (Fin m → α) → Prop), Prop
| 0, P => P ![]
| _ + 1, P => ∃ x : α, Exists fun v => P (Matrix.vecCons x v)
/-- This can be used to prove
```lean
example (P : (Fin 2 → α) → Prop) : (∃ f, P f) ↔ ∃ a₀ a₁, P ![a₀, a₁] :=
(exists_iff _).symm
```
-/
theorem exists_iff : ∀ {m} (P : (Fin m → α) → Prop), Exists P ↔ ∃ x, P x
| 0, P => by
simp only [Exists, Fin.exists_fin_zero_pi, Matrix.vecEmpty]
rfl
| .succ n, P => by simp only [Exists, exists_iff, Fin.exists_fin_succ_pi, Matrix.vecCons]
example (P : (Fin 2 → α) → Prop) : (∃ f, P f) ↔ ∃ a₀ a₁, P ![a₀, a₁] :=
(exists_iff _).symm
/-- `Finset.univ.sum` with better defeq for `Fin`. -/
def sum [Add α] [Zero α] : ∀ {m} (_ : Fin m → α), α
| 0, _ => 0
| 1, v => v 0
| _ + 2, v => sum (fun i => v (Fin.castSucc i)) + v (Fin.last _)
-- `to_additive` without `existing` fails, see
-- https://leanprover.zulipchat.com/#narrow/channel/287929-mathlib4/topic/to_additive.20complains.20about.20equation.20lemmas/near/508910537
/-- `Finset.univ.prod` with better defeq for `Fin`. -/
@[to_additive existing]
def prod [Mul α] [One α] : ∀ {m} (_ : Fin m → α), α
| 0, _ => 1
| 1, v => v 0
| _ + 2, v => prod (fun i => v (Fin.castSucc i)) * v (Fin.last _)
/-- This can be used to prove
```lean
example [CommMonoid α] (a : Fin 3 → α) : ∏ i, a i = a 0 * a 1 * a 2 :=
(prod_eq _).symm
```
-/
@[to_additive (attr := simp)
/-- This can be used to prove
```lean
example [AddCommMonoid α] (a : Fin 3 → α) : ∑ i, a i = a 0 + a 1 + a 2 :=
(sum_eq _).symm
``` -/]
theorem prod_eq [CommMonoid α] : ∀ {m} (a : Fin m → α), prod a = ∏ i, a i
| 0, _ => rfl
| 1, a => (Fintype.prod_unique a).symm
| n + 2, a => by rw [Fin.prod_univ_castSucc, prod, prod_eq]
example [CommMonoid α] (a : Fin 3 → α) : ∏ i, a i = a 0 * a 1 * a 2 :=
(prod_eq _).symm
example [AddCommMonoid α] (a : Fin 3 → α) : ∑ i, a i = a 0 + a 1 + a 2 :=
(sum_eq _).symm
section Meta
open Lean Meta Qq
/-- Produce a term of the form `f 0 * f 1 * ... * f (n - 1)` and an application of `FinVec.prod_eq`
that shows it is equal to `∏ i, f i`. -/
def mkProdEqQ {u : Level} {α : Q(Type u)} (inst : Q(CommMonoid $α)) (n : ℕ) (f : Q(Fin $n → $α)) :
MetaM <| (val : Q($α)) × Q(∏ i, $f i = $val) := do
match n with
| 0 => return ⟨q((1 : $α)), q(Fin.prod_univ_zero $f)⟩
| m + 1 =>
let nezero : Q(NeZero ($m + 1)) := q(⟨Nat.succ_ne_zero _⟩)
let val ← makeRHS (m + 1) f nezero (m + 1)
let _ : $val =Q FinVec.prod $f := ⟨⟩
return ⟨q($val), q(FinVec.prod_eq $f |>.symm)⟩
where
/-- Creates the expression `f 0 * f 1 * ... * f (n - 1)`. -/
makeRHS (n : ℕ) (f : Q(Fin $n → $α)) (nezero : Q(NeZero $n)) (k : ℕ) : MetaM Q($α) := do
match k with
| 0 => failure
| 1 => pure q($f 0)
| m + 1 =>
let pre ← makeRHS n f nezero m
let mRaw : Q(ℕ) := mkRawNatLit m
pure q($pre * $f (OfNat.ofNat $mRaw))
/-- Produce a term of the form `f 0 + f 1 + ... + f (n - 1)` and an application of `FinVec.sum_eq`
that shows it is equal to `∑ i, f i`. -/
def mkSumEqQ {u : Level} {α : Q(Type u)} (inst : Q(AddCommMonoid $α)) (n : ℕ) (f : Q(Fin $n → $α)) :
MetaM <| (val : Q($α)) × Q(∑ i, $f i = $val) := do
match n with
| 0 => return ⟨q((0 : $α)), q(Fin.sum_univ_zero $f)⟩
| m + 1 =>
let nezero : Q(NeZero ($m + 1)) := q(⟨Nat.succ_ne_zero _⟩)
let val ← makeRHS (m + 1) f nezero (m + 1)
let _ : $val =Q FinVec.sum $f := ⟨⟩
return ⟨q($val), q(FinVec.sum_eq $f |>.symm)⟩
where
/-- Creates the expression `f 0 + f 1 + ... + f (n - 1)`. -/
makeRHS (n : ℕ) (f : Q(Fin $n → $α)) (nezero : Q(NeZero $n)) (k : ℕ) : MetaM Q($α) := do
match k with
| 0 => failure
| 1 => pure q($f 0)
| m + 1 =>
let pre ← makeRHS n f nezero m
let mRaw : Q(ℕ) := mkRawNatLit m
pure q($pre + $f (OfNat.ofNat $mRaw))
end Meta
end FinVec
namespace Fin
open Qq Lean FinVec
/-- Rewrites `∏ i : Fin n, f i` as `f 0 * f 1 * ... * f (n - 1)` when `n` is a numeral. -/
simproc_decl prod_univ_ofNat (∏ _ : Fin _, _) := .ofQ fun u _ e => do
match u, e with
| .succ _, ~q(@Finset.prod (Fin $n) _ $inst (@Finset.univ _ $instF) $f) => do
match (generalizing := false) n.nat? with
| none =>
return .continue
| some nVal =>
let ⟨res, pf⟩ ← mkProdEqQ inst nVal f
let ⟨_⟩ ← assertDefEqQ q($instF) q(Fin.fintype _)
have _ : $n =Q $nVal := ⟨⟩
return .visit <| .mk q($res) <| some q($pf)
| _, _ => return .continue
/-- Rewrites `∑ i : Fin n, f i` as `f 0 + f 1 + ... + f (n - 1)` when `n` is a numeral. -/
simproc_decl sum_univ_ofNat (∑ _ : Fin _, _) := .ofQ fun u _ e => do
match u, e with
| .succ _, ~q(@Finset.sum (Fin $n) _ $inst (@Finset.univ _ $instF) $f) => do
match n.nat? with
| none =>
return .continue
| some nVal =>
let ⟨res, pf⟩ ← mkSumEqQ inst nVal f
let ⟨_⟩ ← assertDefEqQ q($instF) q(Fin.fintype _)
have _ : $n =Q $nVal := ⟨⟩
return .visit <| .mk q($res) <| some q($pf)
| _, _ => return .continue
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Take.lean | import Mathlib.Data.Fin.Tuple.Basic
/-!
# Take operations on tuples
We define the `take` operation on `n`-tuples, which restricts a tuple to its first `m` elements.
* `Fin.take`: Given `h : m ≤ n`, `Fin.take m h v` for a `n`-tuple `v = (v 0, ..., v (n - 1))` is the
`m`-tuple `(v 0, ..., v (m - 1))`.
-/
namespace Fin
open Function
variable {n : ℕ} {α : Fin n → Sort*}
section Take
/-- Take the first `m` elements of an `n`-tuple where `m ≤ n`, returning an `m`-tuple. -/
def take (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) : (i : Fin m) → α (castLE h i) :=
fun i ↦ v (castLE h i)
@[simp]
theorem take_apply (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) (i : Fin m) :
(take m h v) i = v (castLE h i) := rfl
@[simp]
theorem take_zero (v : (i : Fin n) → α i) : take 0 n.zero_le v = fun i ↦ elim0 i := by
ext i; exact elim0 i
@[simp]
theorem take_one {α : Fin (n + 1) → Sort*} (v : (i : Fin (n + 1)) → α i) :
take 1 (Nat.le_add_left 1 n) v = (fun i => v (castLE (Nat.le_add_left 1 n) i)) := by
ext i
simp only [take]
@[simp]
theorem take_eq_init {α : Fin (n + 1) → Sort*} (v : (i : Fin (n + 1)) → α i) :
take n n.le_succ v = init v := rfl
@[simp]
theorem take_eq_self (v : (i : Fin n) → α i) : take n (le_refl n) v = v := by
ext i
simp [take]
@[simp]
theorem take_take {m n' : ℕ} (h : m ≤ n') (h' : n' ≤ n) (v : (i : Fin n) → α i) :
take m h (take n' h' v) = take m (Nat.le_trans h h') v := rfl
@[simp]
theorem take_init {α : Fin (n + 1) → Sort*} (m : ℕ) (h : m ≤ n) (v : (i : Fin (n + 1)) → α i) :
take m h (init v) = take m (Nat.le_succ_of_le h) v := rfl
theorem take_repeat {α : Type*} {n' : ℕ} (m : ℕ) (h : m ≤ n) (a : Fin n' → α) :
take (m * n') (Nat.mul_le_mul_right n' h) (Fin.repeat n a) = Fin.repeat m a := by
ext i
simp only [take, repeat_apply, modNat, coe_castLE]
/-- Taking `m + 1` elements is equal to taking `m` elements and adding the `(m + 1)`th one. -/
theorem take_succ_eq_snoc (m : ℕ) (h : m < n) (v : (i : Fin n) → α i) :
take m.succ h v = snoc (take m h.le v) (v ⟨m, h⟩) := by
ext i
induction m with
| zero =>
have h' : i = 0 := by ext; simp
subst h'
simp [take, snoc, castLE]
| succ m _ =>
induction i using reverseInduction with
| last => simp [take, snoc]; congr
| cast i _ => simp
/-- `take` commutes with `update` for indices in the range of `take`. -/
@[simp]
theorem take_update_of_lt (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) (i : Fin m)
(x : α (castLE h i)) : take m h (update v (castLE h i) x) = update (take m h v) i x := by
ext j
by_cases h' : j = i
· rw [h']
simp only [take, update_self]
· have : castLE h j ≠ castLE h i := by simp [h']
simp only [take, update_of_ne h', update_of_ne this]
/-- `take` is the same after `update` for indices outside the range of `take`. -/
@[simp]
theorem take_update_of_ge (m : ℕ) (h : m ≤ n) (v : (i : Fin n) → α i) (i : Fin n) (hi : i ≥ m)
(x : α i) : take m h (update v i x) = take m h v := by
ext j
have : castLE h j ≠ i := by
refine ne_of_val_ne ?_
simp only [coe_castLE]
exact Nat.ne_of_lt (lt_of_lt_of_le j.isLt hi)
simp only [take, update_of_ne this]
/-- Taking the first `m ≤ n` elements of an `addCases u v`, where `u` is a `n`-tuple, is the same as
taking the first `m` elements of `u`. -/
theorem take_addCases_left {n' : ℕ} {motive : Fin (n + n') → Sort*} (m : ℕ) (h : m ≤ n)
(u : (i : Fin n) → motive (castAdd n' i)) (v : (i : Fin n') → motive (natAdd n i)) :
take m (Nat.le_add_right_of_le h) (addCases u v) = take m h u := by
ext i
have : i < n := Nat.lt_of_lt_of_le i.isLt h
simp only [take, addCases, this, coe_castLE, ↓reduceDIte]
congr
/-- Version of `take_addCases_left` that specializes `addCases` to `append`. -/
theorem take_append_left {n' : ℕ} {α : Sort*} (m : ℕ) (h : m ≤ n) (u : (i : Fin n) → α)
(v : (i : Fin n') → α) : take m (Nat.le_add_right_of_le h) (append u v) = take m h u :=
take_addCases_left m h _ _
/-- Taking the first `n + m` elements of an `addCases u v`, where `v` is a `n'`-tuple and `m ≤ n'`,
is the same as appending `u` with the first `m` elements of `v`. -/
theorem take_addCases_right {n' : ℕ} {motive : Fin (n + n') → Sort*} (m : ℕ) (h : m ≤ n')
(u : (i : Fin n) → motive (castAdd n' i)) (v : (i : Fin n') → motive (natAdd n i)) :
take (n + m) (Nat.add_le_add_left h n) (addCases u v) = addCases u (take m h v) := by
ext i
simp only [take, addCases, coe_castLE]
by_cases h' : i < n
· simp only [h', ↓reduceDIte]
congr
· simp only [h', ↓reduceDIte, subNat, castLE, Fin.cast, eqRec_eq_cast]
/-- Version of `take_addCases_right` that specializes `addCases` to `append`. -/
theorem take_append_right {n' : ℕ} {α : Sort*} (m : ℕ) (h : m ≤ n') (u : (i : Fin n) → α)
(v : (i : Fin n') → α) : take (n + m) (Nat.add_le_add_left h n) (append u v)
= append u (take m h v) :=
take_addCases_right m h _ _
/-- `Fin.take` intertwines with `List.take` via `List.ofFn`. -/
theorem ofFn_take_eq_take_ofFn {α : Type*} {m : ℕ} (h : m ≤ n) (v : Fin n → α) :
List.ofFn (take m h v) = (List.ofFn v).take m :=
List.ext_get (by simp [h]) (fun n h1 h2 => by simp)
/-- Alternative version of `take_eq_take_list_ofFn` with `l : List α` instead of `v : Fin n → α`. -/
theorem ofFn_take_get {α : Type*} {m : ℕ} (l : List α) (h : m ≤ l.length) :
List.ofFn (take m h l.get) = l.take m :=
List.ext_get (by simp [h]) (fun n h1 h2 => by simp)
/-- `Fin.take` intertwines with `List.take` via `List.get`. -/
theorem get_take_eq_take_get_comp_cast {α : Type*} {m : ℕ} (l : List α) (h : m ≤ l.length) :
(l.take m).get = take m h l.get ∘ Fin.cast (List.length_take_of_le h) := by
ext i
simp only [List.get_eq_getElem, List.getElem_take, comp_apply, take_apply, coe_castLE, coe_cast]
/-- Alternative version of `take_eq_take_list_get` with `v : Fin n → α` instead of `l : List α`. -/
theorem get_take_ofFn_eq_take_comp_cast {α : Type*} {m : ℕ} (v : Fin n → α) (h : m ≤ n) :
((List.ofFn v).take m).get = take m h v ∘ Fin.cast (by simp [h]) := by
ext i
simp [castLE]
end Take
end Fin |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Finset.lean | import Mathlib.Data.Finset.Prod
import Mathlib.Data.Fintype.Pi
/-!
# Fin-indexed tuples of finsets
-/
open Fin Fintype
namespace Fin
variable {n : ℕ} {α : Fin (n + 1) → Type*} {f : ∀ i, α i} {s : ∀ i, Finset (α i)} {p : Fin (n + 1)}
lemma mem_piFinset_iff_zero_tail :
f ∈ Fintype.piFinset s ↔ f 0 ∈ s 0 ∧ tail f ∈ piFinset (tail s) := by
simp only [Fintype.mem_piFinset, forall_fin_succ, tail]
lemma mem_piFinset_iff_last_init :
f ∈ piFinset s ↔ f (last n) ∈ s (last n) ∧ init f ∈ piFinset (init s) := by
simp only [Fintype.mem_piFinset, forall_fin_succ', init, and_comm]
lemma mem_piFinset_iff_pivot_removeNth (p : Fin (n + 1)) :
f ∈ piFinset s ↔ f p ∈ s p ∧ removeNth p f ∈ piFinset (removeNth p s) := by
simp only [Fintype.mem_piFinset, forall_iff_succAbove p, removeNth]
lemma cons_mem_piFinset_cons {x_zero : α 0} {x_tail : (i : Fin n) → α i.succ}
{s_zero : Finset (α 0)} {s_tail : (i : Fin n) → Finset (α i.succ)} :
cons x_zero x_tail ∈ piFinset (cons s_zero s_tail) ↔
x_zero ∈ s_zero ∧ x_tail ∈ piFinset s_tail := by
simp_rw [mem_piFinset_iff_zero_tail, cons_zero, tail_cons]
lemma snoc_mem_piFinset_snoc {x_last : α (last n)} {x_init : (i : Fin n) → α i.castSucc}
{s_last : Finset (α (last n))} {s_init : (i : Fin n) → Finset (α i.castSucc)} :
snoc x_init x_last ∈ piFinset (snoc s_init s_last) ↔
x_last ∈ s_last ∧ x_init ∈ piFinset s_init := by
simp_rw [mem_piFinset_iff_last_init, init_snoc, snoc_last]
lemma insertNth_mem_piFinset_insertNth {x_pivot : α p} {x_remove : ∀ i, α (succAbove p i)}
{s_pivot : Finset (α p)} {s_remove : ∀ i, Finset (α (succAbove p i))} :
insertNth p x_pivot x_remove ∈ piFinset (insertNth p s_pivot s_remove) ↔
x_pivot ∈ s_pivot ∧ x_remove ∈ piFinset s_remove := by
simp [mem_piFinset_iff_pivot_removeNth p]
end Fin
namespace Finset
variable {n : ℕ} {α : Fin (n + 1) → Type*} {p : Fin (n + 1)} (S : ∀ i, Finset (α i))
lemma map_consEquiv_filter_piFinset (P : (∀ i, α (succ i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (tail r)}.map (consEquiv α).symm.toEmbedding =
S 0 ×ˢ {r ∈ piFinset (tail S) | P r} := by
unfold tail; ext; simp [Fin.forall_iff_succ, and_assoc]
lemma map_snocEquiv_filter_piFinset (P : (∀ i, α (castSucc i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (init r)}.map (snocEquiv α).symm.toEmbedding =
S (last _) ×ˢ {r ∈ piFinset (init S) | P r} := by
unfold init; ext; simp [Fin.forall_iff_castSucc, and_assoc]
lemma map_insertNthEquiv_filter_piFinset (P : (∀ i, α (p.succAbove i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (p.removeNth r)}.map (p.insertNthEquiv α).symm.toEmbedding =
S p ×ˢ {r ∈ piFinset (p.removeNth S) | P r} := by
unfold removeNth; ext; simp [Fin.forall_iff_succAbove p, and_assoc]
lemma filter_piFinset_eq_map_consEquiv (P : (∀ i, α (succ i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (tail r)} =
(S 0 ×ˢ {r ∈ piFinset (tail S) | P r}).map (consEquiv α).toEmbedding := by
simp [← map_consEquiv_filter_piFinset, map_map]
lemma filter_piFinset_eq_map_snocEquiv (P : (∀ i, α (castSucc i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (init r)} =
(S (last _) ×ˢ {r ∈ piFinset (init S) | P r}).map (snocEquiv α).toEmbedding := by
simp [← map_snocEquiv_filter_piFinset, map_map]
lemma filter_piFinset_eq_map_insertNthEquiv (P : (∀ i, α (p.succAbove i)) → Prop)
[DecidablePred P] :
{r ∈ piFinset S | P (p.removeNth r)} =
(S p ×ˢ {r ∈ piFinset (p.removeNth S) | P r}).map (p.insertNthEquiv α).toEmbedding := by
simp [← map_insertNthEquiv_filter_piFinset, map_map]
lemma card_consEquiv_filter_piFinset (P : (∀ i, α (succ i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (tail r)}.card = (S 0).card * {r ∈ piFinset (tail S) | P r}.card := by
rw [← card_product, ← map_consEquiv_filter_piFinset, card_map]
lemma card_snocEquiv_filter_piFinset (P : (∀ i, α (castSucc i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (init r)}.card =
(S (last _)).card * {r ∈ piFinset (init S) | P r}.card := by
rw [← card_product, ← map_snocEquiv_filter_piFinset, card_map]
lemma card_insertNthEquiv_filter_piFinset (P : (∀ i, α (p.succAbove i)) → Prop) [DecidablePred P] :
{r ∈ piFinset S | P (p.removeNth r)}.card =
(S p).card * {r ∈ piFinset (p.removeNth S) | P r}.card := by
rw [← card_product, ← map_insertNthEquiv_filter_piFinset, card_map]
end Finset |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Basic.lean | import Mathlib.Data.Fin.Rev
import Mathlib.Data.Nat.Find
import Mathlib.Order.Fin.Basic
/-!
# Operation on tuples
We interpret maps `∀ i : Fin n, α i` as `n`-tuples of elements of possibly varying type `α i`,
`(α 0, …, α (n-1))`. A particular case is `Fin n → α` of elements with all the same type.
In this case when `α i` is a constant map, then tuples are isomorphic (but not definitionally equal)
to `Vector`s.
## Main declarations
There are three (main) ways to consider `Fin n` as a subtype of `Fin (n + 1)`, hence three (main)
ways to move between tuples of length `n` and of length `n + 1` by adding/removing an entry.
### Adding at the start
* `Fin.succ`: Send `i : Fin n` to `i + 1 : Fin (n + 1)`. This is defined in Core.
* `Fin.cases`: Induction/recursion principle for `Fin`: To prove a property/define a function for
all `Fin (n + 1)`, it is enough to prove/define it for `0` and for `i.succ` for all `i : Fin n`.
This is defined in Core.
* `Fin.cons`: Turn a tuple `f : Fin n → α` and an entry `a : α` into a tuple
`Fin.cons a f : Fin (n + 1) → α` by adding `a` at the start. In general, tuples can be dependent
functions, in which case `f : ∀ i : Fin n, α i.succ` and `a : α 0`. This is a special case of
`Fin.cases`.
* `Fin.tail`: Turn a tuple `f : Fin (n + 1) → α` into a tuple `Fin.tail f : Fin n → α` by forgetting
the start. In general, tuples can be dependent functions,
in which case `Fin.tail f : ∀ i : Fin n, α i.succ`.
### Adding at the end
* `Fin.castSucc`: Send `i : Fin n` to `i : Fin (n + 1)`. This is defined in Core.
* `Fin.lastCases`: Induction/recursion principle for `Fin`: To prove a property/define a function
for all `Fin (n + 1)`, it is enough to prove/define it for `last n` and for `i.castSucc` for all
`i : Fin n`. This is defined in Core.
* `Fin.snoc`: Turn a tuple `f : Fin n → α` and an entry `a : α` into a tuple
`Fin.snoc f a : Fin (n + 1) → α` by adding `a` at the end. In general, tuples can be dependent
functions, in which case `f : ∀ i : Fin n, α i.castSucc` and `a : α (last n)`. This is a
special case of `Fin.lastCases`.
* `Fin.init`: Turn a tuple `f : Fin (n + 1) → α` into a tuple `Fin.init f : Fin n → α` by forgetting
the end. In general, tuples can be dependent functions,
in which case `Fin.init f : ∀ i : Fin n, α i.castSucc`.
### Adding in the middle
For a **pivot** `p : Fin (n + 1)`,
* `Fin.succAbove`: Send `i : Fin n` to
* `i : Fin (n + 1)` if `i < p`,
* `i + 1 : Fin (n + 1)` if `p ≤ i`.
* `Fin.succAboveCases`: Induction/recursion principle for `Fin`: To prove a property/define a
function for all `Fin (n + 1)`, it is enough to prove/define it for `p` and for `p.succAbove i`
for all `i : Fin n`.
* `Fin.insertNth`: Turn a tuple `f : Fin n → α` and an entry `a : α` into a tuple
`Fin.insertNth f a : Fin (n + 1) → α` by adding `a` in position `p`. In general, tuples can be
dependent functions, in which case `f : ∀ i : Fin n, α (p.succAbove i)` and `a : α p`. This is a
special case of `Fin.succAboveCases`.
* `Fin.removeNth`: Turn a tuple `f : Fin (n + 1) → α` into a tuple `Fin.removeNth p f : Fin n → α`
by forgetting the `p`-th value. In general, tuples can be dependent functions,
in which case `Fin.removeNth f : ∀ i : Fin n, α (succAbove p i)`.
`p = 0` means we add at the start. `p = last n` means we add at the end.
### Miscellaneous
* `Fin.find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied.
* `Fin.append a b` : append two tuples.
* `Fin.repeat n a` : repeat a tuple `n` times.
-/
assert_not_exists Monoid
universe u v
namespace Fin
variable {m n : ℕ}
open Function
section Tuple
/-- There is exactly one tuple of size zero. -/
example (α : Fin 0 → Sort u) : Unique (∀ i : Fin 0, α i) := by infer_instance
theorem tuple0_le {α : Fin 0 → Type*} [∀ i, Preorder (α i)] (f g : ∀ i, α i) : f ≤ g :=
finZeroElim
variable {α : Fin (n + 1) → Sort u} (x : α 0) (q : ∀ i, α i) (p : ∀ i : Fin n, α i.succ) (i : Fin n)
(y : α i.succ) (z : α 0)
/-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/
def tail (q : ∀ i, α i) : ∀ i : Fin n, α i.succ := fun i ↦ q i.succ
theorem tail_def {n : ℕ} {α : Fin (n + 1) → Sort*} {q : ∀ i, α i} :
(tail fun k : Fin (n + 1) ↦ q k) = fun k : Fin n ↦ q k.succ :=
rfl
/-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/
def cons (x : α 0) (p : ∀ i : Fin n, α i.succ) : ∀ i, α i := fun j ↦ Fin.cases x p j
@[simp]
theorem tail_cons : tail (cons x p) = p := by
simp +unfoldPartialApp [tail, cons]
@[simp]
theorem cons_succ : cons x p i.succ = p i := by simp [cons]
@[simp]
theorem cons_zero : cons x p 0 = x := by simp [cons]
@[simp]
theorem cons_one {α : Fin (n + 2) → Sort*} (x : α 0) (p : ∀ i : Fin n.succ, α i.succ) :
cons x p 1 = p 0 := by
rw [← cons_succ x p]; rfl
@[simp]
theorem cons_last {α : Fin (n + 2) → Sort*} (x : α 0) (p : ∀ i : Fin n.succ, α i.succ) :
cons x p (.last _) = p (.last _) := by
rw [← cons_succ x p]; rfl
/-- Updating a tuple and adding an element at the beginning commute. -/
@[simp]
theorem cons_update : cons x (update p i y) = update (cons x p) i.succ y := by
ext j
cases j using Fin.cases <;> simp [Ne.symm, update_apply_of_injective _ (succ_injective _)]
/-- As a binary function, `Fin.cons` is injective. -/
theorem cons_injective2 : Function.Injective2 (@cons n α) := fun x₀ y₀ x y h ↦
⟨congr_fun h 0, funext fun i ↦ by simpa using congr_fun h (Fin.succ i)⟩
@[simp]
theorem cons_inj {x₀ y₀ : α 0} {x y : ∀ i : Fin n, α i.succ} :
cons x₀ x = cons y₀ y ↔ x₀ = y₀ ∧ x = y :=
cons_injective2.eq_iff
theorem cons_left_injective (x : ∀ i : Fin n, α i.succ) : Function.Injective fun x₀ ↦ cons x₀ x :=
cons_injective2.left _
theorem cons_right_injective (x₀ : α 0) : Function.Injective (cons x₀) :=
cons_injective2.right _
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
@[simp]
theorem update_cons_zero : update (cons x p) 0 z = cons z p := by
ext j
cases j using Fin.cases <;> simp
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp]
theorem cons_self_tail : cons (q 0) (tail q) = q := by
ext j
cases j using Fin.cases <;> simp [tail]
/-- Equivalence between tuples of length `n + 1` and pairs of an element and a tuple of length `n`
given by separating out the first element of the tuple.
This is `Fin.cons` as an `Equiv`. -/
@[simps]
def consEquiv (α : Fin (n + 1) → Type*) : α 0 × (∀ i, α (succ i)) ≃ ∀ i, α i where
toFun f := cons f.1 f.2
invFun f := (f 0, tail f)
left_inv f := by simp
right_inv f := by simp
/-- Recurse on an `n+1`-tuple by splitting it into a single element and an `n`-tuple. -/
@[elab_as_elim]
def consCases {P : (∀ i : Fin n.succ, α i) → Sort v} (h : ∀ x₀ x, P (Fin.cons x₀ x))
(x : ∀ i : Fin n.succ, α i) : P x :=
_root_.cast (by rw [cons_self_tail]) <| h (x 0) (tail x)
@[simp]
theorem consCases_cons {P : (∀ i : Fin n.succ, α i) → Sort v} (h : ∀ x₀ x, P (Fin.cons x₀ x))
(x₀ : α 0) (x : ∀ i : Fin n, α i.succ) : consCases h (cons x₀ x) = h x₀ x := by
rw [consCases, cast_eq]
congr
/-- Recurse on a tuple by splitting into `Fin.elim0` and `Fin.cons`. -/
@[elab_as_elim]
def consInduction {α : Sort*} {motive : ∀ {n : ℕ}, (Fin n → α) → Sort v} (elim0 : motive Fin.elim0)
(cons : ∀ {n} (x₀) (x : Fin n → α), motive x → motive (Fin.cons x₀ x)) :
∀ {n : ℕ} (x : Fin n → α), motive x
| 0, x => by convert elim0
| _ + 1, x => consCases (fun _ _ ↦ cons _ _ <| consInduction elim0 cons _) x
theorem cons_injective_of_injective {α} {x₀ : α} {x : Fin n → α} (hx₀ : x₀ ∉ Set.range x)
(hx : Function.Injective x) : Function.Injective (cons x₀ x : Fin n.succ → α) := by
intro i j
cases i using Fin.cases <;> cases j using Fin.cases <;> aesop (add simp [hx.eq_iff])
theorem cons_injective_iff {α} {x₀ : α} {x : Fin n → α} :
Function.Injective (cons x₀ x : Fin n.succ → α) ↔ x₀ ∉ Set.range x ∧ Function.Injective x := by
refine ⟨fun h ↦ ⟨?_, ?_⟩, fun h ↦ cons_injective_of_injective h.1 h.2⟩
· rintro ⟨i, hi⟩
replace h := @h i.succ 0
simp [hi] at h
· simpa [Function.comp] using h.comp (Fin.succ_injective _)
@[simp]
theorem forall_fin_zero_pi {α : Fin 0 → Sort*} {P : (∀ i, α i) → Prop} :
(∀ x, P x) ↔ P finZeroElim :=
⟨fun h ↦ h _, fun h x ↦ Subsingleton.elim finZeroElim x ▸ h⟩
@[simp]
theorem exists_fin_zero_pi {α : Fin 0 → Sort*} {P : (∀ i, α i) → Prop} :
(∃ x, P x) ↔ P finZeroElim :=
⟨fun ⟨x, h⟩ ↦ Subsingleton.elim x finZeroElim ▸ h, fun h ↦ ⟨_, h⟩⟩
theorem forall_fin_succ_pi {P : (∀ i, α i) → Prop} : (∀ x, P x) ↔ ∀ a v, P (Fin.cons a v) :=
⟨fun h a v ↦ h (Fin.cons a v), consCases⟩
theorem exists_fin_succ_pi {P : (∀ i, α i) → Prop} : (∃ x, P x) ↔ ∃ a v, P (Fin.cons a v) :=
⟨fun ⟨x, h⟩ ↦ ⟨x 0, tail x, (cons_self_tail x).symm ▸ h⟩, fun ⟨_, _, h⟩ ↦ ⟨_, h⟩⟩
/-- Updating the first element of a tuple does not change the tail. -/
@[simp]
theorem tail_update_zero : tail (update q 0 z) = tail q := by
ext j
simp [tail]
/-- Updating a nonzero element and taking the tail commute. -/
@[simp]
theorem tail_update_succ : tail (update q i.succ y) = update (tail q) i y := by
ext j
by_cases h : j = i
· rw [h]
simp [tail]
· simp [tail, (Fin.succ_injective n).ne h, h]
theorem comp_cons {α : Sort*} {β : Sort*} (g : α → β) (y : α) (q : Fin n → α) :
g ∘ cons y q = cons (g y) (g ∘ q) := by
ext j
by_cases h : j = 0
· rw [h]
rfl
· let j' := pred j h
have : j'.succ = j := succ_pred j h
rw [← this, cons_succ, comp_apply, comp_apply, cons_succ]
theorem comp_tail {α : Sort*} {β : Sort*} (g : α → β) (q : Fin n.succ → α) :
g ∘ tail q = tail (g ∘ q) := by
ext j
simp [tail]
section Preorder
variable {α : Fin (n + 1) → Type*}
theorem le_cons [∀ i, Preorder (α i)] {x : α 0} {q : ∀ i, α i} {p : ∀ i : Fin n, α i.succ} :
q ≤ cons x p ↔ q 0 ≤ x ∧ tail q ≤ p :=
forall_fin_succ.trans <| and_congr Iff.rfl <| forall_congr' fun j ↦ by simp [tail]
theorem cons_le [∀ i, Preorder (α i)] {x : α 0} {q : ∀ i, α i} {p : ∀ i : Fin n, α i.succ} :
cons x p ≤ q ↔ x ≤ q 0 ∧ p ≤ tail q :=
@le_cons _ (fun i ↦ (α i)ᵒᵈ) _ x q p
theorem cons_le_cons [∀ i, Preorder (α i)] {x₀ y₀ : α 0} {x y : ∀ i : Fin n, α i.succ} :
cons x₀ x ≤ cons y₀ y ↔ x₀ ≤ y₀ ∧ x ≤ y :=
forall_fin_succ.trans <| and_congr_right' <| by simp only [cons_succ, Pi.le_def]
end Preorder
theorem range_fin_succ {α} (f : Fin (n + 1) → α) :
Set.range f = insert (f 0) (Set.range (Fin.tail f)) :=
Set.ext fun _ ↦ exists_fin_succ.trans <| eq_comm.or Iff.rfl
@[simp]
theorem range_cons {α} {n : ℕ} (x : α) (b : Fin n → α) :
Set.range (Fin.cons x b : Fin n.succ → α) = insert x (Set.range b) := by
rw [range_fin_succ, cons_zero, tail_cons]
section Append
variable {α : Sort*}
/-- Append a tuple of length `m` to a tuple of length `n` to get a tuple of length `m + n`.
This is a non-dependent version of `Fin.add_cases`. -/
def append (a : Fin m → α) (b : Fin n → α) : Fin (m + n) → α :=
@Fin.addCases _ _ (fun _ => α) a b
@[simp]
theorem append_left (u : Fin m → α) (v : Fin n → α) (i : Fin m) :
append u v (Fin.castAdd n i) = u i :=
addCases_left _
/-- Variant of `append_left` using `Fin.castLE` instead of `Fin.castAdd`. -/
@[simp]
theorem append_left' (u : Fin m → α) (v : Fin n → α) (i : Fin m) :
append u v (Fin.castLE (by cutsat) i) = u i :=
addCases_left _
@[simp]
theorem append_right (u : Fin m → α) (v : Fin n → α) (i : Fin n) :
append u v (natAdd m i) = v i :=
addCases_right _
theorem append_right_nil (u : Fin m → α) (v : Fin n → α) (hv : n = 0) :
append u v = u ∘ Fin.cast (by rw [hv, Nat.add_zero]) := by
refine funext (Fin.addCases (fun l => ?_) fun r => ?_)
· rw [append_left, Function.comp_apply]
refine congr_arg u (Fin.ext ?_)
simp
· exact (Fin.cast hv r).elim0
@[simp]
theorem append_elim0 (u : Fin m → α) :
append u Fin.elim0 = u ∘ Fin.cast (Nat.add_zero _) :=
append_right_nil _ _ rfl
theorem append_left_nil (u : Fin m → α) (v : Fin n → α) (hu : m = 0) :
append u v = v ∘ Fin.cast (by rw [hu, Nat.zero_add]) := by
refine funext (Fin.addCases (fun l => ?_) fun r => ?_)
· exact (Fin.cast hu l).elim0
· rw [append_right, Function.comp_apply]
refine congr_arg v (Fin.ext ?_)
simp [hu]
@[simp]
theorem elim0_append (v : Fin n → α) :
append Fin.elim0 v = v ∘ Fin.cast (Nat.zero_add _) :=
append_left_nil _ _ rfl
theorem append_assoc {p : ℕ} (a : Fin m → α) (b : Fin n → α) (c : Fin p → α) :
append (append a b) c = append a (append b c) ∘ Fin.cast (Nat.add_assoc ..) := by
ext i
rw [Function.comp_apply]
refine Fin.addCases (fun l => ?_) (fun r => ?_) i
· rw [append_left]
refine Fin.addCases (fun ll => ?_) (fun lr => ?_) l
· rw [append_left]
simp [castAdd_castAdd]
· rw [append_right]
simp [castAdd_natAdd]
· rw [append_right]
simp [← natAdd_natAdd]
/-- Appending a one-tuple to the left is the same as `Fin.cons`. -/
theorem append_left_eq_cons {n : ℕ} (x₀ : Fin 1 → α) (x : Fin n → α) :
Fin.append x₀ x = Fin.cons (x₀ 0) x ∘ Fin.cast (Nat.add_comm ..) := by
ext i
refine Fin.addCases ?_ ?_ i <;> clear i
· intro i
rw [Subsingleton.elim i 0, Fin.append_left, Function.comp_apply, eq_comm]
exact Fin.cons_zero _ _
· intro i
rw [Fin.append_right, Function.comp_apply, Fin.cast_natAdd, eq_comm, Fin.addNat_one]
exact Fin.cons_succ _ _ _
/-- `Fin.cons` is the same as appending a one-tuple to the left. -/
theorem cons_eq_append (x : α) (xs : Fin n → α) :
cons x xs = append (cons x Fin.elim0) xs ∘ Fin.cast (Nat.add_comm ..) := by
funext i; simp [append_left_eq_cons]
@[simp] lemma append_cast_left {n m} (xs : Fin n → α) (ys : Fin m → α) (n' : ℕ)
(h : n' = n) :
Fin.append (xs ∘ Fin.cast h) ys = Fin.append xs ys ∘ (Fin.cast <| by rw [h]) := by
subst h; simp
@[simp] lemma append_cast_right {n m} (xs : Fin n → α) (ys : Fin m → α) (m' : ℕ)
(h : m' = m) :
Fin.append xs (ys ∘ Fin.cast h) = Fin.append xs ys ∘ (Fin.cast <| by rw [h]) := by
subst h; simp
lemma append_rev {m n} (xs : Fin m → α) (ys : Fin n → α) (i : Fin (m + n)) :
append xs ys (rev i) = append (ys ∘ rev) (xs ∘ rev) (i.cast (Nat.add_comm ..)) := by
rcases rev_surjective i with ⟨i, rfl⟩
rw [rev_rev]
induction i using Fin.addCases
· simp [rev_castAdd]
· simp [cast_rev, rev_addNat]
lemma append_comp_rev {m n} (xs : Fin m → α) (ys : Fin n → α) :
append xs ys ∘ rev = append (ys ∘ rev) (xs ∘ rev) ∘ Fin.cast (Nat.add_comm ..) :=
funext <| append_rev xs ys
theorem append_castAdd_natAdd {f : Fin (m + n) → α} :
append (fun i ↦ f (castAdd n i)) (fun i ↦ f (natAdd m i)) = f := by
unfold append addCases
simp
/-- Splitting a dependent finite sequence v into an initial part and a final part,
and then concatenating these components, produces an identical sequence. -/
theorem addCases_castAdd_natAdd {γ : Fin (m + n) → Sort*} (v : ∀ i, γ i) :
addCases (fun i ↦ v (castAdd n i)) (fun j ↦ v (natAdd m j)) = v := by
ext i
cases i using addCases <;> simp
theorem append_comp_sumElim {xs : Fin m → α} {ys : Fin n → α} :
Fin.append xs ys ∘ Sum.elim (Fin.castAdd _) (Fin.natAdd _) = Sum.elim xs ys := by
ext (i | j) <;> simp
theorem append_injective_iff {xs : Fin m → α} {ys : Fin n → α} :
Function.Injective (Fin.append xs ys) ↔
Function.Injective xs ∧ Function.Injective ys ∧ ∀ i j, xs i ≠ ys j := by
-- TODO: move things around so we can just import this.
-- We inline it because it's still shorter than proving from scratch.
let finSumFinEquiv : Fin m ⊕ Fin n ≃ Fin (m + n) :=
{ toFun := Sum.elim (Fin.castAdd n) (Fin.natAdd m)
invFun i := @Fin.addCases m n (fun _ => Fin m ⊕ Fin n) Sum.inl Sum.inr i
left_inv x := by rcases x with y | y <;> simp
right_inv x := by refine Fin.addCases (fun i => ?_) (fun i => ?_) x <;> simp }
rw [← Sum.elim_injective, ← append_comp_sumElim, ← finSumFinEquiv.injective_comp,
Equiv.coe_fn_mk]
end Append
section Repeat
variable {α : Sort*}
/-- Repeat `a` `m` times. For example `Fin.repeat 2 ![0, 3, 7] = ![0, 3, 7, 0, 3, 7]`. -/
def «repeat» (m : ℕ) (a : Fin n → α) : Fin (m * n) → α
| i => a i.modNat
@[simp]
theorem repeat_apply (a : Fin n → α) (i : Fin (m * n)) :
Fin.repeat m a i = a i.modNat :=
rfl
@[simp]
theorem repeat_zero (a : Fin n → α) :
Fin.repeat 0 a = Fin.elim0 ∘ Fin.cast (Nat.zero_mul _) :=
funext fun x => (x.cast (Nat.zero_mul _)).elim0
@[simp]
theorem repeat_one (a : Fin n → α) : Fin.repeat 1 a = a ∘ Fin.cast (Nat.one_mul _) := by
generalize_proofs h
apply funext
rw [(Fin.rightInverse_cast h.symm).surjective.forall]
intro i
simp [modNat, Nat.mod_eq_of_lt i.is_lt]
theorem repeat_succ (a : Fin n → α) (m : ℕ) :
Fin.repeat m.succ a =
append a (Fin.repeat m a) ∘ Fin.cast ((Nat.succ_mul _ _).trans (Nat.add_comm ..)) := by
generalize_proofs h
apply funext
rw [(Fin.rightInverse_cast h.symm).surjective.forall]
refine Fin.addCases (fun l => ?_) fun r => ?_
· simp [modNat, Nat.mod_eq_of_lt l.is_lt]
· simp [modNat]
@[simp]
theorem repeat_add (a : Fin n → α) (m₁ m₂ : ℕ) : Fin.repeat (m₁ + m₂) a =
append (Fin.repeat m₁ a) (Fin.repeat m₂ a) ∘ Fin.cast (Nat.add_mul ..) := by
generalize_proofs h
apply funext
rw [(Fin.rightInverse_cast h.symm).surjective.forall]
refine Fin.addCases (fun l => ?_) fun r => ?_
· simp [modNat]
· simp [modNat, Nat.add_mod]
theorem repeat_rev (a : Fin n → α) (k : Fin (m * n)) :
Fin.repeat m a k.rev = Fin.repeat m (a ∘ Fin.rev) k :=
congr_arg a k.modNat_rev
theorem repeat_comp_rev (a : Fin n → α) :
Fin.repeat m a ∘ Fin.rev = Fin.repeat m (a ∘ Fin.rev) :=
funext <| repeat_rev a
end Repeat
end Tuple
section TupleRight
/-! In the previous section, we have discussed inserting or removing elements on the left of a
tuple. In this section, we do the same on the right. A difference is that `Fin (n+1)` is constructed
inductively from `Fin n` starting from the left, not from the right. This implies that Lean needs
more help to realize that elements belong to the right types, i.e., we need to insert casts at
several places. -/
variable {α : Fin (n + 1) → Sort*} (x : α (last n)) (q : ∀ i, α i)
(p : ∀ i : Fin n, α i.castSucc) (i : Fin n) (y : α i.castSucc) (z : α (last n))
/-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/
def init (q : ∀ i, α i) (i : Fin n) : α i.castSucc :=
q i.castSucc
theorem init_def {q : ∀ i, α i} :
(init fun k : Fin (n + 1) ↦ q k) = fun k : Fin n ↦ q k.castSucc :=
rfl
/-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from
`cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/
def snoc (p : ∀ i : Fin n, α i.castSucc) (x : α (last n)) (i : Fin (n + 1)) : α i :=
if h : i.val < n then _root_.cast (by rw [Fin.castSucc_castLT i h]) (p (castLT i h))
else _root_.cast (by rw [eq_last_of_not_lt h]) x
@[simp]
theorem init_snoc : init (snoc p x) = p := by
ext i
simp only [init, snoc, coe_castSucc, is_lt, cast_eq, dite_true]
convert cast_eq rfl (p i)
@[simp]
theorem snoc_castSucc : snoc p x i.castSucc = p i := by
simp only [snoc, coe_castSucc, is_lt, cast_eq, dite_true]
convert cast_eq rfl (p i)
@[simp]
theorem snoc_apply_zero [NeZero n] : snoc p x 0 = p 0 := snoc_castSucc x p 0
@[simp]
theorem snoc_comp_castSucc {α : Sort*} {a : α} {f : Fin n → α} :
(snoc f a : Fin (n + 1) → α) ∘ castSucc = f :=
funext fun i ↦ by rw [Function.comp_apply, snoc_castSucc]
@[simp]
theorem snoc_last : snoc p x (last n) = x := by simp [snoc]
lemma snoc_zero {α : Sort*} (p : Fin 0 → α) (x : α) :
Fin.snoc p x = fun _ ↦ x := rfl
@[simp]
theorem snoc_comp_natAdd {n m : ℕ} {α : Sort*} (f : Fin (m + n) → α) (a : α) :
(snoc f a : Fin _ → α) ∘ (natAdd m : Fin (n + 1) → Fin (m + n + 1)) =
snoc (f ∘ natAdd m) a := by
ext i
refine Fin.lastCases ?_ (fun i ↦ ?_) i
· simp only [Function.comp_apply]
rw [snoc_last, natAdd_last, snoc_last]
· simp only [comp_apply, snoc_castSucc]
rw [natAdd_castSucc, snoc_castSucc]
@[deprecated (since := "2025-07-04")] alias snoc_comp_nat_add := snoc_comp_natAdd
@[simp]
theorem snoc_castAdd {α : Fin (n + m + 1) → Sort*} (f : ∀ i : Fin (n + m), α i.castSucc)
(a : α (last (n + m))) (i : Fin n) : (snoc f a) (castAdd (m + 1) i) = f (castAdd m i) :=
dif_pos _
@[deprecated (since := "2025-07-04")] alias snoc_cast_add := snoc_castAdd
@[simp]
theorem snoc_comp_castAdd {n m : ℕ} {α : Sort*} (f : Fin (n + m) → α) (a : α) :
(snoc f a : Fin _ → α) ∘ castAdd (m + 1) = f ∘ castAdd m :=
funext (snoc_castAdd _ _)
@[deprecated (since := "2025-07-04")] alias snoc_comp_cast_add := snoc_comp_castAdd
/-- Updating a tuple and adding an element at the end commute. -/
@[simp]
theorem snoc_update : snoc (update p i y) x = update (snoc p x) i.castSucc y := by
ext j
cases j using lastCases with
| cast j => rcases eq_or_ne j i with rfl | hne <;> simp [*]
| last => simp [Ne.symm]
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
theorem update_snoc_last : update (snoc p x) (last n) z = snoc p z := by
ext j
cases j using lastCases <;> simp
@[simp]
lemma range_snoc {α : Type*} (f : Fin n → α) (x : α) :
Set.range (snoc f x) = insert x (Set.range f) := by
ext; simp [Fin.exists_fin_succ', or_comm, eq_comm]
/-- As a binary function, `Fin.snoc` is injective. -/
theorem snoc_injective2 : Function.Injective2 (@snoc n α) := fun x y xₙ yₙ h ↦
⟨funext fun i ↦ by simpa using congr_fun h (castSucc i), by simpa using congr_fun h (last n)⟩
@[simp]
theorem snoc_inj {x y : ∀ i : Fin n, α i.castSucc} {xₙ yₙ : α (last n)} :
snoc x xₙ = snoc y yₙ ↔ x = y ∧ xₙ = yₙ :=
snoc_injective2.eq_iff
theorem snoc_right_injective (x : ∀ i : Fin n, α i.castSucc) :
Function.Injective (snoc x) :=
snoc_injective2.right _
theorem snoc_left_injective (xₙ : α (last n)) : Function.Injective (snoc · xₙ) :=
snoc_injective2.left _
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp]
theorem snoc_init_self : snoc (init q) (q (last n)) = q := by
ext j
cases j using Fin.lastCases <;> simp [init]
/-- Updating the last element of a tuple does not change the beginning. -/
@[simp]
theorem init_update_last : init (update q (last n) z) = init q := by
ext j
simp [init, Fin.ne_of_lt]
/-- Updating an element and taking the beginning commute. -/
@[simp]
theorem init_update_castSucc : init (update q i.castSucc y) = update (init q) i y := by
ext j
by_cases h : j = i
· rw [h]
simp [init]
· simp [init, h, castSucc_inj]
/-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
theorem tail_init_eq_init_tail {β : Sort*} (q : Fin (n + 2) → β) :
tail (init q) = init (tail q) := by
ext i
simp [tail, init]
/-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
theorem cons_snoc_eq_snoc_cons {β : Sort*} (a : β) (q : Fin n → β) (b : β) :
@cons n.succ (fun _ ↦ β) a (snoc q b) = snoc (cons a q) b := by
ext i
cases i using Fin.cases with
| zero => simp
| succ j =>
cases j using Fin.lastCases with
| last => simp
| cast j =>
rw [cons_succ]
simp [← castSucc_succ]
theorem comp_snoc {α : Sort*} {β : Sort*} (g : α → β) (q : Fin n → α) (y : α) :
g ∘ snoc q y = snoc (g ∘ q) (g y) := by
ext j
by_cases h : j.val < n
· simp [h, snoc, castSucc_castLT]
· rw [eq_last_of_not_lt h]
simp
/-- Appending a one-tuple to the right is the same as `Fin.snoc`. -/
theorem append_right_eq_snoc {α : Sort*} {n : ℕ} (x : Fin n → α) (x₀ : Fin 1 → α) :
Fin.append x x₀ = Fin.snoc x (x₀ 0) := by
ext i
refine Fin.addCases ?_ ?_ i <;> clear i
· intro i
rw [Fin.append_left]
exact (@snoc_castSucc _ (fun _ => α) _ _ i).symm
· intro i
rw [Subsingleton.elim i 0, Fin.append_right]
exact (@snoc_last _ (fun _ => α) _ _).symm
/-- `Fin.snoc` is the same as appending a one-tuple -/
theorem snoc_eq_append {α : Sort*} (xs : Fin n → α) (x : α) :
snoc xs x = append xs (cons x Fin.elim0) :=
(append_right_eq_snoc xs (cons x Fin.elim0)).symm
theorem append_left_snoc {n m} {α : Sort*} (xs : Fin n → α) (x : α) (ys : Fin m → α) :
Fin.append (Fin.snoc xs x) ys =
Fin.append xs (Fin.cons x ys) ∘ Fin.cast (Nat.succ_add_eq_add_succ ..) := by
rw [snoc_eq_append, append_assoc, append_left_eq_cons, append_cast_right]; rfl
theorem append_right_cons {n m} {α : Sort*} (xs : Fin n → α) (y : α) (ys : Fin m → α) :
Fin.append xs (Fin.cons y ys) =
Fin.append (Fin.snoc xs y) ys ∘ Fin.cast (Nat.succ_add_eq_add_succ ..).symm := by
rw [append_left_snoc]; rfl
theorem append_cons {α : Sort*} (a : α) (as : Fin n → α) (bs : Fin m → α) :
Fin.append (cons a as) bs
= cons a (Fin.append as bs) ∘ (Fin.cast <| Nat.add_right_comm n 1 m) := by
funext i
rcases i with ⟨i, -⟩
simp only [append, addCases, cons, castLT, comp_apply]
rcases i with - | i
· simp
· split_ifs with h
· have : i < n := Nat.lt_of_succ_lt_succ h
simp [addCases, this]
· have : ¬i < n := Nat.not_le.mpr <| Nat.lt_succ.mp <| Nat.not_le.mp h
simp [addCases, this]
theorem append_snoc {α : Sort*} (as : Fin n → α) (bs : Fin m → α) (b : α) :
Fin.append as (snoc bs b) = snoc (Fin.append as bs) b := by
funext i
rcases i with ⟨i, isLt⟩
simp only [append, addCases, castLT, cast_mk, subNat_mk, natAdd_mk, cast, snoc.eq_1,
eq_rec_constant, Nat.add_eq, castLT_mk]
split_ifs with lt_n lt_add sub_lt nlt_add lt_add <;> (try rfl)
· have := Nat.lt_add_right m lt_n
contradiction
· obtain rfl := Nat.eq_of_le_of_lt_succ (Nat.not_lt.mp nlt_add) isLt
simp [Nat.add_comm n m] at sub_lt
· have := Nat.sub_lt_left_of_lt_add (Nat.not_lt.mp lt_n) lt_add
contradiction
theorem comp_init {α : Sort*} {β : Sort*} (g : α → β) (q : Fin n.succ → α) :
g ∘ init q = init (g ∘ q) := by
ext j
simp [init]
/-- Equivalence between tuples of length `n + 1` and pairs of an element and a tuple of length `n`
given by separating out the last element of the tuple.
This is `Fin.snoc` as an `Equiv`. -/
@[simps]
def snocEquiv (α : Fin (n + 1) → Type*) : α (last n) × (∀ i, α (castSucc i)) ≃ ∀ i, α i where
toFun f _ := Fin.snoc f.2 f.1 _
invFun f := ⟨f _, Fin.init f⟩
left_inv f := by simp
right_inv f := by simp
/-- Recurse on an `n+1`-tuple by splitting it its initial `n`-tuple and its last element. -/
@[elab_as_elim, inline]
def snocCases {P : (∀ i : Fin n.succ, α i) → Sort*}
(h : ∀ xs x, P (Fin.snoc xs x))
(x : ∀ i : Fin n.succ, α i) : P x :=
_root_.cast (by rw [Fin.snoc_init_self]) <| h (Fin.init x) (x <| Fin.last _)
@[simp] lemma snocCases_snoc
{P : (∀ i : Fin (n + 1), α i) → Sort*} (h : ∀ x x₀, P (Fin.snoc x x₀))
(x : ∀ i : Fin n, (Fin.init α) i) (x₀ : α (Fin.last _)) :
snocCases h (Fin.snoc x x₀) = h x x₀ := by
rw [snocCases, cast_eq_iff_heq, Fin.init_snoc, Fin.snoc_last]
/-- Recurse on a tuple by splitting into `Fin.elim0` and `Fin.snoc`. -/
@[elab_as_elim]
def snocInduction {α : Sort*}
{P : ∀ {n : ℕ}, (Fin n → α) → Sort*}
(h0 : P Fin.elim0)
(h : ∀ {n} (x : Fin n → α) (x₀), P x → P (Fin.snoc x x₀)) : ∀ {n : ℕ} (x : Fin n → α), P x
| 0, x => by convert h0
| _ + 1, x => snocCases (fun _ _ ↦ h _ _ <| snocInduction h0 h _) x
theorem snoc_injective_of_injective {α} {x₀ : α} {x : Fin n → α}
(hx : Function.Injective x) (hx₀ : x₀ ∉ Set.range x) :
Function.Injective (snoc x x₀ : Fin n.succ → α) := fun i j h ↦ by
induction i using lastCases with
| cast i =>
induction j using lastCases with
| cast j =>
simpa only [castSucc_inj, ← Injective.eq_iff hx, snoc_castSucc] using h
| last =>
simp only [snoc_castSucc, snoc_last] at h
rw [← h] at hx₀
apply hx₀.elim (Set.mem_range_self i)
| last =>
induction j using lastCases with
| cast j =>
simp only [snoc_castSucc, snoc_last] at h
rw [h] at hx₀
apply hx₀.elim (Set.mem_range_self j)
| last => simp
theorem snoc_injective_iff {α} {x₀ : α} {x : Fin n → α} :
Function.Injective (snoc x x₀ : Fin n.succ → α) ↔ Function.Injective x ∧ x₀ ∉ Set.range x := by
refine ⟨fun h ↦ ⟨?_, ?_⟩, fun h ↦ snoc_injective_of_injective h.1 h.2⟩
· simpa [Function.comp] using h.comp (Fin.castSucc_injective _)
· rintro ⟨i, hi⟩
rw [← @snoc_last n (fun i ↦ α) x₀ x, ← @snoc_castSucc n (fun i ↦ α) x₀ x i,
h.eq_iff] at hi
exact ne_last_of_lt i.castSucc_lt_last hi
end TupleRight
section InsertNth
variable {α : Fin (n + 1) → Sort*} {β : Sort*}
/-- Define a function on `Fin (n + 1)` from a value on `i : Fin (n + 1)` and values on each
`Fin.succAbove i j`, `j : Fin n`. This version is elaborated as eliminator and works for
propositions, see also `Fin.insertNth` for a version without an `@[elab_as_elim]`
attribute. -/
@[elab_as_elim]
def succAboveCases {α : Fin (n + 1) → Sort u} (i : Fin (n + 1)) (x : α i)
(p : ∀ j : Fin n, α (i.succAbove j)) (j : Fin (n + 1)) : α j :=
if hj : j = i then Eq.rec x hj.symm
else
if hlt : j < i then (succAbove_castPred_of_lt _ _ hlt) ▸ (p _)
else (succAbove_pred_of_lt _ _ <| (Fin.lt_or_lt_of_ne hj).resolve_left hlt) ▸ (p _)
-- This is a duplicate of `Fin.exists_fin_succ` in Core. We should upstream the name change.
alias forall_iff_succ := forall_fin_succ
-- This is a duplicate of `Fin.exists_fin_succ` in Core. We should upstream the name change.
alias exists_iff_succ := exists_fin_succ
lemma forall_iff_castSucc {P : Fin (n + 1) → Prop} :
(∀ i, P i) ↔ P (last n) ∧ ∀ i : Fin n, P i.castSucc :=
⟨fun h ↦ ⟨h _, fun _ ↦ h _⟩, fun h ↦ lastCases h.1 h.2⟩
/-- A finite sequence of properties P holds for {0, ..., m + n - 1} iff
it holds separately for both {0, ..., m - 1} and {m, ..., m + n - 1}. -/
theorem forall_fin_add {m n} (P : Fin (m + n) → Prop) :
(∀ i, P i) ↔ (∀ i, P (castAdd _ i)) ∧ (∀ j, P (natAdd _ j)) :=
⟨fun h => ⟨fun _ => h _, fun _ => h _⟩, fun ⟨hm, hn⟩ => Fin.addCases hm hn⟩
/-- A property holds for all dependent finite sequence of length m + n iff
it holds for the concatenation of all pairs of length m sequences and length n sequences. -/
theorem forall_fin_add_pi {γ : Fin (m + n) → Sort*} {P : (∀ i, γ i) → Prop} :
(∀ v, P v) ↔
(∀ (vₘ : ∀ i, γ (castAdd n i)) (vₙ : ∀ j, γ (natAdd m j)), P (addCases vₘ vₙ)) where
mp hv vm vn := hv (addCases vm vn)
mpr h v := by
convert h (fun i => v (castAdd n i)) (fun j => v (natAdd m j))
exact (addCases_castAdd_natAdd v).symm
lemma exists_iff_castSucc {P : Fin (n + 1) → Prop} :
(∃ i, P i) ↔ P (last n) ∨ ∃ i : Fin n, P i.castSucc where
mp := by
rintro ⟨i, hi⟩
cases i using lastCases with
| last => exact .inl hi
| cast _ => exact .inr ⟨_, hi⟩
mpr := by rintro (h | ⟨i, hi⟩) <;> exact ⟨_, ‹_›⟩
theorem forall_iff_succAbove {P : Fin (n + 1) → Prop} (p : Fin (n + 1)) :
(∀ i, P i) ↔ P p ∧ ∀ i, P (p.succAbove i) :=
⟨fun h ↦ ⟨h _, fun _ ↦ h _⟩, fun h ↦ succAboveCases p h.1 h.2⟩
lemma exists_iff_succAbove {P : Fin (n + 1) → Prop} (p : Fin (n + 1)) :
(∃ i, P i) ↔ P p ∨ ∃ i, P (p.succAbove i) where
mp := by
rintro ⟨i, hi⟩
induction i using p.succAboveCases
· exact .inl hi
· exact .inr ⟨_, hi⟩
mpr := by rintro (h | ⟨i, hi⟩) <;> exact ⟨_, ‹_›⟩
/-- Analogue of `Fin.eq_zero_or_eq_succ` for `succAbove`. -/
theorem eq_self_or_eq_succAbove (p i : Fin (n + 1)) : i = p ∨ ∃ j, i = p.succAbove j :=
succAboveCases p (.inl rfl) (fun j => .inr ⟨j, rfl⟩) i
/-- Remove the `p`-th entry of a tuple. -/
def removeNth (p : Fin (n + 1)) (f : ∀ i, α i) : ∀ i, α (p.succAbove i) := fun i ↦ f (p.succAbove i)
/-- Insert an element into a tuple at a given position. For `i = 0` see `Fin.cons`,
for `i = Fin.last n` see `Fin.snoc`. See also `Fin.succAboveCases` for a version elaborated
as an eliminator. -/
def insertNth (i : Fin (n + 1)) (x : α i) (p : ∀ j : Fin n, α (i.succAbove j)) (j : Fin (n + 1)) :
α j :=
succAboveCases i x p j
@[simp]
theorem insertNth_apply_same (i : Fin (n + 1)) (x : α i) (p : ∀ j, α (i.succAbove j)) :
insertNth i x p i = x := by simp [insertNth, succAboveCases]
@[simp]
theorem insertNth_apply_succAbove (i : Fin (n + 1)) (x : α i) (p : ∀ j, α (i.succAbove j))
(j : Fin n) : insertNth i x p (i.succAbove j) = p j := by
simp only [insertNth, succAboveCases, dif_neg (succAbove_ne _ _), succAbove_lt_iff_castSucc_lt]
split_ifs with hlt
· generalize_proofs H₁ H₂; revert H₂
generalize hk : castPred ((succAbove i) j) H₁ = k
rw [castPred_succAbove _ _ hlt] at hk; cases hk
intro; rfl
· generalize_proofs H₀ H₁ H₂; revert H₂
generalize hk : pred (succAbove i j) H₁ = k
rw [pred_succAbove _ _ (Fin.not_lt.1 hlt)] at hk; cases hk
intro; rfl
@[simp]
theorem succAbove_cases_eq_insertNth : @succAboveCases = @insertNth :=
rfl
lemma removeNth_apply (p : Fin (n + 1)) (f : ∀ i, α i) (i : Fin n) :
p.removeNth f i = f (p.succAbove i) :=
rfl
@[simp] lemma removeNth_insertNth (p : Fin (n + 1)) (a : α p) (f : ∀ i, α (succAbove p i)) :
removeNth p (insertNth p a f) = f := by ext; unfold removeNth; simp
@[simp] lemma removeNth_zero (f : ∀ i, α i) : removeNth 0 f = tail f := by
ext; simp [tail, removeNth]
@[simp] lemma removeNth_last {α : Type*} (f : Fin (n + 1) → α) : removeNth (last n) f = init f := by
ext; simp [init, removeNth]
@[simp]
theorem insertNth_comp_succAbove (i : Fin (n + 1)) (x : β) (p : Fin n → β) :
insertNth i x p ∘ i.succAbove = p :=
funext (insertNth_apply_succAbove i _ _)
theorem insertNth_eq_iff {p : Fin (n + 1)} {a : α p} {f : ∀ i, α (p.succAbove i)} {g : ∀ j, α j} :
insertNth p a f = g ↔ a = g p ∧ f = removeNth p g := by
simp [funext_iff, forall_iff_succAbove p, removeNth]
theorem eq_insertNth_iff {p : Fin (n + 1)} {a : α p} {f : ∀ i, α (p.succAbove i)} {g : ∀ j, α j} :
g = insertNth p a f ↔ g p = a ∧ removeNth p g = f := by
simpa [eq_comm] using insertNth_eq_iff
/-- As a binary function, `Fin.insertNth` is injective. -/
theorem insertNth_injective2 {p : Fin (n + 1)} :
Function.Injective2 (@insertNth n α p) := fun xₚ yₚ x y h ↦
⟨by simpa using congr_fun h p, funext fun i ↦ by simpa using congr_fun h (succAbove p i)⟩
@[simp]
theorem insertNth_inj {p : Fin (n + 1)} {x y : ∀ i, α (succAbove p i)} {xₚ yₚ : α p} :
insertNth p xₚ x = insertNth p yₚ y ↔ xₚ = yₚ ∧ x = y :=
insertNth_injective2.eq_iff
theorem insertNth_left_injective {p : Fin (n + 1)} (x : ∀ i, α (succAbove p i)) :
Function.Injective (insertNth p · x) :=
insertNth_injective2.left _
theorem insertNth_right_injective {p : Fin (n + 1)} (x : α p) :
Function.Injective (insertNth p x) :=
insertNth_injective2.right _
theorem insertNth_apply_below {i j : Fin (n + 1)} (h : j < i) (x : α i)
(p : ∀ k, α (i.succAbove k)) :
i.insertNth x p j = succAbove_castPred_of_lt _ _ h ▸ (p <| j.castPred _) := by
rw [insertNth, succAboveCases, dif_neg (Fin.ne_of_lt h), dif_pos h]
theorem insertNth_apply_above {i j : Fin (n + 1)} (h : i < j) (x : α i)
(p : ∀ k, α (i.succAbove k)) :
i.insertNth x p j = succAbove_pred_of_lt _ _ h ▸ (p <| j.pred _) := by
rw [insertNth, succAboveCases, dif_neg (Fin.ne_of_gt h), dif_neg (Fin.lt_asymm h)]
theorem insertNth_zero (x : α 0) (p : ∀ j : Fin n, α (succAbove 0 j)) :
insertNth 0 x p =
cons x fun j ↦ _root_.cast (congr_arg α (congr_fun succAbove_zero j)) (p j) := by
refine insertNth_eq_iff.2 ⟨by simp, ?_⟩
ext j
convert (cons_succ x p j).symm
@[simp]
theorem insertNth_zero' (x : β) (p : Fin n → β) : @insertNth _ (fun _ ↦ β) 0 x p = cons x p := by
simp [insertNth_zero]
theorem insertNth_last (x : α (last n)) (p : ∀ j : Fin n, α ((last n).succAbove j)) :
insertNth (last n) x p =
snoc (fun j ↦ _root_.cast (congr_arg α (succAbove_last_apply j)) (p j)) x := by
refine insertNth_eq_iff.2 ⟨by simp, ?_⟩
ext j
apply eq_of_heq
trans snoc (fun j ↦ _root_.cast (congr_arg α (succAbove_last_apply j)) (p j)) x j.castSucc
· rw [snoc_castSucc]
exact (cast_heq _ _).symm
· apply congr_arg_heq
rw [succAbove_last]
@[simp]
theorem insertNth_last' (x : β) (p : Fin n → β) :
@insertNth _ (fun _ ↦ β) (last n) x p = snoc p x := by simp [insertNth_last]
lemma insertNth_rev {α : Sort*} (i : Fin (n + 1)) (a : α) (f : Fin n → α) (j : Fin (n + 1)) :
insertNth (α := fun _ ↦ α) i a f (rev j) = insertNth (α := fun _ ↦ α) i.rev a (f ∘ rev) j := by
induction j using Fin.succAboveCases
· exact rev i
· simp
· simp [rev_succAbove]
theorem insertNth_comp_rev {α} (i : Fin (n + 1)) (x : α) (p : Fin n → α) :
(Fin.insertNth i x p) ∘ Fin.rev = Fin.insertNth (Fin.rev i) x (p ∘ Fin.rev) := by
funext x
apply insertNth_rev
theorem cons_rev {α n} (a : α) (f : Fin n → α) (i : Fin <| n + 1) :
cons (α := fun _ => α) a f i.rev = snoc (α := fun _ => α) (f ∘ Fin.rev : Fin _ → α) a i := by
simpa using insertNth_rev 0 a f i
theorem cons_comp_rev {α n} (a : α) (f : Fin n → α) :
Fin.cons a f ∘ Fin.rev = Fin.snoc (f ∘ Fin.rev) a := by
funext i; exact cons_rev ..
theorem snoc_rev {α n} (a : α) (f : Fin n → α) (i : Fin <| n + 1) :
snoc (α := fun _ => α) f a i.rev = cons (α := fun _ => α) a (f ∘ Fin.rev : Fin _ → α) i := by
simpa using insertNth_rev (last n) a f i
theorem snoc_comp_rev {α n} (a : α) (f : Fin n → α) :
Fin.snoc f a ∘ Fin.rev = Fin.cons a (f ∘ Fin.rev) :=
funext <| snoc_rev a f
theorem insertNth_binop (op : ∀ j, α j → α j → α j) (i : Fin (n + 1)) (x y : α i)
(p q : ∀ j, α (i.succAbove j)) :
(i.insertNth (op i x y) fun j ↦ op _ (p j) (q j)) = fun j ↦
op j (i.insertNth x p j) (i.insertNth y q j) :=
insertNth_eq_iff.2 <| by unfold removeNth; simp
section Preorder
variable {α : Fin (n + 1) → Type*} [∀ i, Preorder (α i)]
theorem insertNth_le_iff {i : Fin (n + 1)} {x : α i} {p : ∀ j, α (i.succAbove j)} {q : ∀ j, α j} :
i.insertNth x p ≤ q ↔ x ≤ q i ∧ p ≤ fun j ↦ q (i.succAbove j) := by
simp [Pi.le_def, forall_iff_succAbove i]
theorem le_insertNth_iff {i : Fin (n + 1)} {x : α i} {p : ∀ j, α (i.succAbove j)} {q : ∀ j, α j} :
q ≤ i.insertNth x p ↔ q i ≤ x ∧ (fun j ↦ q (i.succAbove j)) ≤ p := by
simp [Pi.le_def, forall_iff_succAbove i]
end Preorder
open Set
@[simp] lemma removeNth_update (p : Fin (n + 1)) (x) (f : ∀ j, α j) :
removeNth p (update f p x) = removeNth p f := by ext i; simp [removeNth]
@[simp]
lemma removeNth_update_succAbove (p : Fin (n + 1)) (i : Fin n) (x : α (p.succAbove i))
(f : ∀ j, α j) :
removeNth p (update f (p.succAbove i) x) = update (removeNth p f) i x := by
ext j
rcases eq_or_ne j i with rfl | hne <;> simp [removeNth, *]
@[simp] lemma insertNth_removeNth (p : Fin (n + 1)) (x) (f : ∀ j, α j) :
insertNth p x (removeNth p f) = update f p x := by simp [Fin.insertNth_eq_iff]
lemma insertNth_self_removeNth (p : Fin (n + 1)) (f : ∀ j, α j) :
insertNth p (f p) (removeNth p f) = f := by simp
@[simp]
theorem update_insertNth (p : Fin (n + 1)) (x y : α p) (f : ∀ i, α (p.succAbove i)) :
update (p.insertNth x f) p y = p.insertNth y f := by
simp [eq_insertNth_iff]
@[simp]
theorem insertNth_update (p : Fin (n + 1)) (x : α p) (i : Fin n) (y : α (p.succAbove i))
(f : ∀ j, α (p.succAbove j)) :
p.insertNth x (update f i y) = update (p.insertNth x f) (p.succAbove i) y := by
simp [insertNth_eq_iff]
/-- Equivalence between tuples of length `n + 1` and pairs of an element and a tuple of length `n`
given by separating out the `p`-th element of the tuple.
This is `Fin.insertNth` as an `Equiv`. -/
@[simps]
def insertNthEquiv (α : Fin (n + 1) → Type u) (p : Fin (n + 1)) :
α p × (∀ i, α (p.succAbove i)) ≃ ∀ i, α i where
toFun f := insertNth p f.1 f.2
invFun f := (f p, removeNth p f)
left_inv f := by ext <;> simp
right_inv f := by simp
@[simp] lemma insertNthEquiv_zero (α : Fin (n + 1) → Type*) : insertNthEquiv α 0 = consEquiv α :=
Equiv.symm_bijective.injective <| by ext <;> rfl
/-- Note this lemma can only be written about non-dependent tuples as `insertNth (last n) = snoc` is
not a definitional equality. -/
@[simp] lemma insertNthEquiv_last (n : ℕ) (α : Type*) :
insertNthEquiv (fun _ ↦ α) (last n) = snocEquiv (fun _ ↦ α) := by ext; simp
/-- A `HEq` version of `Fin.removeNth_removeNth_eq_swap`. -/
theorem removeNth_removeNth_heq_swap {α : Fin (n + 2) → Sort*} (m : ∀ i, α i)
(i : Fin (n + 1)) (j : Fin (n + 2)) :
i.removeNth (j.removeNth m) ≍
(i.predAbove j).removeNth ((j.succAbove i).removeNth m) := by
apply Function.hfunext rfl
simp only [heq_iff_eq]
rintro k _ rfl
unfold removeNth
apply congr_arg_heq
rw [succAbove_succAbove_succAbove_predAbove]
/-- Given an `(n + 2)`-tuple `m` and two indexes `i : Fin (n + 1)` and `j : Fin (n + 2)`,
one can remove `j`th element from `m`, then remove `i`th element from the result,
or one can remove `(j.succAbove i)`th element from `m`,
then remove `(i.predAbove j)`th element from the result.
These two operations correspond to removing the same two elements in a different order,
so they result in the same `n`-tuple. -/
theorem removeNth_removeNth_eq_swap {α : Sort*} (m : Fin (n + 2) → α)
(i : Fin (n + 1)) (j : Fin (n + 2)) :
i.removeNth (j.removeNth m) = (i.predAbove j).removeNth ((j.succAbove i).removeNth m) :=
heq_iff_eq.mp (removeNth_removeNth_heq_swap m i j)
end InsertNth
section Find
/-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied. -/
def find : ∀ {n : ℕ} (p : Fin n → Prop) [DecidablePred p], Option (Fin n)
| 0, _p, _ => none
| n + 1, p, _ => by
exact
Option.casesOn (@find n (fun i ↦ p (i.castLT (Nat.lt_succ_of_lt i.2))) _)
(if _ : p (Fin.last n) then some (Fin.last n) else none) fun i ↦
some (i.castLT (Nat.lt_succ_of_lt i.2))
/-- If `find p = some i`, then `p i` holds -/
theorem find_spec :
∀ {n : ℕ} (p : Fin n → Prop) [DecidablePred p] {i : Fin n} (_ : i ∈ Fin.find p), p i
| 0, _, _, _, hi => Option.noConfusion hi
| n + 1, p, I, i, hi => by
rw [find] at hi
rcases h : find fun i : Fin n ↦ p (i.castLT (Nat.lt_succ_of_lt i.2)) with - | j
· rw [h] at hi
dsimp at hi
split_ifs at hi with hl
· simp only [Option.mem_def, Option.some.injEq] at hi
exact hi ▸ hl
· exact (Option.not_mem_none _ hi).elim
· rw [h] at hi
dsimp at hi
rw [← Option.some_inj.1 hi]
exact @find_spec n (fun i ↦ p (i.castLT (Nat.lt_succ_of_lt i.2))) _ _ h
/-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/
theorem isSome_find_iff :
∀ {n : ℕ} {p : Fin n → Prop} [DecidablePred p], (find p).isSome ↔ ∃ i, p i
| 0, _, _ => iff_of_false (fun h ↦ Bool.noConfusion h) fun ⟨i, _⟩ ↦ Fin.elim0 i
| n + 1, p, _ =>
⟨fun h ↦ by
rw [Option.isSome_iff_exists] at h
obtain ⟨i, hi⟩ := h
exact ⟨i, find_spec _ hi⟩, fun ⟨⟨i, hin⟩, hi⟩ ↦ by
dsimp [find]
rcases h : find fun i : Fin n ↦ p (i.castLT (Nat.lt_succ_of_lt i.2)) with - | j
· split_ifs with hl
· exact Option.isSome_some
· have := (@isSome_find_iff n (fun x ↦ p (x.castLT (Nat.lt_succ_of_lt x.2))) _).2
⟨⟨i, lt_of_le_of_ne (Nat.le_of_lt_succ hin) fun h ↦ by cases h; exact hl hi⟩, hi⟩
rw [h] at this
exact this
· simp⟩
/-- `find p` returns `none` if and only if `p i` never holds. -/
theorem find_eq_none_iff {n : ℕ} {p : Fin n → Prop} [DecidablePred p] :
find p = none ↔ ∀ i, ¬p i := by rw [← not_exists, ← isSome_find_iff]; cases find p <;> simp
/-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among
the indices where `p` holds. -/
theorem find_min :
∀ {n : ℕ} {p : Fin n → Prop} [DecidablePred p] {i : Fin n} (_ : i ∈ Fin.find p) {j : Fin n}
(_ : j < i), ¬p j
| 0, _, _, _, hi, _, _, _ => Option.noConfusion hi
| n + 1, p, _, i, hi, ⟨j, hjn⟩, hj, hpj => by
rw [find] at hi
rcases h : find fun i : Fin n ↦ p (i.castLT (Nat.lt_succ_of_lt i.2)) with - | k
· simp only [h] at hi
split_ifs at hi with hl
· cases hi
rw [find_eq_none_iff] at h
exact h ⟨j, hj⟩ hpj
· exact Option.not_mem_none _ hi
· rw [h] at hi
dsimp at hi
obtain rfl := Option.some_inj.1 hi
exact find_min h (show (⟨j, lt_trans hj k.2⟩ : Fin n) < k from hj) hpj
theorem find_min' {p : Fin n → Prop} [DecidablePred p] {i : Fin n} (h : i ∈ Fin.find p) {j : Fin n}
(hj : p j) : i ≤ j := Fin.not_lt.1 fun hij ↦ find_min h hij hj
theorem nat_find_mem_find {p : Fin n → Prop} [DecidablePred p]
(h : ∃ i, ∃ hin : i < n, p ⟨i, hin⟩) :
(⟨Nat.find h, (Nat.find_spec h).fst⟩ : Fin n) ∈ find p := by
let ⟨i, hin, hi⟩ := h
rcases hf : find p with - | f
· rw [find_eq_none_iff] at hf
exact (hf ⟨i, hin⟩ hi).elim
· refine Option.some_inj.2 (Fin.le_antisymm ?_ ?_)
· exact find_min' hf (Nat.find_spec h).snd
· exact Nat.find_min' _ ⟨f.2, by convert find_spec p hf⟩
theorem mem_find_iff {p : Fin n → Prop} [DecidablePred p] {i : Fin n} :
i ∈ Fin.find p ↔ p i ∧ ∀ j, p j → i ≤ j :=
⟨fun hi ↦ ⟨find_spec _ hi, fun _ ↦ find_min' hi⟩, by
rintro ⟨hpi, hj⟩
cases hfp : Fin.find p
· rw [find_eq_none_iff] at hfp
exact (hfp _ hpi).elim
· exact Option.some_inj.2 (Fin.le_antisymm (find_min' hfp hpi) (hj _ (find_spec _ hfp)))⟩
theorem find_eq_some_iff {p : Fin n → Prop} [DecidablePred p] {i : Fin n} :
Fin.find p = some i ↔ p i ∧ ∀ j, p j → i ≤ j :=
mem_find_iff
theorem mem_find_of_unique {p : Fin n → Prop} [DecidablePred p] (h : ∀ i j, p i → p j → i = j)
{i : Fin n} (hi : p i) : i ∈ Fin.find p :=
mem_find_iff.2 ⟨hi, fun j hj ↦ Fin.le_of_eq <| h i j hi hj⟩
end Find
section ContractNth
variable {α : Sort*}
/-- Sends `(g₀, ..., gₙ)` to `(g₀, ..., op gⱼ gⱼ₊₁, ..., gₙ)`. -/
def contractNth (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n) : α :=
if (k : ℕ) < j then g (Fin.castSucc k)
else if (k : ℕ) = j then op (g (Fin.castSucc k)) (g k.succ) else g k.succ
theorem contractNth_apply_of_lt (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n)
(h : (k : ℕ) < j) : contractNth j op g k = g (Fin.castSucc k) :=
if_pos h
theorem contractNth_apply_of_eq (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n)
(h : (k : ℕ) = j) : contractNth j op g k = op (g (Fin.castSucc k)) (g k.succ) := by
have : ¬(k : ℕ) < j := not_lt.2 (le_of_eq h.symm)
rw [contractNth, if_neg this, if_pos h]
theorem contractNth_apply_of_gt (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n)
(h : (j : ℕ) < k) : contractNth j op g k = g k.succ := by
rw [contractNth, if_neg (not_lt_of_gt h), if_neg (Ne.symm <| ne_of_lt h)]
theorem contractNth_apply_of_ne (j : Fin (n + 1)) (op : α → α → α) (g : Fin (n + 1) → α) (k : Fin n)
(hjk : (j : ℕ) ≠ k) : contractNth j op g k = g (j.succAbove k) := by
rcases lt_trichotomy (k : ℕ) j with (h | h | h)
· rwa [j.succAbove_of_castSucc_lt, contractNth_apply_of_lt]
· rwa [Fin.lt_iff_val_lt_val]
· exact False.elim (hjk h.symm)
· rwa [j.succAbove_of_le_castSucc, contractNth_apply_of_gt]
· exact Fin.le_iff_val_le_val.2 (le_of_lt h)
lemma comp_contractNth {β : Sort*} (opα : α → α → α) (opβ : β → β → β) {f : α → β}
(hf : ∀ x y, f (opα x y) = opβ (f x) (f y)) (j : Fin (n + 1)) (g : Fin (n + 1) → α) :
f ∘ contractNth j opα g = contractNth j opβ (f ∘ g) := by
ext x
rcases lt_trichotomy (x : ℕ) j with (h | h | h)
· simp only [Function.comp_apply, contractNth_apply_of_lt, h]
· simp only [Function.comp_apply, contractNth_apply_of_eq, h, hf]
· simp only [Function.comp_apply, contractNth_apply_of_gt, h]
end ContractNth
/-- To show two sigma pairs of tuples agree, it to show the second elements are related via
`Fin.cast`. -/
theorem sigma_eq_of_eq_comp_cast {α : Type*} :
∀ {a b : Σ ii, Fin ii → α} (h : a.fst = b.fst), a.snd = b.snd ∘ Fin.cast h → a = b
| ⟨ai, a⟩, ⟨bi, b⟩, hi, h => by
dsimp only at hi
subst hi
simpa using h
/-- `Fin.sigma_eq_of_eq_comp_cast` as an `iff`. -/
theorem sigma_eq_iff_eq_comp_cast {α : Type*} {a b : Σ ii, Fin ii → α} :
a = b ↔ ∃ h : a.fst = b.fst, a.snd = b.snd ∘ Fin.cast h :=
⟨fun h ↦ h ▸ ⟨rfl, funext <| Fin.rec fun _ _ ↦ rfl⟩, fun ⟨_, h'⟩ ↦
sigma_eq_of_eq_comp_cast _ h'⟩
end Fin
/-- `Π i : Fin 2, α i` is equivalent to `α 0 × α 1`. See also `finTwoArrowEquiv` for a
non-dependent version and `prodEquivPiFinTwo` for a version with inputs `α β : Type u`. -/
@[simps -fullyApplied]
def piFinTwoEquiv (α : Fin 2 → Type u) : (∀ i, α i) ≃ α 0 × α 1 where
toFun f := (f 0, f 1)
invFun p := Fin.cons p.1 <| Fin.cons p.2 finZeroElim
left_inv _ := funext <| Fin.forall_fin_two.2 ⟨rfl, rfl⟩ |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Sort.lean | import Mathlib.Algebra.Group.End
import Mathlib.Data.Finset.Sort
import Mathlib.Data.Fintype.Sum
import Mathlib.Data.Prod.Lex
import Mathlib.Order.Interval.Finset.Fin
/-!
# Sorting tuples by their values
Given an `n`-tuple `f : Fin n → α` where `α` is ordered,
we may want to turn it into a sorted `n`-tuple.
This file provides an API for doing so, with the sorted `n`-tuple given by
`f ∘ Tuple.sort f`.
## Main declarations
* `Tuple.sort`: given `f : Fin n → α`, produces a permutation on `Fin n`
* `Tuple.monotone_sort`: `f ∘ Tuple.sort f` is `Monotone`
-/
namespace Tuple
variable {n : ℕ}
variable {α : Type*} [LinearOrder α]
/-- `graph f` produces the finset of pairs `(f i, i)`
equipped with the lexicographic order.
-/
def graph (f : Fin n → α) : Finset (α ×ₗ Fin n) :=
Finset.univ.image fun i => (f i, i)
/-- Given `p : α ×ₗ (Fin n) := (f i, i)` with `p ∈ graph f`,
`graph.proj p` is defined to be `f i`.
-/
def graph.proj {f : Fin n → α} : graph f → α := fun p => p.1.1
@[simp]
theorem graph.card (f : Fin n → α) : (graph f).card = n := by
rw [graph, Finset.card_image_of_injective]
· exact Finset.card_fin _
· intro _ _
-- Porting note: proof was `simp`
rw [Prod.ext_iff]
simp
/-- `graphEquiv₁ f` is the natural equivalence between `Fin n` and `graph f`,
mapping `i` to `(f i, i)`. -/
def graphEquiv₁ (f : Fin n → α) : Fin n ≃ graph f where
toFun i := ⟨(f i, i), by simp [graph]⟩
invFun p := p.1.2
left_inv i := by simp
right_inv := fun ⟨⟨x, i⟩, h⟩ => by
-- Porting note: was `simpa [graph] using h`
simp only [graph, Finset.mem_image, Finset.mem_univ, true_and] at h
obtain ⟨i', hi'⟩ := h
obtain ⟨-, rfl⟩ := Prod.mk_inj.mp hi'
simpa
@[simp]
theorem proj_equiv₁' (f : Fin n → α) : graph.proj ∘ graphEquiv₁ f = f :=
rfl
/-- `graphEquiv₂ f` is an equivalence between `Fin n` and `graph f` that respects the order.
-/
def graphEquiv₂ (f : Fin n → α) : Fin n ≃o graph f :=
Finset.orderIsoOfFin _ (by simp)
/-- `sort f` is the permutation that orders `Fin n` according to the order of the outputs of `f`. -/
def sort (f : Fin n → α) : Equiv.Perm (Fin n) :=
(graphEquiv₂ f).toEquiv.trans (graphEquiv₁ f).symm
theorem graphEquiv₂_apply (f : Fin n → α) (i : Fin n) :
graphEquiv₂ f i = graphEquiv₁ f (sort f i) :=
((graphEquiv₁ f).apply_symm_apply _).symm
theorem self_comp_sort (f : Fin n → α) : f ∘ sort f = graph.proj ∘ graphEquiv₂ f :=
show graph.proj ∘ (graphEquiv₁ f ∘ (graphEquiv₁ f).symm) ∘ (graphEquiv₂ f).toEquiv = _ by simp
theorem monotone_proj (f : Fin n → α) : Monotone (graph.proj : graph f → α) := by
rintro ⟨⟨x, i⟩, hx⟩ ⟨⟨y, j⟩, hy⟩ (_ | h)
· exact le_of_lt ‹_›
· simp [graph.proj]
theorem monotone_sort (f : Fin n → α) : Monotone (f ∘ sort f) := by
rw [self_comp_sort]
exact (monotone_proj f).comp (graphEquiv₂ f).monotone
end Tuple
namespace Tuple
open List
variable {n : ℕ} {α : Type*}
/-- If `f₀ ≤ f₁ ≤ f₂ ≤ ⋯` is a sorted `m`-tuple of elements of `α`, then for any `j : Fin m` and
`a : α` we have `j < #{i | fᵢ ≤ a}` iff `fⱼ ≤ a`. -/
theorem lt_card_le_iff_apply_le_of_monotone [Preorder α] [DecidableLE α]
{m : ℕ} (f : Fin m → α) (a : α) (h_sorted : Monotone f) (j : Fin m) :
j < Fintype.card {i // f i ≤ a} ↔ f j ≤ a := by
suffices h1 : ∀ k : Fin m, (k < Fintype.card {i // f i ≤ a}) → f k ≤ a by
refine ⟨h1 j, fun h ↦ ?_⟩
by_contra! hc
let p : Fin m → Prop := fun x ↦ f x ≤ a
let q : Fin m → Prop := fun x ↦ x < Fintype.card {i // f i ≤ a}
let q' : {i // f i ≤ a} → Prop := fun x ↦ q x
have hw : 0 < Fintype.card {j : {x : Fin m // f x ≤ a} // ¬ q' j} :=
Fintype.card_pos_iff.2 ⟨⟨⟨j, h⟩, not_lt.2 hc⟩⟩
apply hw.ne'
have he := Fintype.card_congr <| Equiv.sumCompl <| q'
have h4 := (Fintype.card_congr (@Equiv.subtypeSubtypeEquivSubtype _ p q (h1 _)))
have h_le : Fintype.card { i // f i ≤ a } ≤ m := by omega
rwa [Fintype.card_sum, h4, Fintype.card_fin_lt_of_le h_le, add_eq_left] at he
intro _ h
contrapose! h
rw [← Fin.card_Iio, Fintype.card_subtype]
refine Finset.card_mono (fun i => Function.mtr ?_)
rw [Finset.mem_filter_univ, Finset.mem_Iio]
exact fun hij hia ↦ h ((h_sorted (le_of_not_gt hij)).trans hia)
theorem lt_card_ge_iff_apply_ge_of_antitone [Preorder α] [DecidableLE α]
{m : ℕ} (f : Fin m → α) (a : α) (h_sorted : Antitone f) (j : Fin m) :
j < Fintype.card {i // a ≤ f i} ↔ a ≤ f j :=
lt_card_le_iff_apply_le_of_monotone _ (OrderDual.toDual a) h_sorted.dual_right j
/-- If two permutations of a tuple `f` are both monotone, then they are equal. -/
theorem unique_monotone [PartialOrder α] {f : Fin n → α} {σ τ : Equiv.Perm (Fin n)}
(hfσ : Monotone (f ∘ σ)) (hfτ : Monotone (f ∘ τ)) : f ∘ σ = f ∘ τ :=
ofFn_injective <|
eq_of_perm_of_sorted ((σ.ofFn_comp_perm f).trans (τ.ofFn_comp_perm f).symm)
hfσ.ofFn_sorted hfτ.ofFn_sorted
/-- If two permutations of a tuple `f` are both antitone, then they are equal. -/
theorem unique_antitone [PartialOrder α] {f : Fin n → α} {σ τ : Equiv.Perm (Fin n)}
(hfσ : Antitone (f ∘ σ)) (hfτ : Antitone (f ∘ τ)) : f ∘ σ = f ∘ τ :=
ofFn_injective <|
eq_of_perm_of_sorted ((σ.ofFn_comp_perm f).trans (τ.ofFn_comp_perm f).symm)
hfσ.ofFn_sorted hfτ.ofFn_sorted
variable [LinearOrder α] {f : Fin n → α} {σ : Equiv.Perm (Fin n)}
/-- A permutation `σ` equals `sort f` if and only if the map `i ↦ (f (σ i), σ i)` is
strictly monotone (w.r.t. the lexicographic ordering on the target). -/
theorem eq_sort_iff' : σ = sort f ↔ StrictMono (σ.trans <| graphEquiv₁ f) := by
constructor <;> intro h
· rw [h, sort, Equiv.trans_assoc, Equiv.symm_trans_self]
exact (graphEquiv₂ f).strictMono
· have := Subsingleton.elim (graphEquiv₂ f) (h.orderIsoOfSurjective _ <| Equiv.surjective _)
ext1 x
exact (graphEquiv₁ f).apply_eq_iff_eq_symm_apply.1 (DFunLike.congr_fun this x).symm
/-- A permutation `σ` equals `sort f` if and only if `f ∘ σ` is monotone and whenever `i < j`
and `f (σ i) = f (σ j)`, then `σ i < σ j`. This means that `sort f` is the lexicographically
smallest permutation `σ` such that `f ∘ σ` is monotone. -/
theorem eq_sort_iff :
σ = sort f ↔ Monotone (f ∘ σ) ∧ ∀ i j, i < j → f (σ i) = f (σ j) → σ i < σ j := by
rw [eq_sort_iff']
refine ⟨fun h => ⟨(monotone_proj f).comp h.monotone, fun i j hij hfij => ?_⟩, fun h i j hij => ?_⟩
· exact ((Prod.Lex.toLex_lt_toLex.1 <| h hij).resolve_left hfij.not_lt).2
· obtain he | hl := (h.1 hij.le).eq_or_lt <;> apply Prod.Lex.toLex_lt_toLex.2
exacts [Or.inr ⟨he, h.2 i j hij he⟩, Or.inl hl]
/-- The permutation that sorts `f` is the identity if and only if `f` is monotone. -/
theorem sort_eq_refl_iff_monotone : sort f = Equiv.refl _ ↔ Monotone f := by
rw [eq_comm, eq_sort_iff, Equiv.coe_refl, Function.comp_id]
simp only [id, and_iff_left_iff_imp]
exact fun _ _ _ hij _ => hij
/-- A permutation of a tuple `f` is `f` sorted if and only if it is monotone. -/
theorem comp_sort_eq_comp_iff_monotone : f ∘ σ = f ∘ sort f ↔ Monotone (f ∘ σ) :=
⟨fun h => h.symm ▸ monotone_sort f, fun h => unique_monotone h (monotone_sort f)⟩
/-- The sorted versions of a tuple `f` and of any permutation of `f` agree. -/
theorem comp_perm_comp_sort_eq_comp_sort : (f ∘ σ) ∘ sort (f ∘ σ) = f ∘ sort f := by
rw [Function.comp_assoc, ← Equiv.Perm.coe_mul]
exact unique_monotone (monotone_sort (f ∘ σ)) (monotone_sort f)
/-- If a permutation `f ∘ σ` of the tuple `f` is not the same as `f ∘ sort f`, then `f ∘ σ`
has a pair of strictly decreasing entries. -/
theorem antitone_pair_of_not_sorted' (h : f ∘ σ ≠ f ∘ sort f) :
∃ i j, i < j ∧ (f ∘ σ) j < (f ∘ σ) i := by
contrapose! h
exact comp_sort_eq_comp_iff_monotone.mpr (monotone_iff_forall_lt.mpr h)
/-- If the tuple `f` is not the same as `f ∘ sort f`, then `f` has a pair of strictly decreasing
entries. -/
theorem antitone_pair_of_not_sorted (h : f ≠ f ∘ sort f) : ∃ i j, i < j ∧ f j < f i :=
antitone_pair_of_not_sorted' (id h : f ∘ Equiv.refl _ ≠ _)
end Tuple |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/Embedding.lean | import Mathlib.Data.Fin.Tuple.Basic
import Mathlib.Order.Fin.Basic
/-! # Constructions of embeddings of `Fin n` into a type
* `Fin.Embedding.cons` : from an embedding `x : Fin n ↪ α` and `a : α` such that
`a ∉ x.range`, construct an embedding `Fin (n + 1) ↪ α` by putting `a` at `0`
* `Fin.Embedding.tail`: the tail of an embedding `x : Fin (n + 1) ↪ α`
* `Fin.Embedding.snoc` : from an embedding `x : Fin n ↪ α` and `a : α`
such that `a ∉ x.range`, construct an embedding `Fin (n + 1) ↪ α`
by putting `a` at the end.
* `Fin.Embedding.init`: the init of an embedding `x : Fin (n + 1) ↪ α`
* `Fin.Embedding.append` : merges two embeddings `Fin m ↪ α` and `Fin n ↪ α`
into an embedding `Fin (m + n) ↪ α` if they have disjoint ranges
-/
open Function.Embedding Fin Set Nat
namespace Fin.Embedding
variable {α : Type*}
/-- Remove the first element from an injective (n + 1)-tuple. -/
def tail {n : ℕ} (x : Fin (n + 1) ↪ α) : Fin n ↪ α :=
⟨Fin.tail x, x.injective.comp <| Fin.succ_injective _⟩
@[simp, norm_cast]
theorem coe_tail {n : ℕ} (x : Fin (n + 1) ↪ α) : ↑(tail x) = Fin.tail x := rfl
/-- Adding a new element at the beginning of an injective n-tuple, to get an injective n+1-tuple. -/
def cons {n : ℕ} (x : Fin n ↪ α) {a : α} (ha : a ∉ range x) : Fin (n + 1) ↪ α :=
⟨Fin.cons a x, cons_injective_iff.mpr ⟨ha, x.inj'⟩⟩
@[simp, norm_cast]
theorem coe_cons {n : ℕ} (x : Fin n ↪ α) {a : α} (ha : a ∉ range x) :
↑(cons x ha) = Fin.cons a x := rfl
theorem tail_cons {n : ℕ} (x : Fin n ↪ α) {a : α} (ha : a ∉ range x) :
tail (cons x ha) = x := rfl
/-- Remove the last element from an injective (n + 1)-tuple. -/
def init {n : ℕ} (x : Fin (n + 1) ↪ α) : Fin n ↪ α :=
⟨Fin.init x, x.injective.comp <| castSucc_injective _⟩
/-- Adding a new element at the end of an injective n-tuple, to get an injective n+1-tuple. -/
def snoc {n : ℕ} (x : Fin n ↪ α) {a : α} (ha : a ∉ range x) :
Fin (n + 1) ↪ α :=
⟨Fin.snoc x a, snoc_injective_iff.mpr ⟨x.inj', ha⟩⟩
@[simp, norm_cast]
theorem coe_snoc {n : ℕ} (x : Fin n ↪ α) {a : α} (ha : a ∉ range x) :
↑(snoc x ha) = Fin.snoc x a := rfl
theorem init_snoc {n : ℕ} (x : Fin n ↪ α) {a : α} (ha : a ∉ range x) :
init (snoc x ha) = x := by
simp [snoc, init]
theorem snoc_castSucc {n : ℕ} {x : Fin n ↪ α} {a : α} {ha : a ∉ range x} {i : Fin n} :
snoc x ha i.castSucc = x i := by
rw [coe_snoc, Fin.snoc_castSucc]
theorem snoc_last {n : ℕ} {x : Fin n ↪ α} {a : α} {ha : a ∉ range x} :
snoc x ha (last n) = a := by
rw [coe_snoc, Fin.snoc_last]
/-- Append a `Fin n ↪ α` at the end of a `Fin m ↪ α` if their ranges are disjoint. -/
def append {m n : ℕ} {x : Fin m ↪ α} {y : Fin n ↪ α} (h : Disjoint (range x) (range y)) :
Fin (m + n) ↪ α :=
⟨Fin.append x y,
Fin.append_injective_iff.mpr ⟨x.inj', y.inj', disjoint_range_iff.mp h⟩⟩
@[simp, norm_cast]
theorem coe_append {m n : ℕ} {x : Fin m ↪ α} {y : Fin n ↪ α} (h : Disjoint (range x) (range y)) :
append h = Fin.append x y := rfl
end Fin.Embedding
namespace Function.Embedding
variable {α : Type*}
/-- The natural equivalence of `Fin 2 ↪ α` with pairs `(a, b)` of distinct elements of `α`. -/
def twoEmbeddingEquiv : (Fin 2 ↪ α) ≃ { (a, b) : α × α | a ≠ b } where
toFun e := ⟨(e 0, e 1), by
simp only [ne_eq, Fin.isValue, mem_setOf_eq, EmbeddingLike.apply_eq_iff_eq, zero_eq_one_iff,
succ_ne_self, not_false_eq_true]⟩
invFun := fun ⟨⟨a, b⟩, h⟩ ↦ {
toFun i := if i = 0 then a else b
inj' i j hij := by
by_cases hi : i = 0
· by_cases hj : j = 0
· simp [hi, hj]
· simp only [if_pos hi, eq_one_of_ne_zero j hj,
if_neg (Ne.symm Fin.zero_ne_one)] at hij
apply (h hij).elim
· rw [eq_one_of_ne_zero i hi] at hij ⊢
by_cases hj : j = 0
· simp [hj] at hij; exact False.elim (h hij.symm)
· rw [eq_one_of_ne_zero j hj] }
left_inv e := by
ext i
by_cases hi : i = 0
· simp [hi]
· simp [Fin.eq_one_of_ne_zero i hi]
/-- Two distinct elements of `α` give an embedding `Fin 2 ↪ α`. -/
def embFinTwo {a b : α} (h : a ≠ b) : Fin 2 ↪ α :=
twoEmbeddingEquiv.invFun ⟨(a, b), h⟩
theorem embFinTwo_apply_zero {a b : α} (h : a ≠ b) :
embFinTwo h 0 = a := rfl
theorem embFinTwo_apply_one {a b : α} (h : a ≠ b) :
embFinTwo h 1 = b := rfl
end Function.Embedding |
.lake/packages/mathlib/Mathlib/Data/Fin/Tuple/NatAntidiagonal.lean | import Mathlib.Algebra.BigOperators.Fin
import Mathlib.Algebra.Group.Fin.Tuple
import Mathlib.Data.Finset.NatAntidiagonal
import Mathlib.Order.Fin.Tuple
/-!
# Collections of tuples of naturals with the same sum
This file generalizes `List.Nat.Antidiagonal n`, `Multiset.Nat.Antidiagonal n`, and
`Finset.Nat.Antidiagonal n` from the pair of elements `x : ℕ × ℕ` such that `n = x.1 + x.2`, to
the sequence of elements `x : Fin k → ℕ` such that `n = ∑ i, x i`.
## Main definitions
* `List.Nat.antidiagonalTuple`
* `Multiset.Nat.antidiagonalTuple`
* `Finset.Nat.antidiagonalTuple`
## Main results
* `antidiagonalTuple 2 n` is analogous to `antidiagonal n`:
* `List.Nat.antidiagonalTuple_two`
* `Multiset.Nat.antidiagonalTuple_two`
* `Finset.Nat.antidiagonalTuple_two`
## Implementation notes
While we could implement this by filtering `(Fintype.PiFinset fun _ ↦ range (n + 1))` or similar,
this implementation would be much slower.
In the future, we could consider generalizing `Finset.Nat.antidiagonalTuple` further to
support finitely-supported functions, as is done with `cut` in
`archive/100-theorems-list/45_partition.lean`.
-/
/-! ### Lists -/
namespace List.Nat
/-- `List.antidiagonalTuple k n` is a list of all `k`-tuples which sum to `n`.
This list contains no duplicates (`List.Nat.nodup_antidiagonalTuple`), and is sorted
lexicographically (`List.Nat.antidiagonalTuple_pairwise_pi_lex`), starting with `![0, ..., n]`
and ending with `![n, ..., 0]`.
```
#eval antidiagonalTuple 3 2
-- [![0, 0, 2], ![0, 1, 1], ![0, 2, 0], ![1, 0, 1], ![1, 1, 0], ![2, 0, 0]]
```
-/
def antidiagonalTuple : ∀ k, ℕ → List (Fin k → ℕ)
| 0, 0 => [![]]
| 0, _ + 1 => []
| k + 1, n =>
(List.Nat.antidiagonal n).flatMap fun ni =>
(antidiagonalTuple k ni.2).map fun x => Fin.cons ni.1 x
@[simp]
theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = [![]] :=
rfl
@[simp]
theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 (n + 1) = [] :=
rfl
theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} :
x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n := by
induction x using Fin.consInduction generalizing n with
| elim0 =>
cases n
· decide
· simp
| cons x₀ x ih =>
simp_rw [Fin.sum_cons, antidiagonalTuple, List.mem_flatMap, List.mem_map,
List.Nat.mem_antidiagonal, Fin.cons_inj, exists_eq_right_right, ih,
@eq_comm _ _ (Prod.snd _), and_comm (a := Prod.snd _ = _),
← Prod.mk_inj (a₁ := Prod.fst _), exists_eq_right]
/-- The antidiagonal of `n` does not contain duplicate entries. -/
theorem nodup_antidiagonalTuple (k n : ℕ) : List.Nodup (antidiagonalTuple k n) := by
induction k generalizing n with
| zero => cases n <;> simp
| succ k ih => ?_
simp_rw [antidiagonalTuple, List.nodup_flatMap]
constructor
· intro i _
exact (ih i.snd).map (Fin.cons_right_injective (α := fun _ => ℕ) i.fst)
induction n with
| zero => exact List.pairwise_singleton _ _
| succ n n_ih =>
rw [List.Nat.antidiagonal_succ]
refine List.Pairwise.cons (fun a ha x hx₁ hx₂ => ?_) (n_ih.map _ fun a b h x hx₁ hx₂ => ?_)
· rw [List.mem_map] at hx₁ hx₂ ha
obtain ⟨⟨a, -, rfl⟩, ⟨x₁, -, rfl⟩, ⟨x₂, -, h⟩⟩ := ha, hx₁, hx₂
rw [Fin.cons_inj] at h
injection h.1
· rw [List.mem_map] at hx₁ hx₂
obtain ⟨⟨x₁, hx₁, rfl⟩, ⟨x₂, hx₂, h₁₂⟩⟩ := hx₁, hx₂
dsimp at h₁₂
rw [Fin.cons_inj, Nat.succ_inj] at h₁₂
obtain ⟨h₁₂, rfl⟩ := h₁₂
rw [Function.onFun, h₁₂] at h
exact h (List.mem_map_of_mem hx₁) (List.mem_map_of_mem hx₂)
theorem antidiagonalTuple_zero_right : ∀ k, antidiagonalTuple k 0 = [0]
| 0 => (congr_arg fun x => [x]) <| Subsingleton.elim _ _
| k + 1 => by
rw [antidiagonalTuple, antidiagonal_zero, List.flatMap_singleton,
antidiagonalTuple_zero_right k, List.map_singleton]
exact congr_arg (fun x => [x]) Matrix.cons_zero_zero
@[simp]
theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = [![n]] := by
simp_rw [antidiagonalTuple, antidiagonal, List.range_succ, List.map_append, List.map_singleton,
Nat.sub_self, List.flatMap_append, List.flatMap_singleton, List.flatMap_map]
conv_rhs => rw [← List.nil_append [![n]]]
congr 1
simp_rw [List.flatMap_eq_nil_iff, List.mem_range, List.map_eq_nil_iff]
intro x hx
obtain ⟨m, rfl⟩ := Nat.exists_eq_add_of_lt hx
rw [add_assoc, add_tsub_cancel_left, antidiagonalTuple_zero_succ]
theorem antidiagonalTuple_two (n : ℕ) :
antidiagonalTuple 2 n = (antidiagonal n).map fun i => ![i.1, i.2] := by
rw [antidiagonalTuple]
simp_rw [antidiagonalTuple_one, List.map_singleton]
rw [List.map_eq_flatMap]
rfl
theorem antidiagonalTuple_pairwise_pi_lex :
∀ k n, (antidiagonalTuple k n).Pairwise (Pi.Lex (· < ·) @fun _ => (· < ·))
| 0, 0 => List.pairwise_singleton _ _
| 0, _ + 1 => List.Pairwise.nil
| k + 1, n => by
simp_rw [antidiagonalTuple, List.pairwise_flatMap, List.pairwise_map, List.mem_map,
forall_exists_index, and_imp, forall_apply_eq_imp_iff₂]
simp only [mem_antidiagonal, Prod.forall]
simp only [Fin.pi_lex_lt_cons_cons, true_and, lt_self_iff_false,
false_or]
refine ⟨fun _ _ _ => antidiagonalTuple_pairwise_pi_lex k _, ?_⟩
induction n with
| zero =>
rw [antidiagonal_zero]
exact List.pairwise_singleton _ _
| succ n n_ih =>
rw [antidiagonal_succ, List.pairwise_cons, List.pairwise_map]
refine ⟨fun p hp x hx y hy => ?_, ?_⟩
· rw [List.mem_map, Prod.exists] at hp
obtain ⟨a, b, _, rfl : (Nat.succ a, b) = p⟩ := hp
exact Or.inl (Nat.zero_lt_succ _)
dsimp
simp_rw [Nat.succ_inj, Nat.succ_lt_succ_iff]
exact n_ih
end List.Nat
/-! ### Multisets -/
namespace Multiset.Nat
/-- `Multiset.Nat.antidiagonalTuple k n` is a multiset of `k`-tuples summing to `n` -/
def antidiagonalTuple (k n : ℕ) : Multiset (Fin k → ℕ) :=
List.Nat.antidiagonalTuple k n
@[simp]
theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = {![]} :=
rfl
@[simp]
theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 n.succ = 0 :=
rfl
theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} :
x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n :=
List.Nat.mem_antidiagonalTuple
theorem nodup_antidiagonalTuple (k n : ℕ) : (antidiagonalTuple k n).Nodup :=
List.Nat.nodup_antidiagonalTuple _ _
theorem antidiagonalTuple_zero_right (k : ℕ) : antidiagonalTuple k 0 = {0} :=
congr_arg _ (List.Nat.antidiagonalTuple_zero_right k)
@[simp]
theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = {![n]} :=
congr_arg _ (List.Nat.antidiagonalTuple_one n)
theorem antidiagonalTuple_two (n : ℕ) :
antidiagonalTuple 2 n = (antidiagonal n).map fun i => ![i.1, i.2] :=
congr_arg _ (List.Nat.antidiagonalTuple_two n)
end Multiset.Nat
/-! ### Finsets -/
namespace Finset.Nat
/-- `Finset.Nat.antidiagonalTuple k n` is a finset of `k`-tuples summing to `n` -/
def antidiagonalTuple (k n : ℕ) : Finset (Fin k → ℕ) :=
⟨Multiset.Nat.antidiagonalTuple k n, Multiset.Nat.nodup_antidiagonalTuple k n⟩
@[simp]
theorem antidiagonalTuple_zero_zero : antidiagonalTuple 0 0 = {![]} :=
rfl
@[simp]
theorem antidiagonalTuple_zero_succ (n : ℕ) : antidiagonalTuple 0 n.succ = ∅ :=
rfl
theorem mem_antidiagonalTuple {n : ℕ} {k : ℕ} {x : Fin k → ℕ} :
x ∈ antidiagonalTuple k n ↔ ∑ i, x i = n :=
List.Nat.mem_antidiagonalTuple
theorem antidiagonalTuple_zero_right (k : ℕ) : antidiagonalTuple k 0 = {0} :=
Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_zero_right k)
@[simp]
theorem antidiagonalTuple_one (n : ℕ) : antidiagonalTuple 1 n = {![n]} :=
Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_one n)
theorem antidiagonalTuple_two (n : ℕ) :
antidiagonalTuple 2 n = (antidiagonal n).map (piFinTwoEquiv fun _ => ℕ).symm.toEmbedding :=
Finset.eq_of_veq (Multiset.Nat.antidiagonalTuple_two n)
section EquivProd
/-- The disjoint union of antidiagonal tuples `Σ n, antidiagonalTuple k n` is equivalent to the
`k`-tuple `Fin k → ℕ`. This is such an equivalence, obtained by mapping `(n, x)` to `x`.
This is the tuple version of `Finset.sigmaAntidiagonalEquivProd`. -/
@[simps]
def sigmaAntidiagonalTupleEquivTuple (k : ℕ) : (Σ n, antidiagonalTuple k n) ≃ (Fin k → ℕ) where
toFun x := x.2
invFun x := ⟨∑ i, x i, x, mem_antidiagonalTuple.mpr rfl⟩
left_inv := fun ⟨_, _, h⟩ => Sigma.subtype_ext (mem_antidiagonalTuple.mp h) rfl
end EquivProd
end Finset.Nat |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Fintype.lean | import Mathlib.Data.Finsupp.Single
import Mathlib.Data.Fintype.BigOperators
/-!
# Finiteness and infiniteness of `Finsupp`
Some lemmas on the combination of `Finsupp`, `Fintype` and `Infinite`.
-/
variable {ι α : Type*} [DecidableEq ι] [Fintype ι] [Zero α] [Fintype α]
noncomputable instance Finsupp.fintype : Fintype (ι →₀ α) :=
Fintype.ofEquiv _ Finsupp.equivFunOnFinite.symm
instance Finsupp.infinite_of_left [Nontrivial α] [Infinite ι] : Infinite (ι →₀ α) :=
let ⟨_, hm⟩ := exists_ne (0 : α)
Infinite.of_injective _ <| Finsupp.single_left_injective hm
instance Finsupp.infinite_of_right [Infinite α] [Nonempty ι] : Infinite (ι →₀ α) :=
Infinite.of_injective (fun i => Finsupp.single (Classical.arbitrary ι) i)
(Finsupp.single_injective (Classical.arbitrary ι))
variable (ι α) in
@[simp] lemma Fintype.card_finsupp : card (ι →₀ α) = card α ^ card ι := by
simp [card_congr Finsupp.equivFunOnFinite] |
.lake/packages/mathlib/Mathlib/Data/Finsupp/SMul.lean | import Mathlib.Algebra.Group.Action.Basic
import Mathlib.Algebra.Module.Basic
import Mathlib.Algebra.Regular.SMul
import Mathlib.Data.Finsupp.Basic
import Mathlib.Data.Finsupp.SMulWithZero
import Mathlib.GroupTheory.GroupAction.Hom
/-!
# Declarations about scalar multiplication on `Finsupp`
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
-/
noncomputable section
open Finset Function
variable {α β M N G R : Type*}
namespace Finsupp
section
variable [Zero M] [MonoidWithZero R] [MulActionWithZero R M]
@[simp]
theorem single_smul (a b : α) (f : α → M) (r : R) : single a r b • f a = single a (r • f b) b := by
by_cases h : a = b <;> simp [h]
end
section
variable [Monoid G] [MulAction G α] [AddCommMonoid M]
/-- Scalar multiplication acting on the domain.
This is not an instance as it would conflict with the action on the range.
See the `instance_diamonds` test for examples of such conflicts. -/
def comapSMul : SMul G (α →₀ M) where smul g := mapDomain (g • ·)
attribute [local instance] comapSMul
theorem comapSMul_def (g : G) (f : α →₀ M) : g • f = mapDomain (g • ·) f :=
rfl
@[simp]
theorem comapSMul_single (g : G) (a : α) (b : M) : g • single a b = single (g • a) b :=
mapDomain_single
/-- `Finsupp.comapSMul` is multiplicative -/
def comapMulAction : MulAction G (α →₀ M) where
one_smul f := by rw [comapSMul_def, one_smul_eq_id, mapDomain_id]
mul_smul g g' f := by
rw [comapSMul_def, comapSMul_def, comapSMul_def, ← comp_smul_left, mapDomain_comp]
attribute [local instance] comapMulAction
/-- `Finsupp.comapSMul` is distributive -/
def comapDistribMulAction : DistribMulAction G (α →₀ M) where
smul_zero g := by
ext a
simp only [comapSMul_def]
simp
smul_add g f f' := by
ext
simp only [comapSMul_def]
simp [mapDomain_add]
end
section
variable [Group G] [MulAction G α] [AddCommMonoid M]
attribute [local instance] comapSMul comapMulAction comapDistribMulAction
/-- When `G` is a group, `Finsupp.comapSMul` acts by precomposition with the action of `g⁻¹`.
-/
@[simp]
theorem comapSMul_apply (g : G) (f : α →₀ M) (a : α) : (g • f) a = f (g⁻¹ • a) := by
conv_lhs => rw [← smul_inv_smul g a]
exact mapDomain_apply (MulAction.injective g) _ (g⁻¹ • a)
end
section
/-!
Throughout this section, some `Monoid` and `Semiring` arguments are specified with `{}` instead of
`[]`. See note [implicit instance arguments].
-/
theorem _root_.IsSMulRegular.finsupp [Zero M] [SMulZeroClass R M] {k : R}
(hk : IsSMulRegular M k) : IsSMulRegular (α →₀ M) k :=
fun _ _ h => ext fun i => hk (DFunLike.congr_fun h i)
instance faithfulSMul [Nonempty α] [Zero M] [SMulZeroClass R M] [FaithfulSMul R M] :
FaithfulSMul R (α →₀ M) where
eq_of_smul_eq_smul h :=
let ⟨a⟩ := ‹Nonempty α›
eq_of_smul_eq_smul fun m : M => by simpa using DFunLike.congr_fun (h (single a m)) a
variable (α M)
instance distribMulAction [Monoid R] [AddMonoid M] [DistribMulAction R M] :
DistribMulAction R (α →₀ M) :=
{ Finsupp.distribSMul _ _ with
one_smul := fun x => ext fun y => one_smul R (x y)
mul_smul := fun r s x => ext fun y => mul_smul r s (x y) }
instance module [Semiring R] [AddCommMonoid M] [Module R M] : Module R (α →₀ M) :=
{ toDistribMulAction := Finsupp.distribMulAction α M
zero_smul := fun _ => ext fun _ => zero_smul _ _
add_smul := fun _ _ _ => ext fun _ => add_smul _ _ _ }
variable {α M}
@[simp]
theorem support_smul_eq [Zero R] [Zero M] [SMulWithZero R M] [NoZeroSMulDivisors R M] {b : R}
(hb : b ≠ 0) {g : α →₀ M} : (b • g).support = g.support :=
Finset.ext fun a => by simp [Finsupp.smul_apply, hb]
section
variable {p : α → Prop} [DecidablePred p]
@[simp]
theorem filter_smul [Zero M] [SMulZeroClass R M] {b : R} {v : α →₀ M} :
(b • v).filter p = b • v.filter p :=
DFunLike.coe_injective <| by
simp only [filter_eq_indicator, coe_smul]
exact Set.indicator_const_smul { x | p x } b v
end
theorem mapDomain_smul [AddCommMonoid M] [DistribSMul R M] {f : α → β} (b : R)
(v : α →₀ M) : mapDomain f (b • v) = b • mapDomain f v :=
mapDomain_mapRange _ _ _ _ (smul_add b)
theorem smul_single' {_ : Semiring R} (c : R) (a : α) (b : R) :
c • Finsupp.single a b = Finsupp.single a (c * b) := by simp
theorem smul_single_one [MulZeroOneClass R] (a : α) (b : R) :
b • single a (1 : R) = single a b := by
rw [smul_single, smul_eq_mul, mul_one]
theorem comapDomain_smul [Zero M] [SMulZeroClass R M] {f : α → β} (r : R)
(v : β →₀ M) (hfv : Set.InjOn f (f ⁻¹' ↑v.support))
(hfrv : Set.InjOn f (f ⁻¹' ↑(r • v).support) :=
hfv.mono <| Set.preimage_mono <| Finset.coe_subset.mpr support_smul) :
comapDomain f (r • v) hfrv = r • comapDomain f v hfv := by
ext
rfl
/-- A version of `Finsupp.comapDomain_smul` that's easier to use. -/
theorem comapDomain_smul_of_injective [Zero M] [SMulZeroClass R M] {f : α → β}
(hf : Function.Injective f) (r : R) (v : β →₀ M) :
comapDomain f (r • v) hf.injOn = r • comapDomain f v hf.injOn :=
comapDomain_smul _ _ _ _
end
theorem sum_smul_index [MulZeroClass R] [AddCommMonoid M] {g : α →₀ R} {b : R} {h : α → R → M}
(h0 : ∀ i, h i 0 = 0) : (b • g).sum h = g.sum fun i a => h i (b * a) :=
Finsupp.sum_mapRange_index h0
theorem sum_smul_index' [Zero M] [SMulZeroClass R M] [AddCommMonoid N] {g : α →₀ M} {b : R}
{h : α → M → N} (h0 : ∀ i, h i 0 = 0) : (b • g).sum h = g.sum fun i c => h i (b • c) :=
Finsupp.sum_mapRange_index h0
/-- A version of `Finsupp.sum_smul_index'` for bundled additive maps. -/
theorem sum_smul_index_addMonoidHom [AddZeroClass M] [AddCommMonoid N] [SMulZeroClass R M]
{g : α →₀ M} {b : R} {h : α → M →+ N} :
((b • g).sum fun a => h a) = g.sum fun i c => h i (b • c) :=
sum_mapRange_index fun i => (h i).map_zero
instance noZeroSMulDivisors [Zero R] [Zero M] [SMulZeroClass R M] {ι : Type*}
[NoZeroSMulDivisors R M] : NoZeroSMulDivisors R (ι →₀ M) :=
⟨fun h => or_iff_not_imp_left.mpr fun hc => Finsupp.ext fun i =>
(eq_zero_or_eq_zero_of_smul_eq_zero (DFunLike.ext_iff.mp h i)).resolve_left hc⟩
section DistribMulActionSemiHom
variable [Monoid R] [AddMonoid M] [AddMonoid N] [DistribMulAction R M] [DistribMulAction R N]
/-- `Finsupp.single` as a `DistribMulActionSemiHom`.
See also `Finsupp.lsingle` for the version as a linear map. -/
def DistribMulActionHom.single (a : α) : M →+[R] α →₀ M :=
{ singleAddHom a with
map_smul' := fun k m => by simp }
theorem distribMulActionHom_ext {f g : (α →₀ M) →+[R] N}
(h : ∀ (a : α) (m : M), f (single a m) = g (single a m)) : f = g :=
DistribMulActionHom.toAddMonoidHom_injective <| addHom_ext h
/-- See note [partially-applied ext lemmas]. -/
@[ext]
theorem distribMulActionHom_ext' {f g : (α →₀ M) →+[R] N}
(h : ∀ a : α, f.comp (DistribMulActionHom.single a) = g.comp (DistribMulActionHom.single a)) :
f = g :=
distribMulActionHom_ext fun a => DistribMulActionHom.congr_fun (h a)
end DistribMulActionSemiHom
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Fin.lean | import Mathlib.Data.Finsupp.Single
/-!
# `cons` and `tail` for maps `Fin n →₀ M`
We interpret maps `Fin n →₀ M` as `n`-tuples of elements of `M`,
We define the following operations:
* `Finsupp.tail` : the tail of a map `Fin (n + 1) →₀ M`, i.e., its last `n` entries;
* `Finsupp.cons` : adding an element at the beginning of an `n`-tuple, to get an `n + 1`-tuple;
In this context, we prove some usual properties of `tail` and `cons`, analogous to those of
`Data.Fin.Tuple.Basic`.
-/
open Function
noncomputable section
namespace Finsupp
variable {n : ℕ} (i : Fin n) {M : Type*} [Zero M] (y : M) (t : Fin (n + 1) →₀ M) (s : Fin n →₀ M)
/-- `tail` for maps `Fin (n + 1) →₀ M`. See `Fin.tail` for more details. -/
def tail (s : Fin (n + 1) →₀ M) : Fin n →₀ M :=
Finsupp.equivFunOnFinite.symm (Fin.tail s)
/-- `cons` for maps `Fin n →₀ M`. See `Fin.cons` for more details. -/
def cons (y : M) (s : Fin n →₀ M) : Fin (n + 1) →₀ M :=
Finsupp.equivFunOnFinite.symm (Fin.cons y s : Fin (n + 1) → M)
theorem tail_apply : tail t i = t i.succ :=
rfl
@[simp]
theorem cons_zero : cons y s 0 = y :=
rfl
@[simp]
theorem cons_succ : cons y s i.succ = s i :=
rfl
@[simp]
theorem tail_cons : tail (cons y s) = s :=
ext fun k => by simp only [tail_apply, cons_succ]
@[simp]
theorem tail_update_zero : tail (update t 0 y) = tail t := by simp [tail]
@[simp]
theorem tail_update_succ : tail (update t i.succ y) = update (tail t) i y := by ext; simp [tail]
@[simp]
theorem cons_tail : cons (t 0) (tail t) = t := by
ext a
by_cases c_a : a = 0
· rw [c_a, cons_zero]
· rw [← Fin.succ_pred a c_a, cons_succ, ← tail_apply]
@[simp]
theorem cons_zero_zero : cons 0 (0 : Fin n →₀ M) = 0 := by
ext a
by_cases c : a = 0
· simp [c]
· rw [← Fin.succ_pred a c, cons_succ]
simp
variable {s} {y}
theorem cons_ne_zero_of_left (h : y ≠ 0) : cons y s ≠ 0 := by
contrapose! h with c
rw [← cons_zero y s, c, Finsupp.coe_zero, Pi.zero_apply]
theorem cons_ne_zero_of_right (h : s ≠ 0) : cons y s ≠ 0 := by
contrapose! h with c
ext a
simp [← cons_succ a y s, c]
theorem cons_ne_zero_iff : cons y s ≠ 0 ↔ y ≠ 0 ∨ s ≠ 0 := by
refine ⟨fun h => ?_, fun h => h.casesOn cons_ne_zero_of_left cons_ne_zero_of_right⟩
refine imp_iff_not_or.1 fun h' c => h ?_
rw [h', c, Finsupp.cons_zero_zero]
lemma cons_support : (s.cons y).support ⊆ insert 0 (s.support.map (Fin.succEmb n)) := by
intro i hi
suffices i = 0 ∨ ∃ a, ¬s a = 0 ∧ a.succ = i by simpa
apply (Fin.eq_zero_or_eq_succ i).imp id (Exists.imp _)
rintro i rfl
simpa [Finsupp.mem_support_iff] using hi
lemma cons_right_injective {n : ℕ} {M : Type*} [Zero M] (y : M) :
Injective (Finsupp.cons y : (Fin n →₀ M) → Fin (n + 1) →₀ M) :=
(equivFunOnFinite.symm.injective.comp ((Fin.cons_right_injective _).comp DFunLike.coe_injective))
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Option.lean | import Mathlib.Data.Finsupp.Basic
import Mathlib.Algebra.Module.Defs
/-!
# Declarations about finitely supported functions whose support is an `Option` type p
## Main declarations
* `Finsupp.some`: restrict a finitely supported function on `Option α` to a finitely supported
function on `α`.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
-/
noncomputable section
open Finset Function
variable {α M N R : Type*}
namespace Finsupp
section Option
/-- Restrict a finitely supported function on `Option α` to a finitely supported function on `α`. -/
def some [Zero M] (f : Option α →₀ M) : α →₀ M :=
f.comapDomain Option.some fun _ => by simp
@[simp]
theorem some_apply [Zero M] (f : Option α →₀ M) (a : α) : f.some a = f (Option.some a) :=
rfl
@[simp]
theorem some_zero [Zero M] : (0 : Option α →₀ M).some = 0 := by
ext
simp
@[simp]
theorem some_add [AddZeroClass M] (f g : Option α →₀ M) : (f + g).some = f.some + g.some := by
ext
simp
@[simp]
theorem some_single_none [Zero M] (m : M) : (single none m : Option α →₀ M).some = 0 := by
ext
simp
@[simp]
theorem some_single_some [Zero M] (a : α) (m : M) :
(single (Option.some a) m : Option α →₀ M).some = single a m := by
classical
ext b
simp [single_apply]
@[simp]
theorem embDomain_some_some [Zero M] (f : α →₀ M) (x) : f.embDomain .some (.some x) = f x := by
simp [← Function.Embedding.some_apply]
@[simp]
theorem some_update_none [Zero M] (f : Option α →₀ M) (a : M) :
(f.update none a).some = f.some := by
ext
simp [Finsupp.update]
/-- `Finsupp`s from `Option` are equivalent to
pairs of an element and a `Finsupp` on the original type. -/
@[simps]
noncomputable
def optionEquiv [Zero M] : (Option α →₀ M) ≃ M × (α →₀ M) where
toFun P := (P none, P.some)
invFun P := (P.2.embDomain .some).update none P.1
left_inv P := by ext (_ | a) <;> simp [Finsupp.update]
right_inv P := by ext <;> simp [Finsupp.update]
theorem eq_option_embedding_update_none_iff [Zero M] {n : Option α →₀ M} {m : α →₀ M} {i : M} :
n = (embDomain Embedding.some m).update none i ↔ n none = i ∧ n.some = m :=
(optionEquiv.apply_eq_iff_eq_symm_apply (y := (_, _))).symm.trans Prod.ext_iff
@[to_additive]
theorem prod_option_index [AddZeroClass M] [CommMonoid N] (f : Option α →₀ M)
(b : Option α → M → N) (h_zero : ∀ o, b o 0 = 1)
(h_add : ∀ o m₁ m₂, b o (m₁ + m₂) = b o m₁ * b o m₂) :
f.prod b = b none (f none) * f.some.prod fun a => b (Option.some a) := by
classical
induction f using induction_linear with
| zero => simp [some_zero, h_zero]
| add f₁ f₂ h₁ h₂ =>
rw [Finsupp.prod_add_index, h₁, h₂, some_add, Finsupp.prod_add_index]
· simp only [h_add, Pi.add_apply, Finsupp.coe_add]
rw [mul_mul_mul_comm]
all_goals simp [h_zero, h_add]
| single a m => cases a <;> simp [h_zero]
theorem sum_option_index_smul [Semiring R] [AddCommMonoid M] [Module R M] (f : Option α →₀ R)
(b : Option α → M) :
(f.sum fun o r => r • b o) = f none • b none + f.some.sum fun a r => r • b (Option.some a) :=
f.sum_option_index _ (fun _ => zero_smul _ _) fun _ _ _ => add_smul _ _ _
@[simp] lemma some_embDomain_some [Zero M] (f : α →₀ M) : (f.embDomain .some).some = f := by
ext; rw [some_apply]; exact embDomain_apply _ _ _
@[simp] lemma embDomain_some_none [Zero M] (f : α →₀ M) : f.embDomain .some none = 0 :=
embDomain_notin_range _ _ _ (by simp)
end Option
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Indicator.lean | import Mathlib.Data.Finsupp.Single
/-!
# Building finitely supported functions off finsets
This file defines `Finsupp.indicator` to help create finsupps from finsets.
## Main declarations
* `Finsupp.indicator`: Turns a map from a `Finset` into a `Finsupp` from the entire type.
-/
noncomputable section
open Finset Function
variable {ι α : Type*}
namespace Finsupp
variable [Zero α] {s : Finset ι} (f : ∀ i ∈ s, α) {i : ι}
/-- Create an element of `ι →₀ α` from a finset `s` and a function `f` defined on this finset. -/
def indicator (s : Finset ι) (f : ∀ i ∈ s, α) : ι →₀ α where
toFun i :=
haveI := Classical.decEq ι
if H : i ∈ s then f i H else 0
support :=
haveI := Classical.decEq α
({i | f i.1 i.2 ≠ 0} : Finset s).map (Embedding.subtype _)
mem_support_toFun i := by
classical simp
theorem indicator_of_mem (hi : i ∈ s) (f : ∀ i ∈ s, α) : indicator s f i = f i hi :=
@dif_pos _ (id _) hi _ _ _
theorem indicator_of_notMem (hi : i ∉ s) (f : ∀ i ∈ s, α) : indicator s f i = 0 :=
@dif_neg _ (id _) hi _ _ _
@[deprecated (since := "2025-05-23")] alias indicator_of_not_mem := indicator_of_notMem
variable (s i)
@[simp]
theorem indicator_apply [DecidableEq ι] : indicator s f i = if hi : i ∈ s then f i hi else 0 := by
simp only [indicator, ne_eq, coe_mk]
congr
theorem indicator_injective : Injective fun f : ∀ i ∈ s, α => indicator s f := by
intro a b h
ext i hi
rw [← indicator_of_mem hi a, ← indicator_of_mem hi b]
exact DFunLike.congr_fun h i
theorem support_indicator_subset : ((indicator s f).support : Set ι) ⊆ s := by
intro i hi
rw [mem_coe, mem_support_iff] at hi
by_contra h
exact hi (indicator_of_notMem h _)
lemma single_eq_indicator (b : α) : single i b = indicator {i} (fun _ _ => b) := by
classical
ext j
simp [single_apply, indicator_apply, @eq_comm _ j]
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/SMulWithZero.lean | import Mathlib.Algebra.Group.Action.Pi
import Mathlib.Algebra.Group.Finsupp
import Mathlib.Algebra.GroupWithZero.Action.Defs
/-!
# Scalar multiplication on `Finsupp`
This file defines the pointwise scalar multiplication on `Finsupp`, assuming it preserves zero.
## Main declarations
* `Finsupp.smulZeroClass`: if the action of `R` on `M` preserves `0`, then it acts on `α →₀ M`
## Implementation notes
This file is intermediate between `Finsupp.Defs` and `Finsupp.Module` in that it covers scalar
multiplication but does not rely on the definition of `Module`. Scalar multiplication is needed to
supply the `nsmul` (and `zsmul`) fields of (semi)ring structures which are fundamental for e.g.
`Polynomial`, so we want to keep the imports required for the `Finsupp.smulZeroClass` instance
reasonably light.
This file is a `noncomputable theory` and uses classical logic throughout.
-/
assert_not_exists Module
noncomputable section
open Finset Function
variable {α β γ ι M M' N P G H R S : Type*}
namespace Finsupp
instance smulZeroClass [Zero M] [SMulZeroClass R M] : SMulZeroClass R (α →₀ M) where
smul a v := v.mapRange (a • ·) (smul_zero _)
smul_zero a := by
ext
apply smul_zero
/-!
Throughout this section, some `Monoid` and `Semiring` arguments are specified with `{}` instead of
`[]`. See note [implicit instance arguments].
-/
@[simp, norm_cast]
theorem coe_smul [Zero M] [SMulZeroClass R M] (b : R) (v : α →₀ M) : ⇑(b • v) = b • ⇑v :=
rfl
theorem smul_apply [Zero M] [SMulZeroClass R M] (b : R) (v : α →₀ M) (a : α) :
(b • v) a = b • v a :=
rfl
instance instSMulWithZero [Zero R] [Zero M] [SMulWithZero R M] : SMulWithZero R (α →₀ M) where
zero_smul f := by ext i; exact zero_smul _ _
variable (α M)
instance distribSMul [AddZeroClass M] [DistribSMul R M] : DistribSMul R (α →₀ M) where
smul_add _ _ _ := ext fun _ => smul_add _ _ _
smul_zero _ := ext fun _ => smul_zero _
instance isScalarTower [Zero M] [SMulZeroClass R M] [SMulZeroClass S M] [SMul R S]
[IsScalarTower R S M] : IsScalarTower R S (α →₀ M) where
smul_assoc _ _ _ := ext fun _ => smul_assoc _ _ _
instance smulCommClass [Zero M] [SMulZeroClass R M] [SMulZeroClass S M] [SMulCommClass R S M] :
SMulCommClass R S (α →₀ M) where
smul_comm _ _ _ := ext fun _ => smul_comm _ _ _
instance isCentralScalar [Zero M] [SMulZeroClass R M] [SMulZeroClass Rᵐᵒᵖ M] [IsCentralScalar R M] :
IsCentralScalar R (α →₀ M) where
op_smul_eq_smul _ _ := ext fun _ => op_smul_eq_smul _ _
variable {α M}
theorem support_smul [Zero M] [SMulZeroClass R M] {b : R} {g : α →₀ M} :
(b • g).support ⊆ g.support := fun a => by
simp only [smul_apply, mem_support_iff, Ne]
exact mt fun h => h.symm ▸ smul_zero _
@[simp]
theorem smul_single [Zero M] [SMulZeroClass R M] (c : R) (a : α) (b : M) :
c • Finsupp.single a b = Finsupp.single a (c • b) :=
mapRange_single
theorem mapRange_smul' [Zero M] [SMulZeroClass R M] [Zero N]
[SMulZeroClass S N] {f : M → N} {hf : f 0 = 0} (c : R) (d : S) (v : α →₀ M)
(hsmul : ∀ x, f (c • x) = d • f x) : mapRange f hf (c • v) = d • mapRange f hf v := by
ext
simp [hsmul]
theorem mapRange_smul [Zero M] [SMulZeroClass R M] [Zero N]
[SMulZeroClass R N] {f : M → N} {hf : f 0 = 0} (c : R) (v : α →₀ M)
(hsmul : ∀ x, f (c • x) = c • f x) : mapRange f hf (c • v) = c • mapRange f hf v :=
mapRange_smul' c c v hsmul
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Interval.lean | import Mathlib.Data.Finset.Finsupp
import Mathlib.Data.Finsupp.Order
import Mathlib.Order.Interval.Finset.Basic
/-!
# Finite intervals of finitely supported functions
This file provides the `LocallyFiniteOrder` instance for `ι →₀ α` when `α` itself is locally
finite and calculates the cardinality of its finite intervals.
## Main declarations
* `Finsupp.rangeSingleton`: Postcomposition with `Singleton.singleton` on `Finset` as a
`Finsupp`.
* `Finsupp.rangeIcc`: Postcomposition with `Finset.Icc` as a `Finsupp`.
Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely
supported.
-/
noncomputable section
open Finset Finsupp Function Pointwise
variable {ι α : Type*}
namespace Finsupp
section RangeSingleton
variable [Zero α] {f : ι →₀ α} {i : ι} {a : α}
/-- Pointwise `Singleton.singleton` bundled as a `Finsupp`. -/
@[simps]
def rangeSingleton (f : ι →₀ α) : ι →₀ Finset α where
toFun i := {f i}
support := f.support
mem_support_toFun i := by
rw [← not_iff_not, notMem_support_iff, not_ne_iff]
exact singleton_injective.eq_iff.symm
theorem mem_rangeSingleton_apply_iff : a ∈ f.rangeSingleton i ↔ a = f i :=
mem_singleton
end RangeSingleton
section RangeIcc
variable [Zero α] [PartialOrder α] [LocallyFiniteOrder α] [DecidableEq ι]
variable {f g : ι →₀ α} {i : ι} {a : α}
/-- Pointwise `Finset.Icc` bundled as a `Finsupp`. -/
@[simps toFun]
def rangeIcc (f g : ι →₀ α) : ι →₀ Finset α where
toFun i := Icc (f i) (g i)
support := f.support ∪ g.support
mem_support_toFun i := by
rw [mem_union, ← not_iff_not, not_or, notMem_support_iff, notMem_support_iff, not_ne_iff]
exact Icc_eq_singleton_iff.symm
lemma coe_rangeIcc (f g : ι →₀ α) : rangeIcc f g i = Icc (f i) (g i) := rfl
@[simp]
theorem rangeIcc_support (f g : ι →₀ α) :
(rangeIcc f g).support = f.support ∪ g.support := rfl
theorem mem_rangeIcc_apply_iff : a ∈ f.rangeIcc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc
end RangeIcc
section PartialOrder
variable [PartialOrder α] [Zero α] [LocallyFiniteOrder α] [DecidableEq ι] [DecidableEq α]
variable (f g : ι →₀ α)
instance instLocallyFiniteOrder : LocallyFiniteOrder (ι →₀ α) :=
LocallyFiniteOrder.ofIcc (ι →₀ α) (fun f g => (f.support ∪ g.support).finsupp <| f.rangeIcc g)
fun f g x => by
refine
(mem_finsupp_iff_of_support_subset <| Finset.subset_of_eq <| rangeIcc_support _ _).trans ?_
simp_rw [mem_rangeIcc_apply_iff]
exact forall_and
theorem Icc_eq : Icc f g = (f.support ∪ g.support).finsupp (f.rangeIcc g) := rfl
theorem card_Icc : #(Icc f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)):= by
simp_rw [Icc_eq, card_finsupp, coe_rangeIcc]
theorem card_Ico : #(Ico f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) - 1 := by
rw [card_Ico_eq_card_Icc_sub_one, card_Icc]
theorem card_Ioc : #(Ioc f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) - 1 := by
rw [card_Ioc_eq_card_Icc_sub_one, card_Icc]
theorem card_Ioo : #(Ioo f g) = ∏ i ∈ f.support ∪ g.support, #(Icc (f i) (g i)) - 2 := by
rw [card_Ioo_eq_card_Icc_sub_two, card_Icc]
end PartialOrder
section Lattice
variable [Lattice α] [Zero α] [LocallyFiniteOrder α] (f g : ι →₀ α)
open scoped Classical in
theorem card_uIcc :
#(uIcc f g) = ∏ i ∈ f.support ∪ g.support, #(uIcc (f i) (g i)) := by
rw [← support_inf_union_support_sup]; exact card_Icc (_ : ι →₀ α) _
end Lattice
section CanonicallyOrdered
variable [AddCommMonoid α] [PartialOrder α] [CanonicallyOrderedAdd α]
[OrderBot α] [LocallyFiniteOrder α]
variable [DecidableEq ι] [DecidableEq α] (f : ι →₀ α)
theorem card_Iic : #(Iic f) = ∏ i ∈ f.support, #(Iic (f i)) := by
classical simp_rw [Iic_eq_Icc, card_Icc, Finsupp.bot_eq_zero, support_zero, empty_union,
zero_apply, bot_eq_zero]
theorem card_Iio : #(Iio f) = ∏ i ∈ f.support, #(Iic (f i)) - 1 := by
rw [card_Iio_eq_card_Iic_sub_one, card_Iic]
end CanonicallyOrdered
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Lex.lean | import Mathlib.Data.Finsupp.Order
import Mathlib.Data.DFinsupp.Lex
import Mathlib.Data.Finsupp.ToDFinsupp
/-!
# Lexicographic order on finitely supported functions
This file defines the lexicographic order on `Finsupp`.
-/
variable {α N : Type*}
namespace Finsupp
section NHasZero
variable [Zero N]
/-- `Finsupp.Lex r s` is the lexicographic relation on `α →₀ N`, where `α` is ordered by `r`,
and `N` is ordered by `s`.
The type synonym `Lex (α →₀ N)` has an order given by `Finsupp.Lex (· < ·) (· < ·)`.
-/
protected def Lex (r : α → α → Prop) (s : N → N → Prop) (x y : α →₀ N) : Prop :=
Pi.Lex r s x y
theorem _root_.Pi.lex_eq_finsupp_lex {r : α → α → Prop} {s : N → N → Prop} (a b : α →₀ N) :
Pi.Lex r s a b = Finsupp.Lex r s a b :=
rfl
theorem lex_def {r : α → α → Prop} {s : N → N → Prop} {a b : α →₀ N} :
Finsupp.Lex r s a b ↔ ∃ j, (∀ d, r d j → a d = b d) ∧ s (a j) (b j) :=
.rfl
theorem lex_eq_invImage_dfinsupp_lex (r : α → α → Prop) (s : N → N → Prop) :
Finsupp.Lex r s = InvImage (DFinsupp.Lex r fun _ ↦ s) toDFinsupp :=
rfl
instance [LT α] [LT N] : LT (Lex (α →₀ N)) :=
⟨fun f g ↦ Finsupp.Lex (· < ·) (· < ·) (ofLex f) (ofLex g)⟩
theorem lex_lt_iff [LT α] [LT N] {a b : Lex (α →₀ N)} :
a < b ↔ ∃ i, (∀ j, j < i → a j = b j) ∧ a i < b i :=
.rfl
theorem lex_lt_iff_of_unique [Preorder α] [LT N] [Unique α] {a b : Lex (α →₀ N)} :
a < b ↔ a default < b default := by
simp only [lex_lt_iff, Unique.exists_iff, and_iff_right_iff_imp]
refine fun _ j hj ↦ False.elim (lt_irrefl j ?_)
simpa only [Unique.uniq] using hj
theorem lex_lt_of_lt_of_preorder [Preorder N] (r) [IsStrictOrder α r] {x y : α →₀ N} (hlt : x < y) :
∃ i, (∀ j, r j i → x j ≤ y j ∧ y j ≤ x j) ∧ x i < y i :=
DFinsupp.lex_lt_of_lt_of_preorder r (id hlt : x.toDFinsupp < y.toDFinsupp)
theorem lex_lt_of_lt [PartialOrder N] (r) [IsStrictOrder α r] {x y : α →₀ N} (hlt : x < y) :
Pi.Lex r (· < ·) x y :=
DFinsupp.lex_lt_of_lt r (id hlt : x.toDFinsupp < y.toDFinsupp)
instance Lex.isStrictOrder [LinearOrder α] [PartialOrder N] :
IsStrictOrder (Lex (α →₀ N)) (· < ·) where
irrefl _ := lt_irrefl (α := Lex (α → N)) _
trans _ _ _ := lt_trans (α := Lex (α → N))
variable [LinearOrder α]
/-- The partial order on `Finsupp`s obtained by the lexicographic ordering.
See `Finsupp.Lex.linearOrder` for a proof that this partial order is in fact linear. -/
instance Lex.partialOrder [PartialOrder N] : PartialOrder (Lex (α →₀ N)) where
lt := (· < ·)
le x y := ⇑(ofLex x) = ⇑(ofLex y) ∨ x < y
__ := PartialOrder.lift (fun x : Lex (α →₀ N) ↦ toLex (⇑(ofLex x)))
(DFunLike.coe_injective (F := Finsupp α N))
/-- The linear order on `Finsupp`s obtained by the lexicographic ordering. -/
instance Lex.linearOrder [LinearOrder N] : LinearOrder (Lex (α →₀ N)) where
__ := Lex.partialOrder
__ := LinearOrder.lift' (toLex ∘ toDFinsupp ∘ ofLex) finsuppEquivDFinsupp.injective
theorem Lex.single_strictAnti : StrictAnti fun (a : α) ↦ toLex (single a 1) := by
intro a b h
simp only [LT.lt, Finsupp.lex_def]
simp only [ofLex_toLex, Nat.lt_eq]
use a
constructor
· intro d hd
simp only [Finsupp.single_eq_of_ne hd.ne, Finsupp.single_eq_of_ne (hd.trans h).ne]
· simp [h.ne']
theorem Lex.single_lt_iff {a b : α} : toLex (single b 1) < toLex (single a 1) ↔ a < b :=
Lex.single_strictAnti.lt_iff_gt
theorem Lex.single_le_iff {a b : α} : toLex (single b 1) ≤ toLex (single a 1) ↔ a ≤ b :=
Lex.single_strictAnti.le_iff_ge
theorem Lex.single_antitone : Antitone fun (a : α) ↦ toLex (single a 1) :=
Lex.single_strictAnti.antitone
variable [PartialOrder N]
theorem toLex_monotone : Monotone (@toLex (α →₀ N)) :=
fun a b h ↦ DFinsupp.toLex_monotone (id h : ∀ i, (toDFinsupp a) i ≤ (toDFinsupp b) i)
@[deprecated lex_lt_iff (since := "2025-10-12")]
theorem lt_of_forall_lt_of_lt (a b : Lex (α →₀ N)) (i : α) :
(∀ j < i, ofLex a j = ofLex b j) → ofLex a i < ofLex b i → a < b :=
fun h1 h2 ↦ ⟨i, h1, h2⟩
theorem lex_le_iff_of_unique [Unique α] {a b : Lex (α →₀ N)} :
a ≤ b ↔ a default ≤ b default := by
simp only [le_iff_eq_or_lt]
apply or_congr _ lex_lt_iff_of_unique
conv_lhs => rw [← toLex_ofLex a, ← toLex_ofLex b, toLex_inj]
simp only [Finsupp.ext_iff, Unique.forall_iff]
end NHasZero
section Covariants
variable [LinearOrder α] [AddMonoid N] [LinearOrder N]
/-! We are about to sneak in a hypothesis that might appear to be too strong.
We assume `AddLeftStrictMono` (covariant with *strict* inequality `<`) also when proving the one
with the *weak* inequality `≤`. This is actually necessary: addition on `Lex (α →₀ N)` may fail to
be monotone, when it is "just" monotone on `N`.
See `Counterexamples/ZeroDivisorsInAddMonoidAlgebras.lean` for a counterexample. -/
section Left
variable [AddLeftStrictMono N]
instance Lex.addLeftStrictMono : AddLeftStrictMono (Lex (α →₀ N)) :=
⟨fun _ _ _ ⟨a, lta, ha⟩ ↦ ⟨a, fun j ja ↦ congr_arg _ (lta j ja), add_lt_add_left ha _⟩⟩
instance Lex.addLeftMono : AddLeftMono (Lex (α →₀ N)) :=
addLeftMono_of_addLeftStrictMono _
end Left
section Right
variable [AddRightStrictMono N]
instance Lex.addRightStrictMono : AddRightStrictMono (Lex (α →₀ N)) :=
⟨fun f _ _ ⟨a, lta, ha⟩ ↦
⟨a, fun j ja ↦ congr_arg (· + f j) (lta j ja), add_lt_add_right ha _⟩⟩
instance Lex.addRightMono : AddRightMono (Lex (α →₀ N)) :=
addRightMono_of_addRightStrictMono _
end Right
end Covariants
section OrderedAddMonoid
variable [LinearOrder α]
instance Lex.orderBot [AddCommMonoid N] [PartialOrder N] [CanonicallyOrderedAdd N] :
OrderBot (Lex (α →₀ N)) where
bot := 0
bot_le _ := Finsupp.toLex_monotone bot_le
instance Lex.isOrderedCancelAddMonoid
[AddCommMonoid N] [PartialOrder N] [IsOrderedCancelAddMonoid N] :
IsOrderedCancelAddMonoid (Lex (α →₀ N)) where
add_le_add_left _ _ h _ := add_le_add_left (α := Lex (α → N)) h _
le_of_add_le_add_left _ _ _ := le_of_add_le_add_left (α := Lex (α → N))
end OrderedAddMonoid
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Antidiagonal.lean | import Mathlib.Data.Finset.NatAntidiagonal
import Mathlib.Data.Finsupp.Multiset
import Mathlib.Data.Multiset.Antidiagonal
/-!
# The `Finsupp` counterpart of `Multiset.antidiagonal`.
The antidiagonal of `s : α →₀ ℕ` consists of
all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`.
-/
namespace Finsupp
open Finset
universe u
variable {α : Type u} [DecidableEq α]
/-- The `Finsupp` counterpart of `Multiset.antidiagonal`: the antidiagonal of
`s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`.
The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/
def antidiagonal' (f : α →₀ ℕ) : (α →₀ ℕ) × (α →₀ ℕ) →₀ ℕ :=
Multiset.toFinsupp
((Finsupp.toMultiset f).antidiagonal.map (Prod.map Multiset.toFinsupp Multiset.toFinsupp))
/-- The antidiagonal of `s : α →₀ ℕ` is the finset of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)`
such that `t₁ + t₂ = s`. -/
instance instHasAntidiagonal : HasAntidiagonal (α →₀ ℕ) where
antidiagonal f := f.antidiagonal'.support
mem_antidiagonal {f} {p} := by
rcases p with ⟨p₁, p₂⟩
simp [antidiagonal', ← and_assoc, Multiset.toFinsupp_eq_iff,
← Multiset.toFinsupp_eq_iff (f := f)]
@[simp]
theorem antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = singleton (0, 0) := rfl
@[to_additive]
theorem prod_antidiagonal_swap {M : Type*} [CommMonoid M] (n : α →₀ ℕ)
(f : (α →₀ ℕ) → (α →₀ ℕ) → M) :
∏ p ∈ antidiagonal n, f p.1 p.2 = ∏ p ∈ antidiagonal n, f p.2 p.1 :=
prod_equiv (Equiv.prodComm _ _) (by simp [add_comm]) (by simp)
@[simp]
theorem antidiagonal_single (a : α) (n : ℕ) :
antidiagonal (single a n) = (antidiagonal n).map
(Function.Embedding.prodMap ⟨_, single_injective a⟩ ⟨_, single_injective a⟩) := by
ext ⟨x, y⟩
simp only [mem_antidiagonal, mem_map, mem_antidiagonal, Function.Embedding.coe_prodMap,
Function.Embedding.coeFn_mk, Prod.map_apply, Prod.mk.injEq, Prod.exists]
constructor
· intro h
refine ⟨x a, y a, DFunLike.congr_fun h a |>.trans single_eq_same, ?_⟩
simp_rw [DFunLike.ext_iff, ← forall_and]
intro i
replace h := DFunLike.congr_fun h i
simp_rw [single_apply, Finsupp.add_apply] at h ⊢
obtain rfl | hai := Decidable.eq_or_ne a i
· exact ⟨if_pos rfl, if_pos rfl⟩
· simp_rw [if_neg hai, add_eq_zero] at h ⊢
exact h.imp Eq.symm Eq.symm
· rintro ⟨a, b, rfl, rfl, rfl⟩
exact (single_add _ _ _).symm
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Pointwise.lean | import Mathlib.Algebra.Group.Finsupp
import Mathlib.Algebra.Module.Defs
import Mathlib.Algebra.Ring.InjSurj
import Mathlib.Algebra.Ring.Pi
/-!
# The pointwise product on `Finsupp`.
For the convolution product on `Finsupp` when the domain has a binary operation,
see the type synonyms `AddMonoidAlgebra`
(which is in turn used to define `Polynomial` and `MvPolynomial`)
and `MonoidAlgebra`.
-/
noncomputable section
open Finset
universe u₁ u₂ u₃ u₄ u₅
variable {α : Type u₁} {β : Type u₂} {γ : Type u₃} {δ : Type u₄} {ι : Type u₅}
namespace Finsupp
/-! ### Declarations about the pointwise product on `Finsupp`s -/
section
variable [MulZeroClass β]
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is `f a * g a`. -/
instance : Mul (α →₀ β) :=
⟨zipWith (· * ·) (mul_zero 0)⟩
theorem coe_mul (g₁ g₂ : α →₀ β) : ⇑(g₁ * g₂) = g₁ * g₂ :=
rfl
@[simp]
theorem mul_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ * g₂) a = g₁ a * g₂ a :=
rfl
@[simp]
theorem single_mul (a : α) (b₁ b₂ : β) : single a (b₁ * b₂) = single a b₁ * single a b₂ :=
(zipWith_single_single _ _ _ _ _).symm
lemma support_mul_subset_left {g₁ g₂ : α →₀ β} :
(g₁ * g₂).support ⊆ g₁.support := fun x hx => by
aesop
lemma support_mul_subset_right {g₁ g₂ : α →₀ β} :
(g₁ * g₂).support ⊆ g₂.support := fun x hx => by
aesop
theorem support_mul [DecidableEq α] {g₁ g₂ : α →₀ β} :
(g₁ * g₂).support ⊆ g₁.support ∩ g₂.support :=
subset_inter support_mul_subset_left support_mul_subset_right
instance : MulZeroClass (α →₀ β) :=
DFunLike.coe_injective.mulZeroClass _ coe_zero coe_mul
end
instance [SemigroupWithZero β] : SemigroupWithZero (α →₀ β) :=
DFunLike.coe_injective.semigroupWithZero _ coe_zero coe_mul
instance [NonUnitalNonAssocSemiring β] : NonUnitalNonAssocSemiring (α →₀ β) :=
DFunLike.coe_injective.nonUnitalNonAssocSemiring _ coe_zero coe_add coe_mul fun _ _ ↦ rfl
instance [NonUnitalSemiring β] : NonUnitalSemiring (α →₀ β) :=
DFunLike.coe_injective.nonUnitalSemiring _ coe_zero coe_add coe_mul fun _ _ ↦ rfl
instance [NonUnitalCommSemiring β] : NonUnitalCommSemiring (α →₀ β) :=
DFunLike.coe_injective.nonUnitalCommSemiring _ coe_zero coe_add coe_mul fun _ _ ↦ rfl
instance [NonUnitalNonAssocRing β] : NonUnitalNonAssocRing (α →₀ β) :=
DFunLike.coe_injective.nonUnitalNonAssocRing _ coe_zero coe_add coe_mul coe_neg coe_sub
(fun _ _ ↦ rfl) fun _ _ ↦ rfl
instance [NonUnitalRing β] : NonUnitalRing (α →₀ β) :=
DFunLike.coe_injective.nonUnitalRing _ coe_zero coe_add coe_mul coe_neg coe_sub (fun _ _ ↦ rfl)
fun _ _ ↦ rfl
instance [NonUnitalCommRing β] : NonUnitalCommRing (α →₀ β) :=
DFunLike.coe_injective.nonUnitalCommRing _ coe_zero coe_add coe_mul coe_neg coe_sub
(fun _ _ ↦ rfl) fun _ _ ↦ rfl
-- TODO can this be generalized in the direction of `Pi.smul'`
-- (i.e. dependent functions and finsupps)
-- TODO in theory this could be generalised, we only really need `smul_zero` for the definition
instance pointwiseScalar [Semiring β] : SMul (α → β) (α →₀ β) where
smul f g :=
Finsupp.ofSupportFinite (fun a ↦ f a • g a) (by
apply Set.Finite.subset g.finite_support
simp only [Function.support_subset_iff, Finsupp.mem_support_iff, Ne,
Finsupp.fun_support_eq, Finset.mem_coe]
intro x hx h
apply hx
rw [h, smul_zero])
@[simp]
theorem coe_pointwise_smul [Semiring β] (f : α → β) (g : α →₀ β) : ⇑(f • g) = f • ⇑g :=
rfl
/-- The pointwise multiplicative action of functions on finitely supported functions -/
instance pointwiseModule [Semiring β] : Module (α → β) (α →₀ β) :=
Function.Injective.module _ coeFnAddHom DFunLike.coe_injective coe_pointwise_smul
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Order.lean | import Mathlib.Algebra.Order.BigOperators.Group.Finset
import Mathlib.Algebra.Order.Module.Defs
import Mathlib.Algebra.Order.Pi
import Mathlib.Algebra.Order.Sub.Basic
import Mathlib.Data.Finsupp.Basic
import Mathlib.Data.Finsupp.SMulWithZero
import Mathlib.Order.Preorder.Finsupp
/-!
# Pointwise order on finitely supported functions
This file lifts order structures on `α` to `ι →₀ α`.
## Main declarations
* `Finsupp.orderEmbeddingToFun`: The order embedding from finitely supported functions to
functions.
-/
noncomputable section
open Finset
variable {ι κ α β : Type*}
namespace Finsupp
/-! ### Order structures -/
section Zero
variable [Zero α]
section OrderedAddCommMonoid
variable [AddCommMonoid β] [PartialOrder β] [IsOrderedAddMonoid β] {f : ι →₀ α} {h₁ h₂ : ι → α → β}
@[gcongr]
lemma sum_le_sum (h : ∀ i ∈ f.support, h₁ i (f i) ≤ h₂ i (f i)) : f.sum h₁ ≤ f.sum h₂ :=
Finset.sum_le_sum h
theorem sum_nonneg (h : ∀ i ∈ f.support, 0 ≤ h₁ i (f i)) : 0 ≤ f.sum h₁ := Finset.sum_nonneg h
theorem sum_nonneg' (h : ∀ i, 0 ≤ h₁ i (f i)) : 0 ≤ f.sum h₁ := sum_nonneg fun _ _ ↦ h _
theorem sum_nonpos (h : ∀ i ∈ f.support, h₁ i (f i) ≤ 0) : f.sum h₁ ≤ 0 := Finset.sum_nonpos h
end OrderedAddCommMonoid
section Preorder
variable [Preorder α] {f g : ι →₀ α} {i : ι} {a b : α}
@[simp] lemma single_le_single : single i a ≤ single i b ↔ a ≤ b := by
classical exact Pi.single_le_single
lemma single_mono : Monotone (single i : α → ι →₀ α) := fun _ _ ↦ single_le_single.2
@[gcongr] protected alias ⟨_, GCongr.single_mono⟩ := single_le_single
@[simp] lemma single_nonneg : 0 ≤ single i a ↔ 0 ≤ a := by classical exact Pi.single_nonneg
@[simp] lemma single_nonpos : single i a ≤ 0 ↔ a ≤ 0 := by classical exact Pi.single_nonpos
variable [AddCommMonoid β] [PartialOrder β] [IsOrderedAddMonoid β]
lemma sum_le_sum_index [DecidableEq ι] {f₁ f₂ : ι →₀ α} {h : ι → α → β} (hf : f₁ ≤ f₂)
(hh : ∀ i ∈ f₁.support ∪ f₂.support, Monotone (h i))
(hh₀ : ∀ i ∈ f₁.support ∪ f₂.support, h i 0 = 0) : f₁.sum h ≤ f₂.sum h := by
classical
rw [sum_of_support_subset _ Finset.subset_union_left _ hh₀,
sum_of_support_subset _ Finset.subset_union_right _ hh₀]
exact Finset.sum_le_sum fun i hi ↦ hh _ hi <| hf _
end Preorder
end Zero
/-! ### Algebraic order structures -/
section OrderedAddCommMonoid
variable [AddCommMonoid α] [PartialOrder α] [IsOrderedAddMonoid α]
{i : ι} {f : ι → κ} {g g₁ g₂ : ι →₀ α}
instance isOrderedAddMonoid : IsOrderedAddMonoid (ι →₀ α) :=
{ add_le_add_left := fun _a _b h c s => add_le_add_left (h s) (c s) }
@[gcongr]
lemma mapDomain_mono : Monotone (mapDomain f : (ι →₀ α) → (κ →₀ α)) := by
classical exact fun g₁ g₂ h ↦ sum_le_sum_index h (fun _ _ ↦ single_mono) (by simp)
lemma mapDomain_nonneg (hg : 0 ≤ g) : 0 ≤ g.mapDomain f := by simpa using mapDomain_mono hg
lemma mapDomain_nonpos (hg : g ≤ 0) : g.mapDomain f ≤ 0 := by simpa using mapDomain_mono hg
end OrderedAddCommMonoid
instance isOrderedCancelAddMonoid [AddCommMonoid α] [PartialOrder α] [IsOrderedCancelAddMonoid α] :
IsOrderedCancelAddMonoid (ι →₀ α) :=
{ le_of_add_le_add_left := fun _f _g _i h s => le_of_add_le_add_left (h s) }
instance addLeftReflectLE [AddCommMonoid α] [PartialOrder α] [AddLeftReflectLE α] :
AddLeftReflectLE (ι →₀ α) :=
⟨fun _f _g _h H x => le_of_add_le_add_left <| H x⟩
section SMulZeroClass
variable [Zero α] [Preorder α] [Zero β] [Preorder β] [SMulZeroClass α β]
instance instPosSMulMono [PosSMulMono α β] : PosSMulMono α (ι →₀ β) :=
PosSMulMono.lift _ coe_le_coe coe_smul
instance instSMulPosMono [SMulPosMono α β] : SMulPosMono α (ι →₀ β) :=
SMulPosMono.lift _ coe_le_coe coe_smul coe_zero
instance instPosSMulReflectLE [PosSMulReflectLE α β] : PosSMulReflectLE α (ι →₀ β) :=
PosSMulReflectLE.lift _ coe_le_coe coe_smul
instance instSMulPosReflectLE [SMulPosReflectLE α β] : SMulPosReflectLE α (ι →₀ β) :=
SMulPosReflectLE.lift _ coe_le_coe coe_smul coe_zero
end SMulZeroClass
section SMulWithZero
variable [Zero α] [PartialOrder α] [Zero β] [PartialOrder β] [SMulWithZero α β]
instance instPosSMulStrictMono [PosSMulStrictMono α β] : PosSMulStrictMono α (ι →₀ β) :=
PosSMulStrictMono.lift _ coe_le_coe coe_smul
instance instSMulPosStrictMono [SMulPosStrictMono α β] : SMulPosStrictMono α (ι →₀ β) :=
SMulPosStrictMono.lift _ coe_le_coe coe_smul coe_zero
-- `PosSMulReflectLT α (ι →₀ β)` already follows from the other instances
instance instSMulPosReflectLT [SMulPosReflectLT α β] : SMulPosReflectLT α (ι →₀ β) :=
SMulPosReflectLT.lift _ coe_le_coe coe_smul coe_zero
end SMulWithZero
section PartialOrder
variable [AddCommMonoid α] [PartialOrder α] [CanonicallyOrderedAdd α] {f g : ι →₀ α}
instance orderBot : OrderBot (ι →₀ α) where
bot := 0
bot_le := by simp only [le_def, coe_zero, Pi.zero_apply, imp_true_iff, zero_le]
protected theorem bot_eq_zero : (⊥ : ι →₀ α) = 0 :=
rfl
@[simp]
theorem add_eq_zero_iff (f g : ι →₀ α) : f + g = 0 ↔ f = 0 ∧ g = 0 := by
simp [DFunLike.ext_iff, forall_and]
theorem le_iff' (f g : ι →₀ α) {s : Finset ι} (hf : f.support ⊆ s) : f ≤ g ↔ ∀ i ∈ s, f i ≤ g i :=
⟨fun h s _hs => h s, fun h s => by
classical exact
if H : s ∈ f.support then h s (hf H) else (notMem_support_iff.1 H).symm ▸ zero_le (g s)⟩
theorem le_iff (f g : ι →₀ α) : f ≤ g ↔ ∀ i ∈ f.support, f i ≤ g i :=
le_iff' f g <| Subset.refl _
lemma support_monotone : Monotone (support (α := ι) (M := α)) :=
fun f g h a ha ↦ by rw [mem_support_iff, ← pos_iff_ne_zero] at ha ⊢; exact ha.trans_le (h _)
lemma support_mono (hfg : f ≤ g) : f.support ⊆ g.support := support_monotone hfg
instance decidableLE [DecidableLE α] : DecidableLE (ι →₀ α) := fun f g =>
decidable_of_iff _ (le_iff f g).symm
instance decidableLT [DecidableLE α] : DecidableLT (ι →₀ α) :=
decidableLTOfDecidableLE
@[simp]
theorem single_le_iff {i : ι} {x : α} {f : ι →₀ α} : single i x ≤ f ↔ x ≤ f i :=
(le_iff' _ _ support_single_subset).trans <| by simp
variable [Sub α] [OrderedSub α] {f g : ι →₀ α} {i : ι} {a b : α}
/-- This is called `tsub` for truncated subtraction, to distinguish it with subtraction in an
additive group. -/
instance tsub : Sub (ι →₀ α) :=
⟨zipWith (fun m n => m - n) (tsub_self 0)⟩
instance orderedSub : OrderedSub (ι →₀ α) :=
⟨fun _n _m _k => forall_congr' fun _x => tsub_le_iff_right⟩
instance [AddLeftMono α] : CanonicallyOrderedAdd (ι →₀ α) where
exists_add_of_le := fun {f g} h => ⟨g - f, ext fun x => (add_tsub_cancel_of_le <| h x).symm⟩
le_add_self _ _ _ := le_add_self
le_self_add := fun _f _g _x => le_self_add
@[simp, norm_cast] lemma coe_tsub (f g : ι →₀ α) : ⇑(f - g) = f - g := rfl
theorem tsub_apply (f g : ι →₀ α) (a : ι) : (f - g) a = f a - g a :=
rfl
@[simp]
theorem single_tsub : single i (a - b) = single i a - single i b := by
ext j
obtain rfl | h := eq_or_ne j i
· rw [tsub_apply, single_eq_same, single_eq_same, single_eq_same]
· rw [tsub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, tsub_self]
theorem support_tsub {f1 f2 : ι →₀ α} : (f1 - f2).support ⊆ f1.support := by
simp +contextual only [subset_iff, tsub_eq_zero_iff_le, mem_support_iff,
Ne, coe_tsub, Pi.sub_apply, not_imp_not, zero_le, imp_true_iff]
theorem subset_support_tsub [DecidableEq ι] {f1 f2 : ι →₀ α} :
f1.support \ f2.support ⊆ (f1 - f2).support := by
simp +contextual [subset_iff]
end PartialOrder
section LinearOrder
variable [AddCommMonoid α] [LinearOrder α] [CanonicallyOrderedAdd α]
@[simp]
theorem support_inf [DecidableEq ι] (f g : ι →₀ α) : (f ⊓ g).support = f.support ∩ g.support := by
ext
simp only [inf_apply, mem_support_iff, Ne,
Finset.mem_inter]
simp only [← nonpos_iff_eq_zero, min_le_iff, not_or]
@[simp]
theorem support_sup [DecidableEq ι] (f g : ι →₀ α) : (f ⊔ g).support = f.support ∪ g.support := by
ext
simp only [mem_support_iff, Ne, sup_apply, ← nonpos_iff_eq_zero, sup_le_iff, mem_union,
not_and_or]
nonrec theorem disjoint_iff {f g : ι →₀ α} : Disjoint f g ↔ Disjoint f.support g.support := by
classical
rw [disjoint_iff, disjoint_iff, Finsupp.bot_eq_zero, ← Finsupp.support_eq_empty,
Finsupp.support_inf]
rfl
end LinearOrder
/-! ### Some lemmas about `ℕ` -/
section Nat
theorem sub_single_one_add {a : ι} {u u' : ι →₀ ℕ} (h : u a ≠ 0) :
u - single a 1 + u' = u + u' - single a 1 :=
tsub_add_eq_add_tsub <| single_le_iff.mpr <| Nat.one_le_iff_ne_zero.mpr h
theorem add_sub_single_one {a : ι} {u u' : ι →₀ ℕ} (h : u' a ≠ 0) :
u + (u' - single a 1) = u + u' - single a 1 :=
(add_tsub_assoc_of_le (single_le_iff.mpr <| Nat.one_le_iff_ne_zero.mpr h) _).symm
lemma sub_add_single_one_cancel {u : ι →₀ ℕ} {i : ι} (h : u i ≠ 0) :
u - single i 1 + single i 1 = u := by
rw [sub_single_one_add h, add_tsub_cancel_right]
end Nat
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/PointwiseSMul.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Basic
import Mathlib.Algebra.GroupWithZero.Action.Defs
import Mathlib.Data.Finsupp.Defs
import Mathlib.Data.Set.SMulAntidiagonal
/-!
# Scalar multiplication by finitely supported functions.
Given sets `G` and `P`, with a left-cancellative vector-addition of `G` on `P`, we define an
antidiagonal function that assigns, for any element `a` in `P`, finite subset `s` of `G`, and subset
`t` in `P`, the `Set` of all pairs of an element in `s` and an element in `t` that vector-add to
`a`. When `R` is a ring and `V` is an `R`-module, we obtain a convolution-type action of the ring of
finitely supported `R`-valued functions on `G` on the space of `V`-valued functions on `P`.
## Definitions
* Finsupp.vaddAntidiagonal : The finset of pairs that vector-add to a given element.
-/
open Finset Function
noncomputable section
variable {G P F R S U V : Type*}
namespace Finsupp
theorem finite_vaddAntidiagonal [VAdd G P] [IsLeftCancelVAdd G P] [Zero R] [Zero V]
(f : G →₀ R) (x : P → V) (p : P) :
Set.Finite (Set.vaddAntidiagonal (SetLike.coe f.support) x.support p) := by
refine Set.Finite.of_injOn (f := Prod.fst) (t := (SetLike.coe f.support)) ?_ ?_
f.support.finite_toSet
· intro _ ⟨h, _⟩
exact h
· intro _ ⟨_, _, h13⟩ gh' ⟨_, _, h23⟩ h
rw [h, ← h23] at h13
exact Prod.ext h (IsLeftCancelVAdd.left_cancel gh'.1 _ _ h13)
/-- The finset of pairs that vector-add to a given element. -/
def vaddAntidiagonal [VAdd G P] [IsLeftCancelVAdd G P] [Zero R] [Zero V] (f : G →₀ R) (x : P → V)
(p : P) :
Finset (G × P) := (finite_vaddAntidiagonal f x p).toFinset
theorem mem_vaddAntidiagonal_iff [VAdd G P] [IsLeftCancelVAdd G P] [Zero R] [Zero V] (f : G →₀ R)
(x : P → V) (p : P) (gh : G × P) :
gh ∈ vaddAntidiagonal f x p ↔ f gh.1 ≠ 0 ∧ x gh.2 ≠ 0 ∧ gh.1 +ᵥ gh.2 = p := by
simp [vaddAntidiagonal]
theorem mem_vaddAntidiagonal_of_addGroup [AddGroup G] [AddAction G P] [Zero R] [Zero V]
(f : G →₀ R) (x : P → V) (p : P) (gh : G × P) :
gh ∈ vaddAntidiagonal f x p ↔ f gh.1 ≠ 0 ∧ x gh.2 ≠ 0 ∧ gh.2 = -gh.1 +ᵥ p := by
rw [mem_vaddAntidiagonal_iff, eq_neg_vadd_iff]
/-- A convolution-type scalar multiplication of finitely supported functions on formal functions. -/
scoped instance [VAdd G P] [IsLeftCancelVAdd G P] [Zero R] [AddCommMonoid V] [SMulWithZero R V] :
SMul (G →₀ R) (P → V) where
smul f x p := ∑ G ∈ f.vaddAntidiagonal x p, f G.1 • x G.2
theorem smul_eq [VAdd G P] [IsLeftCancelVAdd G P] [Zero R] [AddCommMonoid V] [SMulWithZero R V]
(f : G →₀ R) (x : P → V) (p : P) :
(f • x) p = ∑ G ∈ f.vaddAntidiagonal x p, f G.1 • x G.2 := rfl
theorem smul_apply_addAction [AddGroup G] [AddAction G P] [Zero R] [AddCommMonoid V]
[SMulWithZero R V] (f : G →₀ R) (x : P → V) (p : P) :
(f • x) p = ∑ i ∈ f.support, (f i) • x (-i +ᵥ p) := by
rw [smul_eq, Finset.sum_of_injOn Prod.fst]
· intro _ h₁ _ h₂ h
rw [mem_coe, mem_vaddAntidiagonal_of_addGroup] at h₁ h₂
simp [Prod.ext_iff, h₁.2.2, h₂.2.2, h]
· intro g hg
rw [mem_coe, mem_vaddAntidiagonal_iff] at hg
exact mem_coe.mpr <| mem_support_iff.mpr hg.1
· intro g hg hgn
have h : f g = 0 ∨ x (-g +ᵥ p) = 0 := by
simpa [mem_vaddAntidiagonal_of_addGroup, or_iff_not_imp_left] using hgn
rcases h with (h | h) <;> simp [h]
· intro g hg
rw [mem_vaddAntidiagonal_of_addGroup] at hg
rw [hg.2.2]
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Single.lean | import Mathlib.Algebra.Notation.Indicator
import Mathlib.Data.Finsupp.Defs
/-!
# Finitely supported functions on exactly one point
This file contains definitions and basic results on defining/updating/removing `Finsupp`s
using one point of the domain.
## Main declarations
* `Finsupp.single`: The `Finsupp` which is nonzero in exactly one point.
* `Finsupp.update`: Changes one value of a `Finsupp`.
* `Finsupp.erase`: Replaces one value of a `Finsupp` by `0`.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
-/
assert_not_exists CompleteLattice
noncomputable section
open Finset Function
variable {α β γ ι M M' N P G H R S : Type*}
namespace Finsupp
/-! ### Declarations about `single` -/
section Single
variable [Zero M] {a a' : α} {b : M}
/-- `single a b` is the finitely supported function with value `b` at `a` and zero otherwise. -/
def single (a : α) (b : M) : α →₀ M where
support :=
haveI := Classical.decEq M
if b = 0 then ∅ else {a}
toFun :=
haveI := Classical.decEq α
Pi.single a b
mem_support_toFun a' := by
classical
obtain rfl | hb := eq_or_ne b 0
· simp [Pi.single, update]
rw [if_neg hb, mem_singleton]
obtain rfl | ha := eq_or_ne a' a
· simp [hb, Pi.single, update]
simp [ha]
theorem single_apply [Decidable (a = a')] : single a b a' = if a = a' then b else 0 := by
classical
simp_rw [@eq_comm _ a a', single, coe_mk, Pi.single_apply]
theorem single_apply_left {f : α → β} (hf : Function.Injective f) (x z : α) (y : M) :
single (f x) y (f z) = single x y z := by classical simp only [single_apply, hf.eq_iff]
theorem single_eq_set_indicator : ⇑(single a b) = Set.indicator {a} fun _ => b := by
classical
ext
simp [single_apply, Set.indicator, @eq_comm _ a]
@[simp]
theorem single_eq_same : (single a b : α →₀ M) a = b := by
classical exact Pi.single_eq_same (M := fun _ ↦ M) a b
@[simp]
theorem single_eq_of_ne (h : a' ≠ a) : (single a b : α →₀ M) a' = 0 := by
classical exact Pi.single_eq_of_ne h _
@[simp]
theorem single_eq_of_ne' (h : a ≠ a') : (single a b : α →₀ M) a' = 0 := by
classical exact Pi.single_eq_of_ne' h _
theorem single_eq_update [DecidableEq α] (a : α) (b : M) :
⇑(single a b) = Function.update (0 : _) a b := by
classical rw [single_eq_set_indicator, ← Set.piecewise_eq_indicator, Set.piecewise_singleton]
theorem single_eq_pi_single [DecidableEq α] (a : α) (b : M) : ⇑(single a b) = Pi.single a b :=
single_eq_update a b
@[simp]
theorem single_zero (a : α) : (single a 0 : α →₀ M) = 0 :=
DFunLike.coe_injective <| by
classical simpa only [single_eq_update, coe_zero] using Function.update_eq_self a (0 : α → M)
theorem single_of_single_apply (a a' : α) (b : M) :
single a ((single a' b) a) = single a' (single a' b) a := by
classical
rw [single_apply, single_apply]
ext
split_ifs with h
· rw [h]
· rw [zero_apply, single_apply, ite_self]
theorem support_single_ne_zero (a : α) (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
theorem support_single_subset : (single a b).support ⊆ {a} := by
classical
simp only [single]
split_ifs <;> [exact empty_subset _; exact Subset.refl _]
theorem single_apply_mem (x) : single a b x ∈ ({0, b} : Set M) := by
rcases em (x = a) with (rfl | hx) <;> [simp; simp [hx]]
theorem range_single_subset : Set.range (single a b) ⊆ {0, b} :=
Set.range_subset_iff.2 single_apply_mem
/-- `Finsupp.single a b` is injective in `b`. For the statement that it is injective in `a`, see
`Finsupp.single_left_injective` -/
theorem single_injective (a : α) : Function.Injective (single a : M → α →₀ M) := fun b₁ b₂ eq => by
have : (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a := by rw [eq]
rwa [single_eq_same, single_eq_same] at this
theorem single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ x = a → b = 0 := by
simp [single_eq_set_indicator]
theorem single_apply_ne_zero {a x : α} {b : M} : single a b x ≠ 0 ↔ x = a ∧ b ≠ 0 := by
simp [single_apply_eq_zero]
theorem mem_support_single (a a' : α) (b : M) : a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 := by
simp [single_apply_eq_zero]
theorem eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b := by
refine ⟨fun h => h.symm ▸ ⟨support_single_subset, single_eq_same⟩, ?_⟩
rintro ⟨h, rfl⟩
ext x
by_cases hx : x = a <;> simp only [hx, single_eq_same, single_eq_of_ne, Ne, not_false_iff]
exact notMem_support_iff.1 (mt (fun hx => (mem_singleton.1 (h hx))) hx)
theorem single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) :
single a₁ b₁ = single a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ b₁ = 0 ∧ b₂ = 0 := by
constructor
· intro eq
by_cases h : a₁ = a₂
· refine Or.inl ⟨h, ?_⟩
rwa [h, (single_injective a₂).eq_iff] at eq
· rw [DFunLike.ext_iff] at eq
have h₁ := eq a₁
have h₂ := eq a₂
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne' h] at h₁ h₂
exact Or.inr ⟨h₁, h₂.symm⟩
· rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩)
· rfl
· rw [single_zero, single_zero]
/-- `Finsupp.single a b` is injective in `a`. For the statement that it is injective in `b`, see
`Finsupp.single_injective` -/
theorem single_left_injective (h : b ≠ 0) : Function.Injective fun a : α => single a b :=
fun _a _a' H => (((single_eq_single_iff _ _ _ _).mp H).resolve_right fun hb => h hb.1).left
theorem single_left_inj (h : b ≠ 0) : single a b = single a' b ↔ a = a' :=
(single_left_injective h).eq_iff
lemma apply_surjective (a : α) : Surjective fun f : α →₀ M ↦ f a :=
RightInverse.surjective fun _ ↦ single_eq_same
theorem support_single_ne_bot (i : α) (h : b ≠ 0) : (single i b).support ≠ ⊥ := by
simpa only [support_single_ne_zero _ h] using singleton_ne_empty _
theorem support_single_disjoint {b' : M} (hb : b ≠ 0) (hb' : b' ≠ 0) {i j : α} :
Disjoint (single i b).support (single j b').support ↔ i ≠ j := by
rw [support_single_ne_zero _ hb, support_single_ne_zero _ hb', disjoint_singleton]
@[simp]
theorem single_eq_zero : single a b = 0 ↔ b = 0 := by
simp [DFunLike.ext_iff, single_eq_set_indicator]
theorem single_ne_zero : single a b ≠ 0 ↔ b ≠ 0 :=
single_eq_zero.not
theorem single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ := by
classical simp only [single_apply, eq_comm]
instance instNontrivial [Nonempty α] [Nontrivial M] : Nontrivial (α →₀ M) := by
inhabit α
rcases exists_ne (0 : M) with ⟨x, hx⟩
exact nontrivial_of_ne (single default x) 0 (mt single_eq_zero.1 hx)
theorem unique_single [Unique α] (x : α →₀ M) : x = single default (x default) :=
ext <| Unique.forall_iff.2 single_eq_same.symm
@[simp]
theorem unique_single_eq_iff [Unique α] {b' : M} : single a b = single a' b' ↔ b = b' := by
rw [Finsupp.unique_ext_iff, Unique.eq_default a, Unique.eq_default a', single_eq_same,
single_eq_same]
lemma apply_single' [Zero N] [Zero P] (e : N → P) (he : e 0 = 0) (a : α) (n : N) (b : α) :
e ((single a n) b) = single a (e n) b := by
classical
simp only [single_apply]
split_ifs
· rfl
· exact he
theorem support_eq_singleton {f : α →₀ M} {a : α} :
f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) :=
⟨fun h =>
⟨mem_support_iff.1 <| h.symm ▸ Finset.mem_singleton_self a,
eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩,
fun h => h.2.symm ▸ support_single_ne_zero _ h.1⟩
theorem support_eq_singleton' {f : α →₀ M} {a : α} :
f.support = {a} ↔ ∃ b ≠ 0, f = single a b :=
⟨fun h =>
let h := support_eq_singleton.1 h
⟨_, h.1, h.2⟩,
fun ⟨_b, hb, hf⟩ => hf.symm ▸ support_single_ne_zero _ hb⟩
theorem card_support_eq_one {f : α →₀ M} :
#f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) := by
simp only [card_eq_one, support_eq_singleton]
theorem card_support_eq_one' {f : α →₀ M} :
#f.support = 1 ↔ ∃ a, ∃ b ≠ 0, f = single a b := by
simp only [card_eq_one, support_eq_singleton']
theorem support_subset_singleton {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ f = single a (f a) :=
⟨fun h => eq_single_iff.mpr ⟨h, rfl⟩, fun h => (eq_single_iff.mp h).left⟩
theorem support_subset_singleton' {f : α →₀ M} {a : α} : f.support ⊆ {a} ↔ ∃ b, f = single a b :=
⟨fun h => ⟨f a, support_subset_singleton.mp h⟩, fun ⟨b, hb⟩ => by
rw [hb, support_subset_singleton, single_eq_same]⟩
theorem card_support_le_one [Nonempty α] {f : α →₀ M} :
#f.support ≤ 1 ↔ ∃ a, f = single a (f a) := by
simp only [card_le_one_iff_subset_singleton, support_subset_singleton]
theorem card_support_le_one' [Nonempty α] {f : α →₀ M} :
#f.support ≤ 1 ↔ ∃ a b, f = single a b := by
simp only [card_le_one_iff_subset_singleton, support_subset_singleton']
@[simp]
theorem equivFunOnFinite_single [DecidableEq α] [Finite α] (x : α) (m : M) :
Finsupp.equivFunOnFinite (Finsupp.single x m) = Pi.single x m := by
simp [Finsupp.single_eq_pi_single, equivFunOnFinite]
@[simp]
theorem equivFunOnFinite_symm_single [DecidableEq α] [Finite α] (x : α) (m : M) :
Finsupp.equivFunOnFinite.symm (Pi.single x m) = Finsupp.single x m := by
rw [← equivFunOnFinite_single, Equiv.symm_apply_apply]
end Single
/-! ### Declarations about `update` -/
section Update
variable [Zero M] (f : α →₀ M) (a : α) (b : M) (i : α)
/-- Replace the value of a `α →₀ M` at a given point `a : α` by a given value `b : M`.
If `b = 0`, this amounts to removing `a` from the `Finsupp.support`.
Otherwise, if `a` was not in the `Finsupp.support`, it is added to it.
This is the finitely-supported version of `Function.update`. -/
def update (f : α →₀ M) (a : α) (b : M) : α →₀ M where
support := by
haveI := Classical.decEq α; haveI := Classical.decEq M
exact if b = 0 then f.support.erase a else insert a f.support
toFun :=
haveI := Classical.decEq α
Function.update f a b
mem_support_toFun i := by
classical
rw [Function.update]
simp only [eq_rec_constant, dite_eq_ite, ne_eq]
split_ifs with hb ha ha <;>
try simp only [*, not_false_iff, iff_true, not_true, iff_false]
· rw [Finset.mem_erase]
simp
· rw [Finset.mem_erase]
simp [ha]
· rw [Finset.mem_insert]
simp
· rw [Finset.mem_insert]
simp [ha]
@[simp, norm_cast]
theorem coe_update [DecidableEq α] : (f.update a b : α → M) = Function.update f a b := by
delta update Function.update
ext
dsimp
split_ifs <;> simp
@[simp]
theorem update_self : f.update a (f a) = f := by
classical
ext
simp
@[simp]
theorem zero_update : update 0 a b = single a b := rfl
theorem support_update [DecidableEq α] [DecidableEq M] :
support (f.update a b) = if b = 0 then f.support.erase a else insert a f.support := by
classical
dsimp only [update]
congr!
@[simp]
theorem support_update_zero [DecidableEq α] : support (f.update a 0) = f.support.erase a := by
classical
simp only [update, ite_true]
congr!
variable {b}
theorem support_update_ne_zero [DecidableEq α] (h : b ≠ 0) :
support (f.update a b) = insert a f.support := by
classical
simp only [update, h, ite_false]
congr!
theorem support_update_subset [DecidableEq α] :
support (f.update a b) ⊆ insert a f.support := by
classical
rw [support_update]
split_ifs
· exact (erase_subset _ _).trans (subset_insert _ _)
· rfl
theorem update_comm (f : α →₀ M) {a₁ a₂ : α} (h : a₁ ≠ a₂) (m₁ m₂ : M) :
update (update f a₁ m₁) a₂ m₂ = update (update f a₂ m₂) a₁ m₁ :=
letI := Classical.decEq α
DFunLike.coe_injective <| Function.update_comm h _ _ _
@[simp] theorem update_idem (f : α →₀ M) (a : α) (b c : M) :
update (update f a b) a c = update f a c :=
letI := Classical.decEq α
DFunLike.coe_injective <| Function.update_idem _ _ _
end Update
/-! ### Declarations about `erase` -/
section Erase
variable [Zero M]
/--
`erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to `0`.
If `a` is not in the support of `f` then `erase a f = f`.
-/
def erase (a : α) (f : α →₀ M) : α →₀ M where
support :=
haveI := Classical.decEq α
f.support.erase a
toFun a' :=
haveI := Classical.decEq α
if a' = a then 0 else f a'
mem_support_toFun a' := by
classical
rw [mem_erase, mem_support_iff]; dsimp
split_ifs with h
· exact ⟨fun H _ => H.1 h, fun H => (H rfl).elim⟩
· exact and_iff_right h
@[simp]
theorem support_erase [DecidableEq α] {a : α} {f : α →₀ M} :
(f.erase a).support = f.support.erase a := by
classical
dsimp only [erase]
congr!
@[simp]
theorem erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 := by
classical simp only [erase, coe_mk, ite_true]
@[simp]
theorem erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' := by
classical simp only [erase, coe_mk, h, ite_false]
theorem erase_apply [DecidableEq α] {a a' : α} {f : α →₀ M} :
f.erase a a' = if a' = a then 0 else f a' := by
rw [erase, coe_mk]
simp only [ite_eq_ite]
@[simp]
theorem erase_single {a : α} {b : M} : erase a (single a b) = 0 := by
ext s; by_cases hs : s = a
· rw [hs, erase_same, coe_zero, Pi.zero_apply]
· rw [erase_ne hs]
exact single_eq_of_ne hs
theorem erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : erase a (single a' b) = single a' b := by
ext s; by_cases hs : s = a
· rw [hs, erase_same, single_eq_of_ne h]
· rw [erase_ne hs]
@[simp]
theorem erase_of_notMem_support {f : α →₀ M} {a} (haf : a ∉ f.support) : erase a f = f := by
ext b; by_cases hab : b = a
· rwa [hab, erase_same, eq_comm, ← notMem_support_iff]
· rw [erase_ne hab]
@[deprecated (since := "2025-05-23")] alias erase_of_not_mem_support := erase_of_notMem_support
theorem erase_zero (a : α) : erase a (0 : α →₀ M) = 0 := by
simp
theorem erase_eq_update_zero (f : α →₀ M) (a : α) : f.erase a = update f a 0 :=
letI := Classical.decEq α
ext fun _ => (Function.update_apply _ _ _ _).symm
-- The name matches `Finset.erase_insert_of_ne`
theorem erase_update_of_ne (f : α →₀ M) {a a' : α} (ha : a ≠ a') (b : M) :
erase a (update f a' b) = update (erase a f) a' b := by
rw [erase_eq_update_zero, erase_eq_update_zero, update_comm _ ha]
-- not `simp` as `erase_of_notMem_support` can prove this
theorem erase_idem (f : α →₀ M) (a : α) :
erase a (erase a f) = erase a f := by
rw [erase_eq_update_zero, erase_eq_update_zero, update_idem]
@[simp] theorem update_erase_eq_update (f : α →₀ M) (a : α) (b : M) :
update (erase a f) a b = update f a b := by
rw [erase_eq_update_zero, update_idem]
@[simp] theorem erase_update_eq_erase (f : α →₀ M) (a : α) (b : M) :
erase a (update f a b) = erase a f := by
rw [erase_eq_update_zero, erase_eq_update_zero, update_idem]
end Erase
/-! ### Declarations about `mapRange` -/
section MapRange
variable [Zero M] [Zero N] [Zero P]
@[simp]
theorem mapRange_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} :
mapRange f hf (single a b) = single a (f b) :=
ext fun a' => by
classical simpa only [single_eq_pi_single] using Pi.apply_single _ (fun _ => hf) a _ a'
end MapRange
/-! ### Declarations about `embDomain` -/
section EmbDomain
variable [Zero M] [Zero N]
theorem single_of_embDomain_single (l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0)
(h : l.embDomain f = single a b) : ∃ x, l = single x b ∧ f x = a := by
classical
have h_map_support : Finset.map f l.support = {a} := by
rw [← support_embDomain, h, support_single_ne_zero _ hb]
have ha : a ∈ Finset.map f l.support := by simp only [h_map_support, Finset.mem_singleton]
rcases Finset.mem_map.1 ha with ⟨c, _hc₁, hc₂⟩
use c
constructor
· ext d
rw [← embDomain_apply f l, h]
by_cases h_cases : c = d
· simp only [Eq.symm h_cases, hc₂, single_eq_same]
· rw [single_apply, single_apply, if_neg, if_neg h_cases]
by_contra hfd
exact h_cases (f.injective (hc₂.trans hfd))
· exact hc₂
@[simp]
theorem embDomain_single (f : α ↪ β) (a : α) (m : M) :
embDomain f (single a m) = single (f a) m := by
classical
ext b
by_cases h : b ∈ Set.range f
· rcases h with ⟨a', rfl⟩
simp [single_apply]
· simp only [embDomain_notin_range, h, single_apply, not_false_iff]
rw [if_neg]
rintro rfl
simp at h
end EmbDomain
/-! ### Declarations about `zipWith` -/
section ZipWith
variable [Zero M] [Zero N] [Zero P]
@[simp]
theorem zipWith_single_single (f : M → N → P) (hf : f 0 0 = 0) (a : α) (m : M) (n : N) :
zipWith f hf (single a m) (single a n) = single a (f m n) := by
ext a'
rw [zipWith_apply]
obtain rfl | ha' := eq_or_ne a' a
· rw [single_eq_same, single_eq_same, single_eq_same]
· rw [single_eq_of_ne ha', single_eq_of_ne ha', single_eq_of_ne ha', hf]
end ZipWith
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Basic.lean | import Mathlib.Algebra.BigOperators.Finsupp.Basic
import Mathlib.Algebra.BigOperators.Group.Finset.Preimage
import Mathlib.Algebra.Group.Indicator
import Mathlib.Data.Rat.BigOperators
/-!
# Miscellaneous definitions, lemmas, and constructions using finsupp
## Main declarations
* `Finsupp.graph`: the finset of input and output pairs with non-zero outputs.
* `Finsupp.mapRange.equiv`: `Finsupp.mapRange` as an equiv.
* `Finsupp.mapDomain`: maps the domain of a `Finsupp` by a function and by summing.
* `Finsupp.comapDomain`: postcomposition of a `Finsupp` with a function injective on the preimage
of its support.
* `Finsupp.filter`: `filter p f` is the finitely supported function that is `f a` if `p a` is true
and 0 otherwise.
* `Finsupp.frange`: the image of a finitely supported function on its support.
* `Finsupp.subtype_domain`: the restriction of a finitely supported function `f` to a subtype.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## TODO
* Expand the list of definitions and important lemmas to the module docstring.
-/
noncomputable section
open Finset Function
variable {α β γ ι M N P G H R S : Type*}
namespace Finsupp
/-! ### Declarations about `graph` -/
section Graph
variable [Zero M]
/-- The graph of a finitely supported function over its support, i.e. the finset of input and output
pairs with non-zero outputs. -/
def graph (f : α →₀ M) : Finset (α × M) :=
f.support.map ⟨fun a => Prod.mk a (f a), fun _ _ h => (Prod.mk.inj h).1⟩
theorem mk_mem_graph_iff {a : α} {m : M} {f : α →₀ M} : (a, m) ∈ f.graph ↔ f a = m ∧ m ≠ 0 := by
simp_rw [graph, mem_map, mem_support_iff]
constructor
· rintro ⟨b, ha, rfl, -⟩
exact ⟨rfl, ha⟩
· rintro ⟨rfl, ha⟩
exact ⟨a, ha, rfl⟩
@[simp]
theorem mem_graph_iff {c : α × M} {f : α →₀ M} : c ∈ f.graph ↔ f c.1 = c.2 ∧ c.2 ≠ 0 := by
cases c
exact mk_mem_graph_iff
theorem mk_mem_graph (f : α →₀ M) {a : α} (ha : a ∈ f.support) : (a, f a) ∈ f.graph :=
mk_mem_graph_iff.2 ⟨rfl, mem_support_iff.1 ha⟩
theorem apply_eq_of_mem_graph {a : α} {m : M} {f : α →₀ M} (h : (a, m) ∈ f.graph) : f a = m :=
(mem_graph_iff.1 h).1
@[simp 1100] -- Higher priority shortcut instance for `mem_graph_iff`.
theorem notMem_graph_snd_zero (a : α) (f : α →₀ M) : (a, (0 : M)) ∉ f.graph := fun h =>
(mem_graph_iff.1 h).2.irrefl
@[deprecated (since := "2025-05-23")] alias not_mem_graph_snd_zero := notMem_graph_snd_zero
@[simp]
theorem image_fst_graph [DecidableEq α] (f : α →₀ M) : f.graph.image Prod.fst = f.support := by
classical
simp_rw [graph, map_eq_image, image_image, Embedding.coeFn_mk, Function.comp_def, image_id']
theorem graph_injective (α M) [Zero M] : Injective (@graph α M _) := by
intro f g h
classical
have hsup : f.support = g.support := by rw [← image_fst_graph, h, image_fst_graph]
refine ext_iff'.2 ⟨hsup, fun x hx => apply_eq_of_mem_graph <| h.symm ▸ ?_⟩
exact mk_mem_graph _ (hsup ▸ hx)
@[simp]
theorem graph_inj {f g : α →₀ M} : f.graph = g.graph ↔ f = g :=
(graph_injective α M).eq_iff
@[simp]
theorem graph_zero : graph (0 : α →₀ M) = ∅ := by simp [graph]
@[simp]
theorem graph_eq_empty {f : α →₀ M} : f.graph = ∅ ↔ f = 0 :=
(graph_injective α M).eq_iff' graph_zero
end Graph
end Finsupp
/-! ### Declarations about `mapRange` -/
section MapRange
namespace Finsupp
variable [AddCommMonoid M] [AddCommMonoid N]
variable {F : Type*} [FunLike F M N] [AddMonoidHomClass F M N]
theorem mapRange_multiset_sum (f : F) (m : Multiset (α →₀ M)) :
mapRange f (map_zero f) m.sum = (m.map fun x => mapRange f (map_zero f) x).sum :=
(mapRange.addMonoidHom (f : M →+ N) : (α →₀ _) →+ _).map_multiset_sum _
theorem mapRange_finset_sum (f : F) (s : Finset ι) (g : ι → α →₀ M) :
mapRange f (map_zero f) (∑ x ∈ s, g x) = ∑ x ∈ s, mapRange f (map_zero f) (g x) :=
map_sum (mapRange.addMonoidHom (f : M →+ N)) _ _
end Finsupp
end MapRange
/-! ### Declarations about `equivCongrLeft` -/
section EquivCongrLeft
variable [Zero M]
namespace Finsupp
/-- Given `f : α ≃ β`, we can map `l : α →₀ M` to `equivMapDomain f l : β →₀ M` (computably)
by mapping the support forwards and the function backwards. -/
def equivMapDomain (f : α ≃ β) (l : α →₀ M) : β →₀ M where
support := l.support.map f.toEmbedding
toFun a := l (f.symm a)
mem_support_toFun a := by simp only [Finset.mem_map_equiv, mem_support_toFun]; rfl
@[simp]
theorem equivMapDomain_apply (f : α ≃ β) (l : α →₀ M) (b : β) :
equivMapDomain f l b = l (f.symm b) :=
rfl
theorem equivMapDomain_symm_apply (f : α ≃ β) (l : β →₀ M) (a : α) :
equivMapDomain f.symm l a = l (f a) :=
rfl
@[simp]
theorem equivMapDomain_refl (l : α →₀ M) : equivMapDomain (Equiv.refl _) l = l := by ext x; rfl
theorem equivMapDomain_refl' : equivMapDomain (Equiv.refl _) = @id (α →₀ M) := by ext x; rfl
theorem equivMapDomain_trans (f : α ≃ β) (g : β ≃ γ) (l : α →₀ M) :
equivMapDomain (f.trans g) l = equivMapDomain g (equivMapDomain f l) := by ext x; rfl
theorem equivMapDomain_trans' (f : α ≃ β) (g : β ≃ γ) :
@equivMapDomain _ _ M _ (f.trans g) = equivMapDomain g ∘ equivMapDomain f := by ext x; rfl
@[simp]
theorem equivMapDomain_single (f : α ≃ β) (a : α) (b : M) :
equivMapDomain f (single a b) = single (f a) b := by
classical
ext x
simp only [single_apply, Equiv.apply_eq_iff_eq_symm_apply, equivMapDomain_apply]
@[simp]
theorem equivMapDomain_zero {f : α ≃ β} : equivMapDomain f (0 : α →₀ M) = (0 : β →₀ M) := by
ext; simp only [equivMapDomain_apply, coe_zero, Pi.zero_apply]
@[to_additive (attr := simp)]
theorem prod_equivMapDomain [CommMonoid N] (f : α ≃ β) (l : α →₀ M) (g : β → M → N) :
prod (equivMapDomain f l) g = prod l (fun a m => g (f a) m) := by
simp [prod, equivMapDomain]
/-- Given `f : α ≃ β`, the finitely supported function spaces are also in bijection:
`(α →₀ M) ≃ (β →₀ M)`.
This is the finitely-supported version of `Equiv.piCongrLeft`. -/
def equivCongrLeft (f : α ≃ β) : (α →₀ M) ≃ (β →₀ M) := by
refine ⟨equivMapDomain f, equivMapDomain f.symm, fun f => ?_, fun f => ?_⟩ <;> ext x <;>
simp only [equivMapDomain_apply, Equiv.symm_symm, Equiv.symm_apply_apply,
Equiv.apply_symm_apply]
@[simp]
theorem equivCongrLeft_apply (f : α ≃ β) (l : α →₀ M) : equivCongrLeft f l = equivMapDomain f l :=
rfl
@[simp]
theorem equivCongrLeft_symm (f : α ≃ β) :
(@equivCongrLeft _ _ M _ f).symm = equivCongrLeft f.symm :=
rfl
end Finsupp
end EquivCongrLeft
section CastFinsupp
variable [Zero M] (f : α →₀ M)
namespace Nat
@[simp, norm_cast]
theorem cast_finsuppProd [CommSemiring R] (g : α → M → ℕ) :
(↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) :=
Nat.cast_prod _ _
@[simp, norm_cast]
theorem cast_finsupp_sum [AddCommMonoidWithOne R] (g : α → M → ℕ) :
(↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) :=
Nat.cast_sum _ _
end Nat
namespace Int
@[simp, norm_cast]
theorem cast_finsuppProd [CommRing R] (g : α → M → ℤ) :
(↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) :=
Int.cast_prod _ _
@[simp, norm_cast]
theorem cast_finsupp_sum [AddCommGroupWithOne R] (g : α → M → ℤ) :
(↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) :=
Int.cast_sum _ _
end Int
namespace Rat
@[simp, norm_cast]
theorem cast_finsupp_sum [DivisionRing R] [CharZero R] (g : α → M → ℚ) :
(↑(f.sum g) : R) = f.sum fun a b => ↑(g a b) :=
cast_sum _ _
@[simp, norm_cast]
theorem cast_finsuppProd [Field R] [CharZero R] (g : α → M → ℚ) :
(↑(f.prod g) : R) = f.prod fun a b => ↑(g a b) :=
cast_prod _ _
end Rat
end CastFinsupp
/-! ### Declarations about `mapDomain` -/
namespace Finsupp
section MapDomain
variable [AddCommMonoid M] {v v₁ v₂ : α →₀ M}
/-- Given `f : α → β` and `v : α →₀ M`, `mapDomain f v : β →₀ M`
is the finitely supported function whose value at `a : β` is the sum
of `v x` over all `x` such that `f x = a`. -/
def mapDomain (f : α → β) (v : α →₀ M) : β →₀ M :=
v.sum fun a => single (f a)
theorem mapDomain_apply {f : α → β} (hf : Function.Injective f) (x : α →₀ M) (a : α) :
mapDomain f x (f a) = x a := by
rw [mapDomain, sum_apply, sum_eq_single a, single_eq_same]
· intro b _ hba
exact single_eq_of_ne' (hf.ne hba)
· intro _
rw [single_zero, coe_zero, Pi.zero_apply]
theorem mapDomain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ Set.range f) :
mapDomain f x a = 0 := by
rw [mapDomain, sum_apply, sum]
exact Finset.sum_eq_zero fun a' _ => single_eq_of_ne fun eq => h <| eq ▸ Set.mem_range_self _
@[simp]
theorem mapDomain_id : mapDomain id v = v :=
sum_single _
theorem mapDomain_comp {f : α → β} {g : β → γ} :
mapDomain (g ∘ f) v = mapDomain g (mapDomain f v) := by
refine ((sum_sum_index ?_ ?_).trans ?_).symm
· intro
exact single_zero _
· intro
exact single_add _
refine sum_congr fun _ _ => sum_single_index ?_
exact single_zero _
@[simp]
theorem mapDomain_single {f : α → β} {a : α} {b : M} : mapDomain f (single a b) = single (f a) b :=
sum_single_index <| single_zero _
@[simp]
theorem mapDomain_zero {f : α → β} : mapDomain f (0 : α →₀ M) = (0 : β →₀ M) :=
sum_zero_index
theorem mapDomain_congr {f g : α → β} (h : ∀ x ∈ v.support, f x = g x) :
v.mapDomain f = v.mapDomain g :=
Finset.sum_congr rfl fun _ H => by simp only [h _ H]
theorem mapDomain_add {f : α → β} : mapDomain f (v₁ + v₂) = mapDomain f v₁ + mapDomain f v₂ :=
sum_add_index' (fun _ => single_zero _) fun _ => single_add _
@[simp]
theorem mapDomain_equiv_apply {f : α ≃ β} (x : α →₀ M) (a : β) :
mapDomain f x a = x (f.symm a) := by
conv_lhs => rw [← f.apply_symm_apply a]
exact mapDomain_apply f.injective _ _
/-- `Finsupp.mapDomain` is an `AddMonoidHom`. -/
@[simps]
def mapDomain.addMonoidHom (f : α → β) : (α →₀ M) →+ β →₀ M where
toFun := mapDomain f
map_zero' := mapDomain_zero
map_add' _ _ := mapDomain_add
@[simp]
theorem mapDomain.addMonoidHom_id : mapDomain.addMonoidHom id = AddMonoidHom.id (α →₀ M) :=
AddMonoidHom.ext fun _ => mapDomain_id
theorem mapDomain.addMonoidHom_comp (f : β → γ) (g : α → β) :
(mapDomain.addMonoidHom (f ∘ g) : (α →₀ M) →+ γ →₀ M) =
(mapDomain.addMonoidHom f).comp (mapDomain.addMonoidHom g) :=
AddMonoidHom.ext fun _ => mapDomain_comp
theorem mapDomain_finset_sum {f : α → β} {s : Finset ι} {v : ι → α →₀ M} :
mapDomain f (∑ i ∈ s, v i) = ∑ i ∈ s, mapDomain f (v i) :=
map_sum (mapDomain.addMonoidHom f) _ _
theorem mapDomain_sum [Zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} :
mapDomain f (s.sum v) = s.sum fun a b => mapDomain f (v a b) :=
map_finsuppSum (mapDomain.addMonoidHom f : (α →₀ M) →+ β →₀ M) _ _
theorem mapDomain_support [DecidableEq β] {f : α → β} {s : α →₀ M} :
(s.mapDomain f).support ⊆ s.support.image f :=
Finset.Subset.trans support_sum <|
Finset.Subset.trans (Finset.biUnion_mono fun _ _ => support_single_subset) <| by
rw [Finset.biUnion_singleton]
theorem mapDomain_apply' (S : Set α) {f : α → β} (x : α →₀ M) (hS : (x.support : Set α) ⊆ S)
(hf : Set.InjOn f S) {a : α} (ha : a ∈ S) : mapDomain f x (f a) = x a := by
classical
rw [mapDomain, sum_apply, sum]
simp_rw [single_apply]
by_cases hax : a ∈ x.support
· rw [← Finset.add_sum_erase _ _ hax, if_pos rfl]
convert add_zero (x a)
refine Finset.sum_eq_zero fun i hi => if_neg ?_
exact (hf.mono hS).ne (Finset.mem_of_mem_erase hi) hax (Finset.ne_of_mem_erase hi)
· rw [notMem_support_iff.1 hax]
refine Finset.sum_eq_zero fun i hi => if_neg ?_
exact hf.ne (hS hi) ha (ne_of_mem_of_not_mem hi hax)
theorem mapDomain_support_of_injOn [DecidableEq β] {f : α → β} (s : α →₀ M)
(hf : Set.InjOn f s.support) : (mapDomain f s).support = Finset.image f s.support :=
Finset.Subset.antisymm mapDomain_support <| by
intro x hx
simp only [mem_image, mem_support_iff, Ne] at hx
rcases hx with ⟨hx_w, hx_h_left, rfl⟩
simp only [mem_support_iff, Ne]
rw [mapDomain_apply' (↑s.support : Set _) _ _ hf]
· exact hx_h_left
· simp_rw [mem_coe, mem_support_iff, Ne]
exact hx_h_left
· exact Subset.refl _
theorem mapDomain_support_of_injective [DecidableEq β] {f : α → β} (hf : Function.Injective f)
(s : α →₀ M) : (mapDomain f s).support = Finset.image f s.support :=
mapDomain_support_of_injOn s hf.injOn
@[to_additive]
theorem prod_mapDomain_index [CommMonoid N] {f : α → β} {s : α →₀ M} {h : β → M → N}
(h_zero : ∀ b, h b 0 = 1) (h_add : ∀ b m₁ m₂, h b (m₁ + m₂) = h b m₁ * h b m₂) :
(mapDomain f s).prod h = s.prod fun a m => h (f a) m :=
(prod_sum_index h_zero h_add).trans <| prod_congr fun _ _ => prod_single_index (h_zero _)
-- Note that in `prod_mapDomain_index`, `M` is still an additive monoid,
-- so there is no analogous version in terms of `MonoidHom`.
/-- A version of `sum_mapDomain_index` that takes a bundled `AddMonoidHom`,
rather than separate linearity hypotheses.
-/
@[simp]
theorem sum_mapDomain_index_addMonoidHom [AddCommMonoid N] {f : α → β} {s : α →₀ M}
(h : β → M →+ N) : ((mapDomain f s).sum fun b m => h b m) = s.sum fun a m => h (f a) m :=
sum_mapDomain_index (fun b => (h b).map_zero) (fun b _ _ => (h b).map_add _ _)
theorem embDomain_eq_mapDomain (f : α ↪ β) (v : α →₀ M) : embDomain f v = mapDomain f v := by
ext a
by_cases h : a ∈ Set.range f
· rcases h with ⟨a, rfl⟩
rw [mapDomain_apply f.injective, embDomain_apply]
· rw [mapDomain_notin_range, embDomain_notin_range] <;> assumption
@[to_additive]
theorem prod_mapDomain_index_inj [CommMonoid N] {f : α → β} {s : α →₀ M} {h : β → M → N}
(hf : Function.Injective f) : (s.mapDomain f).prod h = s.prod fun a b => h (f a) b := by
rw [← Function.Embedding.coeFn_mk f hf, ← embDomain_eq_mapDomain, prod_embDomain]
theorem mapDomain_injective {f : α → β} (hf : Function.Injective f) :
Function.Injective (mapDomain f : (α →₀ M) → β →₀ M) := by
intro v₁ v₂ eq
ext a
have : mapDomain f v₁ (f a) = mapDomain f v₂ (f a) := by rw [eq]
rwa [mapDomain_apply hf, mapDomain_apply hf] at this
theorem mapDomain_surjective {f : α → β} (hf : f.Surjective) :
(mapDomain (M := M) f).Surjective := by
intro x
use mapDomain (surjInv hf) x
rw [← mapDomain_comp, (rightInverse_surjInv hf).id, mapDomain_id]
/-- When `f` is an embedding we have an embedding `(α →₀ ℕ) ↪ (β →₀ ℕ)` given by `mapDomain`. -/
@[simps]
def mapDomainEmbedding {α β : Type*} (f : α ↪ β) : (α →₀ ℕ) ↪ β →₀ ℕ :=
⟨Finsupp.mapDomain f, Finsupp.mapDomain_injective f.injective⟩
theorem mapDomain.addMonoidHom_comp_mapRange [AddCommMonoid N] (f : α → β) (g : M →+ N) :
(mapDomain.addMonoidHom f).comp (mapRange.addMonoidHom g) =
(mapRange.addMonoidHom g).comp (mapDomain.addMonoidHom f) := by
ext
simp
/-- When `g` preserves addition, `mapRange` and `mapDomain` commute. -/
theorem mapDomain_mapRange [AddCommMonoid N] (f : α → β) (v : α →₀ M) (g : M → N) (h0 : g 0 = 0)
(hadd : ∀ x y, g (x + y) = g x + g y) :
mapDomain f (mapRange g h0 v) = mapRange g h0 (mapDomain f v) :=
let g' : M →+ N :=
{ toFun := g
map_zero' := h0
map_add' := hadd }
DFunLike.congr_fun (mapDomain.addMonoidHom_comp_mapRange f g') v
theorem sum_update_add [AddZeroClass α] [AddCommMonoid β] (f : ι →₀ α) (i : ι) (a : α)
(g : ι → α → β) (hg : ∀ i, g i 0 = 0)
(hgg : ∀ (j : ι) (a₁ a₂ : α), g j (a₁ + a₂) = g j a₁ + g j a₂) :
(f.update i a).sum g + g i (f i) = f.sum g + g i a := by
rw [update_eq_erase_add_single, sum_add_index' hg hgg]
conv_rhs => rw [← Finsupp.update_self f i]
rw [update_eq_erase_add_single, sum_add_index' hg hgg, add_assoc, add_assoc]
congr 1
rw [add_comm, sum_single_index (hg _), sum_single_index (hg _)]
theorem mapDomain_injOn (S : Set α) {f : α → β} (hf : Set.InjOn f S) :
Set.InjOn (mapDomain f : (α →₀ M) → β →₀ M) { w | (w.support : Set α) ⊆ S } := by
intro v₁ hv₁ v₂ hv₂ eq
ext a
classical
by_cases h : a ∈ v₁.support ∪ v₂.support
· rw [← mapDomain_apply' S _ hv₁ hf _, ← mapDomain_apply' S _ hv₂ hf _, eq] <;>
· apply Set.union_subset hv₁ hv₂
exact mod_cast h
· simp_all
theorem equivMapDomain_eq_mapDomain {M} [AddCommMonoid M] (f : α ≃ β) (l : α →₀ M) :
equivMapDomain f l = mapDomain f l := by ext x; simp
end MapDomain
/-! ### Declarations about `comapDomain` -/
section ComapDomain
/-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on
the preimage of `l.support`, `comapDomain f l hf` is the finitely supported function
from `α` to `M` given by composing `l` with `f`. -/
@[simps support]
def comapDomain [Zero M] (f : α → β) (l : β →₀ M) (hf : Set.InjOn f (f ⁻¹' ↑l.support)) :
α →₀ M where
support := l.support.preimage f hf
toFun a := l (f a)
mem_support_toFun := by
intro a
rw [Finset.mem_preimage]
exact l.mem_support_toFun (f a)
@[simp]
theorem comapDomain_apply [Zero M] (f : α → β) (l : β →₀ M) (hf : Set.InjOn f (f ⁻¹' ↑l.support))
(a : α) : comapDomain f l hf a = l (f a) :=
rfl
theorem sum_comapDomain [Zero M] [AddCommMonoid N] (f : α → β) (l : β →₀ M) (g : β → M → N)
(hf : Set.BijOn f (f ⁻¹' ↑l.support) ↑l.support) :
(comapDomain f l hf.injOn).sum (g ∘ f) = l.sum g :=
Finset.sum_preimage_of_bij f _ hf fun x => g x (l x)
theorem eq_zero_of_comapDomain_eq_zero [Zero M] (f : α → β) (l : β →₀ M)
(hf : Set.BijOn f (f ⁻¹' ↑l.support) ↑l.support) : comapDomain f l hf.injOn = 0 → l = 0 := by
rw [← support_eq_empty, ← support_eq_empty, comapDomain]
simp_rw [Finset.ext_iff, Finset.notMem_empty, iff_false, mem_preimage]
intro h a ha
obtain ⟨b, hb⟩ := hf.2.2 ha
exact h b (hb.2.symm ▸ ha)
section FInjective
section Zero
variable [Zero M]
lemma embDomain_comapDomain {f : α ↪ β} {g : β →₀ M} (hg : ↑g.support ⊆ Set.range f) :
embDomain f (comapDomain f g f.injective.injOn) = g := by
ext b
by_cases hb : b ∈ Set.range f
· obtain ⟨a, rfl⟩ := hb
rw [embDomain_apply, comapDomain_apply]
· replace hg : g b = 0 := notMem_support_iff.mp <| mt (hg ·) hb
rw [embDomain_notin_range _ _ _ hb, hg]
/-- Note the `hif` argument is needed for this to work in `rw`. -/
@[simp]
theorem comapDomain_zero (f : α → β)
(hif : Set.InjOn f (f ⁻¹' ↑(0 : β →₀ M).support) := Finset.coe_empty ▸ (Set.injOn_empty f)) :
comapDomain f (0 : β →₀ M) hif = (0 : α →₀ M) := by
ext
rfl
@[simp]
theorem comapDomain_single (f : α → β) (a : α) (m : M)
(hif : Set.InjOn f (f ⁻¹' (single (f a) m).support)) :
comapDomain f (Finsupp.single (f a) m) hif = Finsupp.single a m := by
rcases eq_or_ne m 0 with (rfl | hm)
· simp_rw [single_zero, comapDomain_zero]
· rw [eq_single_iff, comapDomain_apply, comapDomain_support, ← Finset.coe_subset, coe_preimage,
support_single_ne_zero _ hm, coe_singleton, coe_singleton, single_eq_same]
rw [support_single_ne_zero _ hm, coe_singleton] at hif
exact ⟨fun x hx => hif hx rfl hx, rfl⟩
lemma comapDomain_surjective [Finite β] {f : α → β} (hf : Function.Injective f) :
Function.Surjective fun l : β →₀ M ↦ Finsupp.comapDomain f l hf.injOn := by
classical
intro x
cases isEmpty_or_nonempty α
· exact ⟨0, Finsupp.ext <| fun a ↦ IsEmpty.elim ‹_› a⟩
obtain ⟨g, hg⟩ := hf.hasLeftInverse
exact ⟨Finsupp.equivFunOnFinite.symm (x ∘ g), Finsupp.ext <| fun a ↦ by simp [hg a]⟩
end Zero
section AddZeroClass
variable [AddZeroClass M] {f : α → β}
theorem comapDomain_add (v₁ v₂ : β →₀ M) (hv₁ : Set.InjOn f (f ⁻¹' ↑v₁.support))
(hv₂ : Set.InjOn f (f ⁻¹' ↑v₂.support)) (hv₁₂ : Set.InjOn f (f ⁻¹' ↑(v₁ + v₂).support)) :
comapDomain f (v₁ + v₂) hv₁₂ = comapDomain f v₁ hv₁ + comapDomain f v₂ hv₂ := by
ext
simp
/-- A version of `Finsupp.comapDomain_add` that's easier to use. -/
theorem comapDomain_add_of_injective (hf : Function.Injective f) (v₁ v₂ : β →₀ M) :
comapDomain f (v₁ + v₂) hf.injOn =
comapDomain f v₁ hf.injOn + comapDomain f v₂ hf.injOn :=
comapDomain_add ..
/-- `Finsupp.comapDomain` is an `AddMonoidHom`. -/
@[simps]
def comapDomain.addMonoidHom (hf : Function.Injective f) : (β →₀ M) →+ α →₀ M where
toFun x := comapDomain f x hf.injOn
map_zero' := comapDomain_zero f
map_add' := comapDomain_add_of_injective hf
end AddZeroClass
variable [AddCommMonoid M] (f : α → β)
theorem mapDomain_comapDomain (hf : Function.Injective f) (l : β →₀ M)
(hl : ↑l.support ⊆ Set.range f) :
mapDomain f (comapDomain f l hf.injOn) = l := by
conv_rhs => rw [← embDomain_comapDomain (f := ⟨f, hf⟩) hl (M := M), embDomain_eq_mapDomain]
rfl
theorem comapDomain_mapDomain (hf : Function.Injective f) (l : α →₀ M) :
comapDomain f (mapDomain f l) hf.injOn = l := by
ext; rw [comapDomain_apply, mapDomain_apply hf]
lemma mem_range_mapDomain_iff (hf : Function.Injective f) (x : β →₀ M) :
x ∈ Set.range (Finsupp.mapDomain f) ↔ ∀ b ∉ Set.range f, x b = 0 := by
refine ⟨fun ⟨y, hy⟩ x hx ↦ hy ▸ Finsupp.mapDomain_notin_range y x hx, fun h ↦ ?_⟩
refine ⟨Finsupp.comapDomain f x hf.injOn, Finsupp.mapDomain_comapDomain f hf _ fun i hi ↦ ?_⟩
by_contra hc
simp only [Finset.mem_coe, Finsupp.mem_support_iff, ne_eq] at hi
exact hi (h _ hc)
end FInjective
end ComapDomain
/-! ### Declarations about `Finsupp.filter` -/
section Filter
section Zero
variable [Zero M] (p : α → Prop) [DecidablePred p] (f : α →₀ M)
/--
`Finsupp.filter p f` is the finitely supported function that is `f a` if `p a` is true and `0`
otherwise. -/
def filter (p : α → Prop) [DecidablePred p] (f : α →₀ M) : α →₀ M where
toFun a := if p a then f a else 0
support := f.support.filter p
mem_support_toFun a := by
split_ifs with h <;>
· simp only [h, mem_filter, mem_support_iff]
tauto
theorem filter_apply (a : α) : f.filter p a = if p a then f a else 0 := rfl
theorem filter_eq_indicator : ⇑(f.filter p) = Set.indicator { x | p x } f := by
ext
simp [filter_apply, Set.indicator_apply]
theorem filter_eq_zero_iff : f.filter p = 0 ↔ ∀ x, p x → f x = 0 := by
simp [DFunLike.ext_iff, filter_eq_indicator]
theorem filter_eq_self_iff : f.filter p = f ↔ ∀ x, f x ≠ 0 → p x := by
simp only [DFunLike.ext_iff, filter_eq_indicator, Set.indicator_apply_eq_self, Set.mem_setOf_eq,
not_imp_comm]
@[simp]
theorem filter_apply_pos {a : α} (h : p a) : f.filter p a = f a := if_pos h
@[simp]
theorem filter_apply_neg {a : α} (h : ¬p a) : f.filter p a = 0 := if_neg h
@[simp]
theorem support_filter : (f.filter p).support = {x ∈ f.support | p x} := rfl
theorem filter_zero : (0 : α →₀ M).filter p = 0 := by
classical rw [← support_eq_empty, support_filter, support_zero, Finset.filter_empty]
@[simp]
theorem filter_single_of_pos {a : α} {b : M} (h : p a) : (single a b).filter p = single a b :=
(filter_eq_self_iff _ _).2 fun _ hx => (single_apply_ne_zero.1 hx).1.symm ▸ h
@[simp]
theorem filter_single_of_neg {a : α} {b : M} (h : ¬p a) : (single a b).filter p = 0 :=
(filter_eq_zero_iff _ _).2 fun _ hpx =>
single_apply_eq_zero.2 fun hxa => absurd hpx (hxa.symm ▸ h)
@[to_additive]
theorem prod_filter_index [CommMonoid N] (g : α → M → N) :
(f.filter p).prod g = ∏ x ∈ (f.filter p).support, g x (f x) := by
refine Finset.prod_congr rfl fun x hx => ?_
rw [support_filter, Finset.mem_filter] at hx
rw [filter_apply_pos _ _ hx.2]
@[to_additive (attr := simp)]
theorem prod_filter_mul_prod_filter_not [CommMonoid N] (g : α → M → N) :
(f.filter p).prod g * (f.filter fun a => ¬p a).prod g = f.prod g := by
simp_rw [prod_filter_index, support_filter, Finset.prod_filter_mul_prod_filter_not, Finsupp.prod]
@[to_additive (attr := simp)]
theorem prod_div_prod_filter [CommGroup G] (g : α → M → G) :
f.prod g / (f.filter p).prod g = (f.filter fun a => ¬p a).prod g :=
div_eq_of_eq_mul' (prod_filter_mul_prod_filter_not _ _ _).symm
end Zero
theorem filter_pos_add_filter_neg [AddZeroClass M] (f : α →₀ M) (p : α → Prop) [DecidablePred p] :
(f.filter p + f.filter fun a => ¬p a) = f :=
DFunLike.coe_injective <| by
simp only [coe_add, filter_eq_indicator]
exact Set.indicator_self_add_compl { x | p x } f
end Filter
/-! ### Declarations about `frange` -/
section Frange
variable [Zero M]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ M) : Finset M :=
haveI := Classical.decEq M
Finset.image f f.support
theorem mem_frange {f : α →₀ M} {y : M} : y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y := by
rw [frange, @Finset.mem_image _ _ (Classical.decEq _) _ f.support]
exact ⟨fun ⟨x, hx1, hx2⟩ => ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩, fun ⟨hy, x, hx⟩ =>
⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_notMem_frange {f : α →₀ M} : (0 : M) ∉ f.frange := fun H => (mem_frange.1 H).1 rfl
@[deprecated (since := "2025-05-23")] alias zero_not_mem_frange := zero_notMem_frange
theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} := fun r hr =>
let ⟨t, ht1, ht2⟩ := mem_frange.1 hr
ht2 ▸ by
classical
rw [single_apply] at ht2 ⊢
split_ifs at ht2 ⊢
· exact Finset.mem_singleton_self _
· exact (t ht2.symm).elim
end Frange
/-! ### Declarations about `Finsupp.subtypeDomain` -/
section SubtypeDomain
section Zero
variable [Zero M] {p : α → Prop}
/--
`subtypeDomain p f` is the restriction of the finitely supported function `f` to subtype `p`. -/
def subtypeDomain (p : α → Prop) (f : α →₀ M) : Subtype p →₀ M where
support :=
haveI := Classical.decPred p
f.support.subtype p
toFun := f ∘ Subtype.val
mem_support_toFun a := by simp only [@mem_subtype _ _ (Classical.decPred p), mem_support_iff]; rfl
@[simp]
theorem support_subtypeDomain [D : DecidablePred p] {f : α →₀ M} :
(subtypeDomain p f).support = f.support.subtype p := by rw [Subsingleton.elim D] <;> rfl
@[simp]
theorem subtypeDomain_apply {a : Subtype p} {v : α →₀ M} : (subtypeDomain p v) a = v a.val :=
rfl
@[simp]
theorem subtypeDomain_zero : subtypeDomain p (0 : α →₀ M) = 0 :=
rfl
theorem subtypeDomain_eq_iff_forall {f g : α →₀ M} :
f.subtypeDomain p = g.subtypeDomain p ↔ ∀ x, p x → f x = g x := by
simp_rw [DFunLike.ext_iff, subtypeDomain_apply, Subtype.forall]
theorem subtypeDomain_eq_iff {f g : α →₀ M}
(hf : ∀ x ∈ f.support, p x) (hg : ∀ x ∈ g.support, p x) :
f.subtypeDomain p = g.subtypeDomain p ↔ f = g :=
subtypeDomain_eq_iff_forall.trans
⟨fun H ↦ Finsupp.ext fun _a ↦ (em _).elim (H _ <| hf _ ·) fun haf ↦ (em _).elim (H _ <| hg _ ·)
fun hag ↦ (notMem_support_iff.mp haf).trans (notMem_support_iff.mp hag).symm,
fun H _ _ ↦ congr($H _)⟩
theorem subtypeDomain_eq_zero_iff' {f : α →₀ M} : f.subtypeDomain p = 0 ↔ ∀ x, p x → f x = 0 :=
subtypeDomain_eq_iff_forall (g := 0)
theorem subtypeDomain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support, p x) :
f.subtypeDomain p = 0 ↔ f = 0 :=
subtypeDomain_eq_iff (g := 0) hf (by simp)
@[to_additive]
theorem prod_subtypeDomain_index [CommMonoid N] {v : α →₀ M} {h : α → M → N}
(hp : ∀ x ∈ v.support, p x) : (v.subtypeDomain p).prod (fun a b ↦ h a b) = v.prod h := by
refine Finset.prod_bij (fun p _ ↦ p) ?_ ?_ ?_ ?_ <;> aesop
end Zero
section AddZeroClass
variable [AddZeroClass M] {p : α → Prop} {v v' : α →₀ M}
@[simp]
theorem subtypeDomain_add {v v' : α →₀ M} :
(v + v').subtypeDomain p = v.subtypeDomain p + v'.subtypeDomain p :=
ext fun _ => rfl
/-- `subtypeDomain` but as an `AddMonoidHom`. -/
def subtypeDomainAddMonoidHom : (α →₀ M) →+ Subtype p →₀ M where
toFun := subtypeDomain p
map_zero' := subtypeDomain_zero
map_add' _ _ := subtypeDomain_add
/-- `Finsupp.filter` as an `AddMonoidHom`. -/
def filterAddHom (p : α → Prop) [DecidablePred p] : (α →₀ M) →+ α →₀ M where
toFun := filter p
map_zero' := filter_zero p
map_add' f g := DFunLike.coe_injective <| by
simp_rw [coe_add, filter_eq_indicator]
exact Set.indicator_add { x | p x } f g
@[simp]
theorem filter_add [DecidablePred p] {v v' : α →₀ M} :
(v + v').filter p = v.filter p + v'.filter p :=
(filterAddHom p).map_add v v'
end AddZeroClass
section CommMonoid
variable [AddCommMonoid M] {p : α → Prop}
theorem subtypeDomain_sum {s : Finset ι} {h : ι → α →₀ M} :
(∑ c ∈ s, h c).subtypeDomain p = ∑ c ∈ s, (h c).subtypeDomain p :=
map_sum subtypeDomainAddMonoidHom _ s
theorem subtypeDomain_finsupp_sum [Zero N] {s : β →₀ N} {h : β → N → α →₀ M} :
(s.sum h).subtypeDomain p = s.sum fun c d => (h c d).subtypeDomain p :=
subtypeDomain_sum
theorem filter_sum [DecidablePred p] (s : Finset ι) (f : ι → α →₀ M) :
(∑ a ∈ s, f a).filter p = ∑ a ∈ s, filter p (f a) :=
map_sum (filterAddHom p) f s
theorem filter_eq_sum (p : α → Prop) [DecidablePred p] (f : α →₀ M) :
f.filter p = ∑ i ∈ f.support.filter p, single i (f i) :=
(f.filter p).sum_single.symm.trans <|
Finset.sum_congr rfl fun x hx => by
rw [filter_apply_pos _ _ (mem_filter.1 hx).2]
end CommMonoid
section Group
variable [AddGroup G] {p : α → Prop} {v v' : α →₀ G}
@[simp]
theorem subtypeDomain_neg : (-v).subtypeDomain p = -v.subtypeDomain p :=
ext fun _ => rfl
@[simp]
theorem subtypeDomain_sub : (v - v').subtypeDomain p = v.subtypeDomain p - v'.subtypeDomain p :=
ext fun _ => rfl
@[simp]
theorem filter_neg (p : α → Prop) [DecidablePred p] (f : α →₀ G) : filter p (-f) = -filter p f :=
(filterAddHom p : (_ →₀ G) →+ _).map_neg f
@[simp]
theorem filter_sub (p : α → Prop) [DecidablePred p] (f₁ f₂ : α →₀ G) :
filter p (f₁ - f₂) = filter p f₁ - filter p f₂ :=
(filterAddHom p : (_ →₀ G) →+ _).map_sub f₁ f₂
end Group
end SubtypeDomain
theorem mem_support_multiset_sum [AddCommMonoid M] {s : Multiset (α →₀ M)} (a : α) :
a ∈ s.sum.support → ∃ f ∈ s, a ∈ (f : α →₀ M).support :=
Multiset.induction_on s (fun h => False.elim (by simp at h))
(by
intro f s ih ha
by_cases h : a ∈ f.support
· exact ⟨f, Multiset.mem_cons_self _ _, h⟩
· simp_rw [Multiset.sum_cons, mem_support_iff, add_apply, notMem_support_iff.1 h,
zero_add] at ha
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩
exact ⟨f', Multiset.mem_cons_of_mem h₀, h₁⟩)
theorem mem_support_finset_sum [AddCommMonoid M] {s : Finset ι} {h : ι → α →₀ M} (a : α)
(ha : a ∈ (∑ c ∈ s, h c).support) : ∃ c ∈ s, a ∈ (h c).support :=
let ⟨_, hf, hfa⟩ := mem_support_multiset_sum a ha
let ⟨c, hc, Eq⟩ := Multiset.mem_map.1 hf
⟨c, hc, Eq.symm ▸ hfa⟩
/-! ### Declarations about `curry` and `uncurry` -/
section Uncurry
variable [Zero M]
/-- Given a finitely supported function `f` from `α` to the type of
finitely supported functions from `β` to `M`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/
protected def uncurry (f : α →₀ β →₀ M) : α × β →₀ M where
toFun x := f x.1 x.2
support := f.support.disjiUnion (fun a ↦ (f a).support.map <| .sectR a _) <| by
intro a₁ _ a₂ _ hne
simp [Finset.disjoint_iff_ne, hne]
mem_support_toFun := by aesop
protected theorem uncurry_apply (f : α →₀ β →₀ M) (x : α × β) : f.uncurry x = f x.1 x.2 := rfl
@[simp]
protected theorem uncurry_apply_pair (f : α →₀ β →₀ M) (a : α) (b : β) :
f.uncurry (a, b) = f a b :=
rfl
@[simp]
lemma uncurry_single (a : α) (b : β) (m : M) :
(single a (single b m)).uncurry = single (a, b) m := by
ext ⟨x, y⟩
rcases eq_or_ne a x with rfl | hne <;> classical simp [single_apply, *]
theorem sum_uncurry_index [AddCommMonoid N] (f : α →₀ β →₀ M) (g : α × β → M → N) :
f.uncurry.sum (fun p c => g p c) = f.sum fun a f => f.sum fun b ↦ g (a, b) := by
simp [Finsupp.sum, Finsupp.uncurry, Finset.sum_disjiUnion]
theorem sum_uncurry_index' [AddCommMonoid N] (f : α →₀ β →₀ M) (g : α → β → M → N) :
f.uncurry.sum (fun p c => g p.1 p.2 c) = f.sum fun a f => f.sum (g a) :=
sum_uncurry_index ..
end Uncurry
section Curry
variable [DecidableEq α] [Zero M]
/-- Given a finitely supported function `f` from a product type `α × β` to `γ`,
`curry f` is the "curried" finitely supported function from `α` to the type of
finitely supported functions from `β` to `γ`. -/
protected def curry (f : α × β →₀ M) : α →₀ β →₀ M where
toFun a :=
{ toFun b := f (a, b)
support := f.support.filterMap (fun x ↦ if x.1 = a then x.2 else none) <| by simp +contextual
mem_support_toFun := by simp }
support := f.support.image Prod.fst
mem_support_toFun := by simp [DFunLike.ext_iff]
@[simp]
theorem curry_apply (f : α × β →₀ M) (x : α) (y : β) : f.curry x y = f (x, y) := rfl
@[simp]
theorem support_curry (f : α × β →₀ M) : f.curry.support = f.support.image Prod.fst :=
rfl
@[simp]
theorem curry_uncurry (f : α →₀ β →₀ M) : f.uncurry.curry = f := by
ext a b
simp
@[simp]
theorem uncurry_curry (f : α × β →₀ M) : f.curry.uncurry = f := by
ext ⟨a, b⟩
simp
@[simp]
lemma curry_single (a : α × β) (m : M) :
(single a m).curry = single a.1 (single a.2 m) := by
rw [← curry_uncurry (single _ _), uncurry_single]
theorem sum_curry_index [AddCommMonoid N] (f : α × β →₀ M) (g : α → β → M → N) :
(f.curry.sum fun a f => f.sum (g a)) = f.sum fun p c => g p.1 p.2 c := by
rw [← sum_uncurry_index', uncurry_curry]
/-- `finsuppProdEquiv` defines the `Equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by
currying and uncurrying. -/
@[simps]
def finsuppProdEquiv : (α × β →₀ M) ≃ (α →₀ β →₀ M) where
toFun := Finsupp.curry
invFun := Finsupp.uncurry
left_inv := uncurry_curry
right_inv := curry_uncurry
theorem filter_curry (f : α × β →₀ M) (p : α → Prop) [DecidablePred p] :
(f.filter fun a : α × β => p a.1).curry = f.curry.filter p := by
ext a b
simp [filter_apply, apply_ite (DFunLike.coe · b)]
end Curry
/-! ### Declarations about finitely supported functions whose support is a `Sum` type -/
section Sum
/-- `Finsupp.sumElim f g` maps `inl x` to `f x` and `inr y` to `g y`. -/
@[simps support]
def sumElim {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) : α ⊕ β →₀ γ where
support := f.support.disjSum g.support
toFun := Sum.elim f g
mem_support_toFun := by simp
@[simp, norm_cast]
theorem coe_sumElim {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) :
⇑(sumElim f g) = Sum.elim f g :=
rfl
theorem sumElim_apply {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α ⊕ β) :
sumElim f g x = Sum.elim f g x :=
rfl
theorem sumElim_inl {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : α) :
sumElim f g (Sum.inl x) = f x :=
rfl
theorem sumElim_inr {α β γ : Type*} [Zero γ] (f : α →₀ γ) (g : β →₀ γ) (x : β) :
sumElim f g (Sum.inr x) = g x :=
rfl
@[to_additive]
lemma prod_sumElim {ι₁ ι₂ α M : Type*} [Zero α] [CommMonoid M]
(f₁ : ι₁ →₀ α) (f₂ : ι₂ →₀ α) (g : ι₁ ⊕ ι₂ → α → M) :
(f₁.sumElim f₂).prod g = f₁.prod (g ∘ Sum.inl) * f₂.prod (g ∘ Sum.inr) := by
simp [Finsupp.prod, Finset.prod_disjSum]
/-- The equivalence between `(α ⊕ β) →₀ γ` and `(α →₀ γ) × (β →₀ γ)`.
This is the `Finsupp` version of `Equiv.sum_arrow_equiv_prod_arrow`. -/
@[simps apply symm_apply]
def sumFinsuppEquivProdFinsupp {α β γ : Type*} [Zero γ] : (α ⊕ β →₀ γ) ≃ (α →₀ γ) × (β →₀ γ) where
toFun f :=
⟨f.comapDomain Sum.inl Sum.inl_injective.injOn,
f.comapDomain Sum.inr Sum.inr_injective.injOn⟩
invFun fg := sumElim fg.1 fg.2
left_inv f := by
ext ab
rcases ab with a | b <;> simp
right_inv fg := by ext <;> simp
theorem fst_sumFinsuppEquivProdFinsupp {α β γ : Type*} [Zero γ] (f : α ⊕ β →₀ γ) (x : α) :
(sumFinsuppEquivProdFinsupp f).1 x = f (Sum.inl x) :=
rfl
theorem snd_sumFinsuppEquivProdFinsupp {α β γ : Type*} [Zero γ] (f : α ⊕ β →₀ γ) (y : β) :
(sumFinsuppEquivProdFinsupp f).2 y = f (Sum.inr y) :=
rfl
theorem sumFinsuppEquivProdFinsupp_symm_inl {α β γ : Type*} [Zero γ] (fg : (α →₀ γ) × (β →₀ γ))
(x : α) : (sumFinsuppEquivProdFinsupp.symm fg) (Sum.inl x) = fg.1 x :=
rfl
theorem sumFinsuppEquivProdFinsupp_symm_inr {α β γ : Type*} [Zero γ] (fg : (α →₀ γ) × (β →₀ γ))
(y : β) : (sumFinsuppEquivProdFinsupp.symm fg) (Sum.inr y) = fg.2 y :=
rfl
variable [AddMonoid M]
/-- The additive equivalence between `(α ⊕ β) →₀ M` and `(α →₀ M) × (β →₀ M)`.
This is the `Finsupp` version of `Equiv.sum_arrow_equiv_prod_arrow`. -/
@[simps! apply symm_apply]
def sumFinsuppAddEquivProdFinsupp {α β : Type*} : (α ⊕ β →₀ M) ≃+ (α →₀ M) × (β →₀ M) :=
{ sumFinsuppEquivProdFinsupp with
map_add' := by
intros
ext <;>
simp only [Equiv.toFun_as_coe, Prod.fst_add, Prod.snd_add, add_apply,
snd_sumFinsuppEquivProdFinsupp, fst_sumFinsuppEquivProdFinsupp] }
theorem fst_sumFinsuppAddEquivProdFinsupp {α β : Type*} (f : α ⊕ β →₀ M) (x : α) :
(sumFinsuppAddEquivProdFinsupp f).1 x = f (Sum.inl x) :=
rfl
theorem snd_sumFinsuppAddEquivProdFinsupp {α β : Type*} (f : α ⊕ β →₀ M) (y : β) :
(sumFinsuppAddEquivProdFinsupp f).2 y = f (Sum.inr y) :=
rfl
theorem sumFinsuppAddEquivProdFinsupp_symm_inl {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (x : α) :
(sumFinsuppAddEquivProdFinsupp.symm fg) (Sum.inl x) = fg.1 x :=
rfl
theorem sumFinsuppAddEquivProdFinsupp_symm_inr {α β : Type*} (fg : (α →₀ M) × (β →₀ M)) (y : β) :
(sumFinsuppAddEquivProdFinsupp.symm fg) (Sum.inr y) = fg.2 y :=
rfl
end Sum
section
variable [Zero R]
/-- The `Finsupp` version of `Pi.unique`. -/
instance uniqueOfRight [Subsingleton R] : Unique (α →₀ R) :=
DFunLike.coe_injective.unique
/-- The `Finsupp` version of `Pi.uniqueOfIsEmpty`. -/
instance uniqueOfLeft [IsEmpty α] : Unique (α →₀ R) :=
DFunLike.coe_injective.unique
end
section
variable {M : Type*} [Zero M] {P : α → Prop} [DecidablePred P]
/-- Combine finitely supported functions over `{a // P a}` and `{a // ¬P a}`, by case-splitting on
`P a`. -/
@[simps]
def piecewise (f : Subtype P →₀ M) (g : {a // ¬ P a} →₀ M) : α →₀ M where
toFun a := if h : P a then f ⟨a, h⟩ else g ⟨a, h⟩
support := (f.support.map (.subtype _)).disjUnion (g.support.map (.subtype _)) <| by
simp_rw [Finset.disjoint_left, mem_map, forall_exists_index, Embedding.coe_subtype,
Subtype.forall, Subtype.exists]
rintro _ a ha ⟨-, rfl⟩ ⟨b, hb, -, rfl⟩
exact hb ha
mem_support_toFun a := by
by_cases ha : P a <;> simp [ha]
@[simp]
theorem subtypeDomain_piecewise (f : Subtype P →₀ M) (g : {a // ¬ P a} →₀ M) :
subtypeDomain P (f.piecewise g) = f :=
Finsupp.ext fun a => dif_pos a.prop
@[simp]
theorem subtypeDomain_not_piecewise (f : Subtype P →₀ M) (g : {a // ¬ P a} →₀ M) :
subtypeDomain (¬P ·) (f.piecewise g) = g :=
Finsupp.ext fun a => dif_neg a.prop
/-- Extend the domain of a `Finsupp` by using `0` where `P x` does not hold. -/
@[simps! support toFun]
def extendDomain (f : Subtype P →₀ M) : α →₀ M := piecewise f 0
theorem extendDomain_eq_embDomain_subtype (f : Subtype P →₀ M) :
extendDomain f = embDomain (.subtype _) f := by
ext a
by_cases h : P a
· refine Eq.trans ?_ (embDomain_apply (.subtype P) f (Subtype.mk a h)).symm
simp [h]
· rw [embDomain_notin_range, extendDomain_toFun, dif_neg h]
simp [h]
theorem support_extendDomain_subset (f : Subtype P →₀ M) :
↑(f.extendDomain).support ⊆ {x | P x} := by
intro x
rw [extendDomain_support, mem_coe, mem_map, Embedding.coe_subtype]
rintro ⟨x, -, rfl⟩
exact x.prop
@[simp]
theorem subtypeDomain_extendDomain (f : Subtype P →₀ M) :
subtypeDomain P f.extendDomain = f :=
subtypeDomain_piecewise _ _
theorem extendDomain_subtypeDomain (f : α →₀ M) (hf : ∀ a ∈ f.support, P a) :
(subtypeDomain P f).extendDomain = f := by
ext a
by_cases h : P a
· exact dif_pos h
· dsimp [extendDomain_toFun]
rw [if_neg h, eq_comm, ← notMem_support_iff]
refine mt ?_ h
exact hf _
@[simp]
theorem extendDomain_single (a : Subtype P) (m : M) :
(single a m).extendDomain = single a.val m := by
ext a'
dsimp only [extendDomain_toFun]
obtain rfl | ha := eq_or_ne a' a.val
· simp_rw [single_eq_same, dif_pos a.prop]
· simp_rw [single_eq_of_ne ha, dite_eq_right_iff]
intro h
rw [single_eq_of_ne]
simp [Subtype.ext_iff, ha]
end
/-- Given an `AddCommMonoid M` and `s : Set α`, `restrictSupportEquiv s M` is the `Equiv`
between the subtype of finitely supported functions with support contained in `s` and
the type of finitely supported functions from `s`. -/
-- TODO: add [DecidablePred (· ∈ s)] as an assumption
@[simps apply] def restrictSupportEquiv (s : Set α) (M : Type*) [AddCommMonoid M] :
{ f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M) where
toFun f := subtypeDomain (· ∈ s) f.1
invFun f := letI := Classical.decPred (· ∈ s); ⟨f.extendDomain, support_extendDomain_subset _⟩
left_inv f :=
letI := Classical.decPred (· ∈ s); Subtype.ext <| extendDomain_subtypeDomain f.1 f.prop
right_inv _ := letI := Classical.decPred (· ∈ s); subtypeDomain_extendDomain _
@[simp] lemma restrictSupportEquiv_symm_apply_coe (s : Set α) (M : Type*) [AddCommMonoid M]
[DecidablePred (· ∈ s)] (f : s →₀ M) :
(restrictSupportEquiv s M).symm f = f.extendDomain := by
rw [restrictSupportEquiv, Equiv.coe_fn_symm_mk, Subtype.coe_mk]; congr
@[simp] lemma restrictSupportEquiv_symm_single (s : Set α) (M : Type*) [AddCommMonoid M]
(a : s) (x : M) :
(restrictSupportEquiv s M).symm (single a x) = single (a : α) x := by
classical simp
/-- Given `AddCommMonoid M` and `e : α ≃ β`, `domCongr e` is the corresponding `Equiv` between
`α →₀ M` and `β →₀ M`.
This is `Finsupp.equivCongrLeft` as an `AddEquiv`. -/
@[simps apply]
protected def domCongr [AddCommMonoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) where
toFun := equivMapDomain e
invFun := equivMapDomain e.symm
left_inv v := by
simp_rw [← equivMapDomain_trans, Equiv.self_trans_symm]
exact equivMapDomain_refl _
right_inv := by
intro v
simp_rw [← equivMapDomain_trans, Equiv.symm_trans_self]
exact equivMapDomain_refl _
map_add' a b := by simp only [equivMapDomain_eq_mapDomain, mapDomain_add]
@[simp]
theorem domCongr_refl [AddCommMonoid M] :
Finsupp.domCongr (Equiv.refl α) = AddEquiv.refl (α →₀ M) :=
AddEquiv.ext fun _ => equivMapDomain_refl _
@[simp]
theorem domCongr_symm [AddCommMonoid M] (e : α ≃ β) :
(Finsupp.domCongr e).symm = (Finsupp.domCongr e.symm : (β →₀ M) ≃+ (α →₀ M)) :=
AddEquiv.ext fun _ => rfl
@[simp]
theorem domCongr_trans [AddCommMonoid M] (e : α ≃ β) (f : β ≃ γ) :
(Finsupp.domCongr e).trans (Finsupp.domCongr f) =
(Finsupp.domCongr (e.trans f) : (α →₀ M) ≃+ _) :=
AddEquiv.ext fun _ => (equivMapDomain_trans _ _ _).symm
end Finsupp
namespace Finsupp
/-! ### Declarations about sigma types -/
section Sigma
variable {αs : ι → Type*} [Zero M] (l : (Σ i, αs i) →₀ M)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `M`.
This is the `Finsupp` version of `Sigma.curry`.
-/
def split (i : ι) : αs i →₀ M :=
l.comapDomain (Sigma.mk i) fun _ _ _ _ hx => heq_iff_eq.1 (Sigma.mk.inj hx).2
theorem split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ := by
rw [split, comapDomain_apply]
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`,
`split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/
def splitSupport (l : (Σ i, αs i) →₀ M) : Finset ι :=
haveI := Classical.decEq ι
l.support.image Sigma.fst
theorem mem_splitSupport_iff_nonzero (i : ι) : i ∈ splitSupport l ↔ split l i ≠ 0 := by
classical rw [splitSupport, mem_image, Ne, ← support_eq_empty, ← Ne,
← Finset.nonempty_iff_ne_empty, split, comapDomain, Finset.Nonempty]
simp only [Finset.mem_preimage, exists_and_right, exists_eq_right, mem_support_iff,
Sigma.exists, Ne]
/-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and
an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a
finitely supported function from the index type `ι` to `γ` given by composing `g i` with
`split l i`. -/
def splitComp [Zero N] (g : ∀ i, (αs i →₀ M) → N) (hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N where
support := splitSupport l
toFun i := g i (split l i)
mem_support_toFun := by
intro i
rw [mem_splitSupport_iff_nonzero, not_iff_not, hg]
theorem sigma_support : l.support = l.splitSupport.sigma fun i => (l.split i).support := by
simp_rw [Finset.ext_iff, splitSupport, split, comapDomain, Sigma.forall, mem_sigma, mem_image,
mem_preimage]
tauto
theorem sigma_sum [AddCommMonoid N] (f : (Σ i : ι, αs i) → M → N) :
l.sum f = ∑ i ∈ splitSupport l, (split l i).sum fun (a : αs i) b => f ⟨i, a⟩ b := by
simp only [sum, sigma_support, sum_sigma, split_apply]
variable {η : Type*} [Fintype η] {ιs : η → Type*} [Zero α]
/-- On a `Fintype η`, `Finsupp.split` is an equivalence between `(Σ (j : η), ιs j) →₀ α`
and `Π j, (ιs j →₀ α)`.
This is the `Finsupp` version of `Equiv.Pi_curry`. -/
noncomputable def sigmaFinsuppEquivPiFinsupp : ((Σ j, ιs j) →₀ α) ≃ ∀ j, ιs j →₀ α where
toFun := split
invFun f :=
onFinset (Finset.univ.sigma fun j => (f j).support) (fun ji => f ji.1 ji.2) fun _ hg =>
Finset.mem_sigma.mpr ⟨Finset.mem_univ _, mem_support_iff.mpr hg⟩
left_inv f := by
ext
simp [split]
right_inv f := by
ext
simp [split]
@[simp]
theorem sigmaFinsuppEquivPiFinsupp_apply (f : (Σ j, ιs j) →₀ α) (j i) :
sigmaFinsuppEquivPiFinsupp f j i = f ⟨j, i⟩ :=
rfl
/-- On a `Fintype η`, `Finsupp.split` is an additive equivalence between
`(Σ (j : η), ιs j) →₀ α` and `Π j, (ιs j →₀ α)`.
This is the `AddEquiv` version of `Finsupp.sigmaFinsuppEquivPiFinsupp`.
-/
noncomputable def sigmaFinsuppAddEquivPiFinsupp {α : Type*} {ιs : η → Type*} [AddMonoid α] :
((Σ j, ιs j) →₀ α) ≃+ ∀ j, ιs j →₀ α :=
{ sigmaFinsuppEquivPiFinsupp with
map_add' := fun f g => by
ext
simp }
@[simp]
theorem sigmaFinsuppAddEquivPiFinsupp_apply {α : Type*} {ιs : η → Type*} [AddMonoid α]
(f : (Σ j, ιs j) →₀ α) (j i) : sigmaFinsuppAddEquivPiFinsupp f j i = f ⟨j, i⟩ :=
rfl
end Sigma
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Multiset.lean | import Mathlib.Algebra.Order.Group.Finset
import Mathlib.Data.Finsupp.Basic
import Mathlib.Data.Sym.Basic
import Mathlib.Order.Preorder.Finsupp
/-!
# Equivalence between `Multiset` and `ℕ`-valued finitely supported functions
This defines `Finsupp.toMultiset` the equivalence between `α →₀ ℕ` and `Multiset α`, along
with `Multiset.toFinsupp` the reverse equivalence and `Finsupp.orderIsoMultiset` (the equivalence
promoted to an order isomorphism).
-/
open Finset
variable {α β ι : Type*}
namespace Finsupp
/-- Given `f : α →₀ ℕ`, `f.toMultiset` is the multiset with multiplicities given by the values of
`f` on the elements of `α`. We define this function as an `AddMonoidHom`.
Under the additional assumption of `[DecidableEq α]`, this is available as
`Multiset.toFinsupp : Multiset α ≃+ (α →₀ ℕ)`; the two declarations are separate as this assumption
is only needed for one direction. -/
def toMultiset : (α →₀ ℕ) →+ Multiset α where
toFun f := Finsupp.sum f fun a n => n • {a}
-- Porting note: have to specify `h` or add a `dsimp only` before `sum_add_index'`.
-- see also: https://github.com/leanprover-community/mathlib4/issues/12129
map_add' _f _g := sum_add_index' (h := fun _ n => n • _)
(fun _ ↦ zero_nsmul _) (fun _ ↦ add_nsmul _)
map_zero' := sum_zero_index
theorem toMultiset_zero : toMultiset (0 : α →₀ ℕ) = 0 :=
rfl
theorem toMultiset_add (m n : α →₀ ℕ) : toMultiset (m + n) = toMultiset m + toMultiset n :=
toMultiset.map_add m n
theorem toMultiset_apply (f : α →₀ ℕ) : toMultiset f = f.sum fun a n => n • {a} :=
rfl
@[simp]
theorem toMultiset_single (a : α) (n : ℕ) : toMultiset (single a n) = n • {a} := by
rw [toMultiset_apply, sum_single_index]; apply zero_nsmul
theorem toMultiset_sum {f : ι → α →₀ ℕ} (s : Finset ι) :
Finsupp.toMultiset (∑ i ∈ s, f i) = ∑ i ∈ s, Finsupp.toMultiset (f i) :=
map_sum Finsupp.toMultiset _ _
theorem toMultiset_sum_single (s : Finset ι) (n : ℕ) :
Finsupp.toMultiset (∑ i ∈ s, single i n) = n • s.val := by
simp_rw [toMultiset_sum, Finsupp.toMultiset_single, Finset.sum_nsmul, sum_multiset_singleton]
@[simp]
theorem card_toMultiset (f : α →₀ ℕ) : Multiset.card (toMultiset f) = f.sum fun _ => id := by
simp [toMultiset_apply, Function.id_def]
theorem toMultiset_map (f : α →₀ ℕ) (g : α → β) :
f.toMultiset.map g = toMultiset (f.mapDomain g) := by
refine f.induction ?_ ?_
· rw [toMultiset_zero, Multiset.map_zero, mapDomain_zero, toMultiset_zero]
· intro a n f _ _ ih
rw [toMultiset_add, Multiset.map_add, ih, mapDomain_add, mapDomain_single,
toMultiset_single, toMultiset_add, toMultiset_single, ← Multiset.coe_mapAddMonoidHom,
(Multiset.mapAddMonoidHom g).map_nsmul]
rfl
@[to_additive (attr := simp)]
theorem prod_toMultiset [CommMonoid α] (f : α →₀ ℕ) :
f.toMultiset.prod = f.prod fun a n => a ^ n := by
refine f.induction ?_ ?_
· rw [toMultiset_zero, Multiset.prod_zero, Finsupp.prod_zero_index]
· intro a n f _ _ ih
rw [toMultiset_add, Multiset.prod_add, ih, toMultiset_single, Multiset.prod_nsmul,
Finsupp.prod_add_index' pow_zero pow_add, Finsupp.prod_single_index, Multiset.prod_singleton]
exact pow_zero a
@[simp]
theorem toFinset_toMultiset [DecidableEq α] (f : α →₀ ℕ) : f.toMultiset.toFinset = f.support := by
refine f.induction ?_ ?_
· rw [toMultiset_zero, Multiset.toFinset_zero, support_zero]
· intro a n f ha hn ih
rw [toMultiset_add, Multiset.toFinset_add, ih, toMultiset_single, support_add_eq,
support_single_ne_zero _ hn, Multiset.toFinset_nsmul _ _ hn, Multiset.toFinset_singleton]
refine Disjoint.mono_left support_single_subset ?_
rwa [Finset.disjoint_singleton_left]
@[simp]
theorem count_toMultiset [DecidableEq α] (f : α →₀ ℕ) (a : α) : (toMultiset f).count a = f a :=
calc
(toMultiset f).count a = Finsupp.sum f (fun x n => (n • {x} : Multiset α).count a) := by
rw [toMultiset_apply]; exact map_sum (Multiset.countAddMonoidHom a) _ f.support
_ = f.sum fun x n => n * ({x} : Multiset α).count a := by simp only [Multiset.count_nsmul]
_ = f a * ({a} : Multiset α).count a :=
sum_eq_single _
(fun a' _ H => by simp only [Multiset.count_singleton, if_false, H.symm, mul_zero])
(fun _ => zero_mul _)
_ = f a := by rw [Multiset.count_singleton_self, mul_one]
theorem toMultiset_sup [DecidableEq α] (f g : α →₀ ℕ) :
toMultiset (f ⊔ g) = toMultiset f ∪ toMultiset g := by
ext
simp_rw [Multiset.count_union, Finsupp.count_toMultiset, Finsupp.sup_apply]
theorem toMultiset_inf [DecidableEq α] (f g : α →₀ ℕ) :
toMultiset (f ⊓ g) = toMultiset f ∩ toMultiset g := by
ext
simp_rw [Multiset.count_inter, Finsupp.count_toMultiset, Finsupp.inf_apply]
@[simp]
theorem mem_toMultiset (f : α →₀ ℕ) (i : α) : i ∈ toMultiset f ↔ i ∈ f.support := by
classical
rw [← Multiset.count_ne_zero, Finsupp.count_toMultiset, Finsupp.mem_support_iff]
end Finsupp
namespace Multiset
variable [DecidableEq α]
/-- Given a multiset `s`, `s.toFinsupp` returns the finitely supported function on `ℕ` given by
the multiplicities of the elements of `s`. -/
@[simps symm_apply]
def toFinsupp : Multiset α ≃+ (α →₀ ℕ) where
toFun s := ⟨s.toFinset, fun a => s.count a, fun a => by simp⟩
invFun f := Finsupp.toMultiset f
map_add' _ _ := Finsupp.ext fun _ => count_add _ _ _
right_inv f :=
Finsupp.ext fun a => by
simp only [Finsupp.toMultiset_apply, Finsupp.sum, Multiset.count_sum',
Multiset.count_singleton, mul_boole, Finsupp.coe_mk, Finsupp.mem_support_iff,
Multiset.count_nsmul, Finset.sum_ite_eq, ite_not, ite_eq_right_iff]
exact Eq.symm
left_inv s := by simp only [Finsupp.toMultiset_apply, Finsupp.sum, Finsupp.coe_mk,
Multiset.toFinset_sum_count_nsmul_eq]
@[simp]
theorem toFinsupp_support (s : Multiset α) : s.toFinsupp.support = s.toFinset := rfl
@[simp]
theorem toFinsupp_apply (s : Multiset α) (a : α) : toFinsupp s a = s.count a := rfl
theorem toFinsupp_zero : toFinsupp (0 : Multiset α) = 0 := _root_.map_zero _
theorem toFinsupp_add (s t : Multiset α) : toFinsupp (s + t) = toFinsupp s + toFinsupp t :=
_root_.map_add toFinsupp s t
@[simp]
theorem toFinsupp_singleton (a : α) : toFinsupp ({a} : Multiset α) = Finsupp.single a 1 := by
ext; rw [toFinsupp_apply, count_singleton, Finsupp.single_eq_pi_single, Pi.single_apply]
@[simp]
theorem toFinsupp_toMultiset (s : Multiset α) : Finsupp.toMultiset (toFinsupp s) = s :=
Multiset.toFinsupp.symm_apply_apply s
theorem toFinsupp_eq_iff {s : Multiset α} {f : α →₀ ℕ} :
toFinsupp s = f ↔ s = Finsupp.toMultiset f :=
Multiset.toFinsupp.apply_eq_iff_symm_apply
theorem toFinsupp_union (s t : Multiset α) : toFinsupp (s ∪ t) = toFinsupp s ⊔ toFinsupp t := by
ext
simp
theorem toFinsupp_inter (s t : Multiset α) : toFinsupp (s ∩ t) = toFinsupp s ⊓ toFinsupp t := by
ext
simp
@[simp]
theorem toFinsupp_sum_eq (s : Multiset α) : s.toFinsupp.sum (fun _ ↦ id) = Multiset.card s := by
rw [← Finsupp.card_toMultiset, toFinsupp_toMultiset]
end Multiset
@[simp]
theorem Finsupp.toMultiset_toFinsupp [DecidableEq α] (f : α →₀ ℕ) :
Multiset.toFinsupp (Finsupp.toMultiset f) = f :=
Multiset.toFinsupp.apply_symm_apply _
theorem Finsupp.toMultiset_eq_iff [DecidableEq α] {f : α →₀ ℕ} {s : Multiset α} :
Finsupp.toMultiset f = s ↔ f = Multiset.toFinsupp s :=
Multiset.toFinsupp.symm_apply_eq
/-! ### As an order isomorphism -/
namespace Finsupp
/-- `Finsupp.toMultiset` as an order isomorphism. -/
def orderIsoMultiset [DecidableEq ι] : (ι →₀ ℕ) ≃o Multiset ι where
toEquiv := Multiset.toFinsupp.symm.toEquiv
map_rel_iff' {f g} := by simp [le_def, Multiset.le_iff_count]
@[simp]
theorem coe_orderIsoMultiset [DecidableEq ι] : ⇑(@orderIsoMultiset ι _) = toMultiset :=
rfl
@[simp]
theorem coe_orderIsoMultiset_symm [DecidableEq ι] :
⇑(@orderIsoMultiset ι).symm = Multiset.toFinsupp :=
rfl
theorem toMultiset_strictMono : StrictMono (@toMultiset ι) := by
classical exact (@orderIsoMultiset ι _).strictMono
theorem sum_id_lt_of_lt (m n : ι →₀ ℕ) (h : m < n) : (m.sum fun _ => id) < n.sum fun _ => id := by
rw [← card_toMultiset, ← card_toMultiset]
apply Multiset.card_lt_card
exact toMultiset_strictMono h
variable (ι)
/-- The order on `ι →₀ ℕ` is well-founded. -/
theorem lt_wf : WellFounded (@LT.lt (ι →₀ ℕ) _) :=
Subrelation.wf (sum_id_lt_of_lt _ _) <| InvImage.wf _ Nat.lt_wfRel.2
-- TODO: generalize to `[WellFoundedRelation α] → WellFoundedRelation (ι →₀ α)`
instance : WellFoundedRelation (ι →₀ ℕ) where
rel := (· < ·)
wf := lt_wf _
end Finsupp
theorem Multiset.toFinsupp_strictMono [DecidableEq ι] : StrictMono (@Multiset.toFinsupp ι _) :=
(@Finsupp.orderIsoMultiset ι).symm.strictMono
namespace Sym
variable (α)
variable [DecidableEq α] (n : ℕ)
/-- The `n`th symmetric power of a type `α` is naturally equivalent to the subtype of
finitely-supported maps `α →₀ ℕ` with total mass `n`.
See also `Sym.equivNatSumOfFintype` when `α` is finite. -/
def equivNatSum :
Sym α n ≃ {P : α →₀ ℕ // P.sum (fun _ ↦ id) = n} :=
Multiset.toFinsupp.toEquiv.subtypeEquiv <| by simp
@[simp] lemma coe_equivNatSum_apply_apply (s : Sym α n) (a : α) :
(equivNatSum α n s : α →₀ ℕ) a = (s : Multiset α).count a :=
rfl
@[simp] lemma coe_equivNatSum_symm_apply (P : {P : α →₀ ℕ // P.sum (fun _ ↦ id) = n}) :
((equivNatSum α n).symm P : Multiset α) = Finsupp.toMultiset P :=
rfl
/-- The `n`th symmetric power of a finite type `α` is naturally equivalent to the subtype of maps
`α → ℕ` with total mass `n`.
See also `Sym.equivNatSum` when `α` is not necessarily finite. -/
noncomputable def equivNatSumOfFintype [Fintype α] :
Sym α n ≃ {P : α → ℕ // ∑ i, P i = n} :=
(equivNatSum α n).trans <| Finsupp.equivFunOnFinite.subtypeEquiv <| by simp [Finsupp.sum_fintype]
@[simp] lemma coe_equivNatSumOfFintype_apply_apply [Fintype α] (s : Sym α n) (a : α) :
(equivNatSumOfFintype α n s : α → ℕ) a = (s : Multiset α).count a :=
rfl
@[simp] lemma coe_equivNatSumOfFintype_symm_apply [Fintype α] (P : {P : α → ℕ // ∑ i, P i = n}) :
((equivNatSumOfFintype α n).symm P : Multiset α) = ∑ a, ((P : α → ℕ) a) • {a} := by
obtain ⟨P, hP⟩ := P
change Finsupp.toMultiset (Finsupp.equivFunOnFinite.symm P) = Multiset.sum _
ext a
rw [Multiset.count_sum]
simp [Multiset.count_singleton]
end Sym |
.lake/packages/mathlib/Mathlib/Data/Finsupp/PWO.lean | import Mathlib.Order.Preorder.Finsupp
import Mathlib.Order.WellFoundedSet
/-!
# Partial well ordering on finsupps
This file contains the fact that finitely supported functions from a fintype are
partially well-ordered when the codomain is a linear order that is well ordered.
It is in a separate file for now so as to not add imports to the file `Order.WellFoundedSet`.
## Main statements
* `Finsupp.isPWO` - finitely supported functions from a fintype are partially well-ordered when
the codomain is a linear order that is well ordered
## Tags
Dickson, order, partial well order
-/
/-- A version of **Dickson's lemma** any subset of functions `σ →₀ α` is partially well
ordered, when `σ` is `Finite` and `α` is a linear well order.
This version uses finsupps on a finite type as it is intended for use with `MVPowerSeries`.
-/
theorem Finsupp.isPWO {α σ : Type*} [Zero α] [LinearOrder α] [WellFoundedLT α] [Finite σ]
(S : Set (σ →₀ α)) : S.IsPWO :=
Finsupp.equivFunOnFinite.symm_image_image S ▸
Set.PartiallyWellOrderedOn.image_of_monotone_on (Pi.isPWO _) fun _a _b _ha _hb => id |
.lake/packages/mathlib/Mathlib/Data/Finsupp/WellFounded.lean | import Mathlib.Data.DFinsupp.WellFounded
import Mathlib.Data.Finsupp.Lex
/-!
# Well-foundedness of the lexicographic and product orders on `Finsupp`
`Finsupp.Lex.wellFounded` and the two variants that follow it essentially say that if `(· > ·)` is
a well order on `α`, `(· < ·)` is well-founded on `N`, and `0` is a bottom element in `N`, then the
lexicographic `(· < ·)` is well-founded on `α →₀ N`.
`Finsupp.Lex.wellFoundedLT_of_finite` says that if `α` is finite and equipped with a linear order
and `(· < ·)` is well-founded on `N`, then the lexicographic `(· < ·)` is well-founded on `α →₀ N`.
`Finsupp.wellFoundedLT` and `wellFoundedLT_of_finite` state the same results for the product
order `(· < ·)`, but without the ordering conditions on `α`.
All results are transferred from `DFinsupp` via `Finsupp.toDFinsupp`.
-/
variable {α N : Type*}
namespace Finsupp
variable [Zero N] {r : α → α → Prop} {s : N → N → Prop}
/-- Transferred from `DFinsupp.Lex.acc`. See the top of that file for an explanation for the
appearance of the relation `rᶜ ⊓ (≠)`. -/
theorem Lex.acc (hbot : ∀ ⦃n⦄, ¬s n 0) (hs : WellFounded s) (x : α →₀ N)
(h : ∀ a ∈ x.support, Acc (rᶜ ⊓ (· ≠ ·)) a) :
Acc (Finsupp.Lex r s) x := by
rw [lex_eq_invImage_dfinsupp_lex]
classical
refine InvImage.accessible toDFinsupp (DFinsupp.Lex.acc (fun _ => hbot) (fun _ => hs) _ ?_)
simpa only [toDFinsupp_support] using h
theorem Lex.wellFounded (hbot : ∀ ⦃n⦄, ¬s n 0) (hs : WellFounded s)
(hr : WellFounded <| rᶜ ⊓ (· ≠ ·)) : WellFounded (Finsupp.Lex r s) :=
⟨fun x => Lex.acc hbot hs x fun a _ => hr.apply a⟩
theorem Lex.wellFounded' (hbot : ∀ ⦃n⦄, ¬s n 0) (hs : WellFounded s)
[IsTrichotomous α r] (hr : WellFounded (Function.swap r)) : WellFounded (Finsupp.Lex r s) :=
(lex_eq_invImage_dfinsupp_lex r s).symm ▸
InvImage.wf _ (DFinsupp.Lex.wellFounded' (fun _ => hbot) (fun _ => hs) hr)
instance Lex.wellFoundedLT {α N} [LT α] [IsTrichotomous α (· < ·)] [hα : WellFoundedGT α]
[AddMonoid N] [PartialOrder N] [CanonicallyOrderedAdd N]
[hN : WellFoundedLT N] : WellFoundedLT (Lex (α →₀ N)) :=
⟨Lex.wellFounded' (fun n => (zero_le n).not_gt) hN.wf hα.wf⟩
variable (r)
theorem Lex.wellFounded_of_finite [IsStrictTotalOrder α r] [Finite α]
(hs : WellFounded s) : WellFounded (Finsupp.Lex r s) :=
InvImage.wf (@equivFunOnFinite α N _ _) (Pi.Lex.wellFounded r fun _ => hs)
theorem Lex.wellFoundedLT_of_finite [LinearOrder α] [Finite α] [LT N]
[hwf : WellFoundedLT N] : WellFoundedLT (Lex (α →₀ N)) :=
⟨Finsupp.Lex.wellFounded_of_finite (· < ·) hwf.1⟩
protected theorem wellFoundedLT [Preorder N] [WellFoundedLT N] (hbot : ∀ n : N, ¬n < 0) :
WellFoundedLT (α →₀ N) :=
⟨InvImage.wf toDFinsupp (DFinsupp.wellFoundedLT fun _ a => hbot a).wf⟩
instance wellFoundedLT' {N}
[AddMonoid N] [PartialOrder N] [CanonicallyOrderedAdd N] [WellFoundedLT N] :
WellFoundedLT (α →₀ N) :=
Finsupp.wellFoundedLT fun a => (zero_le a).not_gt
instance wellFoundedLT_of_finite [Finite α] [Preorder N] [WellFoundedLT N] :
WellFoundedLT (α →₀ N) :=
⟨InvImage.wf equivFunOnFinite Function.wellFoundedLT.wf⟩
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Ext.lean | import Mathlib.Algebra.Group.Finsupp
import Mathlib.Algebra.Group.Submonoid.Basic
import Mathlib.Algebra.Group.TypeTags.Hom
/-!
# Extensionality for maps on `Finsupp`
This file contains some extensionality principles for maps on `Finsupp`.
These have been moved to their own file to avoid depending on submonoids when defining `Finsupp`.
## Main results
* `Finsupp.add_closure_setOf_eq_single`: `Finsupp` is generated by all the `single`s
* `Finsupp.addHom_ext`: additive homomorphisms that are equal on each `single` are equal everywhere
-/
variable {α M N : Type*}
namespace Finsupp
variable [AddZeroClass M]
@[simp]
theorem add_closure_setOf_eq_single :
AddSubmonoid.closure { f : α →₀ M | ∃ a b, f = single a b } = ⊤ :=
top_unique fun x _hx =>
Finsupp.induction x (AddSubmonoid.zero_mem _) fun a b _f _ha _hb hf =>
AddSubmonoid.add_mem _ (AddSubmonoid.subset_closure <| ⟨a, b, rfl⟩) hf
/-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`,
then they are equal. -/
theorem addHom_ext [AddZeroClass N] ⦃f g : (α →₀ M) →+ N⦄
(H : ∀ x y, f (single x y) = g (single x y)) : f = g := by
refine AddMonoidHom.eq_of_eqOn_denseM add_closure_setOf_eq_single ?_
rintro _ ⟨x, y, rfl⟩
apply H
/-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`,
then they are equal.
We formulate this using equality of `AddMonoidHom`s so that `ext` tactic can apply a type-specific
extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to
verify `f (single a 1) = g (single a 1)`. -/
@[ext high]
theorem addHom_ext' [AddZeroClass N] ⦃f g : (α →₀ M) →+ N⦄
(H : ∀ x, f.comp (singleAddHom x) = g.comp (singleAddHom x)) : f = g :=
addHom_ext fun x => DFunLike.congr_fun (H x)
theorem mulHom_ext [MulOneClass N] ⦃f g : Multiplicative (α →₀ M) →* N⦄
(H : ∀ x y, f (Multiplicative.ofAdd <| single x y) = g (Multiplicative.ofAdd <| single x y)) :
f = g :=
MonoidHom.ext <|
DFunLike.congr_fun <| by
have := addHom_ext (f := f.toAdditiveRight) (g := g.toAdditiveRight) H
ext
rw [DFunLike.ext_iff] at this
apply this
@[ext]
theorem mulHom_ext' [MulOneClass N] {f g : Multiplicative (α →₀ M) →* N}
(H : ∀ x, f.comp (AddMonoidHom.toMultiplicative (singleAddHom x)) =
g.comp (AddMonoidHom.toMultiplicative (singleAddHom x))) :
f = g :=
mulHom_ext fun x => DFunLike.congr_fun (H x)
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Notation.lean | import Mathlib.Data.Finsupp.Single
/-!
# Notation for `Finsupp`
This file provides `fun₀ | 3 => a | 7 => b` notation for `Finsupp`, which desugars to
`Finsupp.update` and `Finsupp.single`, in the same way that `{a, b}` desugars to `insert` and
`singleton`.
-/
namespace Finsupp
open Lean Parser Term
-- A variant of `Lean.Parser.Term.matchAlts` with less line wrapping.
@[nolint docBlame] -- we do not want any doc hover on this notation.
def fun₀.matchAlts : Parser :=
leading_parser withPosition <| ppRealGroup <| many1Indent (ppSpace >> ppGroup matchAlt)
/-- `fun₀ | i => a` is notation for `Finsupp.single i a`, and with multiple match arms,
`fun₀ ... | i => a` is notation for `Finsupp.update (fun₀ ...) i a`.
As a result, if multiple match arms coincide, the last one takes precedence. -/
@[term_parser]
def fun₀ := leading_parser:maxPrec
-- Prefer `fun₀` over `λ₀` when pretty printing.
ppAllowUngrouped >> unicodeSymbol "λ₀" "fun₀" (preserveForPP := true) >> fun₀.matchAlts
namespace Internal
/-- Implementation detail for `fun₀`, used by both `Finsupp` and `DFinsupp` -/
scoped syntax:lead (name := stxSingle₀) "single₀" term:arg term:arg : term
/-- Implementation detail for `fun₀`, used by both `Finsupp` and `DFinsupp` -/
scoped syntax:lead (name := stxUpdate₀) "update₀" term:arg term:arg term:arg : term
/-- `Finsupp` elaborator for `single₀`. -/
@[term_elab stxSingle₀]
def elabSingle₀ : Elab.Term.TermElab
| `(term| single₀ $i $x) => fun ty => do Elab.Term.elabTerm (← `(Finsupp.single $i $x)) ty
| _ => fun _ => Elab.throwUnsupportedSyntax
/-- `Finsupp` elaborator for `update₀`. -/
@[term_elab stxUpdate₀]
def elabUpdate₀ : Elab.Term.TermElab
| `(term| update₀ $f $i $x) => fun ty => do Elab.Term.elabTerm (← `(Finsupp.update $f $i $x)) ty
| _ => fun _ => Elab.throwUnsupportedSyntax
macro_rules
| `(term| fun₀ $x:matchAlt*) => do
let mut stx : Term ← `(0)
let mut fst : Bool := true
for xi in x do
for xii in Elab.Term.expandMatchAlt xi do
match xii with
| `(matchAltExpr| | $pat => $val) =>
if fst then
stx ← `(single₀ $pat $val)
else
stx ← `(update₀ $stx $pat $val)
fst := false
| _ => Macro.throwUnsupported
pure stx
end Internal
/-- Unexpander for the `fun₀ | i => x` notation. -/
@[app_unexpander Finsupp.single]
def singleUnexpander : Lean.PrettyPrinter.Unexpander
| `($_ $pat $val) => `(fun₀ | $pat => $val)
| _ => throw ()
/-- Unexpander for the `fun₀ | i => x` notation. -/
@[app_unexpander Finsupp.update]
def updateUnexpander : Lean.PrettyPrinter.Unexpander
| `($_ $f $pat $val) => match f with
| `(fun₀ $xs:matchAlt*) => `(fun₀ $xs:matchAlt* | $pat => $val)
| _ => throw ()
| _ => throw ()
/-- Display `Finsupp` using `fun₀` notation. -/
unsafe instance instRepr {α β} [Repr α] [Repr β] [Zero β] : Repr (α →₀ β) where
reprPrec f p :=
if f.support.card = 0 then
"0"
else
let ret : Std.Format := f!"fun₀" ++ .nest 2 (
.group (.join <| f.support.val.unquot.map fun a =>
.line ++ .group (f!"| {repr a} =>" ++ .line ++ repr (f a))))
if p ≥ leadPrec then Format.paren ret else ret
-- This cannot be put in `Mathlib/Data/DFinsupp/Notation.lean` where it belongs, since doc-strings
-- can only be added/modified in the file where the corresponding declaration is defined.
extend_docs Finsupp.fun₀ after
"If the expected type is `Π₀ i, α i` (`DFinsupp`)
and `Mathlib/Data/DFinsupp/Notation.lean` is imported,
then this is notation for `DFinsupp.single` and `Dfinsupp.update` instead."
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Defs.lean | import Mathlib.Algebra.Notation.Support
import Mathlib.Data.Set.Finite.Basic
/-!
# Type of functions with finite support
For any type `α` and any type `M` with zero, we define the type `Finsupp α M` (notation: `α →₀ M`)
of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere
on `α` except on a finite set.
Functions with finite support are used (at least) in the following parts of the library:
* `MonoidAlgebra R M` and `AddMonoidAlgebra R M` are defined as `M →₀ R`;
* polynomials and multivariate polynomials are defined as `AddMonoidAlgebra`s, hence they use
`Finsupp` under the hood;
* the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to
define linearly independent family `LinearIndependent`) is defined as a map
`Finsupp.linearCombination : (ι → M) → (ι →₀ R) →ₗ[R] M`.
Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined
in a different way in the library:
* `Multiset α ≃+ α →₀ ℕ`;
* `FreeAbelianGroup α ≃+ α →₀ ℤ`.
Most of the theory assumes that the range is a commutative additive monoid. This gives us the big
sum operator as a powerful way to construct `Finsupp` elements, which is defined in
`Mathlib/Algebra/BigOperators/Finsupp/Basic.lean`.
Many constructions based on `α →₀ M` are `def`s rather than `abbrev`s to avoid reusing unwanted type
class instances. E.g., `MonoidAlgebra`, `AddMonoidAlgebra`, and types based on these two have
non-pointwise multiplication.
## Main declarations
* `Finsupp`: The type of finitely supported functions from `α` to `β`.
* `Finsupp.onFinset`: The restriction of a function to a `Finset` as a `Finsupp`.
* `Finsupp.mapRange`: Composition of a `ZeroHom` with a `Finsupp`.
* `Finsupp.embDomain`: Maps the domain of a `Finsupp` by an embedding.
* `Finsupp.zipWith`: Postcomposition of two `Finsupp`s with a function `f` such that `f 0 0 = 0`.
## Notation
This file adds `α →₀ M` as a global notation for `Finsupp α M`.
We also use the following convention for `Type*` variables in this file
* `α`, `β`: types with no additional structure that appear as the first argument to `Finsupp`
somewhere in the statement;
* `ι` : an auxiliary index type;
* `M`, `N`, `O`: types with `Zero` or `(Add)(Comm)Monoid` structure;
* `G`, `H`: groups (commutative or not, multiplicative or additive);
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## TODO
* Expand the list of definitions and important lemmas to the module docstring.
-/
assert_not_exists CompleteLattice Monoid
noncomputable section
open Finset Function
variable {α β ι M N O G H : Type*}
/-- `Finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that
`f x = 0` for all but finitely many `x`. -/
structure Finsupp (α : Type*) (M : Type*) [Zero M] where
/-- The support of a finitely supported function (aka `Finsupp`). -/
support : Finset α
/-- The underlying function of a bundled finitely supported function (aka `Finsupp`). -/
toFun : α → M
/-- The witness that the support of a `Finsupp` is indeed the exact locus where its
underlying function is nonzero. -/
mem_support_toFun : ∀ a, a ∈ support ↔ toFun a ≠ 0
@[inherit_doc]
infixr:25 " →₀ " => Finsupp
namespace Finsupp
/-! ### Basic declarations about `Finsupp` -/
section Basic
variable [Zero M]
instance instFunLike : FunLike (α →₀ M) α M :=
⟨toFun, by
rintro ⟨s, f, hf⟩ ⟨t, g, hg⟩ (rfl : f = g)
congr
ext a
exact (hf _).trans (hg _).symm⟩
@[ext]
theorem ext {f g : α →₀ M} (h : ∀ a, f a = g a) : f = g :=
DFunLike.ext _ _ h
lemma ne_iff {f g : α →₀ M} : f ≠ g ↔ ∃ a, f a ≠ g a := DFunLike.ne_iff
@[simp, norm_cast]
theorem coe_mk (f : α → M) (s : Finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) : ⇑(⟨s, f, h⟩ : α →₀ M) = f :=
rfl
instance instZero : Zero (α →₀ M) :=
⟨⟨∅, 0, fun _ => ⟨fun h ↦ (notMem_empty _ h).elim, fun H => (H rfl).elim⟩⟩⟩
@[simp, norm_cast] lemma coe_zero : ⇑(0 : α →₀ M) = 0 := rfl
theorem zero_apply {a : α} : (0 : α →₀ M) a = 0 :=
rfl
@[simp]
theorem support_zero : (0 : α →₀ M).support = ∅ :=
rfl
instance instInhabited : Inhabited (α →₀ M) :=
⟨0⟩
@[simp]
theorem mem_support_iff {f : α →₀ M} : ∀ {a : α}, a ∈ f.support ↔ f a ≠ 0 :=
@(f.mem_support_toFun)
@[simp, norm_cast]
theorem fun_support_eq (f : α →₀ M) : Function.support f = f.support :=
Set.ext fun _x => mem_support_iff.symm
theorem notMem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[deprecated (since := "2025-05-23")] alias not_mem_support_iff := notMem_support_iff
@[simp, norm_cast]
theorem coe_eq_zero {f : α →₀ M} : (f : α → M) = 0 ↔ f = 0 := by rw [← coe_zero, DFunLike.coe_fn_eq]
theorem ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x :=
⟨fun h => h ▸ ⟨rfl, fun _ _ => rfl⟩, fun ⟨h₁, h₂⟩ =>
ext fun a => by
classical
exact if h : a ∈ f.support then h₂ a h else by
have hf : f a = 0 := notMem_support_iff.1 h
have hg : g a = 0 := by rwa [h₁, notMem_support_iff] at h
rw [hf, hg]⟩
@[simp]
theorem support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 :=
mod_cast @Function.support_eq_empty_iff _ _ _ f
theorem support_nonempty_iff {f : α →₀ M} : f.support.Nonempty ↔ f ≠ 0 := by
simp only [Finsupp.support_eq_empty, Finset.nonempty_iff_ne_empty, Ne]
theorem card_support_eq_zero {f : α →₀ M} : #f.support = 0 ↔ f = 0 := by simp
instance instDecidableEq [DecidableEq α] [DecidableEq M] : DecidableEq (α →₀ M) := fun f g =>
decidable_of_iff (f.support = g.support ∧ ∀ a ∈ f.support, f a = g a) ext_iff'.symm
theorem finite_support (f : α →₀ M) : Set.Finite (Function.support f) :=
f.fun_support_eq.symm ▸ f.support.finite_toSet
theorem support_subset_iff {s : Set α} {f : α →₀ M} :
↑f.support ⊆ s ↔ ∀ a ∉ s, f a = 0 := by
simp only [Set.subset_def, mem_coe, mem_support_iff, forall_congr' fun a => not_imp_comm]
/-- Given `Finite α`, `equivFunOnFinite` is the `Equiv` between `α →₀ β` and `α → β`.
(All functions on a finite type are finitely supported.) -/
@[simps]
def equivFunOnFinite [Finite α] : (α →₀ M) ≃ (α → M) where
toFun := (⇑)
invFun f := mk (Function.support f).toFinite.toFinset f fun _a => Set.Finite.mem_toFinset _
@[simp]
theorem equivFunOnFinite_symm_coe {α} [Finite α] (f : α →₀ M) : equivFunOnFinite.symm f = f :=
equivFunOnFinite.symm_apply_apply f
@[simp]
lemma coe_equivFunOnFinite_symm {α} [Finite α] (f : α → M) : ⇑(equivFunOnFinite.symm f) = f := rfl
/--
If `α` has a unique term, the type of finitely supported functions `α →₀ β` is equivalent to `β`.
-/
@[simps!]
noncomputable def _root_.Equiv.finsuppUnique {ι : Type*} [Unique ι] : (ι →₀ M) ≃ M :=
Finsupp.equivFunOnFinite.trans (Equiv.funUnique ι M)
@[ext]
theorem unique_ext [Unique α] {f g : α →₀ M} (h : f default = g default) : f = g :=
ext fun a => by rwa [Unique.eq_default a]
end Basic
/-! ### Declarations about `onFinset` -/
section OnFinset
variable [Zero M]
private irreducible_def onFinset_support (s : Finset α) (f : α → M) : Finset α :=
haveI := Classical.decEq M
{a ∈ s | f a ≠ 0}
/-- `Finsupp.onFinset s f hf` is the finsupp function representing `f` restricted to the finset `s`.
The function must be `0` outside of `s`. Use this when the set needs to be filtered anyways,
otherwise a better set representation is often available. -/
def onFinset (s : Finset α) (f : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s) : α →₀ M where
support := onFinset_support s f
toFun := f
mem_support_toFun := by classical simpa [onFinset_support_def]
@[simp, norm_cast] lemma coe_onFinset (s : Finset α) (f : α → M) (hf) : onFinset s f hf = f := rfl
@[simp]
theorem onFinset_apply {s : Finset α} {f : α → M} {hf a} : (onFinset s f hf : α →₀ M) a = f a :=
rfl
theorem support_onFinset [DecidableEq M] {s : Finset α} {f : α → M}
(hf : ∀ a : α, f a ≠ 0 → a ∈ s) :
(Finsupp.onFinset s f hf).support = {a ∈ s | f a ≠ 0} := by
dsimp [onFinset]; rw [onFinset_support]; congr
@[simp]
theorem support_onFinset_subset {s : Finset α} {f : α → M} {hf} :
(onFinset s f hf).support ⊆ s := by
classical
rw [support_onFinset]
exact filter_subset (f · ≠ 0) s
theorem mem_support_onFinset {s : Finset α} {f : α → M} (hf : ∀ a : α, f a ≠ 0 → a ∈ s) {a : α} :
a ∈ (Finsupp.onFinset s f hf).support ↔ f a ≠ 0 := by
rw [Finsupp.mem_support_iff, Finsupp.onFinset_apply]
end OnFinset
section OfSupportFinite
variable [Zero M]
/-- The natural `Finsupp` induced by the function `f` given that it has finite support. -/
noncomputable def ofSupportFinite (f : α → M) (hf : (Function.support f).Finite) : α →₀ M where
support := hf.toFinset
toFun := f
mem_support_toFun _ := hf.mem_toFinset
theorem ofSupportFinite_coe {f : α → M} {hf : (Function.support f).Finite} :
(ofSupportFinite f hf : α → M) = f :=
rfl
theorem ofSupportFinite_support {f : α → M} (hf : f.support.Finite) :
(ofSupportFinite f hf).support = hf.toFinset := by
ext; simp [ofSupportFinite_coe]
instance instCanLift : CanLift (α → M) (α →₀ M) (⇑) fun f => (Function.support f).Finite where
prf f hf := ⟨ofSupportFinite f hf, rfl⟩
end OfSupportFinite
/-! ### Declarations about `mapRange` -/
section MapRange
variable [Zero M] [Zero N] [Zero O]
/-- The composition of `f : M → N` and `g : α →₀ M` is `mapRange f hf g : α →₀ N`,
which is well-defined when `f 0 = 0`.
This preserves the structure on `f`, and exists in various bundled forms for when `f` is itself
bundled (defined in `Mathlib/Data/Finsupp/Basic.lean`):
* `Finsupp.mapRange.equiv`
* `Finsupp.mapRange.zeroHom`
* `Finsupp.mapRange.addMonoidHom`
* `Finsupp.mapRange.addEquiv`
* `Finsupp.mapRange.linearMap`
* `Finsupp.mapRange.linearEquiv`
-/
def mapRange (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N :=
onFinset g.support (f ∘ g) fun a => by
rw [mem_support_iff, not_imp_not]; exact fun H => (congr_arg f H).trans hf
@[simp]
theorem mapRange_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} :
mapRange f hf g a = f (g a) :=
rfl
@[simp]
theorem mapRange_zero {f : M → N} {hf : f 0 = 0} : mapRange f hf (0 : α →₀ M) = 0 :=
ext fun _ => by simp only [hf, zero_apply, mapRange_apply]
@[simp]
theorem mapRange_id (g : α →₀ M) : mapRange id rfl g = g :=
ext fun _ => rfl
theorem mapRange_comp (f : N → O) (hf : f 0 = 0) (f₂ : M → N) (hf₂ : f₂ 0 = 0) (h : (f ∘ f₂) 0 = 0)
(g : α →₀ M) : mapRange (f ∘ f₂) h g = mapRange f hf (mapRange f₂ hf₂ g) :=
ext fun _ => rfl
@[simp]
lemma mapRange_mapRange (e₁ : N → O) (e₂ : M → N) (he₁ he₂) (f : α →₀ M) :
mapRange e₁ he₁ (mapRange e₂ he₂ f) = mapRange (e₁ ∘ e₂) (by simp [*]) f := ext fun _ ↦ rfl
theorem support_mapRange {f : M → N} {hf : f 0 = 0} {g : α →₀ M} :
(mapRange f hf g).support ⊆ g.support :=
support_onFinset_subset
theorem support_mapRange_of_injective {e : M → N} (he0 : e 0 = 0) (f : ι →₀ M)
(he : Function.Injective e) : (Finsupp.mapRange e he0 f).support = f.support := by
ext
simp only [Finsupp.mem_support_iff, Ne, Finsupp.mapRange_apply]
exact he.ne_iff' he0
lemma range_mapRange (e : M → N) (he₀ : e 0 = 0) :
Set.range (Finsupp.mapRange (α := α) e he₀) = {g | ∀ i, g i ∈ Set.range e} := by
ext g
simp only [Set.mem_range, Set.mem_setOf]
constructor
· rintro ⟨g, rfl⟩ i
simp
· intro h
classical
choose f h using h
use onFinset g.support (fun x ↦ if x ∈ g.support then f x else 0) (by simp_all)
ext i
simp only [mapRange_apply, onFinset_apply]
split_ifs <;> simp_all
/-- `Finsupp.mapRange` of a injective function is injective. -/
lemma mapRange_injective (e : M → N) (he₀ : e 0 = 0) (he : Injective e) :
Injective (Finsupp.mapRange (α := α) e he₀) := by
intro a b h
rw [Finsupp.ext_iff] at h ⊢
simpa only [mapRange_apply, he.eq_iff] using h
/-- `Finsupp.mapRange` of a surjective function is surjective. -/
lemma mapRange_surjective (e : M → N) (he₀ : e 0 = 0) (he : Surjective e) :
Surjective (Finsupp.mapRange (α := α) e he₀) := by
rw [← Set.range_eq_univ, range_mapRange, he.range_eq]
simp
end MapRange
section Equiv
variable [Zero M] [Zero N] [Zero O]
/-- `Finsupp.mapRange` as an equiv. -/
@[simps apply]
def mapRange.equiv (e : M ≃ N) (hf : e 0 = 0) : (ι →₀ M) ≃ (ι →₀ N) where
toFun := mapRange e hf
invFun := mapRange e.symm <| by simp [← hf]
left_inv x := by ext; simp
right_inv x := by ext; simp
@[simp] lemma mapRange.equiv_refl : mapRange.equiv (.refl M) rfl = .refl (ι →₀ M) := by ext; simp
lemma mapRange.equiv_trans (e : M ≃ N) (hf) (f₂ : N ≃ O) (hf₂) :
mapRange.equiv (ι := ι) (e.trans f₂) (by rw [Equiv.trans_apply, hf, hf₂]) =
(mapRange.equiv e hf).trans (mapRange.equiv f₂ hf₂) := by ext; simp
@[simp] lemma mapRange.equiv_symm (e : M ≃ N) (hf) :
(mapRange.equiv (ι := ι) e hf).symm = mapRange.equiv e.symm (by simp [← hf]) := rfl
end Equiv
/-! ### Declarations about `embDomain` -/
section EmbDomain
variable [Zero M] [Zero N]
/-- Given `f : α ↪ β` and `v : α →₀ M`, `Finsupp.embDomain f v : β →₀ M`
is the finitely supported function whose value at `f a : β` is `v a`.
For a `b : β` outside the range of `f`, it is zero. -/
def embDomain (f : α ↪ β) (v : α →₀ M) : β →₀ M where
support := v.support.map f
toFun a₂ :=
haveI := Classical.decEq β
if h : a₂ ∈ v.support.map f then
v
(v.support.choose (fun a₁ => f a₁ = a₂)
(by
rcases Finset.mem_map.1 h with ⟨a, ha, rfl⟩
exact ExistsUnique.intro a ⟨ha, rfl⟩ fun b ⟨_, hb⟩ => f.injective hb))
else 0
mem_support_toFun a₂ := by
dsimp
split_ifs with h
· simp only [h, true_iff]
rw [← notMem_support_iff, not_not]
classical apply Finset.choose_mem
· simp only [h, not_true_eq_false]
@[simp]
theorem support_embDomain (f : α ↪ β) (v : α →₀ M) : (embDomain f v).support = v.support.map f :=
rfl
@[simp]
theorem embDomain_zero (f : α ↪ β) : (embDomain f 0 : β →₀ M) = 0 :=
rfl
@[simp]
theorem embDomain_apply (f : α ↪ β) (v : α →₀ M) (a : α) : embDomain f v (f a) = v a := by
classical
simp_rw [embDomain, coe_mk, mem_map']
split_ifs with h
· refine congr_arg (v : α → M) (f.inj' ?_)
exact Finset.choose_property (fun a₁ => f a₁ = f a) _ _
· exact (notMem_support_iff.1 h).symm
theorem embDomain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ Set.range f) :
embDomain f v a = 0 := by
classical
refine dif_neg (mt (fun h => ?_) h)
rcases Finset.mem_map.1 h with ⟨a, _h, rfl⟩
exact Set.mem_range_self a
theorem embDomain_injective (f : α ↪ β) : Function.Injective (embDomain f : (α →₀ M) → β →₀ M) :=
fun l₁ l₂ h => ext fun a => by simpa only [embDomain_apply] using DFunLike.ext_iff.1 h (f a)
@[simp]
theorem embDomain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} : embDomain f l₁ = embDomain f l₂ ↔ l₁ = l₂ :=
(embDomain_injective f).eq_iff
@[simp]
theorem embDomain_eq_zero {f : α ↪ β} {l : α →₀ M} : embDomain f l = 0 ↔ l = 0 :=
(embDomain_injective f).eq_iff' <| embDomain_zero f
theorem embDomain_mapRange (f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) :
embDomain f (mapRange g hg p) = mapRange g hg (embDomain f p) := by
ext a
by_cases h : a ∈ Set.range f
· rcases h with ⟨a', rfl⟩
rw [mapRange_apply, embDomain_apply, embDomain_apply, mapRange_apply]
· rw [mapRange_apply, embDomain_notin_range, embDomain_notin_range, ← hg] <;> assumption
end EmbDomain
/-! ### Declarations about `zipWith` -/
section ZipWith
variable [Zero M] [Zero N] [Zero O]
/-- Given finitely supported functions `g₁ : α →₀ M` and `g₂ : α →₀ N` and function `f : M → N → O`,
`Finsupp.zipWith f hf g₁ g₂` is the finitely supported function `α →₀ O` satisfying
`zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, which is well-defined when `f 0 0 = 0`. -/
def zipWith (f : M → N → O) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : α →₀ O :=
onFinset
(haveI := Classical.decEq α; g₁.support ∪ g₂.support)
(fun a => f (g₁ a) (g₂ a))
fun a (H : f _ _ ≠ 0) => by
classical
rw [mem_union, mem_support_iff, mem_support_iff, ← not_and_or]
rintro ⟨h₁, h₂⟩; rw [h₁, h₂] at H; exact H hf
@[simp]
theorem zipWith_apply {f : M → N → O} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} :
zipWith f hf g₁ g₂ a = f (g₁ a) (g₂ a) :=
rfl
theorem support_zipWith [D : DecidableEq α] {f : M → N → O} {hf : f 0 0 = 0} {g₁ : α →₀ M}
{g₂ : α →₀ N} : (zipWith f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support := by
convert support_onFinset_subset
end ZipWith
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Weight.lean | import Mathlib.Data.Finsupp.Antidiagonal
import Mathlib.Data.Finsupp.Order
import Mathlib.LinearAlgebra.Finsupp.LinearCombination
/-! # weights of Finsupp functions
The theory of multivariate polynomials and power series is built
on the type `σ →₀ ℕ` which gives the exponents of the monomials.
Many aspects of the theory (degree, order, graded ring structure)
require classifying these exponents according to their total sum
`∑ i, f i`, or variants, and this file provides some API for that.
## Weight
We fix a type `σ`, a semiring `R`, an `R`-module `M`,
as well as a function `w : σ → M`. (The important case is `R = ℕ`.)
- `Finsupp.weight` of a finitely supported function `f : σ →₀ R`
with respect to `w`: it is the sum `∑ (f i) • (w i)`.
It is an `AddMonoidHom` map defined using `Finsupp.linearCombination`.
- `Finsupp.le_weight` says that `f s ≤ f.weight w` when `M = ℕ`
- `Finsupp.le_weight_of_ne_zero` says that `w s ≤ f.weight w`
for `OrderedAddCommMonoid M`, when `f s ≠ 0` and all `w i` are nonnegative.
- `Finsupp.le_weight_of_ne_zero'` is the same statement for `CanonicallyOrderedAddCommMonoid M`.
- `NonTorsionWeight`: all values `w s` are nontorsion in `M`.
- `Finsupp.weight_eq_zero_iff_eq_zero` says that `f.weight w = 0` iff
`f = 0` for `NonTorsionWeight w` and `CanonicallyOrderedAddCommMonoid M`.
- For `w : σ → ℕ` and `Finite σ`, `Finsupp.finite_of_nat_weight_le` proves that
there are finitely many `f : σ →₀ ℕ` of bounded weight.
## Degree
- `Finsupp.degree f` is the sum of all `f s`, for `s ∈ f.support`.
The present choice is to have it defined as a plain function.
- `Finsupp.degree_eq_zero_iff` says that `f.degree = 0` iff `f = 0`.
- `Finsupp.le_degree` says that `f s ≤ f.degree`.
- `Finsupp.degree_eq_weight_one` says `f.degree = f.weight 1` when `R` is a semiring.
This is useful to access the additivity properties of `Finsupp.degree`
- For `Finite σ`, `Finsupp.finite_of_degree_le` proves that
there are finitely many `f : σ →₀ ℕ` of bounded degree.
## TODO
* Maybe `Finsupp.weight w` and `Finsupp.degree` should have similar types,
both `AddMonoidHom` or both functions.
-/
variable {σ M R : Type*} [Semiring R] (w : σ → M)
namespace Finsupp
section AddCommMonoid
variable [AddCommMonoid M] [Module R M]
/-- The `weight` of the finitely supported function `f : σ →₀ R`
with respect to `w : σ → M` is the sum `∑ i, f i • w i`. -/
noncomputable def weight : (σ →₀ R) →+ M :=
(Finsupp.linearCombination R w).toAddMonoidHom
theorem weight_apply (f : σ →₀ R) :
weight w f = Finsupp.sum f (fun i c => c • w i) := rfl
theorem weight_single_index [DecidableEq σ] (s : σ) (c : M) (f : σ →₀ R) :
weight (Pi.single s c) f = f s • c :=
linearCombination_single_index σ M R c s f
theorem weight_single_one_apply [DecidableEq σ] (s : σ) (f : σ →₀ R) :
weight (Pi.single s 1) f = f s := by
rw [weight_single_index, smul_eq_mul, mul_one]
theorem weight_single (s : σ) (r : R) :
weight w (Finsupp.single s r) = r • w s :=
Finsupp.linearCombination_single _ _ _
variable (R) in
/-- A weight function is nontorsion if its values are not torsion. -/
class NonTorsionWeight (w : σ → M) : Prop where
eq_zero_of_smul_eq_zero {r : R} {s : σ} (h : r • w s = 0) : r = 0
variable (R) in
/-- Without zero divisors, nonzero weight is a `NonTorsionWeight` -/
theorem nonTorsionWeight_of [NoZeroSMulDivisors R M] (hw : ∀ i : σ, w i ≠ 0) :
NonTorsionWeight R w where
eq_zero_of_smul_eq_zero {n s} h := by
rw [smul_eq_zero, or_iff_not_imp_right] at h
exact h (hw s)
variable (R) in
theorem NonTorsionWeight.ne_zero [Nontrivial R] [NonTorsionWeight R w] (s : σ) :
w s ≠ 0 := fun h ↦ by
rw [← one_smul R (w s)] at h
apply zero_ne_one.symm (α := R)
exact NonTorsionWeight.eq_zero_of_smul_eq_zero h
variable {w} in
lemma weight_sub_single_add {f : σ →₀ ℕ} {i : σ} (hi : f i ≠ 0) :
(f - single i 1).weight w + w i = f.weight w := by
conv_rhs => rw [← sub_add_single_one_cancel hi, weight_apply]
rw [sum_add_index', sum_single_index, one_smul, weight_apply]
exacts [zero_smul .., fun _ ↦ zero_smul .., fun _ _ _ ↦ add_smul ..]
end AddCommMonoid
section OrderedAddCommMonoid
theorem le_weight (w : σ → ℕ) {s : σ} (hs : w s ≠ 0) (f : σ →₀ ℕ) :
f s ≤ weight w f := by
classical
simp only [weight_apply, Finsupp.sum]
by_cases h : s ∈ f.support
· rw [Finset.sum_eq_add_sum_diff_singleton h]
refine le_trans ?_ (Nat.le_add_right _ _)
apply Nat.le_mul_of_pos_right
exact Nat.zero_lt_of_ne_zero hs
· simp only [notMem_support_iff] at h
rw [h]
apply zero_le
variable [AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M] (w : σ → M)
{R : Type*} [CommSemiring R] [PartialOrder R] [IsOrderedRing R]
[CanonicallyOrderedAdd R] [NoZeroDivisors R] [Module R M]
variable {w} in
theorem le_weight_of_ne_zero (hw : ∀ s, 0 ≤ w s) {s : σ} {f : σ →₀ ℕ} (hs : f s ≠ 0) :
w s ≤ weight w f := by
classical
simp only [weight_apply, Finsupp.sum]
trans f s • w s
· apply le_smul_of_one_le_left (hw s)
exact Nat.one_le_iff_ne_zero.mpr hs
· rw [← Finsupp.mem_support_iff] at hs
rw [Finset.sum_eq_add_sum_diff_singleton hs]
exact le_add_of_nonneg_right <| Finset.sum_nonneg <|
fun i _ ↦ nsmul_nonneg (hw i) (f i)
end OrderedAddCommMonoid
section CanonicallyOrderedAddCommMonoid
variable {M : Type*} [AddCommMonoid M] [PartialOrder M] [IsOrderedAddMonoid M]
[CanonicallyOrderedAdd M] (w : σ → M)
theorem le_weight_of_ne_zero' {s : σ} {f : σ →₀ ℕ} (hs : f s ≠ 0) :
w s ≤ weight w f :=
le_weight_of_ne_zero (fun _ ↦ zero_le _) hs
/-- If `M` is a `CanonicallyOrderedAddCommMonoid`, then `weight f` is zero iff `f = 0`. -/
theorem weight_eq_zero_iff_eq_zero
(w : σ → M) [NonTorsionWeight ℕ w] {f : σ →₀ ℕ} :
weight w f = 0 ↔ f = 0 := by
classical
constructor
· intro h
ext s
simp only [Finsupp.coe_zero, Pi.zero_apply]
by_contra hs
apply NonTorsionWeight.ne_zero ℕ w s
rw [← nonpos_iff_eq_zero, ← h]
exact le_weight_of_ne_zero' w hs
· intro h
rw [h, map_zero]
theorem finite_of_nat_weight_le [Finite σ] (w : σ → ℕ) (hw : ∀ x, w x ≠ 0) (n : ℕ) :
{d : σ →₀ ℕ | weight w d ≤ n}.Finite := by
classical
set fg := Finset.antidiagonal (Finsupp.equivFunOnFinite.symm (Function.const σ n)) with hfg
suffices {d : σ →₀ ℕ | weight w d ≤ n} ⊆ ↑(fg.image fun uv => uv.fst) by
exact Set.Finite.subset (Finset.finite_toSet _) this
intro d hd
rw [hfg]
simp only [Finset.coe_image, Set.mem_image, Finset.mem_coe,
Finset.mem_antidiagonal, Prod.exists, exists_and_right, exists_eq_right]
use Finsupp.equivFunOnFinite.symm (Function.const σ n) - d
ext x
simp only [Finsupp.coe_add, Finsupp.coe_tsub, Pi.add_apply, Pi.sub_apply,
Finsupp.equivFunOnFinite_symm_apply_toFun, Function.const_apply]
rw [add_comm]
apply Nat.sub_add_cancel
apply le_trans (le_weight w (hw x) d)
simpa only [Set.mem_setOf_eq] using hd
end CanonicallyOrderedAddCommMonoid
variable {R : Type*} [AddCommMonoid R]
/-- The degree of a finsupp function. -/
def degree (d : σ →₀ R) : R := ∑ i ∈ d.support, d i
theorem degree_eq_sum [Fintype σ] (f : σ →₀ R) : f.degree = ∑ i, f i := by
rw [degree, Finset.sum_subset] <;> simp
@[simp]
theorem degree_add (a b : σ →₀ R) : (a + b).degree = a.degree + b.degree :=
sum_add_index' (h := fun _ ↦ id) (congrFun rfl) fun _ _ ↦ congrFun rfl
@[simp]
theorem degree_single (a : σ) (r : R) : (Finsupp.single a r).degree = r :=
Finsupp.sum_single_index (h := fun _ => id) rfl
@[simp]
theorem degree_zero : degree (0 : σ →₀ R) = 0 := by simp [degree]
lemma degree_eq_zero_iff {R : Type*}
[AddCommMonoid R] [PartialOrder R] [CanonicallyOrderedAdd R]
(d : σ →₀ R) :
degree d = 0 ↔ d = 0 := by
simp only [degree, Finset.sum_eq_zero_iff, mem_support_iff, ne_eq, _root_.not_imp_self,
DFunLike.ext_iff, coe_zero, Pi.zero_apply]
theorem le_degree {R : Type*}
[AddCommMonoid R] [PartialOrder R] [CanonicallyOrderedAdd R]
(s : σ) (f : σ →₀ R) :
f s ≤ degree f := by
by_cases h : s ∈ f.support
· exact Finset.single_le_sum_of_canonicallyOrdered h
· simp only [notMem_support_iff] at h
simp only [h, zero_le]
theorem degree_eq_weight_one {R : Type*} [Semiring R] :
degree (R := R) (σ := σ) = weight (fun _ ↦ 1) := by
ext d
simp only [degree, weight_apply, smul_eq_mul, mul_one, Finsupp.sum]
theorem finite_of_degree_le [Finite σ] (n : ℕ) :
{f : σ →₀ ℕ | degree f ≤ n}.Finite := by
simp_rw [degree_eq_weight_one]
refine finite_of_nat_weight_le (Function.const σ 1) ?_ n
intro _
simp only [Function.const_apply, ne_eq, one_ne_zero, not_false_eq_true]
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/AList.lean | import Mathlib.Data.Finsupp.Basic
import Mathlib.Data.List.AList
/-!
# Connections between `Finsupp` and `AList`
## Main definitions
* `Finsupp.toAList`
* `AList.lookupFinsupp`: converts an association list into a finitely supported function
via `AList.lookup`, sending absent keys to zero.
-/
namespace Finsupp
variable {α M : Type*} [Zero M]
/-- Produce an association list for the finsupp over its support using choice. -/
@[simps]
noncomputable def toAList (f : α →₀ M) : AList fun _x : α => M :=
⟨f.graph.toList.map Prod.toSigma,
by
rw [List.NodupKeys, List.keys, List.map_map, Prod.fst_comp_toSigma, List.nodup_map_iff_inj_on]
· rintro ⟨b, m⟩ hb ⟨c, n⟩ hc (rfl : b = c)
rw [Finset.mem_toList, Finsupp.mem_graph_iff] at hb hc
dsimp at hb hc
rw [← hc.1, hb.1]
· apply Finset.nodup_toList⟩
@[simp]
theorem toAList_keys_toFinset [DecidableEq α] (f : α →₀ M) :
f.toAList.keys.toFinset = f.support := by
ext
simp [toAList, AList.keys, List.keys]
@[simp]
theorem mem_toAlist {f : α →₀ M} {x : α} : x ∈ f.toAList ↔ f x ≠ 0 := by
classical rw [AList.mem_keys, ← List.mem_toFinset, toAList_keys_toFinset, mem_support_iff]
end Finsupp
namespace AList
variable {α M : Type*} [Zero M]
open List
/-- Converts an association list into a finitely supported function via `AList.lookup`, sending
absent keys to zero. -/
noncomputable def lookupFinsupp (l : AList fun _x : α => M) : α →₀ M where
support := by
haveI := Classical.decEq α; haveI := Classical.decEq M
exact (l.1.filter fun x => Sigma.snd x ≠ 0).keys.toFinset
toFun a :=
haveI := Classical.decEq α
(l.lookup a).getD 0
mem_support_toFun a := by
classical
simp_rw [mem_toFinset, List.mem_keys, List.mem_filter, ← mem_lookup_iff]
cases lookup a l <;> simp
@[simp]
theorem lookupFinsupp_apply [DecidableEq α] (l : AList fun _x : α => M) (a : α) :
l.lookupFinsupp a = (l.lookup a).getD 0 := by
simp only [lookupFinsupp, ne_eq, Finsupp.coe_mk]
congr
@[simp]
theorem lookupFinsupp_support [DecidableEq α] [DecidableEq M] (l : AList fun _x : α => M) :
l.lookupFinsupp.support = (l.1.filter fun x => Sigma.snd x ≠ 0).keys.toFinset := by
dsimp only [lookupFinsupp]
congr!
theorem lookupFinsupp_eq_iff_of_ne_zero [DecidableEq α] {l : AList fun _x : α => M} {a : α} {x : M}
(hx : x ≠ 0) : l.lookupFinsupp a = x ↔ x ∈ l.lookup a := by
rw [lookupFinsupp_apply]
rcases lookup a l with - | m <;> simp [hx.symm]
theorem lookupFinsupp_eq_zero_iff [DecidableEq α] {l : AList fun _x : α => M} {a : α} :
l.lookupFinsupp a = 0 ↔ a ∉ l ∨ (0 : M) ∈ l.lookup a := by
rw [lookupFinsupp_apply, ← lookup_eq_none]
rcases lookup a l with - | m <;> simp
@[simp]
theorem empty_lookupFinsupp : lookupFinsupp (∅ : AList fun _x : α => M) = 0 := rfl
@[simp]
theorem insert_lookupFinsupp [DecidableEq α] (l : AList fun _x : α => M) (a : α) (m : M) :
(l.insert a m).lookupFinsupp = l.lookupFinsupp.update a m := by
ext b
by_cases h : b = a <;> simp [h]
@[simp]
theorem singleton_lookupFinsupp (a : α) (m : M) :
(singleton a m).lookupFinsupp = Finsupp.single a m := by
classical
simp [← AList.insert_empty]
@[simp]
theorem _root_.Finsupp.toAList_lookupFinsupp (f : α →₀ M) : f.toAList.lookupFinsupp = f := by
ext a
classical
by_cases h : f a = 0
· suffices f.toAList.lookup a = none by simp [h, this]
simp [lookup_eq_none, h]
· suffices f.toAList.lookup a = some (f a) by simp [this]
apply mem_lookup_iff.2
simpa using h
theorem lookupFinsupp_surjective : Function.Surjective (@lookupFinsupp α M _) := fun f =>
⟨_, Finsupp.toAList_lookupFinsupp f⟩
end AList |
.lake/packages/mathlib/Mathlib/Data/Finsupp/BigOperators.lean | import Mathlib.Algebra.BigOperators.Group.Finset.Basic
import Mathlib.Algebra.Group.Finsupp
import Mathlib.Data.Finset.Pairwise
/-!
# Sums of collections of Finsupp, and their support
This file provides results about the `Finsupp.support` of sums of collections of `Finsupp`,
including sums of `List`, `Multiset`, and `Finset`.
The support of the sum is a subset of the union of the supports:
* `List.support_sum_subset`
* `Multiset.support_sum_subset`
* `Finset.support_sum_subset`
The support of the sum of pairwise disjoint finsupps is equal to the union of the supports
* `List.support_sum_eq`
* `Multiset.support_sum_eq`
* `Finset.support_sum_eq`
Member in the support of the indexed union over a collection iff
it is a member of the support of a member of the collection:
* `List.mem_foldr_sup_support_iff`
* `Multiset.mem_sup_map_support_iff`
* `Finset.mem_sup_support_iff`
-/
variable {ι M : Type*} [DecidableEq ι]
theorem List.support_sum_subset [AddZeroClass M] (l : List (ι →₀ M)) :
l.sum.support ⊆ l.foldr (Finsupp.support · ⊔ ·) ∅ := by
induction l with
| nil => simp
| cons hd tl IH =>
simp only [List.sum_cons]
exact Finsupp.support_add.trans (Finset.union_subset_union Finset.Subset.rfl IH)
theorem Multiset.support_sum_subset [AddCommMonoid M] (s : Multiset (ι →₀ M)) :
s.sum.support ⊆ (s.map Finsupp.support).sup := by
induction s using Quot.inductionOn
simpa only [Multiset.quot_mk_to_coe'', Multiset.sum_coe, Multiset.map_coe, Multiset.sup_coe,
List.foldr_map] using List.support_sum_subset _
theorem Finset.support_sum_subset [AddCommMonoid M] (s : Finset (ι →₀ M)) :
(s.sum id).support ⊆ Finset.sup s Finsupp.support := by
classical convert Multiset.support_sum_subset s.1; simp
theorem List.mem_foldr_sup_support_iff [Zero M] {l : List (ι →₀ M)} {x : ι} :
x ∈ l.foldr (Finsupp.support · ⊔ ·) ∅ ↔ ∃ f ∈ l, x ∈ f.support := by
simp only [Finset.sup_eq_union, Finsupp.mem_support_iff]
induction l with
| nil => simp
| cons hd tl IH =>
simp only [foldr, Finset.mem_union, Finsupp.mem_support_iff, ne_eq, IH,
mem_cons, exists_eq_or_imp]
theorem Multiset.mem_sup_map_support_iff [Zero M] {s : Multiset (ι →₀ M)} {x : ι} :
x ∈ (s.map Finsupp.support).sup ↔ ∃ f ∈ s, x ∈ f.support :=
Quot.inductionOn s fun _ ↦ by
simpa only [Multiset.quot_mk_to_coe'', Multiset.map_coe, Multiset.sup_coe, List.foldr_map]
using List.mem_foldr_sup_support_iff
theorem Finset.mem_sup_support_iff [Zero M] {s : Finset (ι →₀ M)} {x : ι} :
x ∈ s.sup Finsupp.support ↔ ∃ f ∈ s, x ∈ f.support :=
Multiset.mem_sup_map_support_iff
open scoped Function -- required for scoped `on` notation
theorem List.support_sum_eq [AddZeroClass M] (l : List (ι →₀ M))
(hl : l.Pairwise (_root_.Disjoint on Finsupp.support)) :
l.sum.support = l.foldr (Finsupp.support · ⊔ ·) ∅ := by
induction l with
| nil => simp
| cons hd tl IH =>
simp only [List.pairwise_cons] at hl
simp only [List.sum_cons, List.foldr_cons]
rw [Finsupp.support_add_eq, IH hl.right, Finset.sup_eq_union]
suffices _root_.Disjoint hd.support (tl.foldr (fun x y ↦ (Finsupp.support x ⊔ y)) ∅) by
exact Finset.disjoint_of_subset_right (List.support_sum_subset _) this
rw [← List.foldr_map, ← Finset.bot_eq_empty, List.foldr_sup_eq_sup_toFinset,
Finset.disjoint_sup_right]
intro f hf
simp only [List.mem_toFinset, List.mem_map] at hf
obtain ⟨f, hf, rfl⟩ := hf
exact hl.left _ hf
theorem Multiset.support_sum_eq [AddCommMonoid M] (s : Multiset (ι →₀ M))
(hs : s.Pairwise (_root_.Disjoint on Finsupp.support)) :
s.sum.support = (s.map Finsupp.support).sup := by
induction s using Quot.inductionOn with | _ a
obtain ⟨l, hl, hd⟩ := hs
suffices a.Pairwise (_root_.Disjoint on Finsupp.support) by
convert List.support_sum_eq a this
dsimp only [Function.comp_def]
simp only [quot_mk_to_coe'', map_coe, sup_coe,
Finset.sup_eq_union, Finset.bot_eq_empty, List.foldr_map]
simp only [Multiset.quot_mk_to_coe'', Multiset.coe_eq_coe] at hl
exact hl.symm.pairwise hd fun h ↦ _root_.Disjoint.symm h
theorem Finset.support_sum_eq [AddCommMonoid M] (s : Finset (ι →₀ M))
(hs : (s : Set (ι →₀ M)).PairwiseDisjoint Finsupp.support) :
(s.sum id).support = Finset.sup s Finsupp.support := by
classical
suffices s.1.Pairwise (_root_.Disjoint on Finsupp.support) by
convert Multiset.support_sum_eq s.1 this
exact (Finset.sum_val _).symm
obtain ⟨l, hl, hn⟩ : ∃ l : List (ι →₀ M), l.toFinset = s ∧ l.Nodup := by
refine ⟨s.toList, ?_, Finset.nodup_toList _⟩
simp
subst hl
rwa [List.toFinset_val, List.dedup_eq_self.mpr hn, Multiset.pairwise_coe_iff_pairwise, ←
List.pairwiseDisjoint_iff_coe_toFinset_pairwise_disjoint hn]
intro x y hxy
exact symmetric_disjoint hxy |
.lake/packages/mathlib/Mathlib/Data/Finsupp/ToDFinsupp.lean | import Mathlib.Algebra.Module.Equiv.Defs
import Mathlib.Data.DFinsupp.Module
import Mathlib.Data.Finsupp.SMul
/-!
# Conversion between `Finsupp` and homogeneous `DFinsupp`
This module provides conversions between `Finsupp` and `DFinsupp`.
It is in its own file since neither `Finsupp` or `DFinsupp` depend on each other.
## Main definitions
* "identity" maps between `Finsupp` and `DFinsupp`:
* `Finsupp.toDFinsupp : (ι →₀ M) → (Π₀ i : ι, M)`
* `DFinsupp.toFinsupp : (Π₀ i : ι, M) → (ι →₀ M)`
* Bundled equiv versions of the above:
* `finsuppEquivDFinsupp : (ι →₀ M) ≃ (Π₀ i : ι, M)`
* `finsuppAddEquivDFinsupp : (ι →₀ M) ≃+ (Π₀ i : ι, M)`
* `finsuppLequivDFinsupp R : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M)`
* stronger versions of `Finsupp.split`:
* `sigmaFinsuppEquivDFinsupp : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N))`
* `sigmaFinsuppAddEquivDFinsupp : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N))`
* `sigmaFinsuppLequivDFinsupp : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N))`
## Theorems
The defining features of these operations is that they preserve the function and support:
* `Finsupp.toDFinsupp_coe`
* `Finsupp.toDFinsupp_support`
* `DFinsupp.toFinsupp_coe`
* `DFinsupp.toFinsupp_support`
and therefore map `Finsupp.single` to `DFinsupp.single` and vice versa:
* `Finsupp.toDFinsupp_single`
* `DFinsupp.toFinsupp_single`
as well as preserving arithmetic operations.
For the bundled equivalences, we provide lemmas that they reduce to `Finsupp.toDFinsupp`:
* `finsupp_add_equiv_dfinsupp_apply`
* `finsupp_lequiv_dfinsupp_apply`
* `finsupp_add_equiv_dfinsupp_symm_apply`
* `finsupp_lequiv_dfinsupp_symm_apply`
## Implementation notes
We provide `DFinsupp.toFinsupp` and `finsuppEquivDFinsupp` computably by adding
`[DecidableEq ι]` and `[Π m : M, Decidable (m ≠ 0)]` arguments. To aid with definitional unfolding,
these arguments are also present on the `noncomputable` equivs.
-/
variable {ι : Type*} {R : Type*} {M : Type*}
/-! ### Basic definitions and lemmas -/
section Defs
/-- Interpret a `Finsupp` as a homogeneous `DFinsupp`. -/
def Finsupp.toDFinsupp [Zero M] (f : ι →₀ M) : Π₀ _ : ι, M where
toFun := f
support' :=
Trunc.mk
⟨f.support.1, fun i => (Classical.em (f i = 0)).symm.imp_left Finsupp.mem_support_iff.mpr⟩
@[simp]
theorem Finsupp.toDFinsupp_coe [Zero M] (f : ι →₀ M) : ⇑f.toDFinsupp = f :=
rfl
section
variable [DecidableEq ι] [Zero M]
@[simp]
theorem Finsupp.toDFinsupp_single (i : ι) (m : M) :
(Finsupp.single i m).toDFinsupp = DFinsupp.single i m := by
ext
simp [Finsupp.single_apply, DFinsupp.single_apply]
variable [∀ m : M, Decidable (m ≠ 0)]
@[simp]
theorem toDFinsupp_support (f : ι →₀ M) : f.toDFinsupp.support = f.support := by
ext
simp
/-- Interpret a homogeneous `DFinsupp` as a `Finsupp`.
Note that the elaborator has a lot of trouble with this definition - it is often necessary to
write `(DFinsupp.toFinsupp f : ι →₀ M)` instead of `f.toFinsupp`, as for some unknown reason
using dot notation or omitting the type ascription prevents the type being resolved correctly. -/
def DFinsupp.toFinsupp (f : Π₀ _ : ι, M) : ι →₀ M :=
⟨f.support, f, fun i => by simp only [DFinsupp.mem_support_iff]⟩
@[simp]
theorem DFinsupp.toFinsupp_coe (f : Π₀ _ : ι, M) : ⇑f.toFinsupp = f :=
rfl
@[simp]
theorem DFinsupp.toFinsupp_support (f : Π₀ _ : ι, M) : f.toFinsupp.support = f.support := by
ext
simp
@[simp]
theorem DFinsupp.toFinsupp_single (i : ι) (m : M) :
(DFinsupp.single i m : Π₀ _ : ι, M).toFinsupp = Finsupp.single i m := by
ext
simp [Finsupp.single_apply, DFinsupp.single_apply]
@[simp]
theorem Finsupp.toDFinsupp_toFinsupp (f : ι →₀ M) : f.toDFinsupp.toFinsupp = f :=
DFunLike.coe_injective rfl
@[simp]
theorem DFinsupp.toFinsupp_toDFinsupp (f : Π₀ _ : ι, M) : f.toFinsupp.toDFinsupp = f :=
DFunLike.coe_injective rfl
end
end Defs
/-! ### Lemmas about arithmetic operations -/
section Lemmas
namespace Finsupp
@[simp]
theorem toDFinsupp_zero [Zero M] : (0 : ι →₀ M).toDFinsupp = 0 :=
DFunLike.coe_injective rfl
@[simp]
theorem toDFinsupp_add [AddZeroClass M] (f g : ι →₀ M) :
(f + g).toDFinsupp = f.toDFinsupp + g.toDFinsupp :=
DFunLike.coe_injective rfl
@[simp]
theorem toDFinsupp_neg [AddGroup M] (f : ι →₀ M) : (-f).toDFinsupp = -f.toDFinsupp :=
DFunLike.coe_injective rfl
@[simp]
theorem toDFinsupp_sub [AddGroup M] (f g : ι →₀ M) :
(f - g).toDFinsupp = f.toDFinsupp - g.toDFinsupp :=
DFunLike.coe_injective rfl
@[simp]
theorem toDFinsupp_smul [Monoid R] [AddMonoid M] [DistribMulAction R M] (r : R) (f : ι →₀ M) :
(r • f).toDFinsupp = r • f.toDFinsupp :=
DFunLike.coe_injective rfl
end Finsupp
namespace DFinsupp
variable [DecidableEq ι]
@[simp]
theorem toFinsupp_zero [Zero M] [∀ m : M, Decidable (m ≠ 0)] : toFinsupp 0 = (0 : ι →₀ M) :=
DFunLike.coe_injective rfl
@[simp]
theorem toFinsupp_add [AddZeroClass M] [∀ m : M, Decidable (m ≠ 0)] (f g : Π₀ _ : ι, M) :
(toFinsupp (f + g) : ι →₀ M) = toFinsupp f + toFinsupp g :=
DFunLike.coe_injective <| DFinsupp.coe_add _ _
@[simp]
theorem toFinsupp_neg [AddGroup M] [∀ m : M, Decidable (m ≠ 0)] (f : Π₀ _ : ι, M) :
(toFinsupp (-f) : ι →₀ M) = -toFinsupp f :=
DFunLike.coe_injective <| DFinsupp.coe_neg _
@[simp]
theorem toFinsupp_sub [AddGroup M] [∀ m : M, Decidable (m ≠ 0)] (f g : Π₀ _ : ι, M) :
(toFinsupp (f - g) : ι →₀ M) = toFinsupp f - toFinsupp g :=
DFunLike.coe_injective <| DFinsupp.coe_sub _ _
@[simp]
theorem toFinsupp_smul [Monoid R] [AddMonoid M] [DistribMulAction R M] [∀ m : M, Decidable (m ≠ 0)]
(r : R) (f : Π₀ _ : ι, M) : (toFinsupp (r • f) : ι →₀ M) = r • toFinsupp f :=
DFunLike.coe_injective <| DFinsupp.coe_smul _ _
end DFinsupp
end Lemmas
/-! ### Bundled `Equiv`s -/
section Equivs
/-- `Finsupp.toDFinsupp` and `DFinsupp.toFinsupp` together form an equiv. -/
@[simps -fullyApplied]
def finsuppEquivDFinsupp [DecidableEq ι] [Zero M] [∀ m : M, Decidable (m ≠ 0)] :
(ι →₀ M) ≃ Π₀ _ : ι, M where
toFun := Finsupp.toDFinsupp
invFun := DFinsupp.toFinsupp
left_inv := Finsupp.toDFinsupp_toFinsupp
right_inv := DFinsupp.toFinsupp_toDFinsupp
/-- The additive version of `finsupp.toFinsupp`. Note that this is `noncomputable` because
`Finsupp.add` is noncomputable. -/
@[simps -fullyApplied]
def finsuppAddEquivDFinsupp [DecidableEq ι] [AddZeroClass M] [∀ m : M, Decidable (m ≠ 0)] :
(ι →₀ M) ≃+ Π₀ _ : ι, M :=
{ finsuppEquivDFinsupp with
toFun := Finsupp.toDFinsupp
invFun := DFinsupp.toFinsupp
map_add' := Finsupp.toDFinsupp_add }
variable (R)
/-- The additive version of `Finsupp.toFinsupp`. Note that this is `noncomputable` because
`Finsupp.add` is noncomputable. -/
def finsuppLequivDFinsupp [DecidableEq ι] [Semiring R] [AddCommMonoid M]
[∀ m : M, Decidable (m ≠ 0)] [Module R M] : (ι →₀ M) ≃ₗ[R] Π₀ _ : ι, M :=
{ finsuppEquivDFinsupp with
toFun := Finsupp.toDFinsupp
invFun := DFinsupp.toFinsupp
map_smul' := Finsupp.toDFinsupp_smul
map_add' := Finsupp.toDFinsupp_add }
@[simp]
theorem finsuppLequivDFinsupp_apply_apply [DecidableEq ι] [Semiring R] [AddCommMonoid M]
[∀ m : M, Decidable (m ≠ 0)] [Module R M] :
(↑(finsuppLequivDFinsupp (M := M) R) : (ι →₀ M) → _) = Finsupp.toDFinsupp := rfl
@[simp]
theorem finsuppLequivDFinsupp_symm_apply [DecidableEq ι] [Semiring R] [AddCommMonoid M]
[∀ m : M, Decidable (m ≠ 0)] [Module R M] :
↑(LinearEquiv.symm (finsuppLequivDFinsupp (ι := ι) (M := M) R)) = DFinsupp.toFinsupp :=
rfl
noncomputable section Sigma
/-! ### Stronger versions of `Finsupp.split` -/
variable {η : ι → Type*} {N : Type*} [Semiring R]
open Finsupp
/-- `Finsupp.split` is an equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/
def sigmaFinsuppEquivDFinsupp [Zero N] : ((Σ i, η i) →₀ N) ≃ Π₀ i, η i →₀ N where
toFun f := ⟨split f, Trunc.mk ⟨(splitSupport f : Finset ι).val, fun i => by
rw [← Finset.mem_def, mem_splitSupport_iff_nonzero]
exact (em _).symm⟩⟩
invFun f := by
haveI := Classical.decEq ι
haveI := fun i => Classical.decEq (η i →₀ N)
refine
onFinset (Finset.sigma f.support fun j => (f j).support) (fun ji => f ji.1 ji.2) fun g hg =>
Finset.mem_sigma.mpr ⟨?_, mem_support_iff.mpr hg⟩
simp only [Ne, DFinsupp.mem_support_toFun]
intro h
dsimp at hg
rw [h] at hg
simp only [coe_zero, Pi.zero_apply, not_true] at hg
left_inv f := by ext; simp [split]
right_inv f := by ext; simp [split]
@[simp]
theorem sigmaFinsuppEquivDFinsupp_apply [Zero N] (f : (Σ i, η i) →₀ N) :
(sigmaFinsuppEquivDFinsupp f : ∀ i, η i →₀ N) = Finsupp.split f :=
rfl
@[simp]
theorem sigmaFinsuppEquivDFinsupp_symm_apply [Zero N] (f : Π₀ i, η i →₀ N) (s : Σ i, η i) :
(sigmaFinsuppEquivDFinsupp.symm f : (Σ i, η i) →₀ N) s = f s.1 s.2 :=
rfl
@[simp]
theorem sigmaFinsuppEquivDFinsupp_support [DecidableEq ι] [Zero N]
[∀ (i : ι) (x : η i →₀ N), Decidable (x ≠ 0)] (f : (Σ i, η i) →₀ N) :
(sigmaFinsuppEquivDFinsupp f).support = Finsupp.splitSupport f := by
ext
rw [DFinsupp.mem_support_toFun]
exact (Finsupp.mem_splitSupport_iff_nonzero _ _).symm
@[simp]
theorem sigmaFinsuppEquivDFinsupp_single [DecidableEq ι] [Zero N] (a : Σ i, η i) (n : N) :
sigmaFinsuppEquivDFinsupp (Finsupp.single a n) =
@DFinsupp.single _ (fun i => η i →₀ N) _ _ a.1 (Finsupp.single a.2 n) := by
obtain ⟨i, a⟩ := a
ext j b
by_cases h : i = j
· subst h
classical simp [split_apply, Finsupp.single_apply]
suffices Finsupp.single (⟨i, a⟩ : Σ i, η i) n ⟨j, b⟩ = 0 by simp [split_apply, dif_neg h, this]
have H : (⟨i, a⟩ : Σ i, η i) ≠ ⟨j, b⟩ := by simp [h]
classical rw [Finsupp.single_apply, if_neg H]
-- Without this Lean fails to find the `AddZeroClass` instance on `Π₀ i, (η i →₀ N)`.
attribute [-instance] Finsupp.instZero
@[simp]
theorem sigmaFinsuppEquivDFinsupp_add [AddZeroClass N] (f g : (Σ i, η i) →₀ N) :
sigmaFinsuppEquivDFinsupp (f + g) =
(sigmaFinsuppEquivDFinsupp f + sigmaFinsuppEquivDFinsupp g : Π₀ i : ι, η i →₀ N) := by
ext
rfl
/-- `Finsupp.split` is an additive equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/
@[simps]
def sigmaFinsuppAddEquivDFinsupp [AddZeroClass N] : ((Σ i, η i) →₀ N) ≃+ Π₀ i, η i →₀ N :=
{ sigmaFinsuppEquivDFinsupp with
toFun := sigmaFinsuppEquivDFinsupp
invFun := sigmaFinsuppEquivDFinsupp.symm
map_add' := sigmaFinsuppEquivDFinsupp_add }
attribute [-instance] Finsupp.instAddZeroClass
@[simp]
theorem sigmaFinsuppEquivDFinsupp_smul {R} [Monoid R] [AddMonoid N] [DistribMulAction R N] (r : R)
(f : (Σ i, η i) →₀ N) :
sigmaFinsuppEquivDFinsupp (r • f) = r • sigmaFinsuppEquivDFinsupp f := by
ext
rfl
attribute [-instance] Finsupp.instAddMonoid
/-- `Finsupp.split` is a linear equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/
@[simps]
def sigmaFinsuppLequivDFinsupp [AddCommMonoid N] [Module R N] :
((Σ i, η i) →₀ N) ≃ₗ[R] Π₀ i, η i →₀ N :=
{ sigmaFinsuppAddEquivDFinsupp with
map_smul' := sigmaFinsuppEquivDFinsupp_smul }
end Sigma
end Equivs |
.lake/packages/mathlib/Mathlib/Data/Finsupp/NeLocus.lean | import Mathlib.Algebra.Group.Finsupp
/-!
# Locus of unequal values of finitely supported functions
Let `α N` be two Types, assume that `N` has a `0` and let `f g : α →₀ N` be finitely supported
functions.
## Main definition
* `Finsupp.neLocus f g : Finset α`, the finite subset of `α` where `f` and `g` differ.
In the case in which `N` is an additive group, `Finsupp.neLocus f g` coincides with
`Finsupp.support (f - g)`.
-/
variable {α M N P : Type*}
namespace Finsupp
variable [DecidableEq α]
section NHasZero
variable [DecidableEq N] [Zero N] (f g : α →₀ N)
/-- Given two finitely supported functions `f g : α →₀ N`, `Finsupp.neLocus f g` is the `Finset`
where `f` and `g` differ. This generalizes `(f - g).support` to situations without subtraction. -/
def neLocus (f g : α →₀ N) : Finset α :=
(f.support ∪ g.support).filter fun x => f x ≠ g x
@[simp]
theorem mem_neLocus {f g : α →₀ N} {a : α} : a ∈ f.neLocus g ↔ f a ≠ g a := by
simpa only [neLocus, Finset.mem_filter, Finset.mem_union, mem_support_iff,
and_iff_right_iff_imp] using Ne.ne_or_ne _
theorem notMem_neLocus {f g : α →₀ N} {a : α} : a ∉ f.neLocus g ↔ f a = g a :=
mem_neLocus.not.trans not_ne_iff
@[deprecated (since := "2025-05-23")] alias not_mem_neLocus := notMem_neLocus
@[simp]
theorem coe_neLocus : ↑(f.neLocus g) = { x | f x ≠ g x } := by
ext
exact mem_neLocus
@[simp]
theorem neLocus_eq_empty {f g : α →₀ N} : f.neLocus g = ∅ ↔ f = g :=
⟨fun h =>
ext fun a => not_not.mp (mem_neLocus.not.mp (Finset.eq_empty_iff_forall_notMem.mp h a)),
fun h => h ▸ by simp only [neLocus, Ne, not_true, Finset.filter_false]⟩
@[simp]
theorem nonempty_neLocus_iff {f g : α →₀ N} : (f.neLocus g).Nonempty ↔ f ≠ g :=
Finset.nonempty_iff_ne_empty.trans neLocus_eq_empty.not
theorem neLocus_comm : f.neLocus g = g.neLocus f := by
simp_rw [neLocus, Finset.union_comm, ne_comm]
@[simp]
theorem neLocus_zero_right : f.neLocus 0 = f.support := by
ext
rw [mem_neLocus, mem_support_iff, coe_zero, Pi.zero_apply]
@[simp]
theorem neLocus_zero_left : (0 : α →₀ N).neLocus f = f.support :=
(neLocus_comm _ _).trans (neLocus_zero_right _)
end NHasZero
section NeLocusAndMaps
theorem subset_mapRange_neLocus [DecidableEq N] [Zero N] [DecidableEq M] [Zero M] (f g : α →₀ N)
{F : N → M} (F0 : F 0 = 0) : (f.mapRange F F0).neLocus (g.mapRange F F0) ⊆ f.neLocus g :=
fun x => by simpa only [mem_neLocus, mapRange_apply, not_imp_not] using congr_arg F
theorem zipWith_neLocus_eq_left [DecidableEq N] [Zero M] [DecidableEq P] [Zero P] [Zero N]
{F : M → N → P} (F0 : F 0 0 = 0) (f : α →₀ M) (g₁ g₂ : α →₀ N)
(hF : ∀ f, Function.Injective fun g => F f g) :
(zipWith F F0 f g₁).neLocus (zipWith F F0 f g₂) = g₁.neLocus g₂ := by
ext
simpa only [mem_neLocus] using (hF _).ne_iff
theorem zipWith_neLocus_eq_right [DecidableEq M] [Zero M] [DecidableEq P] [Zero P] [Zero N]
{F : M → N → P} (F0 : F 0 0 = 0) (f₁ f₂ : α →₀ M) (g : α →₀ N)
(hF : ∀ g, Function.Injective fun f => F f g) :
(zipWith F F0 f₁ g).neLocus (zipWith F F0 f₂ g) = f₁.neLocus f₂ := by
ext
simpa only [mem_neLocus] using (hF _).ne_iff
theorem mapRange_neLocus_eq [DecidableEq N] [DecidableEq M] [Zero M] [Zero N] (f g : α →₀ N)
{F : N → M} (F0 : F 0 = 0) (hF : Function.Injective F) :
(f.mapRange F F0).neLocus (g.mapRange F F0) = f.neLocus g := by
ext
simpa only [mem_neLocus] using hF.ne_iff
end NeLocusAndMaps
variable [DecidableEq N]
@[simp]
theorem neLocus_add_left [AddLeftCancelMonoid N] (f g h : α →₀ N) :
(f + g).neLocus (f + h) = g.neLocus h :=
zipWith_neLocus_eq_left _ _ _ _ add_right_injective
@[simp]
theorem neLocus_add_right [AddRightCancelMonoid N] (f g h : α →₀ N) :
(f + h).neLocus (g + h) = f.neLocus g :=
zipWith_neLocus_eq_right _ _ _ _ add_left_injective
section AddGroup
variable [AddGroup N] (f f₁ f₂ g g₁ g₂ : α →₀ N)
@[simp]
theorem neLocus_neg_neg : neLocus (-f) (-g) = f.neLocus g :=
mapRange_neLocus_eq _ _ neg_zero neg_injective
theorem neLocus_neg : neLocus (-f) g = f.neLocus (-g) := by rw [← neLocus_neg_neg, neg_neg]
theorem neLocus_eq_support_sub : f.neLocus g = (f - g).support := by
rw [← neLocus_add_right _ _ (-g), add_neg_cancel, neLocus_zero_right, sub_eq_add_neg]
@[simp]
theorem neLocus_sub_left : neLocus (f - g₁) (f - g₂) = neLocus g₁ g₂ := by
simp only [sub_eq_add_neg, neLocus_add_left, neLocus_neg_neg]
@[simp]
theorem neLocus_sub_right : neLocus (f₁ - g) (f₂ - g) = neLocus f₁ f₂ := by
simpa only [sub_eq_add_neg] using neLocus_add_right _ _ _
@[simp]
theorem neLocus_self_add_right : neLocus f (f + g) = g.support := by
rw [← neLocus_zero_left, ← neLocus_add_left f 0 g, add_zero]
@[simp]
theorem neLocus_self_add_left : neLocus (f + g) f = g.support := by
rw [neLocus_comm, neLocus_self_add_right]
@[simp]
theorem neLocus_self_sub_right : neLocus f (f - g) = g.support := by
rw [sub_eq_add_neg, neLocus_self_add_right, support_neg]
@[simp]
theorem neLocus_self_sub_left : neLocus (f - g) f = g.support := by
rw [neLocus_comm, neLocus_self_sub_right]
end AddGroup
end Finsupp |
.lake/packages/mathlib/Mathlib/Data/Finsupp/MonomialOrder.lean | import Mathlib.Data.Finsupp.Lex
import Mathlib.Data.Finsupp.WellFounded
import Mathlib.Data.List.TFAE
/-! # Monomial orders
## Monomial orders
A *monomial order* is well ordering relation on a type of the form `σ →₀ ℕ` which
is compatible with addition and for which `0` is the smallest element.
Since several monomial orders may have to be used simultaneously, one cannot
get them as instances.
In this formalization, they are presented as a structure `MonomialOrder` which encapsulates
`MonomialOrder.toSyn`, an additive and monotone isomorphism to a linearly ordered cancellative
additive commutative monoid.
The entry `MonomialOrder.wf` asserts that `MonomialOrder.syn` is well founded.
The terminology comes from commutative algebra and algebraic geometry, especially Gröbner bases,
where `c : σ →₀ ℕ` are exponents of monomials.
Given a monomial order `m : MonomialOrder σ`, we provide the notation
`c ≼[m] d` and `c ≺[m] d` to compare `c d : σ →₀ ℕ` with respect to `m`.
It is activated using `open scoped MonomialOrder`.
## Examples
Commutative algebra defines many monomial orders, with different usefulness ranges.
In this file, we provide the basic example of lexicographic ordering.
For the graded lexicographic ordering, see `Mathlib/Data/Finsupp/DegLex.lean`
* `MonomialOrder.lex` : the lexicographic ordering on `σ →₀ ℕ`.
For this, `σ` needs to be embedded with an ordering relation which satisfies `WellFoundedGT σ`.
(This last property is automatic when `σ` is finite).
The type synonym is `Lex (σ →₀ ℕ)` and the two lemmas `MonomialOrder.lex_le_iff`
and `MonomialOrder.lex_lt_iff` rewrite the ordering as comparisons in the type `Lex (σ →₀ ℕ)`.
## References
* [Cox, Little and O'Shea, *Ideals, varieties, and algorithms*][coxlittleoshea1997]
* [Becker and Weispfenning, *Gröbner bases*][Becker-Weispfenning1993]
## Note
In algebraic geometry, when the finitely many variables are indexed by integers,
it is customary to order them using the opposite order : `MvPolynomial.X 0 > MvPolynomial.X 1 > … `
-/
/-- Monomial orders : equivalence of `σ →₀ ℕ` with a well-ordered type -/
structure MonomialOrder (σ : Type*) where
/-- The synonym type -/
syn : Type*
/-- `syn` is a additive commutative monoid -/
acm : AddCommMonoid syn := by infer_instance
/-- `syn` is linearly ordered -/
lo : LinearOrder syn := by infer_instance
/-- `syn` is a linearly ordered cancellative additive commutative monoid -/
iocam : IsOrderedCancelAddMonoid syn := by infer_instance
/-- the additive equivalence from `σ →₀ ℕ` to `syn` -/
toSyn : (σ →₀ ℕ) ≃+ syn
/-- `toSyn` is monotone -/
toSyn_monotone : Monotone toSyn
/-- `syn` is a well ordering -/
wf : WellFoundedLT syn := by infer_instance
attribute [instance] MonomialOrder.acm MonomialOrder.lo MonomialOrder.iocam MonomialOrder.wf
namespace MonomialOrder
variable {σ : Type*} (m : MonomialOrder σ)
lemma le_add_right (a b : σ →₀ ℕ) :
m.toSyn a ≤ m.toSyn a + m.toSyn b := by
rw [← map_add]
exact m.toSyn_monotone le_self_add
instance orderBot : OrderBot (m.syn) where
bot := 0
bot_le a := by
have := m.le_add_right 0 (m.toSyn.symm a)
simpa [map_add, zero_add]
@[simp]
theorem bot_eq_zero : (⊥ : m.syn) = 0 := rfl
@[simp]
lemma zero_le (a : m.syn) : 0 ≤ a := bot_le
theorem eq_zero_iff {a : m.syn} : a = 0 ↔ a ≤ 0 := eq_bot_iff
lemma toSyn_eq_zero_iff (a : σ →₀ ℕ) :
m.toSyn a = 0 ↔ a = 0 := AddEquiv.map_eq_zero_iff m.toSyn
lemma toSyn_lt_iff_ne_zero {a : m.syn} :
0 < a ↔ a ≠ 0 := bot_lt_iff_ne_bot
lemma toSyn_strictMono : StrictMono (m.toSyn) := by
apply m.toSyn_monotone.strictMono_of_injective m.toSyn.injective
/-- Given a monomial order, notation for the corresponding strict order relation on `σ →₀ ℕ` -/
scoped
notation:50 c " ≺[" m:25 "] " d:50 => (MonomialOrder.toSyn m c < MonomialOrder.toSyn m d)
/-- Given a monomial order, notation for the corresponding order relation on `σ →₀ ℕ` -/
scoped
notation:50 c " ≼[" m:25 "] " d:50 => (MonomialOrder.toSyn m c ≤ MonomialOrder.toSyn m d)
end MonomialOrder
section Lex
open Finsupp
open scoped MonomialOrder
-- The linear order on `Finsupp`s obtained by the lexicographic ordering. -/
noncomputable instance {α N : Type*} [LinearOrder α]
[AddCommMonoid N] [PartialOrder N] [IsOrderedCancelAddMonoid N] :
IsOrderedCancelAddMonoid (Lex (α →₀ N)) where
le_of_add_le_add_left a b c h := by simpa only [add_le_add_iff_left] using h
add_le_add_left a b h c := by simpa using h
/-- for the lexicographic ordering, X 0 * X 1 < X 0 ^ 2 -/
example : toLex (Finsupp.single 0 2) > toLex (Finsupp.single 0 1 + Finsupp.single 1 1) := by
use 0; simp
/-- for the lexicographic ordering, X 1 < X 0 -/
example : toLex (Finsupp.single 1 1) < toLex (Finsupp.single 0 1) := by
use 0; simp
/-- for the lexicographic ordering, X 1 < X 0 ^ 2 -/
example : toLex (Finsupp.single 1 1) < toLex (Finsupp.single 0 2) := by
use 0; simp
variable {σ : Type*} [LinearOrder σ]
/-- The lexicographic order on `σ →₀ ℕ`, as a `MonomialOrder` -/
noncomputable def MonomialOrder.lex [WellFoundedGT σ] :
MonomialOrder σ where
syn := Lex (σ →₀ ℕ)
toSyn :=
{ toEquiv := toLex
map_add' := toLex_add }
toSyn_monotone := Finsupp.toLex_monotone
theorem MonomialOrder.lex_le_iff [WellFoundedGT σ] {c d : σ →₀ ℕ} :
c ≼[lex] d ↔ toLex c ≤ toLex d := Iff.rfl
theorem MonomialOrder.lex_lt_iff [WellFoundedGT σ] {c d : σ →₀ ℕ} :
c ≺[lex] d ↔ toLex c < toLex d := Iff.rfl
theorem MonomialOrder.lex_lt_iff_of_unique [Unique σ] {c d : σ →₀ ℕ} :
c ≺[lex] d ↔ c default < d default := by
simp only [MonomialOrder.lex_lt_iff, Finsupp.lex_lt_iff_of_unique, ofLex_toLex]
theorem MonomialOrder.lex_le_iff_of_unique [Unique σ] {c d : σ →₀ ℕ} :
c ≼[lex] d ↔ c default ≤ d default := by
simp only [MonomialOrder.lex_le_iff, Finsupp.lex_le_iff_of_unique, ofLex_toLex]
end Lex |
.lake/packages/mathlib/Mathlib/Data/Finsupp/Encodable.lean | import Mathlib.Data.Finsupp.ToDFinsupp
import Mathlib.Data.DFinsupp.Encodable
/-!
# `Encodable` and `Countable` instances for `α →₀ β`
In this file we provide instances for `Encodable (α →₀ β)` and `Countable (α →₀ β)`.
-/
instance {α β : Type*} [Encodable α] [Encodable β] [Zero β] [∀ x : β, Decidable (x ≠ 0)] :
Encodable (α →₀ β) :=
letI : DecidableEq α := Encodable.decidableEqOfEncodable _
.ofEquiv _ finsuppEquivDFinsupp
instance {α β : Type*} [Countable α] [Countable β] [Zero β] : Countable (α →₀ β) := by
classical exact .of_equiv _ finsuppEquivDFinsupp.symm |
.lake/packages/mathlib/Mathlib/Data/Finsupp/MonomialOrder/DegLex.lean | import Mathlib.Algebra.Group.TransferInstance
import Mathlib.Data.Finsupp.MonomialOrder
import Mathlib.Data.Finsupp.Weight
/-! Homogeneous lexicographic monomial ordering
* `MonomialOrder.degLex`: a variant of the lexicographic ordering that first compares degrees.
For this, `σ` needs to be embedded with an ordering relation which satisfies `WellFoundedGT σ`.
(This last property is automatic when `σ` is finite).
The type synonym is `DegLex (σ →₀ ℕ)` and the two lemmas `MonomialOrder.degLex_le_iff`
and `MonomialOrder.degLex_lt_iff` rewrite the ordering as comparisons in the type `Lex (σ →₀ ℕ)`.
## References
* [Cox, Little and O'Shea, *Ideals, varieties, and algorithms*][coxlittleoshea1997]
* [Becker and Weispfenning, *Gröbner bases*][Becker-Weispfenning1993]
-/
/-- A type synonym to equip a type with its lexicographic order sorted by degrees. -/
def DegLex (α : Type*) := α
variable {α : Type*}
/-- `toDegLex` is the identity function to the `DegLex` of a type. -/
@[match_pattern] def toDegLex : α ≃ DegLex α := Equiv.refl _
theorem toDegLex_injective : Function.Injective (toDegLex (α := α)) := fun _ _ ↦ _root_.id
theorem toDegLex_inj {a b : α} : toDegLex a = toDegLex b ↔ a = b := Iff.rfl
/-- `ofDegLex` is the identity function from the `DegLex` of a type. -/
@[match_pattern] def ofDegLex : DegLex α ≃ α := Equiv.refl _
theorem ofDegLex_injective : Function.Injective (ofDegLex (α := α)) := fun _ _ ↦ _root_.id
theorem ofDegLex_inj {a b : DegLex α} : ofDegLex a = ofDegLex b ↔ a = b := Iff.rfl
@[simp] theorem ofDegLex_symm_eq : (@ofDegLex α).symm = toDegLex := rfl
@[simp] theorem toDegLex_symm_eq : (@toDegLex α).symm = ofDegLex := rfl
@[simp] theorem ofDegLex_toDegLex (a : α) : ofDegLex (toDegLex a) = a := rfl
@[simp] theorem toDegLex_ofDegLex (a : DegLex α) : toDegLex (ofDegLex a) = a := rfl
/-- A recursor for `DegLex`. Use as `induction x`. -/
@[elab_as_elim, induction_eliminator, cases_eliminator]
protected def DegLex.rec {β : DegLex α → Sort*} (h : ∀ a, β (toDegLex a)) :
∀ a, β a := fun a => h (ofDegLex a)
@[simp] lemma DegLex.forall_iff {p : DegLex α → Prop} : (∀ a, p a) ↔ ∀ a, p (toDegLex a) := Iff.rfl
@[simp] lemma DegLex.exists_iff {p : DegLex α → Prop} : (∃ a, p a) ↔ ∃ a, p (toDegLex a) := Iff.rfl
noncomputable instance [AddCommMonoid α] :
AddCommMonoid (DegLex α) := ofDegLex.addCommMonoid
theorem toDegLex_add [AddCommMonoid α] (a b : α) :
toDegLex (a + b) = toDegLex a + toDegLex b := rfl
theorem ofDegLex_add [AddCommMonoid α] (a b : DegLex α) :
ofDegLex (a + b) = ofDegLex a + ofDegLex b := rfl
namespace Finsupp
open scoped Function in -- required for scoped `on` notation
/-- `Finsupp.DegLex r s` is the homogeneous lexicographic order on `α →₀ M`,
where `α` is ordered by `r` and `M` is ordered by `s`.
The type synonym `DegLex (α →₀ M)` has an order given by `Finsupp.DegLex (· < ·) (· < ·)`. -/
protected def DegLex (r : α → α → Prop) (s : ℕ → ℕ → Prop) :
(α →₀ ℕ) → (α →₀ ℕ) → Prop :=
(Prod.Lex s (Finsupp.Lex r s)) on (fun x ↦ (x.degree, x))
theorem degLex_def {r : α → α → Prop} {s : ℕ → ℕ → Prop} {a b : α →₀ ℕ} :
Finsupp.DegLex r s a b ↔ Prod.Lex s (Finsupp.Lex r s) (a.degree, a) (b.degree, b) :=
Iff.rfl
namespace DegLex
theorem wellFounded
{r : α → α → Prop} [IsTrichotomous α r] (hr : WellFounded (Function.swap r))
{s : ℕ → ℕ → Prop} (hs : WellFounded s) (hs0 : ∀ ⦃n⦄, ¬ s n 0) :
WellFounded (Finsupp.DegLex r s) := by
have wft := WellFounded.prod_lex hs (Finsupp.Lex.wellFounded' hs0 hs hr)
rw [← Set.wellFoundedOn_univ] at wft
unfold Finsupp.DegLex
rw [← Set.wellFoundedOn_range]
exact Set.WellFoundedOn.mono wft (le_refl _) (fun _ _ ↦ trivial)
instance [LT α] : LT (DegLex (α →₀ ℕ)) :=
⟨fun f g ↦ Finsupp.DegLex (· < ·) (· < ·) (ofDegLex f) (ofDegLex g)⟩
theorem lt_def [LT α] {a b : DegLex (α →₀ ℕ)} :
a < b ↔ (toLex ((ofDegLex a).degree, toLex (ofDegLex a))) <
(toLex ((ofDegLex b).degree, toLex (ofDegLex b))) :=
Iff.rfl
theorem lt_iff [LT α] {a b : DegLex (α →₀ ℕ)} :
a < b ↔ (ofDegLex a).degree < (ofDegLex b).degree ∨
(((ofDegLex a).degree = (ofDegLex b).degree) ∧ toLex (ofDegLex a) < toLex (ofDegLex b)) := by
simp [lt_def, Prod.Lex.toLex_lt_toLex]
variable [LinearOrder α]
instance isStrictOrder : IsStrictOrder (DegLex (α →₀ ℕ)) (· < ·) where
irrefl := fun a ↦ by simp [lt_def]
trans := by
intro a b c hab hbc
simp only [lt_iff] at hab hbc ⊢
rcases hab with (hab | hab)
· rcases hbc with (hbc | hbc)
· left; exact lt_trans hab hbc
· left; exact lt_of_lt_of_eq hab hbc.1
· rcases hbc with (hbc | hbc)
· left; exact lt_of_eq_of_lt hab.1 hbc
· right; exact ⟨Eq.trans hab.1 hbc.1, lt_trans hab.2 hbc.2⟩
/-- The linear order on `Finsupp`s obtained by the homogeneous lexicographic ordering. -/
instance : LinearOrder (DegLex (α →₀ ℕ)) :=
LinearOrder.lift'
(fun (f : DegLex (α →₀ ℕ)) ↦ toLex ((ofDegLex f).degree, toLex (ofDegLex f)))
(fun f g ↦ by simp)
theorem le_iff {x y : DegLex (α →₀ ℕ)} :
x ≤ y ↔ (ofDegLex x).degree < (ofDegLex y).degree ∨
(ofDegLex x).degree = (ofDegLex y).degree ∧ toLex (ofDegLex x) ≤ toLex (ofDegLex y) := by
simp only [le_iff_eq_or_lt, lt_iff, EmbeddingLike.apply_eq_iff_eq]
by_cases h : x = y
· simp [h]
· by_cases k : (ofDegLex x).degree < (ofDegLex y).degree
· simp [k]
· simp only [h, k, false_or]
instance : IsOrderedCancelAddMonoid (DegLex (α →₀ ℕ)) where
le_of_add_le_add_left a b c h := by
rw [le_iff] at h ⊢
simpa only [ofDegLex_add, degree_add, add_lt_add_iff_left, add_right_inj, toLex_add,
add_le_add_iff_left] using h
add_le_add_left a b h c := by
rw [le_iff] at h ⊢
simpa [ofDegLex_add, degree_add] using h
theorem single_strictAnti : StrictAnti (fun (a : α) ↦ toDegLex (single a 1)) := by
intro _ _ h
simp only [lt_iff, ofDegLex_toDegLex, degree_single, lt_self_iff_false, Lex.single_lt_iff, h,
and_self, or_true]
theorem single_antitone : Antitone (fun (a : α) ↦ toDegLex (single a 1)) :=
single_strictAnti.antitone
theorem single_lt_iff {a b : α} :
toDegLex (Finsupp.single b 1) < toDegLex (Finsupp.single a 1) ↔ a < b :=
single_strictAnti.lt_iff_gt
theorem single_le_iff {a b : α} :
toDegLex (Finsupp.single b 1) ≤ toDegLex (Finsupp.single a 1) ↔ a ≤ b :=
single_strictAnti.le_iff_ge
theorem monotone_degree :
Monotone (fun (x : DegLex (α →₀ ℕ)) ↦ (ofDegLex x).degree) := by
intro x y
rw [le_iff]
rintro (h | h)
· apply le_of_lt h
· apply le_of_eq h.1
noncomputable instance orderBot : OrderBot (DegLex (α →₀ ℕ)) where
bot := toDegLex (0 : α →₀ ℕ)
bot_le x := by
simp only [le_iff, ofDegLex_toDegLex, toLex_zero, degree_zero]
rcases eq_zero_or_pos (ofDegLex x).degree with (h | h)
· simp only [h, lt_self_iff_false, true_and, false_or]
exact bot_le
· simp [h]
instance wellFoundedLT [WellFoundedGT α] :
WellFoundedLT (DegLex (α →₀ ℕ)) :=
⟨wellFounded wellFounded_gt wellFounded_lt fun n ↦ (zero_le n).not_gt⟩
end DegLex
end Finsupp
namespace MonomialOrder
open Finsupp
variable {σ : Type*} [LinearOrder σ] [WellFoundedGT σ]
/-- The deg-lexicographic order on `σ →₀ ℕ`, as a `MonomialOrder` -/
noncomputable def degLex :
MonomialOrder σ where
syn := DegLex (σ →₀ ℕ)
toSyn := { toEquiv := toDegLex, map_add' := toDegLex_add }
toSyn_monotone a b h := by
simp only [AddEquiv.coe_mk, DegLex.le_iff, ofDegLex_toDegLex]
by_cases! ha : a.degree < b.degree
· exact Or.inl ha
· refine Or.inr ⟨le_antisymm ?_ ha, toLex_monotone h⟩
rw [← add_tsub_cancel_of_le h, degree_add]
exact Nat.le_add_right a.degree (b - a).degree
theorem degLex_le_iff {a b : σ →₀ ℕ} :
a ≼[degLex] b ↔ toDegLex a ≤ toDegLex b :=
Iff.rfl
theorem degLex_lt_iff {a b : σ →₀ ℕ} :
a ≺[degLex] b ↔ toDegLex a < toDegLex b :=
Iff.rfl
theorem degLex_single_le_iff {a b : σ} :
single a 1 ≼[degLex] single b 1 ↔ b ≤ a := by
rw [MonomialOrder.degLex_le_iff, DegLex.single_le_iff]
theorem degLex_single_lt_iff {a b : σ} :
single a 1 ≺[degLex] single b 1 ↔ b < a := by
rw [MonomialOrder.degLex_lt_iff, DegLex.single_lt_iff]
end MonomialOrder
section Examples
open Finsupp MonomialOrder DegLex
/-- for the deg-lexicographic ordering, X 1 < X 0 -/
example : single (1 : Fin 2) 1 ≺[degLex] single 0 1 := by
rw [degLex_lt_iff, single_lt_iff]
exact Nat.one_pos
/-- for the deg-lexicographic ordering, X 0 * X 1 < X 0 ^ 2 -/
example : (single 0 1 + single 1 1) ≺[degLex] single (0 : Fin 2) 2 := by
simp only [degLex_lt_iff, lt_iff, ofDegLex_toDegLex, degree_add,
degree_single, Nat.reduceAdd, lt_self_iff_false, true_and, false_or]
use 0
simp
/-- for the deg-lexicographic ordering, X 0 < X 1 ^ 2 -/
example : single (0 : Fin 2) 1 ≺[degLex] single 1 2 := by
simp [degLex_lt_iff, lt_iff]
end Examples |
.lake/packages/mathlib/Mathlib/Data/Analysis/Topology.lean | import Mathlib.Data.Analysis.Filter
import Mathlib.Topology.Bases
import Mathlib.Topology.LocallyFinite
/-!
# Computational realization of topological spaces (experimental)
This file provides infrastructure to compute with topological spaces.
## Main declarations
* `Ctop`: Realization of a topology basis.
* `Ctop.Realizer`: Realization of a topological space. `Ctop` that generates the given topology.
* `LocallyFinite.Realizer`: Realization of the local finiteness of an indexed family of sets.
* `Compact.Realizer`: Realization of the compactness of a set.
-/
open Set
open Filter hiding Realizer
open Topology
/-- A `Ctop α σ` is a realization of a topology (basis) on `α`,
represented by a type `σ` together with operations for the top element and
the intersection operation. -/
structure Ctop (α σ : Type*) where
f : σ → Set α
top : α → σ
top_mem : ∀ x : α, x ∈ f (top x)
inter : ∀ (a b) (x : α), x ∈ f a ∩ f b → σ
inter_mem : ∀ a b x h, x ∈ f (inter a b x h)
inter_sub : ∀ a b x h, f (inter a b x h) ⊆ f a ∩ f b
variable {α : Type*} {β : Type*} {σ : Type*} {τ : Type*}
instance : Inhabited (Ctop α (Set α)) :=
⟨{ f := id
top := singleton
top_mem := mem_singleton
inter := fun s t _ _ ↦ s ∩ t
inter_mem := fun _s _t _a ↦ id
inter_sub := fun _s _t _a _ha ↦ Subset.rfl }⟩
namespace Ctop
section
variable (F : Ctop α σ)
instance : CoeFun (Ctop α σ) fun _ ↦ σ → Set α :=
⟨Ctop.f⟩
theorem coe_mk (f T h₁ I h₂ h₃ a) : (@Ctop.mk α σ f T h₁ I h₂ h₃) a = f a := rfl
/-- Map a Ctop to an equivalent representation type. -/
def ofEquiv (E : σ ≃ τ) : Ctop α σ → Ctop α τ
| ⟨f, T, h₁, I, h₂, h₃⟩ =>
{ f := fun a ↦ f (E.symm a)
top := fun x ↦ E (T x)
top_mem := fun x ↦ by simpa using h₁ x
inter := fun a b x h ↦ E (I (E.symm a) (E.symm b) x h)
inter_mem := fun a b x h ↦ by simpa using h₂ (E.symm a) (E.symm b) x h
inter_sub := fun a b x h ↦ by simpa using h₃ (E.symm a) (E.symm b) x h }
@[simp]
theorem ofEquiv_val (E : σ ≃ τ) (F : Ctop α σ) (a : τ) : F.ofEquiv E a = F (E.symm a) := by
cases F; rfl
end
/-- Every `Ctop` is a topological space. -/
def toTopsp (F : Ctop α σ) : TopologicalSpace α := TopologicalSpace.generateFrom (Set.range F.f)
theorem toTopsp_isTopologicalBasis (F : Ctop α σ) :
@TopologicalSpace.IsTopologicalBasis _ F.toTopsp (Set.range F.f) :=
letI := F.toTopsp
⟨fun _u ⟨a, e₁⟩ _v ⟨b, e₂⟩ ↦
e₁ ▸ e₂ ▸ fun x h ↦ ⟨_, ⟨_, rfl⟩, F.inter_mem a b x h, F.inter_sub a b x h⟩,
eq_univ_iff_forall.2 fun x ↦ ⟨_, ⟨_, rfl⟩, F.top_mem x⟩, rfl⟩
@[simp]
theorem mem_nhds_toTopsp (F : Ctop α σ) {s : Set α} {a : α} :
s ∈ @nhds _ F.toTopsp a ↔ ∃ b, a ∈ F b ∧ F b ⊆ s :=
(@TopologicalSpace.IsTopologicalBasis.mem_nhds_iff _ F.toTopsp _ _ _
F.toTopsp_isTopologicalBasis).trans <|
⟨fun ⟨_, ⟨x, rfl⟩, h⟩ ↦ ⟨x, h⟩, fun ⟨x, h⟩ ↦ ⟨_, ⟨x, rfl⟩, h⟩⟩
end Ctop
/-- A `Ctop` realizer for the topological space `T` is a `Ctop`
which generates `T`. -/
structure Ctop.Realizer (α) [T : TopologicalSpace α] where
σ : Type*
F : Ctop α σ
eq : F.toTopsp = T
open Ctop
/-- A `Ctop` realizes the topological space it generates. -/
protected def Ctop.toRealizer (F : Ctop α σ) : @Ctop.Realizer _ F.toTopsp :=
@Ctop.Realizer.mk _ F.toTopsp σ F rfl
instance (F : Ctop α σ) : Inhabited (@Ctop.Realizer _ F.toTopsp) :=
⟨F.toRealizer⟩
namespace Ctop.Realizer
protected theorem is_basis [T : TopologicalSpace α] (F : Realizer α) :
TopologicalSpace.IsTopologicalBasis (Set.range F.F.f) := by
have := toTopsp_isTopologicalBasis F.F; rwa [F.eq] at this
protected theorem mem_nhds [T : TopologicalSpace α] (F : Realizer α) {s : Set α} {a : α} :
s ∈ 𝓝 a ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s := by
have := @mem_nhds_toTopsp _ _ F.F s a; rwa [F.eq] at this
theorem isOpen_iff [TopologicalSpace α] (F : Realizer α) {s : Set α} :
IsOpen s ↔ ∀ a ∈ s, ∃ b, a ∈ F.F b ∧ F.F b ⊆ s :=
isOpen_iff_mem_nhds.trans <| forall₂_congr fun _a _h ↦ F.mem_nhds
theorem isClosed_iff [TopologicalSpace α] (F : Realizer α) {s : Set α} :
IsClosed s ↔ ∀ a, (∀ b, a ∈ F.F b → ∃ z, z ∈ F.F b ∩ s) → a ∈ s :=
isOpen_compl_iff.symm.trans <|
F.isOpen_iff.trans <|
forall_congr' fun a ↦
show (a ∉ s → ∃ b : F.σ, a ∈ F.F b ∧ ∀ z ∈ F.F b, z ∉ s) ↔ _ by
haveI := Classical.propDecidable; rw [not_imp_comm]
simp [not_exists, not_and, not_forall, and_comm]
theorem mem_interior_iff [TopologicalSpace α] (F : Realizer α) {s : Set α} {a : α} :
a ∈ interior s ↔ ∃ b, a ∈ F.F b ∧ F.F b ⊆ s :=
mem_interior_iff_mem_nhds.trans F.mem_nhds
protected theorem isOpen [TopologicalSpace α] (F : Realizer α) (s : F.σ) : IsOpen (F.F s) :=
isOpen_iff_nhds.2 fun a m ↦ by simpa using F.mem_nhds.2 ⟨s, m, Subset.refl _⟩
theorem ext' [T : TopologicalSpace α] {σ : Type*} {F : Ctop α σ}
(H : ∀ a s, s ∈ 𝓝 a ↔ ∃ b, a ∈ F b ∧ F b ⊆ s) : F.toTopsp = T := by
refine TopologicalSpace.ext_nhds fun x ↦ ?_
ext s
rw [mem_nhds_toTopsp, H]
theorem ext [T : TopologicalSpace α] {σ : Type*} {F : Ctop α σ} (H₁ : ∀ a, IsOpen (F a))
(H₂ : ∀ a s, s ∈ 𝓝 a → ∃ b, a ∈ F b ∧ F b ⊆ s) : F.toTopsp = T :=
ext' fun a s ↦ ⟨H₂ a s, fun ⟨_b, h₁, h₂⟩ ↦ mem_nhds_iff.2 ⟨_, h₂, H₁ _, h₁⟩⟩
variable [TopologicalSpace α]
/-- The topological space realizer made of the open sets. -/
protected def id : Realizer α :=
⟨{ x : Set α // IsOpen x },
{ f := Subtype.val
top := fun _ ↦ ⟨univ, isOpen_univ⟩
top_mem := mem_univ
inter := fun ⟨_x, h₁⟩ ⟨_y, h₂⟩ _a _h₃ ↦ ⟨_, h₁.inter h₂⟩
inter_mem := fun ⟨_x, _h₁⟩ ⟨_y, _h₂⟩ _a ↦ id
inter_sub := fun ⟨_x, _h₁⟩ ⟨_y, _h₂⟩ _a _h₃ ↦ Subset.refl _ },
ext Subtype.property fun _x _s h ↦
let ⟨t, h, o, m⟩ := mem_nhds_iff.1 h
⟨⟨t, o⟩, m, h⟩⟩
/-- Replace the representation type of a `Ctop` realizer. -/
def ofEquiv (F : Realizer α) (E : F.σ ≃ τ) : Realizer α :=
⟨τ, F.F.ofEquiv E,
ext' fun a s ↦
F.mem_nhds.trans <|
⟨fun ⟨s, h⟩ ↦ ⟨E s, by simpa using h⟩, fun ⟨t, h⟩ ↦ ⟨E.symm t, by simpa using h⟩⟩⟩
@[simp]
theorem ofEquiv_σ (F : Realizer α) (E : F.σ ≃ τ) : (F.ofEquiv E).σ = τ := rfl
@[simp]
theorem ofEquiv_F (F : Realizer α) (E : F.σ ≃ τ) (s : τ) : (F.ofEquiv E).F s = F.F (E.symm s) := by
delta ofEquiv; simp
/-- A realizer of the neighborhood of a point. -/
protected def nhds (F : Realizer α) (a : α) : (𝓝 a).Realizer :=
⟨{ s : F.σ // a ∈ F.F s },
{ f := fun s ↦ F.F s.1
pt := ⟨_, F.F.top_mem a⟩
inf := fun ⟨x, h₁⟩ ⟨y, h₂⟩ ↦ ⟨_, F.F.inter_mem x y a ⟨h₁, h₂⟩⟩
inf_le_left := fun ⟨x, h₁⟩ ⟨y, h₂⟩ _z h ↦ (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).1
inf_le_right := fun ⟨x, h₁⟩ ⟨y, h₂⟩ _z h ↦ (F.F.inter_sub x y a ⟨h₁, h₂⟩ h).2 },
filter_eq <|
Set.ext fun _x ↦
⟨fun ⟨⟨_s, as⟩, h⟩ ↦ mem_nhds_iff.2 ⟨_, h, F.isOpen _, as⟩, fun h ↦
let ⟨s, h, as⟩ := F.mem_nhds.1 h
⟨⟨s, h⟩, as⟩⟩⟩
@[simp]
theorem nhds_σ (F : Realizer α) (a : α) : (F.nhds a).σ = { s : F.σ // a ∈ F.F s } := rfl
@[simp]
theorem nhds_F (F : Realizer α) (a : α) (s) : (F.nhds a).F s = F.F s.1 := rfl
theorem tendsto_nhds_iff {m : β → α} {f : Filter β} (F : f.Realizer) (R : Realizer α) {a : α} :
Tendsto m f (𝓝 a) ↔ ∀ t, a ∈ R.F t → ∃ s, ∀ x ∈ F.F s, m x ∈ R.F t :=
(F.tendsto_iff _ (R.nhds a)).trans Subtype.forall
end Ctop.Realizer
/-- A `LocallyFinite.Realizer F f` is a realization that `f` is locally finite, namely it is a
choice of open sets from the basis of `F` such that they intersect only finitely many of the values
of `f`. -/
structure LocallyFinite.Realizer [TopologicalSpace α] (F : Ctop.Realizer α) (f : β → Set α) where
bas : ∀ a, { s // a ∈ F.F s }
sets : ∀ x : α, Fintype { i | (f i ∩ F.F (bas x)).Nonempty }
theorem LocallyFinite.Realizer.to_locallyFinite [TopologicalSpace α] {F : Ctop.Realizer α}
{f : β → Set α} (R : LocallyFinite.Realizer F f) : LocallyFinite f := fun a ↦
⟨_, F.mem_nhds.2 ⟨(R.bas a).1, (R.bas a).2, Subset.rfl⟩, have := R.sets a; Set.toFinite _⟩
theorem locallyFinite_iff_exists_realizer [TopologicalSpace α] (F : Ctop.Realizer α)
{f : β → Set α} : LocallyFinite f ↔ Nonempty (LocallyFinite.Realizer F f) :=
⟨fun h ↦
let ⟨g, h₁⟩ := Classical.axiom_of_choice h
let ⟨g₂, h₂⟩ :=
Classical.axiom_of_choice fun x ↦
show ∃ b : F.σ, x ∈ F.F b ∧ F.F b ⊆ g x from
let ⟨h, _h'⟩ := h₁ x
F.mem_nhds.1 h
⟨⟨fun x ↦ ⟨g₂ x, (h₂ x).1⟩, fun x ↦
Finite.fintype <|
let ⟨_h, h'⟩ := h₁ x
h'.subset fun _i hi ↦ hi.mono (inter_subset_inter_right _ (h₂ x).2)⟩⟩,
fun ⟨R⟩ ↦ R.to_locallyFinite⟩
instance [TopologicalSpace α] [Finite β] (F : Ctop.Realizer α) (f : β → Set α) :
Nonempty (LocallyFinite.Realizer F f) :=
(locallyFinite_iff_exists_realizer _).1 <| locallyFinite_of_finite _
/-- A `Compact.Realizer s` is a realization that `s` is compact, namely it is a
choice of finite open covers for each set family covering `s`. -/
def Compact.Realizer [TopologicalSpace α] (s : Set α) :=
∀ {f : Filter α} (F : f.Realizer) (x : F.σ), f ≠ ⊥ → F.F x ⊆ s → { a // a ∈ s ∧ 𝓝 a ⊓ f ≠ ⊥ }
instance [TopologicalSpace α] : Inhabited (Compact.Realizer (∅ : Set α)) :=
⟨fun {f} F x h hF ↦ by
suffices f = ⊥ from absurd this h
rw [← F.eq, eq_bot_iff]
exact fun s _ ↦ ⟨x, hF.trans s.empty_subset⟩⟩ |
.lake/packages/mathlib/Mathlib/Data/Analysis/Filter.lean | import Mathlib.Order.Filter.Cofinite
/-!
# Computational realization of filters (experimental)
This file provides infrastructure to compute with filters.
## Main declarations
* `CFilter`: Realization of a filter base. Note that this is in the generality of filters on
lattices, while `Filter` is filters of sets (so corresponding to `CFilter (Set α) σ`).
* `Filter.Realizer`: Realization of a `Filter`. `CFilter` that generates the given filter.
-/
open Set Filter
-- TODO write doc strings
/-- A `CFilter α σ` is a realization of a filter (base) on `α`,
represented by a type `σ` together with operations for the top element and
the binary `inf` operation. -/
structure CFilter (α σ : Type*) [PartialOrder α] where
f : σ → α
pt : σ
inf : σ → σ → σ
inf_le_left : ∀ a b : σ, f (inf a b) ≤ f a
inf_le_right : ∀ a b : σ, f (inf a b) ≤ f b
variable {α : Type*} {β : Type*} {σ : Type*} {τ : Type*}
instance [Inhabited α] [SemilatticeInf α] : Inhabited (CFilter α α) :=
⟨{ f := id
pt := default
inf := (· ⊓ ·)
inf_le_left := fun _ _ ↦ inf_le_left
inf_le_right := fun _ _ ↦ inf_le_right }⟩
namespace CFilter
section
variable [PartialOrder α] (F : CFilter α σ)
/-
A DFunLike instance would not be mathematically meaningful here, since the coercion to f cannot b
injective.
-/
instance : CoeFun (CFilter α σ) fun _ ↦ σ → α :=
⟨CFilter.f⟩
theorem coe_mk (f pt inf h₁ h₂ a) : (@CFilter.mk α σ _ f pt inf h₁ h₂) a = f a :=
rfl
/-- Map a `CFilter` to an equivalent representation type. -/
def ofEquiv (E : σ ≃ τ) : CFilter α σ → CFilter α τ
| ⟨f, p, g, h₁, h₂⟩ =>
{ f := fun a ↦ f (E.symm a)
pt := E p
inf := fun a b ↦ E (g (E.symm a) (E.symm b))
inf_le_left := fun a b ↦ by simpa using h₁ (E.symm a) (E.symm b)
inf_le_right := fun a b ↦ by simpa using h₂ (E.symm a) (E.symm b) }
@[simp]
theorem ofEquiv_val (E : σ ≃ τ) (F : CFilter α σ) (a : τ) : F.ofEquiv E a = F (E.symm a) := by
cases F; rfl
end
/-- The filter represented by a `CFilter` is the collection of supersets of
elements of the filter base. -/
def toFilter (F : CFilter (Set α) σ) : Filter α where
sets := { a | ∃ b, F b ⊆ a }
univ_sets := ⟨F.pt, subset_univ _⟩
sets_of_superset := fun ⟨b, h⟩ s ↦ ⟨b, Subset.trans h s⟩
inter_sets := fun ⟨a, h₁⟩ ⟨b, h₂⟩ ↦ ⟨F.inf a b,
subset_inter (Subset.trans (F.inf_le_left _ _) h₁) (Subset.trans (F.inf_le_right _ _) h₂)⟩
@[simp]
theorem mem_toFilter_sets (F : CFilter (Set α) σ) {a : Set α} : a ∈ F.toFilter ↔ ∃ b, F b ⊆ a :=
Iff.rfl
end CFilter
-- TODO write doc strings
/-- A realizer for filter `f` is a cfilter which generates `f`. -/
structure Filter.Realizer (f : Filter α) where
σ : Type*
F : CFilter (Set α) σ
eq : F.toFilter = f
/-- A `CFilter` realizes the filter it generates. -/
protected def CFilter.toRealizer (F : CFilter (Set α) σ) : F.toFilter.Realizer :=
⟨σ, F, rfl⟩
namespace Filter.Realizer
theorem mem_sets {f : Filter α} (F : f.Realizer) {a : Set α} : a ∈ f ↔ ∃ b, F.F b ⊆ a := by
cases F; subst f; rfl
/-- Transfer a realizer along an equality of filter. This has better definitional equalities than
the `Eq.rec` proof. -/
def ofEq {f g : Filter α} (e : f = g) (F : f.Realizer) : g.Realizer :=
⟨F.σ, F.F, F.eq.trans e⟩
/-- A filter realizes itself. -/
def ofFilter (f : Filter α) : f.Realizer :=
⟨f.sets,
{ f := Subtype.val
pt := ⟨univ, univ_mem⟩
inf := fun ⟨_, h₁⟩ ⟨_, h₂⟩ ↦ ⟨_, inter_mem h₁ h₂⟩
inf_le_left := fun ⟨_, _⟩ ⟨_, _⟩ ↦ inter_subset_left
inf_le_right := fun ⟨_, _⟩ ⟨_, _⟩ ↦ inter_subset_right },
filter_eq <| Set.ext fun _ ↦ by simp [exists_mem_subset_iff]⟩
/-- Transfer a filter realizer to another realizer on a different base type. -/
def ofEquiv {f : Filter α} (F : f.Realizer) (E : F.σ ≃ τ) : f.Realizer :=
⟨τ, F.F.ofEquiv E, by
refine Eq.trans ?_ F.eq
exact filter_eq (Set.ext fun _ ↦
⟨fun ⟨s, h⟩ ↦ ⟨E.symm s, by simpa using h⟩, fun ⟨t, h⟩ ↦ ⟨E t, by simp [h]⟩⟩)⟩
@[simp]
theorem ofEquiv_σ {f : Filter α} (F : f.Realizer) (E : F.σ ≃ τ) : (F.ofEquiv E).σ = τ :=
rfl
@[simp]
theorem ofEquiv_F {f : Filter α} (F : f.Realizer) (E : F.σ ≃ τ) (s : τ) :
(F.ofEquiv E).F s = F.F (E.symm s) := rfl
/-- `Unit` is a realizer for the principal filter -/
protected def principal (s : Set α) : (principal s).Realizer :=
⟨Unit,
{ f := fun _ ↦ s
pt := ()
inf := fun _ _ ↦ ()
inf_le_left := fun _ _ ↦ le_rfl
inf_le_right := fun _ _ ↦ le_rfl },
filter_eq <| Set.ext fun _ ↦ ⟨fun ⟨_, s⟩ ↦ s, fun h ↦ ⟨(), h⟩⟩⟩
@[simp]
theorem principal_σ (s : Set α) : (Realizer.principal s).σ = Unit :=
rfl
@[simp]
theorem principal_F (s : Set α) (u : Unit) : (Realizer.principal s).F u = s :=
rfl
instance (s : Set α) : Inhabited (principal s).Realizer :=
⟨Realizer.principal s⟩
/-- `Unit` is a realizer for the top filter -/
protected def top : (⊤ : Filter α).Realizer :=
(Realizer.principal _).ofEq principal_univ
@[simp]
theorem top_σ : (@Realizer.top α).σ = Unit :=
rfl
@[simp]
theorem top_F (u : Unit) : (@Realizer.top α).F u = univ :=
rfl
/-- `Unit` is a realizer for the bottom filter -/
protected def bot : (⊥ : Filter α).Realizer :=
(Realizer.principal _).ofEq principal_empty
@[simp]
theorem bot_σ : (@Realizer.bot α).σ = Unit :=
rfl
@[simp]
theorem bot_F (u : Unit) : (@Realizer.bot α).F u = ∅ :=
rfl
/-- Construct a realizer for `map m f` given a realizer for `f` -/
protected def map (m : α → β) {f : Filter α} (F : f.Realizer) : (map m f).Realizer :=
⟨F.σ,
{ f := fun s ↦ image m (F.F s)
pt := F.F.pt
inf := F.F.inf
inf_le_left := fun _ _ ↦ image_mono (F.F.inf_le_left _ _)
inf_le_right := fun _ _ ↦ image_mono (F.F.inf_le_right _ _) },
filter_eq <| Set.ext fun _ ↦ by
simp only [CFilter.toFilter, image_subset_iff, mem_setOf_eq, Filter.mem_sets, mem_map]
rw [F.mem_sets]⟩
@[simp]
theorem map_σ (m : α → β) {f : Filter α} (F : f.Realizer) : (F.map m).σ = F.σ :=
rfl
@[simp]
theorem map_F (m : α → β) {f : Filter α} (F : f.Realizer) (s) : (F.map m).F s = image m (F.F s) :=
rfl
/-- Construct a realizer for `comap m f` given a realizer for `f` -/
protected def comap (m : α → β) {f : Filter β} (F : f.Realizer) : (comap m f).Realizer :=
⟨F.σ,
{ f := fun s ↦ preimage m (F.F s)
pt := F.F.pt
inf := F.F.inf
inf_le_left := fun _ _ ↦ preimage_mono (F.F.inf_le_left _ _)
inf_le_right := fun _ _ ↦ preimage_mono (F.F.inf_le_right _ _) },
filter_eq <| Set.ext fun _ ↦ by
cases F; subst f
exact ⟨fun ⟨s, h⟩ ↦ ⟨_, ⟨s, Subset.refl _⟩, h⟩,
fun ⟨_, ⟨s, h⟩, h₂⟩ ↦ ⟨s, Subset.trans (preimage_mono h) h₂⟩⟩⟩
/-- Construct a realizer for the sup of two filters -/
protected def sup {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : (f ⊔ g).Realizer :=
⟨F.σ × G.σ,
{ f := fun ⟨s, t⟩ ↦ F.F s ∪ G.F t
pt := (F.F.pt, G.F.pt)
inf := fun ⟨a, a'⟩ ⟨b, b'⟩ ↦ (F.F.inf a b, G.F.inf a' b')
inf_le_left := fun _ _ ↦ union_subset_union (F.F.inf_le_left _ _) (G.F.inf_le_left _ _)
inf_le_right := fun _ _ ↦ union_subset_union (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) },
filter_eq <| Set.ext fun _ ↦ by cases F; cases G; substs f g; simp [CFilter.toFilter]⟩
/-- Construct a realizer for the inf of two filters -/
protected def inf {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : (f ⊓ g).Realizer :=
⟨F.σ × G.σ,
{ f := fun ⟨s, t⟩ ↦ F.F s ∩ G.F t
pt := (F.F.pt, G.F.pt)
inf := fun ⟨a, a'⟩ ⟨b, b'⟩ ↦ (F.F.inf a b, G.F.inf a' b')
inf_le_left := fun _ _ ↦ inter_subset_inter (F.F.inf_le_left _ _) (G.F.inf_le_left _ _)
inf_le_right := fun _ _ ↦ inter_subset_inter (F.F.inf_le_right _ _) (G.F.inf_le_right _ _) },
by
cases F; cases G; substs f g; simp only [CFilter.toFilter, Prod.exists]; ext
constructor
· rintro ⟨s, t, h⟩
apply mem_inf_of_inter _ _ h
· use s
· use t
· rintro ⟨_, ⟨a, ha⟩, _, ⟨b, hb⟩, rfl⟩
exact ⟨a, b, inter_subset_inter ha hb⟩⟩
/-- Construct a realizer for the cofinite filter -/
protected def cofinite [DecidableEq α] : (@cofinite α).Realizer :=
⟨Finset α,
{ f := fun s ↦ { a | a ∉ s }
pt := ∅
inf := (· ∪ ·)
inf_le_left := fun _ _ _ ↦ mt (Finset.mem_union_left _)
inf_le_right := fun _ _ _ ↦ mt (Finset.mem_union_right _) },
filter_eq <|
Set.ext fun _ ↦
⟨fun ⟨s, h⟩ ↦ s.finite_toSet.subset (compl_subset_comm.1 h), fun h ↦
⟨h.toFinset, by simp⟩⟩⟩
/-- Construct a realizer for filter bind -/
protected def bind {f : Filter α} {m : α → Filter β} (F : f.Realizer) (G : ∀ i, (m i).Realizer) :
(f.bind m).Realizer :=
⟨Σ s : F.σ, ∀ i ∈ F.F s, (G i).σ,
{ f := fun ⟨s, f⟩ ↦ ⋃ i ∈ F.F s, (G i).F (f i (by assumption))
pt := ⟨F.F.pt, fun i _ ↦ (G i).F.pt⟩
inf := fun ⟨a, f⟩ ⟨b, f'⟩ ↦
⟨F.F.inf a b, fun i h ↦
(G i).F.inf (f i (F.F.inf_le_left _ _ h)) (f' i (F.F.inf_le_right _ _ h))⟩
inf_le_left := fun _ _ _ ↦ by
simp only [mem_iUnion, forall_exists_index]
exact fun i h₁ h₂ ↦ ⟨i, F.F.inf_le_left _ _ h₁, (G i).F.inf_le_left _ _ h₂⟩
inf_le_right := fun _ _ _ ↦ by
simp only [mem_iUnion, forall_exists_index]
exact fun i h₁ h₂ ↦ ⟨i, F.F.inf_le_right _ _ h₁, (G i).F.inf_le_right _ _ h₂⟩ },
filter_eq <| Set.ext fun _ ↦ by
obtain ⟨_, F, _⟩ := F; subst f
simp only [CFilter.toFilter, iUnion_subset_iff, Sigma.exists, Filter.mem_sets, mem_bind]
exact
⟨fun ⟨s, f, h⟩ ↦
⟨F s, ⟨s, Subset.refl _⟩, fun i H ↦ (G i).mem_sets.2 ⟨f i H, fun _ h' ↦ h i H h'⟩⟩,
fun ⟨_, ⟨s, h⟩, f⟩ ↦
let ⟨f', h'⟩ := Classical.axiom_of_choice fun i : F s ↦ (G i).mem_sets.1 (f i (h i.2))
⟨s, fun i h ↦ f' ⟨i, h⟩, fun _ H _ m ↦ h' ⟨_, H⟩ m⟩⟩⟩
/-- Construct a realizer for indexed supremum -/
protected def iSup {f : α → Filter β} (F : ∀ i, (f i).Realizer) : (⨆ i, f i).Realizer :=
let F' : (⨆ i, f i).Realizer :=
(Realizer.bind Realizer.top F).ofEq <|
filter_eq <| Set.ext <| by simp [Filter.bind, iSup_sets_eq]
F'.ofEquiv <|
show (Σ _ : Unit, ∀ i : α, True → (F i).σ) ≃ ∀ i, (F i).σ from
⟨fun ⟨_, f⟩ i ↦ f i ⟨⟩, fun f ↦ ⟨(), fun i _ ↦ f i⟩, fun _ ↦ rfl, fun _ ↦ rfl⟩
/-- Construct a realizer for the product of filters -/
protected def prod {f g : Filter α} (F : f.Realizer) (G : g.Realizer) : (f ×ˢ g).Realizer :=
(F.comap _).inf (G.comap _)
theorem le_iff {f g : Filter α} (F : f.Realizer) (G : g.Realizer) :
f ≤ g ↔ ∀ b : G.σ, ∃ a : F.σ, F.F a ≤ G.F b :=
⟨fun H t ↦ F.mem_sets.1 (H (G.mem_sets.2 ⟨t, Subset.refl _⟩)), fun H _ h ↦
F.mem_sets.2 <|
let ⟨s, h₁⟩ := G.mem_sets.1 h
let ⟨t, h₂⟩ := H s
⟨t, Subset.trans h₂ h₁⟩⟩
theorem tendsto_iff (f : α → β) {l₁ : Filter α} {l₂ : Filter β} (L₁ : l₁.Realizer)
(L₂ : l₂.Realizer) : Tendsto f l₁ l₂ ↔ ∀ b, ∃ a, ∀ x ∈ L₁.F a, f x ∈ L₂.F b :=
(le_iff (L₁.map f) L₂).trans <| forall_congr' fun _ ↦ exists_congr fun _ ↦ image_subset_iff
theorem ne_bot_iff {f : Filter α} (F : f.Realizer) : f ≠ ⊥ ↔ ∀ a : F.σ, (F.F a).Nonempty := by
rw [not_iff_comm, ← le_bot_iff, F.le_iff Realizer.bot, not_forall]
simp only [Set.not_nonempty_iff_eq_empty]
exact ⟨fun ⟨x, e⟩ _ ↦ ⟨x, le_of_eq e⟩, fun h ↦
let ⟨x, h⟩ := h ()
⟨x, le_bot_iff.1 h⟩⟩
end Filter.Realizer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.