blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 139 | content_id stringlengths 40 40 | detected_licenses listlengths 0 16 | license_type stringclasses 2
values | repo_name stringlengths 7 55 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 6
values | visit_date int64 1,471B 1,694B | revision_date int64 1,378B 1,694B | committer_date int64 1,378B 1,694B | github_id float64 1.33M 604M ⌀ | star_events_count int64 0 43.5k | fork_events_count int64 0 1.5k | gha_license_id stringclasses 6
values | gha_event_created_at int64 1,402B 1,695B ⌀ | gha_created_at int64 1,359B 1,637B ⌀ | gha_language stringclasses 19
values | src_encoding stringclasses 2
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 1
class | length_bytes int64 3 6.4M | extension stringclasses 4
values | content stringlengths 3 6.12M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7c26f2a92fa064bdecc23065a4a0de97e91dcc40 | 2272e503179a58556187901b8698b789fad7e0c4 | /src/tensor_product.lean | 1be3594a5ceb2674b2e013d018f00096b72e90f9 | [] | no_license | kckennylau/category-theory | f15e582be862379453a5341d83b8cd5ebc686729 | b24962838c7370b5257e38b7648040aec95922bb | refs/heads/master | 1,583,605,043,449 | 1,525,154,882,000 | 1,525,154,882,000 | 127,633,452 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 50,890 | lean | import algebra.group_power linear_algebra.prod_module algebra.module
import data.finsupp data.set.basic tactic.ring Kenny_comm_alg.temp
noncomputable theory
universes u u₁ v v₁ w w₁
open classical set function
local attribute [instance] decidable_inhabited prop_decidable
namespace prod
@[simp] lemma prod_add_prod {α : Type u} {β : Type v} {γ : Type w}
[comm_ring α] [module α β] [module α γ] (x₁ x₂ : β) (y₁ y₂ : γ) :
(x₁, y₁) + (x₂, y₂) = (x₁ + x₂, y₁ + y₂) := rfl
@[simp] lemma smul_prod {α : Type u} {β : Type v} {γ : Type w}
[comm_ring α] [module α β] [module α γ] (r : α) (x : β) (y : γ) :
r • (x, y) = (r • x, r • y) := rfl
@[simp] lemma fst_smul {α : Type u} {β : Type v} {γ : Type w}
[comm_ring α] [module α β] [module α γ] (r : α) (z : β × γ) :
(r • z).fst = r • z.fst := rfl
@[simp] lemma snd_smul {α : Type u} {β : Type v} {γ : Type w}
[comm_ring α] [module α β] [module α γ] (r : α) (z : β × γ) :
(r • z).snd = r • z.snd := rfl
end prod
class type_singleton (α : Type u) : Type u :=
(default : α)
(unique : ∀ x : α, x = default)
namespace type_singleton
variables (α : Type u) [type_singleton α]
variables (β : Type v) [type_singleton β]
def equiv_unit : equiv α unit :=
{ to_fun := λ x, unit.star,
inv_fun := λ x, type_singleton.default α,
left_inv := λ x, by rw type_singleton.unique x,
right_inv := λ x, punit.cases_on x rfl }
def equiv_singleton : equiv α β :=
{ to_fun := λ x, type_singleton.default β,
inv_fun := λ x, type_singleton.default α,
left_inv := λ x, by rw type_singleton.unique x,
right_inv := λ x, by rw type_singleton.unique x }
end type_singleton
-- (moved to temp)
section bilinear
variables {α : Type u} [comm_ring α]
include α
variables {β : Type v} {γ : Type w} {α₁ : Type u₁} {β₁ : Type v₁}
variables [module α β] [module α γ] [module α α₁] [module α β₁]
structure is_bilinear_map {β γ α₁}
[module α β] [module α γ] [module α α₁]
(f : β → γ → α₁) : Prop :=
(add_pair : ∀ x y z, f (x + y) z = f x z + f y z)
(pair_add : ∀ x y z, f x (y + z) = f x y + f x z)
(smul_pair : ∀ r x y, f (r • x) y = r • f x y)
(pair_smul : ∀ r x y, f x (r • y) = r • f x y)
variables {f : β → γ → α₁} (hf : is_bilinear_map f)
include hf
theorem is_bilinear_map.zero_pair : ∀ y, f 0 y = 0 :=
λ y, calc f 0 y
= f (0 + 0) y - f 0 y : by rw [hf.add_pair 0 0 y]; simp
... = 0 : by simp
theorem is_bilinear_map.pair_zero : ∀ x, f x 0 = 0 :=
λ x, calc f x 0
= f x (0 + 0) - f x 0 : by rw [hf.pair_add x 0 0]; simp
... = 0 : by simp
theorem is_bilinear_map.linear_pair (y : γ) : is_linear_map (λ x, f x y) :=
{ add := λ m n, hf.add_pair m n y,
smul := λ r m, hf.smul_pair r m y }
theorem is_bilinear_map.pair_linear (x : β) : is_linear_map (λ y, f x y) :=
{ add := λ m n, hf.pair_add x m n,
smul := λ r m, hf.pair_smul r x m }
variables {g : α₁ → β₁} (hg : is_linear_map g)
include hg
theorem is_bilinear_map.comp : is_bilinear_map (λ x y, g (f x y)) :=
{ add_pair := λ x y z, by rw [hf.add_pair, hg.add],
pair_add := λ x y z, by rw [hf.pair_add, hg.add],
smul_pair := λ r x y, by rw [hf.smul_pair, hg.smul],
pair_smul := λ r x y, by rw [hf.pair_smul, hg.smul] }
omit hf hg
variables (β γ)
structure module_iso (β γ) [module α β] [module α γ] extends equiv β γ :=
( linear : is_linear_map to_fun )
end bilinear
infix ` ≃ₘ `:25 := module_iso
namespace module_iso
variables (α : Type u) [comm_ring α]
variables (β : Type v) (γ : Type w) (α₁ : Type u₁) [module α β] [module α γ] [module α α₁]
variables {α β γ α₁}
include α
protected def refl : β ≃ₘ β :=
{ linear := is_linear_map.id
..equiv.refl β }
protected def symm (hbc : β ≃ₘ γ) : γ ≃ₘ β :=
{ linear := is_linear_map.inverse hbc.linear hbc.left_inv hbc.right_inv
..equiv.symm hbc.to_equiv }
protected def trans : β ≃ₘ γ → γ ≃ₘ α₁ → β ≃ₘ α₁ :=
λ hbc hca,
{ linear := is_linear_map.comp hca.linear hbc.linear
..equiv.trans hbc.to_equiv hca.to_equiv }
end module_iso
namespace multiset
variable {α : Type u}
@[simp] theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_id _
end multiset
namespace list
theorem map_neg {α : Type u} [add_comm_group α] :
∀ L:list α, (L.map (λ x, -x)).sum = -L.sum
| [] := by simp
| (h::t) := by simp [map_neg t]
theorem sum_singleton {α : Type u} [add_group α] {x : α} :
list.sum [x] = x :=
calc list.sum [x] = x + list.sum [] : list.sum_cons
... = x + 0 : congr_arg _ list.sum_nil
... = x : add_zero x
end list
namespace finsupp
variables {α : Type u} {β : Type v} [add_comm_group β] {a : α} {b b₁ b₂ : β}
variables {α₁ : Type u₁}
variables {γ : Type w} [add_comm_group γ]
@[simp] lemma single_neg : single a (-b) = -single a b :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, neg_apply, single_eq_same, single_eq_same] },
{ rw [neg_apply, single_eq_of_ne h, single_eq_of_ne h, neg_zero] }
end
@[simp] lemma single_sub : single a (b₁ - b₂) = single a b₁ - single a b₂ :=
by simp
theorem sum_neg_index' {g : α →₀ β} {h : α → β → γ}:
(∀ (a : α) (b₁ b₂ : β), h a (b₁ - b₂) = h a b₁ - h a b₂) → finsupp.sum (-g) h = -finsupp.sum g h :=
begin
intro H,
rw ← zero_sub,
rw sum_sub_index H,
rw sum_zero_index,
rw zero_sub
end
@[simp] theorem finsum_apply {S : finset α₁} {f : α₁ → α →₀ β} {z : α} :
(S.sum f) z = S.sum (λ x, f x z) :=
eq.symm $ finset.sum_hom (λ g : α →₀ β, g z) rfl (λ x y, rfl)
end finsupp
namespace tensor_product
variables (α : Type u) [comm_ring α]
variables (β : Type v) (γ : Type w) (α₁ : Type u₁) (β₁ : Type v₁) (γ₁ : Type w₁)
variables [module α β] [module α γ] [module α α₁] [module α β₁] [module α γ₁]
def free_abelian_group : Type (max v w) := β × γ →₀ ℤ
instance free_abelian_group.has_coe_to_fun : has_coe_to_fun (free_abelian_group β γ) :=
finsupp.has_coe_to_fun
instance free_abelian_group.add_comm_monoid : add_comm_monoid (free_abelian_group β γ) :=
finsupp.add_comm_monoid
instance free_abelian_group.add_comm_group : add_comm_group (free_abelian_group β γ) :=
finsupp.add_comm_group
theorem structural_theorem (f : free_abelian_group β γ) :
∃ S : finset (free_abelian_group β γ), (∀ g ∈ S, ∃ (x : β) (y : γ) (n : ℤ) (H : n ≠ 0), g = finsupp.single (x, y) n) ∧ S.sum id = f :=
begin
-- apply finsupp.induction f,
rcases f with ⟨S, f, hs⟩,
existsi S.image (λ z, finsupp.single z $ f z),
split,
{ intros g hg,
rw finset.mem_image at hg,
rcases hg with ⟨z, hzs, hg⟩,
cases z with x y,
exact ⟨x, y, f (x, y), (hs (x, y)).1 hzs, by simp [hg]⟩ },
{ rw finset.sum_image,
{ apply finsupp.ext,
intro z,
by_cases hz : f z = 0,
{ simp,
rw ← finset.sum_subset (finset.empty_subset S),
{ simpa using hz.symm },
{ intros x hx hnx,
rw id,
rw finsupp.single_apply,
by_cases x = z; simp [h, hz] } },
{ simp,
have h1 : finset.singleton z ⊆ S,
{ intros x hx,
rw finset.mem_singleton at hx,
rw hs, subst hx, exact hz },
rw ← finset.sum_subset h1,
{ rw finset.sum_singleton,
rw id,
rw finsupp.single_apply,
rw if_pos rfl,
refl },
{ intros x hx hnxz,
rw finset.mem_singleton at hnxz,
rw id,
rw finsupp.single_apply,
rw if_neg hnxz } } },
{ intros x hx y hy hxy,
by_contradiction hnxy,
have hxyx : (finsupp.single x (f x) : β × γ →₀ ℤ) x = (finsupp.single y (f y) : β × γ →₀ ℤ) x,
{ rw hxy },
rw finsupp.single_apply at hxyx,
rw finsupp.single_apply at hxyx,
rw if_pos rfl at hxyx,
rw if_neg (ne.symm hnxy) at hxyx,
rw hs at hx,
exact hx hxyx } }
end
variables α {β γ}
include α
namespace relators
def pair_add : β → γ → γ → ℤ → free_abelian_group β γ :=
λ x y₁ y₂ n, finsupp.single (x, y₁) n + finsupp.single (x, y₂) n - finsupp.single (x, y₁ + y₂) n
def add_pair : β → β → γ → ℤ → free_abelian_group β γ :=
λ x₁ x₂ y n, finsupp.single (x₁, y) n + finsupp.single (x₂, y) n - finsupp.single (x₁ + x₂, y) n
def smul_trans : α → β → γ → ℤ → free_abelian_group β γ :=
λ r x y n, finsupp.single (r • x, y) n - finsupp.single (x, r • y) n
variables α β γ
def smul_aux : α → β × γ → ℤ → free_abelian_group β γ :=
λ r f y, finsupp.single (r • f.fst, f.snd) y
variables {α β γ}
theorem smul_aux_zero {r : α} (xy : β × γ) :
smul_aux α β γ r xy (0:ℤ) = 0 :=
by simp [smul_aux]; refl
theorem smul_aux_add {r : α} (xy : β × γ) (m n : ℤ) :
smul_aux α β γ r xy (m + n) = smul_aux α β γ r xy m + smul_aux α β γ r xy n :=
by simp [smul_aux]
theorem smul_aux_sub {r : α} (xy : β × γ) (m n : ℤ) :
smul_aux α β γ r xy (m - n) = smul_aux α β γ r xy m - smul_aux α β γ r xy n :=
by simp [smul_aux]
theorem pair_add.neg (x : β) (y₁ y₂ : γ) (n : ℤ) :
-pair_add α x y₁ y₂ n = pair_add α x y₁ y₂ (-n) :=
begin
unfold pair_add,
rw finsupp.single_neg,
rw finsupp.single_neg,
rw finsupp.single_neg,
simp,
repeat { rw add_comm, rw add_assoc }
end
theorem pair_add.smul (r : α) (x : β) (y₁ y₂ : γ) (n : ℤ) :
finsupp.sum (pair_add α x y₁ y₂ n) (smul_aux α β γ r) = relators.pair_add α (r • x) y₁ y₂ n :=
begin
unfold pair_add,
rw finsupp.sum_sub_index smul_aux_sub,
rw finsupp.sum_add_index,
repeat { rw finsupp.sum_single_index },
repeat { intros, simp [smul_aux] },
repeat { refl }
end
theorem add_pair.neg (x₁ x₂ : β) (y : γ) (n : ℤ) :
-add_pair α x₁ x₂ y n = add_pair α x₁ x₂ y (-n) :=
begin
unfold add_pair,
rw finsupp.single_neg,
rw finsupp.single_neg,
rw finsupp.single_neg,
simp,
repeat { rw add_comm, rw add_assoc }
end
theorem add_pair.smul (r : α) (x₁ x₂ : β) (y : γ) (n : ℤ) :
finsupp.sum (add_pair α x₁ x₂ y n) (smul_aux α β γ r) = relators.add_pair α (r • x₁) (r • x₂) y n :=
begin
unfold add_pair,
rw finsupp.sum_sub_index smul_aux_sub,
rw finsupp.sum_add_index,
repeat { rw finsupp.sum_single_index },
repeat { intros, simp [smul_aux, smul_add] },
repeat { refl }
end
theorem smul_trans.neg (r : α) (x : β) (y : γ) (n : ℤ) :
-smul_trans α r x y n = smul_trans α r x y (-n) :=
begin
unfold smul_trans,
rw finsupp.single_neg,
rw finsupp.single_neg,
simp
end
theorem smul_trans.smul (r r' : α) (x : β) (y : γ) (n : ℤ) :
finsupp.sum (smul_trans α r' x y n) (smul_aux α β γ r) = relators.smul_trans α r' (r • x) y n :=
begin
unfold smul_trans,
rw finsupp.sum_sub_index smul_aux_sub,
repeat { rw finsupp.sum_single_index },
repeat { intros, simp [smul_aux, smul_add, smul_smul, mul_comm] },
repeat { refl },
end
end relators
variables (α β γ)
def relators : set (free_abelian_group β γ) :=
{f | (∃ x y₁ y₂ n, f = relators.pair_add α x y₁ y₂ n) ∨
(∃ x₁ x₂ y n, f = relators.add_pair α x₁ x₂ y n) ∨
(∃ r x y n, f = relators.smul_trans α r x y n)}
theorem relators.zero_mem : (0 : free_abelian_group β γ ) ∈ relators α β γ :=
or.inl ⟨0, 0, 0, 0, by simpa [relators.pair_add, finsupp.single_zero]⟩
theorem relators.neg_mem : ∀ f, f ∈ relators α β γ → -f ∈ relators α β γ :=
begin
intros f hf,
rcases hf with hf | hf | hf;
rcases hf with ⟨a, b, c, d, hf⟩,
{ from or.inl ⟨a, b, c, -d, by rw [hf, relators.pair_add.neg]⟩ },
{ from or.inr (or.inl ⟨a, b, c, -d, by rw [hf, relators.add_pair.neg]⟩) },
{ from or.inr (or.inr ⟨a, b, c, -d, by rw [hf, relators.smul_trans.neg]⟩) }
end
def closure : set (free_abelian_group β γ) :=
{f | ∃ (L : list (free_abelian_group β γ)),
(∀ x ∈ L, x ∈ relators α β γ) ∧ L.sum = f}
def r : free_abelian_group β γ → free_abelian_group β γ → Prop :=
λ f g, f - g ∈ closure α β γ
local infix ≈ := r α β γ
theorem refl (f : free_abelian_group β γ) : f ≈ f :=
⟨[], by simp⟩
theorem symm (f g : free_abelian_group β γ) : f ≈ g → g ≈ f :=
λ ⟨L, hL, hLfg⟩, ⟨L.map (λ x, -x),
λ x hx, let ⟨y, hyL, hyx⟩ := list.exists_of_mem_map hx in
by rw ← hyx; exact relators.neg_mem α β γ y (hL y hyL),
by simp [list.map_neg, hLfg]⟩
theorem trans (f g h : free_abelian_group β γ) : f ≈ g → g ≈ h → f ≈ h :=
λ ⟨L₁, hL₁, hLfg₁⟩ ⟨L₂, hL₂, hLfg₂⟩,
⟨L₁ ++ L₂,
λ x hx, by rw [list.mem_append] at hx; from or.cases_on hx (hL₁ x) (hL₂ x),
by simp [hLfg₁, hLfg₂]⟩
instance : setoid (free_abelian_group β γ) :=
⟨r α β γ, refl α β γ, symm α β γ, trans α β γ⟩
end tensor_product
def tensor_product {α} (β γ) [comm_ring α] [module α β] [module α γ] : Type (max v w) :=
quotient (tensor_product.setoid α β γ)
local infix ` ⊗ `:100 := tensor_product
namespace tensor_product
variables (α : Type u) [comm_ring α]
variables (β : Type v) (γ : Type w) (α₁ : Type u₁) (β₁ : Type v₁) (γ₁ : Type w₁)
variables [module α β] [module α γ] [module α α₁] [module α β₁] [module α γ₁]
include α
def add : β ⊗ γ → β ⊗ γ → β ⊗ γ :=
quotient.lift₂ (λ f g, ⟦f + g⟧ : free_abelian_group β γ → free_abelian_group β γ → β ⊗ γ) $
λ f₁ f₂ g₁ g₂ ⟨L₁, hL₁, hLfg₁⟩ ⟨L₂, hL₂, hLfg₂⟩, quotient.sound
⟨L₁ ++ L₂,
λ x hx, by rw [list.mem_append] at hx; from or.cases_on hx (hL₁ x) (hL₂ x),
by rw [@list.sum_append _ _ L₁ L₂, hLfg₁, hLfg₂]; simp⟩
protected theorem add_assoc (f g h : β ⊗ γ) : add α β γ (add α β γ f g) h = add α β γ f (add α β γ g h) :=
quotient.induction_on₃ f g h $ λ m n k, quotient.sound $ by simp
def zero : β ⊗ γ := ⟦0⟧
protected theorem zero_add (f : β ⊗ γ) : add α β γ (zero α β γ) f = f :=
quotient.induction_on f $ λ m, quotient.sound $ by simp
protected theorem add_zero (f : β ⊗ γ) : add α β γ f (zero α β γ) = f :=
quotient.induction_on f $ λ m, quotient.sound $ by simp
def neg : β ⊗ γ → β ⊗ γ :=
quotient.lift (λ f, ⟦-f⟧ : free_abelian_group β γ → β ⊗ γ) $
λ f g ⟨L, hL, hLfg⟩, quotient.sound ⟨L.map (λ x, -x),
λ x hx, let ⟨y, hyL, hyx⟩ := list.exists_of_mem_map hx in
by rw ← hyx; exact relators.neg_mem α β γ y (hL y hyL),
by simp [list.map_neg, hLfg]⟩
protected theorem add_left_neg (f : β ⊗ γ) : add α β γ (neg α β γ f) f = zero α β γ :=
quotient.induction_on f $ λ m, quotient.sound $ by simp
protected theorem add_comm (f g : β ⊗ γ) : add α β γ f g = add α β γ g f :=
quotient.induction_on₂ f g $ λ m n, quotient.sound $ by simp
instance : add_comm_group (β ⊗ γ) :=
{ add := add α β γ,
add_assoc := tensor_product.add_assoc α β γ,
zero := zero α β γ,
zero_add := tensor_product.zero_add α β γ,
add_zero := tensor_product.add_zero α β γ,
neg := neg α β γ,
add_left_neg := tensor_product.add_left_neg α β γ,
add_comm := tensor_product.add_comm α β γ }
theorem mem_closure_of_finset {f : free_abelian_group β γ} :
(∃ (S : finset (free_abelian_group β γ)) g,
S.sum g = f ∧ ∀ x ∈ S, g x ∈ relators α β γ) →
f ∈ closure α β γ :=
λ ⟨S, g, hSf, hSr⟩, begin
cases S with ms hms,
cases quot.exists_rep ms with L hL,
existsi L.map g,
split,
{ intros x hxL,
rcases list.exists_of_mem_map hxL with ⟨y, hyL, hyx⟩,
have hyms : y ∈ ms,
{ unfold has_mem.mem,
unfold multiset.mem,
rw ← hL,
rw quot.lift_on,
rwa @quot.lift_beta _ (list.perm.setoid (free_abelian_group β γ)).r,
exact multiset.mem._proof_1 y },
rw ← hyx,
exact hSr y hyms },
{ change multiset.sum (multiset.map g ms) = f at hSf,
rw ← hL at hSf,
rw ← multiset.coe_sum (list.map g L),
exact hSf }
end
private lemma zero_eq_zero : (0 : free_abelian_group β γ) = (0 : β × γ →₀ ℤ) := rfl
private lemma sum_zero_index (f : β × γ → ℤ → free_abelian_group β γ) :
@finsupp.sum (β × γ) ℤ (free_abelian_group β γ) int.has_zero _ (0 : free_abelian_group β γ) f = 0 :=
begin
rw zero_eq_zero,
simp [finsupp.sum],
refl
end
private lemma sum_zero_index' [add_comm_group α₁] (f : β × γ → ℤ → α₁) :
@finsupp.sum (β × γ) ℤ α₁ int.has_zero _ (0 : free_abelian_group β γ) f = 0 :=
begin
rw zero_eq_zero,
simp [finsupp.sum]
end
def smul : α → β ⊗ γ → β ⊗ γ :=
λ r, quotient.lift (λ f, ⟦f.sum (relators.smul_aux α β γ r)⟧ : free_abelian_group β γ → β ⊗ γ) $
λ f g ⟨L, hL, hLfg⟩, quotient.sound
begin
clear _fun_match,
induction L generalizing f g,
{ existsi [],
have : f = g,
by simpa [add_neg_eq_zero] using hLfg.symm,
simp [this] },
{ specialize L_ih (λ z hzt, hL z (or.inr hzt)) L_tl.sum (0:free_abelian_group β γ),
specialize L_ih ⟨L_tl,
λ z hzt, hL z (or.inr hzt),
eq.symm (sub_zero _)⟩,
specialize L_ih (eq.symm $ sub_zero _),
rcases L_ih with ⟨L', hL', hLfg'⟩,
rw [sum_zero_index] at hLfg',
simp at hLfg',
rcases hL L_hd (or.inl rfl) with h | h | h,
{ rcases h with ⟨x, y₁, y₂, n, h⟩,
existsi list.cons (relators.pair_add α (r • x) y₁ y₂ n) L',
split,
{ exact λ z hz, or.cases_on (list.eq_or_mem_of_mem_cons hz)
(λ hzh, or.inl ⟨r • x, y₁, y₂, n, hzh⟩)
(λ hzt, hL' z hzt) },
{ rw ← finsupp.sum_sub_index,
rw ← hLfg,
rw list.sum_cons,
rw @list.sum_cons _ _ L',
rw finsupp.sum_add_index,
rw ← hLfg',
rw h,
rw relators.pair_add.smul,
all_goals { intros, simp [relators.smul_aux], try {refl} } } },
{ rcases h with ⟨x₁, x₂, y, n, h⟩,
existsi list.cons (relators.add_pair α (r • x₁) (r • x₂) y n) L',
split,
{ exact λ z hz, or.cases_on (list.eq_or_mem_of_mem_cons hz)
(λ hzh, or.inr $ or.inl ⟨r • x₁, r • x₂, y, n, hzh⟩)
(λ hzt, hL' z hzt) },
{ rw ← finsupp.sum_sub_index,
rw ← hLfg,
rw list.sum_cons,
rw @list.sum_cons _ _ L',
rw finsupp.sum_add_index,
rw ← hLfg',
rw h,
rw relators.add_pair.smul,
all_goals { intros, simp [relators.smul_aux], try {refl} } } },
{ rcases h with ⟨r', x, y, n, h⟩,
existsi list.cons (relators.smul_trans α r' (r • x) y n) L',
split,
{ exact λ z hz, or.cases_on (list.eq_or_mem_of_mem_cons hz)
(λ hzh, or.inr $ or.inr ⟨r', r • x, y, n, hzh⟩)
(λ hzt, hL' z hzt) },
{ rw ← finsupp.sum_sub_index,
rw ← hLfg,
rw list.sum_cons,
rw @list.sum_cons _ _ L',
rw finsupp.sum_add_index,
rw ← hLfg',
rw h,
rw relators.smul_trans.smul,
all_goals { intros, simp [relators.smul_aux], try {refl} } } } }
end
protected theorem smul_add (r : α) (f g : β ⊗ γ) : smul α β γ r (add α β γ f g) = add α β γ (smul α β γ r f) (smul α β γ r g) :=
quotient.induction_on₂ f g $ λ m n, quotient.sound $ by rw [finsupp.sum_add_index]; all_goals { intros, simp [relators.smul_aux], try {refl} }
protected theorem add_smul (r₁ r₂ : α) (f : β ⊗ γ) : smul α β γ (r₁ + r₂) f = add α β γ (smul α β γ r₁ f) (smul α β γ r₂ f) :=
quotient.induction_on f $ λ m, quotient.sound $
begin
unfold relators.smul_aux,
simp [add_smul],
rcases structural_theorem β γ m with ⟨S, hS, hSm⟩,
rw ← hSm,
apply symm,
apply mem_closure_of_finset,
existsi S,
revert m hS hSm,
apply finset.induction_on S,
{ intros m hS hSm,
existsi id,
split,
{ simp,
rw sum_zero_index,
rw sum_zero_index,
rw sum_zero_index,
simp },
{ intros x hx,
exfalso,
exact hx } },
{ intros g T hgT ih m hS hSm,
rcases hS g (finset.mem_insert_self g T) with ⟨x, y, n, H, h⟩,
rcases ih (T.sum id) (λ g' hg', hS g' $
finset.mem_insert_of_mem hg') rfl with ⟨φ', hst', hss'⟩,
existsi (λ f, if f = g then finsupp.single (r₁ • x, y) n +
finsupp.single (r₂ • x, y) n -
finsupp.single (r₁ • x + r₂ • x, y) n else φ' f),
split,
{ rw finset.sum_insert,
rw finset.sum_insert,
rw finsupp.sum_add_index,
rw finsupp.sum_add_index,
rw finsupp.sum_add_index,
rw if_pos rfl,
rw h,
rw id.def,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
have h1 : finset.sum T
(λ (f : free_abelian_group β γ),
ite (f = finsupp.single (x, y) n)
(finsupp.single (r₁ • x, y) n + finsupp.single (r₂ • x, y) n -
finsupp.single (r₁ • x + r₂ • x, y) n)
(φ' f)) = finset.sum T φ',
{ apply finset.sum_congr,
{ refl },
{ intros g' hg',
have h1 : g' ≠ g,
{ intro hgg',
rw hgg' at hg',
exact hgT hg' },
rw h at h1,
rw if_neg h1 } },
rw h1,
rw hst',
unfold prod.fst,
unfold prod.snd,
simp,
all_goals { intros,
try {rw finsupp.single_zero},
try {rw finsupp.single_zero},
try {rw finsupp.single_add},
try {refl},
try {refl},
try {exact hgT} } },
{ intros f' hf',
rw finset.mem_insert at hf',
cases hf',
{ dsimp,
rw if_pos hf',
from or.inr (or.inl ⟨r₁ • x, r₂ • x, y, n, rfl⟩) },
{ have h1 : f' ≠ g,
{ intro hfg',
rw hfg' at hf',
exact hgT hf' },
dsimp,
rw if_neg h1,
from hss' f' hf' } } }
end
protected theorem mul_smul (r₁ r₂ : α) (f : β ⊗ γ) : smul α β γ (r₁ * r₂) f = smul α β γ r₁ (smul α β γ r₂ f) :=
quotient.induction_on f $ λ m, quotient.sound $
begin
unfold relators.smul_aux,
simp [mul_smul],
rcases structural_theorem β γ m with ⟨S, hS, hSm⟩,
rw ← hSm,
apply symm,
apply mem_closure_of_finset,
existsi S,
existsi (λ f, 0 : free_abelian_group β γ → free_abelian_group β γ),
revert m hS hSm,
apply finset.induction_on S,
{ intros m hS hSm,
split,
{ simp,
rw sum_zero_index,
rw sum_zero_index,
rw sum_zero_index,
simp },
{ intros x hx,
exfalso,
exact hx } },
{ intros g T hgT ih m hS hSm,
rcases hS g (finset.mem_insert_self g T) with ⟨x, y, n, H, h⟩,
rcases ih (T.sum id) (λ g' hg', hS g' $
finset.mem_insert_of_mem hg') rfl with ⟨hst', hss'⟩,
split,
{ rw finset.sum_insert,
rw finset.sum_insert,
rw finset.sum_const_zero,
rw finset.sum_const_zero at hst',
rw finsupp.sum_add_index,
rw finsupp.sum_add_index,
rw finsupp.sum_add_index,
rw h,
rw id.def,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
unfold prod.fst,
unfold prod.snd,
rw add_comm_group.zero_add,
rw hst',
simp,
all_goals { intros,
try {rw finsupp.single_zero},
try {rw finsupp.single_zero},
try {rw finsupp.single_add},
try {refl},
try {refl},
try {exact hgT} } },
{ intros f' hf',
dsimp,
exact relators.zero_mem α β γ } }
end
protected theorem one_smul (f : β ⊗ γ) : smul α β γ 1 f = f :=
quotient.induction_on f $ λ m, quotient.sound $ by simp [relators.smul_aux]
instance : module α (β ⊗ γ) :=
{ smul := smul α β γ,
smul_add := tensor_product.smul_add α β γ,
add_smul := tensor_product.add_smul α β γ,
mul_smul := tensor_product.mul_smul α β γ,
one_smul := tensor_product.one_smul α β γ }
@[simp] lemma add_quot (f g : free_abelian_group β γ) : @has_add.add (β ⊗ γ) _ (⟦f⟧ : β ⊗ γ) ⟦g⟧ = ⟦f + g⟧ := rfl
@[simp] lemma neg_quot (f : free_abelian_group β γ) : @has_neg.neg (β ⊗ γ) _ (⟦f⟧ : β ⊗ γ) = ⟦-f⟧ := rfl
variables {α β γ}
def tprod : β → γ → β ⊗ γ :=
λ x y, ⟦finsupp.single (x, y) 1⟧
infix ` ⊗ₛ `:100 := tprod
variables {r r₁ r₂ : α} {x x₁ x₂ : β} {y y₁ y₂ : γ}
theorem tprod_unfold : x ⊗ₛ y = tprod x y := rfl
theorem tprod.is_bilinear_map : is_bilinear_map (@tprod α _ β γ _ _) :=
{ add_pair := λ x y z, quotient.sound $ setoid.symm $
⟨[(finsupp.single (x, z) 1 +
finsupp.single (y, z) 1 -
finsupp.single (x + y, z) 1 : free_abelian_group β γ)],
λ u hu, or.inr $ or.inl ⟨x, y, z, 1, list.eq_of_mem_singleton hu⟩,
list.sum_singleton⟩,
pair_add := λ x y z, quotient.sound $ setoid.symm $
⟨[(finsupp.single (x, y) 1 +
finsupp.single (x, z) 1 -
finsupp.single (x, y + z) 1 : free_abelian_group β γ)],
λ u hu, or.inl ⟨x, y, z, 1, list.eq_of_mem_singleton hu⟩,
list.sum_singleton⟩,
smul_pair := λ r x y, quotient.sound $ setoid.symm $
begin
simp [relators.smul_aux],
rw finsupp.sum_single_index,
exact finsupp.single_zero
end,
pair_smul := λ r x y, quotient.sound $ setoid.symm $
begin
simp [relators.smul_aux],
rw finsupp.sum_single_index,
unfold prod.fst,
unfold prod.snd,
existsi ([(finsupp.single (r • x, y) 1 -
finsupp.single (x, r • y) 1 : free_abelian_group β γ)]),
split,
{ intros z hz,
rw list.mem_singleton at hz,
rw hz,
from or.inr (or.inr ⟨r, x, y, 1, by simp [relators.smul_trans]⟩) },
simp [list.sum_singleton],
{ rw finsupp.single_zero,
refl }
end }
@[simp] lemma add_tprod : (x₁ + x₂) ⊗ₛ y = x₁ ⊗ₛ y + x₂ ⊗ₛ y :=
tprod.is_bilinear_map.add_pair x₁ x₂ y
@[simp] lemma tprod_add : x ⊗ₛ (y₁ + y₂) = x ⊗ₛ y₁ + x ⊗ₛ y₂ :=
tprod.is_bilinear_map.pair_add x y₁ y₂
@[simp] lemma smul_tprod : (r • x) ⊗ₛ y = r • x ⊗ₛ y :=
tprod.is_bilinear_map.smul_pair r x y
@[simp] lemma tprod_smul : x ⊗ₛ (r • y) = r • x ⊗ₛ y :=
tprod.is_bilinear_map.pair_smul r x y
@[simp] lemma zero_tprod : (0:β) ⊗ₛ y = 0 :=
tprod.is_bilinear_map.zero_pair y
@[simp] lemma tprod_zero {x : β} : x ⊗ₛ (0:γ) = 0 :=
tprod.is_bilinear_map.pair_zero x
namespace universal_property
variables {β γ α₁}
variables {f : β → γ → α₁} (hf : is_bilinear_map f)
include β γ α₁ hf
def factor_aux : free_abelian_group β γ → α₁ :=
λ g : free_abelian_group β γ, (g.sum (λ z n, n • (f z.fst z.snd)))
theorem factor_equiv : ∀ g₁ g₂ : free_abelian_group β γ, g₁ ≈ g₂ → factor_aux hf g₁ = factor_aux hf g₂ :=
λ g₁ g₂ ⟨L, hL, hgL⟩,
begin
clear _fun_match _x,
induction L generalizing hgL hL g₂ g₁,
{ simp at hgL,
replace hgL := hgL.symm,
rw add_neg_eq_zero at hgL,
rw hgL },
{ specialize L_ih L_tl.sum 0,
specialize L_ih (λ x hx, hL x (list.mem_cons_of_mem L_hd hx)),
specialize L_ih (sub_zero _).symm,
rw ← sub_eq_zero,
unfold factor_aux at L_ih ⊢,
rw ← finsupp.sum_sub_index,
rw ← hgL,
rw @list.sum_cons _ _ L_tl,
rw finsupp.sum_add_index,
rw L_ih,
rw sum_zero_index',
specialize hL L_hd,
specialize hL (or.inl rfl),
rcases hL with h | h | h,
{ rcases h with ⟨x, y₁, y₂, n, h⟩,
rw h,
unfold relators.pair_add,
rw finsupp.sum_sub_index,
rw finsupp.sum_add_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw ← smul_add,
rw ← smul_sub,
rw hf.pair_add,
simp,
{ dsimp, rw zero_smul },
{ dsimp, rw zero_smul },
{ dsimp, rw zero_smul },
{ intros, dsimp, rw zero_smul },
{ intros, simp, rw add_smul },
{ intros, simp [add_smul] } },
{ rcases h with ⟨x₁, x₂, y, n, h⟩,
rw h,
unfold relators.add_pair,
rw finsupp.sum_sub_index,
rw finsupp.sum_add_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw ← smul_add,
rw ← smul_sub,
rw hf.add_pair,
simp,
{ dsimp, rw zero_smul },
{ dsimp, rw zero_smul },
{ dsimp, rw zero_smul },
{ intros, dsimp, rw zero_smul },
{ intros, simp, rw add_smul },
{ intros, simp [add_smul] } },
{ rcases h with ⟨r, x, y, n, h⟩,
rw h,
unfold relators.smul_trans,
rw finsupp.sum_sub_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw ← smul_sub,
rw hf.smul_pair,
rw hf.pair_smul,
simp,
{ dsimp, rw zero_smul },
{ dsimp, rw zero_smul },
{ intros, simp [add_smul] } },
{ intros, dsimp, rw zero_smul },
{ intros, simp, rw add_smul },
{ intros, simp [add_smul] } }
end
def factor : β ⊗ γ → α₁ :=
quotient.lift (factor_aux hf) (factor_equiv hf)
theorem factor_add : ∀ g₁ g₂ : β ⊗ γ, factor hf (g₁ + g₂) = factor hf g₁ + factor hf g₂ :=
λ x y, quotient.induction_on₂ x y
begin
intros m n,
simp [universal_property.factor],
simp [universal_property.factor_aux],
rw finsupp.sum_add_index,
{ intros, dsimp, rw zero_smul },
{ intros, simp [add_smul] }
end
theorem factor_smul : ∀ (r : α) (g : β ⊗ γ), factor hf (r • g) = r • factor hf g :=
λ r x, quotient.induction_on x
begin
intros m,
simp [has_scalar.smul, smul, relators.smul_aux],
rcases structural_theorem β γ m with ⟨S, hS, hSm⟩,
rw ← hSm,
revert m hS hSm,
apply finset.induction_on S,
{ intros m hS hSm,
unfold universal_property.factor,
unfold universal_property.factor_aux,
simp [finsupp.sum_zero_index],
rw sum_zero_index,
rw sum_zero_index',
simp },
{ intros n T hnT ih m hS hSm,
unfold universal_property.factor,
unfold universal_property.factor_aux,
simp,
specialize ih (finset.sum T id),
specialize ih (λ g hg, hS g (finset.mem_insert_of_mem hg)),
specialize ih rfl,
unfold universal_property.factor at ih,
unfold universal_property.factor_aux at ih,
simp at ih,
rw finset.sum_insert,
rw finsupp.sum_add_index,
rw finsupp.sum_add_index,
rw finsupp.sum_add_index,
rw ih,
specialize hS n (finset.mem_insert_self n T),
rcases hS with ⟨x', y', n', H', hn'⟩,
rw hn',
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw finsupp.sum_single_index,
rw hf.smul_pair,
simp [smul_add, smul_smul, mul_comm],
{ dsimp, rw zero_smul },
{ dsimp, rw zero_smul },
{ rw finsupp.single_zero, refl },
{ intros, dsimp, rw zero_smul },
{ intros, simp [add_smul] },
{ intros, dsimp, rw zero_smul },
{ intros, simp [add_smul] },
{ intros, rw finsupp.single_zero, refl },
{ intros, rw finsupp.single_add },
{ exact hnT } }
end
theorem factor_linear : is_linear_map (factor hf) :=
{ add := factor_add hf,
smul := factor_smul hf }
theorem factor_commutes : ∀ x y, factor hf (x ⊗ₛ y) = f x y :=
begin
intros,
simp [function.comp, tprod, factor, factor_aux],
simp [finsupp.sum_single_index]
end
theorem factor_unique (h : β ⊗ γ → α₁) (H : is_linear_map h)
(hh : ∀ x y, h (x ⊗ₛ y) = f x y) :
h = factor hf :=
begin
apply funext,
intro x,
apply quotient.induction_on x,
intro y,
unfold universal_property.factor,
unfold universal_property.factor_aux,
simp,
rcases structural_theorem β γ y with ⟨S, hS, hSy⟩,
revert hSy hS y,
apply finset.induction_on S,
{ intros y hS hSy,
rw ← hSy,
rw finset.sum_empty,
rw sum_zero_index',
exact H.zero },
{ intros n T hnT ih y hS hSy,
rw ← hSy,
rw finset.sum_insert,
rw ← add_quot,
rw H.add,
rw finsupp.sum_add_index,
rw id.def,
specialize ih (T.sum id),
specialize ih (λ z hz, hS z (finset.mem_insert_of_mem hz)),
specialize ih rfl,
rw ih,
specialize hS n,
specialize hS (finset.mem_insert_self n T),
rcases hS with ⟨x', y', n', H', hn'⟩,
rw hn',
rw finsupp.sum_single_index,
specialize hh x' y',
simp [function.comp, tprod] at hh,
clear H' hn',
suffices : h ⟦finsupp.single (x', y') n'⟧ = n' • (f x' y'),
{ rw this },
cases n',
{ induction n' with n' ih',
{ rw int.of_nat_zero,
rw finsupp.single_zero,
dsimp, rw zero_smul,
exact H.zero },
{ rw int.of_nat_succ,
rw finsupp.single_add,
rw ← add_quot,
rw H.add,
rw [ih', hh],
simp, rw add_smul,
rw one_smul } },
{ induction n' with n' ih',
{ rw int.neg_succ_of_nat_eq,
rw finsupp.single_neg,
simp,
rw ← neg_quot,
rw H.neg,
rw hh },
{ rw int.neg_succ_of_nat_coe,
rw int.neg_succ_of_nat_eq at ih',
rw int.coe_nat_add,
rw finsupp.single_neg at ih' ⊢,
rw ← neg_quot at ih' ⊢,
rw H.neg at ih' ⊢,
rw nat.succ_eq_add_one,
rw finsupp.single_add,
rw ← add_quot,
rw H.add,
rw neg_add,
rw int.coe_nat_add,
rw int.coe_nat_eq 1,
rw int.of_nat_one,
rw ih',
rw hh,
simp [add_smul] } },
{ dsimp, rw zero_smul },
{ intros, dsimp, rw zero_smul },
{ intros, simp [add_smul] },
{ exact hnT } }
end
end universal_property
instance universal_property {f : β → γ → α₁} (hf : is_bilinear_map f) :
type_singleton { h : β ⊗ γ → α₁ // ∃ (H : is_linear_map h), ∀ x y, h (x ⊗ₛ y) = f x y } :=
{ default := ⟨universal_property.factor hf,
universal_property.factor_linear hf,
universal_property.factor_commutes hf⟩,
unique := λ ⟨h, H, hh⟩, subtype.eq $
universal_property.factor_unique hf h H hh }
variables {β γ α₁}
protected theorem ext {f g : β ⊗ γ → α₁} (hf : is_linear_map f) (hg : is_linear_map g)
(h : ∀ x y, f (x ⊗ₛ y) = g (x ⊗ₛ y)) (z : β ⊗ γ) : f z = g z :=
have h1 : _ := universal_property.factor_unique
(tprod.is_bilinear_map.comp hg)
f hf h,
have h2 : _ := universal_property.factor_unique
(tprod.is_bilinear_map.comp hg)
g hg (λ x y, rfl),
congr_fun (h1.trans h2.symm) z
variables (β γ)
protected def id : β ⊗ α ≃ₘ β :=
let hba1 : β → α → β := λ x y, y • x in
have hba2 : is_bilinear_map hba1,
by refine {..}; intros; simp [hba1, smul_add, add_smul, smul_smul, mul_comm, mul_left_comm],
let hba3 : β ⊗ α → β := universal_property.factor hba2 in
have hba4 : _ := universal_property.factor_linear hba2,
have hba5 : _ := universal_property.factor_commutes hba2,
let hb1 : β → β ⊗ α := λ x, x ⊗ₛ 1 in
have hb2 : is_linear_map hb1, from
{ add := λ x y, add_tprod,
smul := λ r x, smul_tprod },
have hbb1 : ∀ (x : β) (y : α), hb1 (hba3 (x ⊗ₛ y)) = x ⊗ₛ y,
from λ x y, calc
hb1 (hba3 (x ⊗ₛ y))
= (y • x) ⊗ₛ 1 : congr_arg hb1 (hba5 _ _)
... = y • x ⊗ₛ 1 : smul_tprod
... = x ⊗ₛ (y • 1) : eq.symm $ tprod_smul
... = x ⊗ₛ y : by simp,
{ to_fun := hba3,
inv_fun := hb1,
left_inv := tensor_product.ext (hb2.comp hba4) is_linear_map.id hbb1,
right_inv := λ x, by simp *,
linear := hba4 }
protected def comm : β ⊗ γ ≃ₘ γ ⊗ β :=
let hbg1 : β → γ → γ ⊗ β := λ x y, y ⊗ₛ x in
have hbg2 : is_bilinear_map hbg1, from
{ add_pair := λ x y z, tprod_add,
pair_add := λ x y z, add_tprod,
smul_pair := λ r x y, tprod_smul,
pair_smul := λ r x y, smul_tprod },
let hbg3 : β ⊗ γ → γ ⊗ β := universal_property.factor hbg2 in
have hbg4 : _ := universal_property.factor_linear hbg2,
have hbg5 : _ := universal_property.factor_commutes hbg2,
let hgb1 : γ → β → β ⊗ γ := λ y x , x ⊗ₛ y in
have hgb2 : is_bilinear_map hgb1, from
{ add_pair := λ x y z, tprod_add,
pair_add := λ x y z, add_tprod,
smul_pair := λ r x y, tprod_smul,
pair_smul := λ r x y, smul_tprod },
let hgb3 : γ ⊗ β → β ⊗ γ := universal_property.factor hgb2 in
have hgb4 : _ := universal_property.factor_linear hgb2,
have hgb5 : _ := universal_property.factor_commutes hgb2,
have hbb1 : ∀ x y, (hgb3 ∘ hbg3) (x ⊗ₛ y) = x ⊗ₛ y,
from λ x y, by simp [function.comp, *],
have hbb2 : is_linear_map (hgb3 ∘ hbg3) := hgb4.comp hbg4,
have hbb3 : _ := tensor_product.ext hbb2 is_linear_map.id hbb1,
have hgg1 : ∀ y x, (hbg3 ∘ hgb3) (y ⊗ₛ x) = y ⊗ₛ x,
from λ x y, by simp [function.comp, *],
have hgg2 : is_linear_map (hbg3 ∘ hgb3) := hbg4.comp hgb4,
have hgg3 : _ := tensor_product.ext hgg2 is_linear_map.id hgg1,
{ to_fun := hbg3,
inv_fun := hgb3,
left_inv := hbb3,
right_inv := hgg3,
linear := hbg4 }
protected def prod_tensor : (β × γ) ⊗ α₁ ≃ₘ β ⊗ α₁ × γ ⊗ α₁ :=
let ha1 : β × γ → α₁ → β ⊗ α₁ × γ ⊗ α₁ :=
λ z r, (z.fst ⊗ₛ r, z.snd ⊗ₛ r) in
have ha2 : is_bilinear_map ha1, from
{ add_pair := λ x y z, prod.ext.2 ⟨add_tprod, add_tprod⟩,
pair_add := λ x y z, prod.ext.2 ⟨tprod_add, tprod_add⟩,
smul_pair := λ r x y, prod.ext.2 ⟨smul_tprod, smul_tprod⟩ ,
pair_smul := λ r x y, prod.ext.2 ⟨tprod_smul, tprod_smul⟩ },
let ha3 : (β × γ) ⊗ α₁ → β ⊗ α₁ × γ ⊗ α₁ :=
universal_property.factor ha2 in
have ha4 : _ := universal_property.factor_linear ha2,
have ha5 : _ := universal_property.factor_commutes ha2,
let hb1 : β → α₁ → (β × γ) ⊗ α₁ :=
λ x r, (x, 0) ⊗ₛ r in
have hb2 : is_bilinear_map hb1, from
{ add_pair := λ x y z, calc
(x + y, (0:γ)) ⊗ₛ z
= (x + y, 0 + 0) ⊗ₛ z : congr_arg (λ r, (x + y, r) ⊗ₛ z) (zero_add 0).symm
... = ((x, 0) + (y, 0)) ⊗ₛ z : rfl
... = (x, 0) ⊗ₛ z + (y, 0) ⊗ₛ z : add_tprod,
pair_add := λ x y z, tprod_add,
smul_pair := λ r x y, calc
(r • x, (0:γ)) ⊗ₛ y
= (r • (x, 0)) ⊗ₛ y : by simp only [prod.smul_prod, smul_zero]
... = r • (x, 0) ⊗ₛ y : smul_tprod,
pair_smul := λ r x y, tprod_smul },
let hb3 : β ⊗ α₁ → (β × γ) ⊗ α₁ :=
universal_property.factor hb2 in
have hb4 : _ := universal_property.factor_linear hb2,
have hb5 : _ := universal_property.factor_commutes hb2,
have hb6 : ∀ x, ha3 (hb3 x) = prod.inl x := tensor_product.ext (ha4.comp hb4) prod.is_linear_map_prod_inl $ λ x y, calc
ha3 (hb3 (x ⊗ₛ y))
= ha3 ((x, 0) ⊗ₛ y) : congr_arg ha3 (hb5 x y)
... = (x ⊗ₛ y, 0 ⊗ₛ y) : ha5 (x, 0) y
... = (x ⊗ₛ y, 0) : congr_arg (λ z, (x ⊗ₛ y, z)) zero_tprod,
let hc1 : γ → α₁ → (β × γ) ⊗ α₁ :=
λ x r, (0, x) ⊗ₛ r in
have hc2 : is_bilinear_map hc1, from
{ add_pair := λ x y z, calc
((0:β), x + y) ⊗ₛ z
= (0 + 0, x + y) ⊗ₛ z : congr_arg (λ r, (r, x + y) ⊗ₛ z) (zero_add 0).symm
... = ((0, x) + (0, y)) ⊗ₛ z : rfl
... = (0, x) ⊗ₛ z + (0, y) ⊗ₛ z : add_tprod,
pair_add := λ x y z, tprod_add,
smul_pair := λ r x y, calc
((0:β), r • x) ⊗ₛ y
= (r • (0, x)) ⊗ₛ y : by simp only [prod.smul_prod, smul_zero]
... = r • (0, x) ⊗ₛ y : smul_tprod,
pair_smul := λ r x y, tprod_smul },
let hc3 : γ ⊗ α₁ → (β × γ) ⊗ α₁ :=
universal_property.factor hc2 in
have hc4 : _ := universal_property.factor_linear hc2,
have hc5 : _ := universal_property.factor_commutes hc2,
have hc6 : ∀ y, ha3 (hc3 y) = prod.inr y := tensor_product.ext (ha4.comp hc4) prod.is_linear_map_prod_inr $ λ x y, calc
ha3 (hc3 (x ⊗ₛ y))
= ha3 ((0, x) ⊗ₛ y) : congr_arg ha3 (hc5 x y)
... = (0 ⊗ₛ y, x ⊗ₛ y) : ha5 (0, x) y
... = (0, x ⊗ₛ y) : congr_arg (λ z, (z, x ⊗ₛ y)) zero_tprod,
let hd1 : β ⊗ α₁ × γ ⊗ α₁ → (β × γ) ⊗ α₁ :=
λ z, hb3 z.fst + hc3 z.snd in
have hd2 : is_linear_map hd1, from
{ add := λ x y, calc
hb3 (x + y).fst + hc3 (x + y).snd
= hb3 (x.fst + y.fst) + hc3 (x.snd + y.snd) : rfl
... = (hb3 x.fst + hb3 y.fst) + hc3 (x.snd + y.snd) : congr_arg (λ z, z + hc3 (x.snd + y.snd)) (hb4.add x.fst y.fst)
... = (hb3 x.fst + hb3 y.fst) + (hc3 x.snd + hc3 y.snd) : congr_arg (λ z, (hb3 x.fst + hb3 y.fst) + z) (hc4.add x.snd y.snd)
... = hb3 x.fst + (hb3 y.fst + (hc3 x.snd + hc3 y.snd)) : add_assoc _ _ _
... = hb3 x.fst + ((hc3 x.snd + hc3 y.snd) + hb3 y.fst) : congr_arg _ (add_comm _ _)
... = hb3 x.fst + (hc3 x.snd + (hc3 y.snd + hb3 y.fst)) : congr_arg _ (add_assoc _ _ _)
... = hb3 x.fst + (hc3 x.snd + (hb3 y.fst + hc3 y.snd)) : by have := congr_arg (λ z, hb3 x.fst + (hc3 x.snd + z)) (add_comm (hc3 y.snd) (hb3 y.fst)); dsimp at this; exact this
... = (hb3 x.fst + hc3 x.snd) + (hb3 y.fst + hc3 y.snd) : eq.symm $ add_assoc _ _ _,
smul := λ r x, calc
hb3 (r • x.fst) + hc3 (r • x.snd)
= hb3 (r • x.fst) + r • (hc3 x.snd) : congr_arg _ (hc4.smul r x.snd)
... = r • (hb3 x.fst) + r • (hc3 x.snd) : congr_arg (λ z, z + r • (hc3 x.snd)) (hb4.smul r x.fst)
... = r • (hb3 x.fst + hc3 x.snd) : eq.symm $ @smul_add _ _ _ _ r (hb3 x.fst) (hc3 x.snd)
... = r • hd1 x : rfl },
have h1 : is_linear_map (hd1 ∘ ha3), from hd2.comp ha4,
have h2 : _ := tensor_product.ext h1 is_linear_map.id (λ x y, by simp [function.comp, *, add_tprod.symm]),
have h3 : ∀ z, (ha3 ∘ hd1) z = id z, from λ z, calc
ha3 (hd1 z)
= ha3 (hb3 z.fst + hc3 z.snd) : rfl
... = ha3 (hb3 z.fst) + ha3 (hc3 z.snd) : ha4.add _ _
... = prod.inl z.fst + prod.inr z.snd : by rw [hb6, hc6]
... = (z.fst + 0, 0 + z.snd) : rfl
... = z : by cases z; simp [prod.inl, prod.inr],
{ to_fun := ha3,
inv_fun := hd1,
left_inv := h2,
right_inv := h3,
linear := ha4 }
protected def assoc : (β ⊗ γ) ⊗ α₁ ≃ₘ β ⊗ (γ ⊗ α₁) :=
let ha1 (z : α₁) : β → γ → β ⊗ (γ ⊗ α₁) :=
λ x y, x ⊗ₛ (y ⊗ₛ z) in
have ha2 : Π (z : α₁), is_bilinear_map (ha1 z), from λ z,
{ add_pair := λ m n k, add_tprod,
pair_add := λ m n k, calc
m ⊗ₛ ((n + k) ⊗ₛ z)
= m ⊗ₛ (n ⊗ₛ z + k ⊗ₛ z) : congr_arg (λ b, m ⊗ₛ b) add_tprod
... = m ⊗ₛ (n ⊗ₛ z) + m ⊗ₛ (k ⊗ₛ z) : tprod_add,
smul_pair := λ r m n, smul_tprod,
pair_smul := λ r m n, calc
m ⊗ₛ ((r • n) ⊗ₛ z)
= m ⊗ₛ (r • n ⊗ₛ z) : congr_arg _ smul_tprod
... = r • m ⊗ₛ (n ⊗ₛ z) : tprod_smul },
let ha3 : β ⊗ γ → α₁ → β ⊗ (γ ⊗ α₁) :=
λ xy z, universal_property.factor (ha2 z) xy in
have ha4 : _ := λ z, universal_property.factor_linear (ha2 z),
have ha5 : _ := λ z, universal_property.factor_commutes (ha2 z),
have ha6 : is_bilinear_map ha3, from
{ add_pair := λ m n k, (ha4 k).add m n,
pair_add := λ m n k, (tensor_product.ext (ha4 $ n + k) ((ha4 n).map_add (ha4 k)) $ λ x y, calc
ha3 (x ⊗ₛ y) (n + k)
= x ⊗ₛ (y ⊗ₛ (n + k)) : ha5 (n + k) x y
... = x ⊗ₛ (y ⊗ₛ n + y ⊗ₛ k) : congr_arg ((⊗ₛ) x) tprod_add
... = x ⊗ₛ (y ⊗ₛ n) + x ⊗ₛ (y ⊗ₛ k) : tprod_add
... = x ⊗ₛ (y ⊗ₛ n) + ha3 (x ⊗ₛ y) k : congr_arg (λ b, x ⊗ₛ (y ⊗ₛ n) + b) (ha5 k _ _).symm
... = ha3 (x ⊗ₛ y) n + ha3 (x ⊗ₛ y) k : congr_arg (λ b, b + ha3 (x ⊗ₛ y) k) (ha5 n _ _).symm)
m,
smul_pair := λ r x y, (ha4 y).smul r x,
pair_smul := λ r x y, (tensor_product.ext (ha4 $ r • y) (ha4 y).map_smul_right $ λ m n, calc
ha3 (m ⊗ₛ n) (r • y)
= m ⊗ₛ (n ⊗ₛ (r • y)) : ha5 (r • y) m n
... = m ⊗ₛ (r • n ⊗ₛ y) : congr_arg _ tprod_smul
... = r • m ⊗ₛ (n ⊗ₛ y) : tprod_smul
... = r • ha3 (m ⊗ₛ n) y : congr_arg _ (ha5 y m n).symm)
x },
let ha7 : (β ⊗ γ) ⊗ α₁ → β ⊗ (γ ⊗ α₁) :=
universal_property.factor ha6 in
have ha8 : _ := universal_property.factor_linear ha6,
have ha9 : _ := universal_property.factor_commutes ha6,
let hb1 (x : β) : γ → α₁ → (β ⊗ γ) ⊗ α₁ :=
λ y z, (x ⊗ₛ y) ⊗ₛ z in
have hb2 : Π (x : β), is_bilinear_map (hb1 x), from λ x,
{ add_pair := λ m n k, calc
(x ⊗ₛ (m + n)) ⊗ₛ k
= (x ⊗ₛ m + x ⊗ₛ n) ⊗ₛ k : congr_arg (λ z, z ⊗ₛ k) tprod_add
... = (x ⊗ₛ m) ⊗ₛ k + (x ⊗ₛ n) ⊗ₛ k : add_tprod,
pair_add := λ m n k, tprod_add,
smul_pair := λ r m n, calc
(x ⊗ₛ (r • m)) ⊗ₛ n
= (r • x ⊗ₛ m) ⊗ₛ n : congr_arg (λ z, z ⊗ₛ n) tprod_smul
... = r • (x ⊗ₛ m) ⊗ₛ n : smul_tprod,
pair_smul := λ r m n, tprod_smul },
let hb3 : β → γ ⊗ α₁ → (β ⊗ γ) ⊗ α₁ :=
λ x, universal_property.factor (hb2 x) in
have hb4 : _ := λ x, universal_property.factor_linear (hb2 x),
have hb5 : _ := λ x, universal_property.factor_commutes (hb2 x),
have hb6 : is_bilinear_map hb3, from
{ add_pair := λ m n k, (tensor_product.ext (hb4 $ m + n) ((hb4 m).map_add (hb4 n)) $ λ x y, calc
hb3 (m + n) (x ⊗ₛ y)
= ((m + n) ⊗ₛ x) ⊗ₛ y : (hb5 $ m + n) x y
... = (m ⊗ₛ x + n ⊗ₛ x) ⊗ₛ y : congr_arg (λ z, z ⊗ₛ y) add_tprod
... = (m ⊗ₛ x) ⊗ₛ y + (n ⊗ₛ x) ⊗ₛ y : add_tprod
... = (m ⊗ₛ x) ⊗ₛ y + hb3 n (x ⊗ₛ y) : congr_arg _ ((hb5 n) x y).symm
... = hb3 m (x ⊗ₛ y) + hb3 n (x ⊗ₛ y) : congr_arg (λ z, z + hb3 n (x ⊗ₛ y)) ((hb5 m) x y).symm)
k,
pair_add := λ m n k, (hb4 m).add n k,
smul_pair := λ r x y, (tensor_product.ext (hb4 $ r • x) (hb4 x).map_smul_right $ λ m n, calc
hb3 (r • x) (m ⊗ₛ n)
= ((r • x) ⊗ₛ m) ⊗ₛ n : (hb5 $ r • x) m n
... = (r • x ⊗ₛ m) ⊗ₛ n : congr_arg (λ z, z ⊗ₛ n) smul_tprod
... = r • (x ⊗ₛ m) ⊗ₛ n : smul_tprod
... = r • hb3 x (m ⊗ₛ n) : congr_arg _ ((hb5 $ x) m n).symm)
y,
pair_smul := λ r x y, (hb4 x).smul r y },
let hb7 : β ⊗ (γ ⊗ α₁) → (β ⊗ γ) ⊗ α₁ :=
universal_property.factor hb6 in
have hb8 : _ := universal_property.factor_linear hb6,
have hb9 : _ := universal_property.factor_commutes hb6,
have hc1 : _ := λ z, tensor_product.ext (hb8.comp $ ha6.linear_pair z) (tprod.is_bilinear_map.linear_pair z) $ λ x y, calc
hb7 (ha3 (x ⊗ₛ y) z)
= hb7 (x ⊗ₛ (y ⊗ₛ z)) : congr_arg hb7 (ha5 z x y)
... = hb3 x (y ⊗ₛ z) : hb9 x (y ⊗ₛ z)
... = (x ⊗ₛ y) ⊗ₛ z : hb5 x y z,
have hc2 : _ := tensor_product.ext (hb8.comp ha8) is_linear_map.id $ λ xy z, calc
hb7 (ha7 (xy ⊗ₛ z))
= hb7 (ha3 xy z) : congr_arg hb7 (ha9 xy z)
... = xy ⊗ₛ z : hc1 z xy,
have hd1 : _ := λ x, tensor_product.ext (ha8.comp $ hb6.pair_linear x) (tprod.is_bilinear_map.pair_linear x) $ λ y z, calc
ha7 (hb3 x (y ⊗ₛ z))
= ha7 ((x ⊗ₛ y) ⊗ₛ z) : congr_arg ha7 (hb5 x y z)
... = ha3 (x ⊗ₛ y) z : ha9 (x ⊗ₛ y) z
... = x ⊗ₛ (y ⊗ₛ z) : ha5 z x y,
have hd2 : _ := tensor_product.ext (ha8.comp hb8) is_linear_map.id $ λ x yz, calc
ha7 (hb7 (x ⊗ₛ yz))
= ha7 (hb3 x yz) : congr_arg ha7 (hb9 x yz)
... = x ⊗ₛ yz : hd1 x yz,
{ to_fun := ha7,
inv_fun := hb7,
left_inv := hc2,
right_inv := hd2,
linear := ha8 }
variables {α β γ α₁ β₁ γ₁}
variables {f : β → γ} (hf : is_linear_map f)
variables {g : β₁ → γ₁} (hg : is_linear_map g)
include hf hg
def tprod_map : β ⊗ β₁ → γ ⊗ γ₁ :=
let h1 : β → β₁ → γ ⊗ γ₁ :=
λ x y, f x ⊗ₛ g y in
have h2 : is_bilinear_map h1 :=
{ add_pair := λ m n k, by simp [h1]; rw [hf.add, add_tprod],
pair_add := λ m n k, by simp [h1]; rw [hg.add, tprod_add],
smul_pair := λ r m n, by simp [h1]; rw [hf.smul, smul_tprod],
pair_smul := λ r m n, by simp [h1]; rw [hg.smul, tprod_smul] },
universal_property.factor h2
theorem tprod_map.linear : is_linear_map (tprod_map hf hg) :=
universal_property.factor_linear _
theorem tprod_map.commutes (x : β) (y : β₁) :
tprod_map hf hg (x ⊗ₛ y) = f x ⊗ₛ g y :=
universal_property.factor_commutes
(tprod_map._proof_1 hf hg) x y
end tensor_product
def is_ring_hom.to_module {α : Type u} {β : Type v}
[comm_ring α] [comm_ring β]
(f : α → β) [is_ring_hom f] : module α β :=
{ smul := λ r x, f r * x,
smul_add := λ r x y, by simp [mul_add],
add_smul := λ r₁ r₂ x, by simp [is_ring_hom.map_add f, add_mul],
mul_smul := λ r₁ r₂ x, by simp [is_ring_hom.map_mul f, mul_assoc],
one_smul := λ x, by simp [is_ring_hom.map_one f] }
|
77301d53680cfe50c6cc280d90f300f6cb2603b2 | bae21755a4a03bbe0a5c22e258db8633407711ad | /library/init/category/reader.lean | 65c8a73105f1c023a57764d0f0d8c81ac532beff | [
"Apache-2.0"
] | permissive | nor-code/lean | f437357a8f85db0f06f186fa50fcb1bc75f6b122 | aa306af3d7c47de3c7937c98d3aa919eb8da6f34 | refs/heads/master | 1,662,613,329,886 | 1,586,696,014,000 | 1,586,696,014,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,978 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
The reader monad transformer for passing immutable state.
-/
prelude
import init.category.lift init.category.id init.category.alternative init.category.except
universes u v w
/-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/
structure reader_t (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) :=
(run : ρ → m α)
@[reducible] def reader (ρ : Type u) := reader_t ρ id
attribute [pp_using_anonymous_constructor] reader_t
namespace reader_t
section
variable {ρ : Type u}
variable {m : Type u → Type v}
variable [monad m]
variables {α β : Type u}
@[inline] protected def read : reader_t ρ m ρ :=
⟨pure⟩
@[inline] protected def pure (a : α) : reader_t ρ m α :=
⟨λ r, pure a⟩
@[inline] protected def bind (x : reader_t ρ m α) (f : α → reader_t ρ m β) : reader_t ρ m β :=
⟨λ r, do a ← x.run r,
(f a).run r⟩
instance : monad (reader_t ρ m) :=
{ pure := @reader_t.pure _ _ _, bind := @reader_t.bind _ _ _ }
@[inline] protected def lift (a : m α) : reader_t ρ m α :=
⟨λ r, a⟩
instance (m) [monad m] : has_monad_lift m (reader_t ρ m) :=
⟨@reader_t.lift ρ m _⟩
@[inline] protected def monad_map {ρ m m'} [monad m] [monad m'] {α} (f : Π {α}, m α → m' α) : reader_t ρ m α → reader_t ρ m' α :=
λ x, ⟨λ r, f (x.run r)⟩
instance (ρ m m') [monad m] [monad m'] : monad_functor m m' (reader_t ρ m) (reader_t ρ m') :=
⟨@reader_t.monad_map ρ m m' _ _⟩
@[inline] protected def adapt {ρ' : Type u} [monad m] {α : Type u} (f : ρ' → ρ) : reader_t ρ m α → reader_t ρ' m α :=
λ x, ⟨λ r, x.run (f r)⟩
protected def orelse [alternative m] {α : Type u} (x₁ x₂ : reader_t ρ m α) : reader_t ρ m α :=
⟨λ s, x₁.run s <|> x₂.run s⟩
protected def failure [alternative m] {α : Type u} : reader_t ρ m α :=
⟨λ s, failure⟩
instance [alternative m] : alternative (reader_t ρ m) :=
{ failure := @reader_t.failure _ _ _ _,
orelse := @reader_t.orelse _ _ _ _ }
instance (ε) [monad m] [monad_except ε m] : monad_except ε (reader_t ρ m) :=
{ throw := λ α, reader_t.lift ∘ throw,
catch := λ α x c, ⟨λ r, catch (x.run r) (λ e, (c e).run r)⟩ }
end
end reader_t
/-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader).
It does not contain `local` because this function cannot be lifted using `monad_lift`.
Instead, the `monad_reader_adapter` class provides the more general `adapt_reader` function.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_reader (ρ : out_param (Type u)) (n : Type u → Type u) :=
(lift {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α) → n α)
```
-/
class monad_reader (ρ : out_param (Type u)) (m : Type u → Type v) :=
(read : m ρ)
export monad_reader (read)
instance monad_reader_trans {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w}
[monad_reader ρ m] [has_monad_lift m n] : monad_reader ρ n :=
⟨monad_lift (monad_reader.read : m ρ)⟩
instance {ρ : Type u} {m : Type u → Type v} [monad m] : monad_reader ρ (reader_t ρ m) :=
⟨reader_t.read⟩
/-- Adapt a monad stack, changing the type of its top-most environment.
This class is comparable to [Control.Lens.Magnify](https://hackage.haskell.org/package/lens-4.15.4/docs/Control-Lens-Zoom.html#t:Magnify), but does not use lenses (why would it), and is derived automatically for any transformer implementing `monad_functor`.
Note: This class can be seen as a simplification of the more "principled" definition
```
class monad_reader_functor (ρ ρ' : out_param (Type u)) (n n' : Type u → Type u) :=
(map {α : Type u} : (∀ {m : Type u → Type u} [monad m], reader_t ρ m α → reader_t ρ' m α) → n α → n' α)
```
-/
class monad_reader_adapter (ρ ρ' : out_param (Type u)) (m m' : Type u → Type v) :=
(adapt_reader {α : Type u} : (ρ' → ρ) → m α → m' α)
export monad_reader_adapter (adapt_reader)
section
variables {ρ ρ' : Type u} {m m' : Type u → Type v}
instance monad_reader_adapter_trans {n n' : Type u → Type v} [monad_functor m m' n n'] [monad_reader_adapter ρ ρ' m m'] : monad_reader_adapter ρ ρ' n n' :=
⟨λ α f, monad_map (λ α, (adapt_reader f : m α → m' α))⟩
instance [monad m] : monad_reader_adapter ρ ρ' (reader_t ρ m) (reader_t ρ' m) :=
⟨λ α, reader_t.adapt⟩
end
instance (ρ : Type u) (m out) [monad_run out m] : monad_run (λ α, ρ → out α) (reader_t ρ m) :=
⟨λ α x, run ∘ x.run⟩
|
ada5cd021dc3f0df23a66ce41152b257e5942c6e | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Lean/Data/Json/Parser.lean | 3ad9d16e814b2e3ee3f9abb20004256f370a8d45 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,250 | lean | /-
Copyright (c) 2019 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Marc Huisinga
-/
import Lean.Data.Json.Basic
namespace Lean
open Std (RBNode RBNode.singleton RBNode.leaf)
inductive Quickparse.Result (α : Type)
| success (pos : String.Iterator) (res : α) : Quickparse.Result
| error (pos : String.Iterator) (err : String) : Quickparse.Result
def Quickparse (α : Type) : Type := String.Iterator → Quickparse.Result α
instance Quickparse.inhabited (α : Type) : Inhabited (Quickparse α) :=
⟨fun it => Quickparse.Result.error it ""⟩
namespace Quickparse
open Result
partial def skipWs : String.Iterator → String.Iterator | it =>
if it.hasNext then
let c := it.curr;
if c = '\u0009' ∨ c = '\u000a' ∨ c = '\u000d' ∨ c = '\u0020' then
skipWs it.next
else
it
else
it
@[inline]
protected def pure {α : Type} (a : α) : Quickparse α | it =>
success it a
@[inline]
protected def bind {α β : Type} (f : Quickparse α) (g : α → Quickparse β) : Quickparse β | it =>
match f it with
| success rem a => g a rem
| error pos msg => error pos msg
@[inline]
def fail {α : Type} (msg : String) : Quickparse α | it =>
error it msg
@[inline]
instance : Monad Quickparse :=
{ pure := @Quickparse.pure, bind := @Quickparse.bind }
def unexpectedEndOfInput := "unexpected end of input"
@[inline]
def peek? : Quickparse (Option Char) | it =>
if it.hasNext then
success it it.curr
else
success it none
@[inline]
def peek! : Quickparse Char := do
some c <- peek? | fail unexpectedEndOfInput;
pure c
@[inline]
def skip : Quickparse Unit | it =>
success it.next ()
@[inline]
def next : Quickparse Char := do
c ← peek!; skip;
pure c
def expect (s : String) : Quickparse Unit | it =>
if it.extract (it.forward s.length) = s then
success (it.forward s.length) ()
else
error it ("expected: " ++ s)
@[inline]
def ws : Quickparse Unit | it =>
success (skipWs it) ()
def expectedEndOfInput := "expected end of input"
@[inline]
def eoi : Quickparse Unit | it =>
if it.hasNext then
error it expectedEndOfInput
else
success it ()
end Quickparse
namespace Json.Parser
open Quickparse
@[inline]
def hexChar : Quickparse Nat := do
c ← next;
if '0' ≤ c ∧ c ≤ '9' then
pure $ c.val.toNat - '0'.val.toNat
else if 'a' ≤ c ∧ c ≤ 'f' then
pure $ c.val.toNat - 'a'.val.toNat
else if 'A' ≤ c ∧ c ≤ 'F' then
pure $ c.val.toNat - 'A'.val.toNat
else
fail "invalid hex character"
def escapedChar : Quickparse Char := do
c ← next;
match c with
| '\\' => pure '\\'
| '"' => pure '"'
| '/' => pure '/'
| 'b' => pure '\x08'
| 'f' => pure '\x0c'
| 'n' => pure '\n'
| 'r' => pure '\x0d'
| 't' => pure '\t'
| 'u' => do
u1 ← hexChar; u2 ← hexChar; u3 ← hexChar; u4 ← hexChar;
pure $ Char.ofNat $ 4096*u1 + 256*u2 + 16*u3 + u4
| _ => fail "illegal \\u escape"
partial def strCore : String → Quickparse String | acc => do
c ← peek!;
if c = '"' then do -- "
skip;
pure acc
else do
c ← next;
ec ←
if c = '\\' then
escapedChar
-- as to whether c.val > 0xffff should be split up and encoded with multiple \u,
-- the JSON standard is not definite: both directly printing the character
-- and encoding it with multiple \u is allowed. we choose the former.
else if 0x0020 ≤ c.val ∧ c.val ≤ 0x10ffff then
pure c
else
fail "unexpected character in string";
strCore (acc.push ec)
def str : Quickparse String := strCore ""
partial def natCore : Nat → Nat → Quickparse (Nat × Nat) | acc, digits => do
some c ← peek? | pure (acc, digits);
if '0' ≤ c ∧ c ≤ '9' then do
skip;
let acc' := 10*acc + (c.val.toNat - '0'.val.toNat);
natCore acc' (digits+1)
else
pure (acc, digits)
@[inline]
def lookahead (p : Char → Prop) (desc : String) [DecidablePred p] : Quickparse Unit := do
c <- peek!;
if p c then
pure ()
else
fail $ "expected " ++ desc
@[inline]
def natNonZero : Quickparse Nat := do
lookahead (fun c => '1' ≤ c ∧ c ≤ '9') "1-9";
(n, _) ← natCore 0 0;
pure n
@[inline]
def natNumDigits : Quickparse (Nat × Nat) := do
lookahead (fun c => '0' ≤ c ∧ c ≤ '9') "digit";
natCore 0 0
@[inline]
def natMaybeZero : Quickparse Nat := do
(n, _) ← natNumDigits;
pure n
def num : Quickparse JsonNumber := do
c ← peek!;
sign ←
if c = '-' then do
skip;
pure (-1 : Int)
else
pure 1;
c ← peek!;
res ←
if c = '0' then do
skip;
pure 0
else
natNonZero;
let res := JsonNumber.fromInt (sign * res);
c? ← peek?;
res ←
if c? = some '.' then do
skip;
(n, d) ← natNumDigits;
if d > usizeSz then do fail "too many decimals" else pure ();
let mantissa' := res.mantissa * (10^d : Nat) + n;
let exponent' := res.exponent + d;
pure $ JsonNumber.mk mantissa' exponent'
else
pure res;
c? ← peek?;
if c? = some 'e' ∨ c? = some 'E' then do
skip;
c ← peek!;
if c = '-' then do
skip;
n ← natMaybeZero;
pure (res.shiftr n)
else do
if c = '+' then skip else pure ();
n ← natMaybeZero;
if n > usizeSz then do fail "exp too large" else pure ();
pure (res.shiftl n)
else pure res
partial def arrayCore (anyCore : Unit → Quickparse Json) : Array Json → Quickparse (Array Json) | acc => do
hd ← anyCore ();
let acc' := acc.push hd;
c ← next;
if c = ']' then do
ws;
pure acc'
else if c = ',' then do
ws;
arrayCore acc'
else
fail "unexpected character in array"
partial def objectCore : (Unit → Quickparse Json) → Quickparse (RBNode String (fun _ => Json)) | anyCore => do
lookahead (fun c => c = '"') "\""; skip; -- "
k ← strCore ""; ws;
lookahead (fun c => c = ':') ":"; skip; ws;
v ← anyCore ();
c ← next;
if c = '}' then do
ws;
pure (RBNode.singleton k v)
else if c = ',' then do
ws;
kvs ← objectCore anyCore;
pure (kvs.insert strLt k v)
else
fail "unexpected character in object"
-- takes a unit parameter so that
-- we can use the equation compiler and recursion
partial def anyCore : Unit → Quickparse Json | () => do
c ← peek!;
if c = '[' then do
skip; ws;
c ← peek!;
if c = ']' then do
skip; ws;
pure (Json.arr (Array.mkEmpty 0))
else do
a ← arrayCore anyCore (Array.mkEmpty 4);
pure (Json.arr a)
else if c = '{' then do
skip; ws;
c ← peek!;
if c = '}' then do
skip; ws;
pure (Json.obj (RBNode.leaf))
else do
kvs ← objectCore anyCore;
pure (Json.obj kvs)
else if c = '"' then do --"
skip;
s ← strCore ""; ws;
pure (Json.str s)
else if c = 'f' then do
expect "false"; ws;
pure (Json.bool false)
else if c = 't' then do
expect "true"; ws;
pure (Json.bool true)
else if c = 'n' then do
expect "null"; ws;
pure Json.null
else if c = '-' ∨ ('0' ≤ c ∧ c ≤ '9') then do
n ← num; ws;
pure (Json.num n)
else
fail "unexpected input"
def any : Quickparse Json := do
ws;
res ← anyCore ();
eoi;
pure res
end Json.Parser
namespace Json
def parse (s : String) : Except String Lean.Json :=
match Json.Parser.any s.mkIterator with
| Result.success _ res => Except.ok res
| Result.error it err => Except.error ("offset " ++ it.i.repr ++ ": " ++ err)
end Json
end Lean
|
ea4dae5c89657639b4621b46c5135f062aae2c6a | 67190c9aacc0cac64fb4463d93e84c696a5be896 | /Exercises/18. The Natural Numbers and Induction in Lean.lean | 4f8733a8aa86b267b87c37c82ee35162a01129fa | [] | no_license | lucasresck/Discrete-Mathematics | ffbaf55943e7ce2c7bc50cef7e3ef66a0212f738 | 0a08081c5f393e5765259d3f1253c3a6dd043dac | refs/heads/master | 1,596,627,857,734 | 1,573,411,500,000 | 1,573,411,500,000 | 212,489,764 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,859 | lean | open nat
--1.a.
example : ∀ m n k : nat, m * (n + k) = m * n + m * k :=
assume m n k,
nat.rec_on k
(show m * (n + 0) = m * n + m * 0, from calc
m * (n + 0) = m * n : by rw add_zero
... = m * n + 0 : by rw add_zero
... = m * n + m * 0 : by rw mul_zero)
(assume p,
assume ih: m * (n + p) = m * n + m * p,
show m * (n + succ p) = m * n + m * (succ p), from
calc
m * (n + succ p) = m * (succ (n + p)) : by rw add_succ
... = m * (n + p) + m : by rw mul_succ
... = m * n + m * p + m : by rw ih
... = m * n + (m * p + m) : by rw add_assoc
... = m * n + m * (succ p) : by rw mul_succ)
--1.b.
example : ∀ n : nat, 0 * n = 0 :=
assume n,
nat.rec_on n
(show 0 * 0 = 0, from rfl)
(assume k,
assume ih : 0 * k = 0,
show 0 * (succ k) = 0, from
calc
0 * (succ k) = 0 * k + 0 : by rw mul_succ
... = 0 * k : by rw add_zero
... = 0 : by rw ih)
--1.c.
example : ∀ n : nat, 1 * n = n :=
assume n,
nat.rec_on n
(show 1 * 0 = 0, by rw mul_zero)
(assume k,
assume ih : 1 * k = k,
calc
1 * (succ k) = 1 * k + 1 : by rw mul_succ
... = k + 1 : by rw ih
... = succ k : rfl)
--1.d.
example : ∀ m n k : nat, (m * n) * k = m * (n * k) :=
assume m n k,
nat.rec_on k
(show (m * n) * 0 = m * (n * 0), from
calc
(m * n) * 0 = 0 : by rw mul_zero
... = m * 0 : by rw mul_zero
... = 0 * m : by rw mul_comm
... = (n * 0) * m : by rw mul_zero
... = m * (n * 0) : by rw mul_comm)
(assume i (ih : (m * n) * i = m * (n * i)),
show (m * n) * succ i = m * (n * succ i), from
begin
rw mul_succ,
rw ih,
rw ← left_distrib,
rw mul_succ
end)
--1.e.
example : ∀ m n : nat, m * n = n * m :=
assume m n,
nat.rec_on n
(begin
rw mul_zero,
apply eq.symm,
rw zero_mul
end)
(begin
intros k ih,
rw mul_succ,
rw ih,
rw succ_mul
end) |
56a00b3c2aa5913230bb24352210fb9408380dca | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/tensor_power.lean | 94287845afd8e240ebe2cfc8950625655dcb7bb4 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 11,183 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import linear_algebra.pi_tensor_product
import logic.equiv.fin
import algebra.direct_sum.algebra
/-!
# Tensor power of a semimodule over a commutative semirings
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the `n`th tensor power of `M` as the n-ary tensor product indexed by `fin n` of `M`,
`⨂[R] (i : fin n), M`. This is a special case of `pi_tensor_product`.
This file introduces the notation `⨂[R]^n M` for `tensor_power R n M`, which in turn is an
abbreviation for `⨂[R] i : fin n, M`.
## Main definitions:
* `tensor_power.gsemiring`: the tensor powers form a graded semiring.
* `tensor_power.galgebra`: the tensor powers form a graded algebra.
## Implementation notes
In this file we use `ₜ1` and `ₜ*` as local notation for the graded multiplicative structure on
tensor powers. Elsewhere, using `1` and `*` on `graded_monoid` should be preferred.
-/
open_locale tensor_product
/-- Homogenous tensor powers $M^{\otimes n}$. `⨂[R]^n M` is a shorthand for
`⨂[R] (i : fin n), M`. -/
@[reducible] protected def tensor_power (R : Type*) (n : ℕ) (M : Type*)
[comm_semiring R] [add_comm_monoid M] [module R M] : Type* :=
⨂[R] i : fin n, M
variables {R : Type*} {M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M]
localized "notation (name := tensor_power)
`⨂[`:100 R `]^`:80 n:max := tensor_power R n" in tensor_product
namespace pi_tensor_product
/-- Two dependent pairs of tensor products are equal if their index is equal and the contents
are equal after a canonical reindexing. -/
@[ext]
lemma graded_monoid_eq_of_reindex_cast {ιι : Type*} {ι : ιι → Type*} :
∀ {a b : graded_monoid (λ ii, ⨂[R] i : ι ii, M)} (h : a.fst = b.fst),
reindex R M (equiv.cast $ congr_arg ι h) a.snd = b.snd → a = b
| ⟨ai, a⟩ ⟨bi, b⟩ := λ (hi : ai = bi) (h : reindex R M _ a = b),
begin
subst hi,
simpa using h,
end
end pi_tensor_product
namespace tensor_power
open_locale tensor_product direct_sum
open pi_tensor_product
/-- As a graded monoid, `⨂[R]^i M` has a `1 : ⨂[R]^0 M`. -/
instance ghas_one : graded_monoid.ghas_one (λ i, ⨂[R]^i M) :=
{ one := tprod R $ @fin.elim0' M }
local notation `ₜ1` := @graded_monoid.ghas_one.one ℕ (λ i, ⨂[R]^i M) _ _
lemma ghas_one_def : ₜ1 = tprod R (@fin.elim0' M) := rfl
/-- A variant of `pi_tensor_prod.tmul_equiv` with the result indexed by `fin (n + m)`. -/
def mul_equiv {n m : ℕ} : (⨂[R]^n M) ⊗[R] (⨂[R]^m M) ≃ₗ[R] ⨂[R]^(n + m) M :=
(tmul_equiv R M).trans (reindex R M fin_sum_fin_equiv)
/-- As a graded monoid, `⨂[R]^i M` has a `(*) : ⨂[R]^i M → ⨂[R]^j M → ⨂[R]^(i + j) M`. -/
instance ghas_mul : graded_monoid.ghas_mul (λ i, ⨂[R]^i M) :=
{ mul := λ i j a b, (tensor_product.mk R _ _).compr₂ ↑(mul_equiv : _ ≃ₗ[R] ⨂[R]^(i + j) M) a b}
local infix ` ₜ* `:70 := @graded_monoid.ghas_mul.mul ℕ (λ i, ⨂[R]^i M) _ _ _ _
lemma ghas_mul_def {i j} (a : ⨂[R]^i M) (b : ⨂[R]^j M) : a ₜ* b = mul_equiv (a ⊗ₜ b) := rfl
lemma ghas_mul_eq_coe_linear_map {i j} (a : ⨂[R]^i M) (b : ⨂[R]^j M) :
a ₜ* b =
((tensor_product.mk R _ _).compr₂ ↑(mul_equiv : _ ≃ₗ[R] ⨂[R]^(i + j) M)
: ⨂[R]^i M →ₗ[R] ⨂[R]^j M →ₗ[R] ⨂[R]^(i + j) M) a b := rfl
variables (R M)
/-- Cast between "equal" tensor powers. -/
def cast {i j} (h : i = j) : ⨂[R]^i M ≃ₗ[R] (⨂[R]^j M) :=
reindex R M (fin.cast h).to_equiv
lemma cast_tprod {i j} (h : i = j) (a : fin i → M) :
cast R M h (tprod R a) = tprod R (a ∘ fin.cast h.symm) :=
reindex_tprod _ _
@[simp] lemma cast_refl {i} (h : i = i) : cast R M h = linear_equiv.refl _ _ :=
(congr_arg (λ f, reindex R M (rel_iso.to_equiv f)) $ fin.cast_refl h).trans reindex_refl
@[simp] lemma cast_symm {i j} (h : i = j) : (cast R M h).symm = cast R M h.symm := reindex_symm _
@[simp] lemma cast_trans {i j k} (h : i = j) (h' : j = k) :
(cast R M h).trans (cast R M h') = cast R M (h.trans h') := reindex_trans _ _
variables {R M}
@[simp] lemma cast_cast {i j k} (h : i = j) (h' : j = k) (a : ⨂[R]^i M) :
cast R M h' (cast R M h a) = cast R M (h.trans h') a := reindex_reindex _ _ _
@[ext]
lemma graded_monoid_eq_of_cast {a b : graded_monoid (λ n, ⨂[R] i : fin n, M)}
(h : a.fst = b.fst) (h2 : cast R M h a.snd = b.snd) : a = b :=
begin
refine graded_monoid_eq_of_reindex_cast h _,
rw cast at h2,
rw [←fin.cast_to_equiv, ← h2],
end
-- named to match `fin.cast_eq_cast`
lemma cast_eq_cast {i j} (h : i = j) : ⇑(cast R M h) = _root_.cast (congr_arg _ h) :=
begin
subst h,
rw [cast_refl],
refl,
end
variables (R)
include R
lemma tprod_mul_tprod {na nb} (a : fin na → M) (b : fin nb → M) :
tprod R a ₜ* tprod R b = tprod R (fin.append a b) :=
begin
dsimp [ghas_mul_def, mul_equiv],
rw [tmul_equiv_apply R M a b],
refine (reindex_tprod _ _).trans _,
congr' 1,
dsimp only [fin.append, fin_sum_fin_equiv, equiv.coe_fn_symm_mk],
apply funext,
apply fin.add_cases; simp,
end
omit R
variables {R}
lemma one_mul {n} (a : ⨂[R]^n M) :
cast R M (zero_add n) (ₜ1 ₜ* a) = a :=
begin
rw [ghas_mul_def, ghas_one_def],
induction a using pi_tensor_product.induction_on with r a x y hx hy,
{ dsimp only at a,
rw [tensor_product.tmul_smul, linear_equiv.map_smul, linear_equiv.map_smul, ←ghas_mul_def,
tprod_mul_tprod, cast_tprod],
congr' 2 with i,
rw fin.elim0'_append,
refine congr_arg a (fin.ext _),
simp },
{ rw [tensor_product.tmul_add, map_add, map_add, hx, hy], },
end
lemma mul_one {n} (a : ⨂[R]^n M) : cast R M (add_zero _) (a ₜ* ₜ1) = a :=
begin
rw [ghas_mul_def, ghas_one_def],
induction a using pi_tensor_product.induction_on with r a x y hx hy,
{ dsimp only at a,
rw [←tensor_product.smul_tmul', linear_equiv.map_smul, linear_equiv.map_smul, ←ghas_mul_def,
tprod_mul_tprod R a _, cast_tprod],
congr' 2 with i,
rw fin.append_elim0',
refine congr_arg a (fin.ext _),
simp },
{ rw [tensor_product.add_tmul, map_add, map_add, hx, hy], },
end
lemma mul_assoc {na nb nc} (a : ⨂[R]^na M) (b : ⨂[R]^nb M) (c : ⨂[R]^nc M) :
cast R M (add_assoc _ _ _) ((a ₜ* b) ₜ* c) = a ₜ* (b ₜ* c) :=
begin
let mul : Π (n m : ℕ), (⨂[R]^n M) →ₗ[R] (⨂[R]^m M) →ₗ[R] ⨂[R]^(n + m) M :=
(λ n m, (tensor_product.mk R _ _).compr₂ ↑(mul_equiv : _ ≃ₗ[R] ⨂[R]^(n + m) M)),
-- replace `a`, `b`, `c` with `tprod R a`, `tprod R b`, `tprod R c`
let e : ⨂[R]^(na + nb + nc) M ≃ₗ[R] ⨂[R]^(na + (nb + nc)) M := cast R M (add_assoc _ _ _),
let lhs : (⨂[R]^na M) →ₗ[R] (⨂[R]^nb M) →ₗ[R] (⨂[R]^nc M) →ₗ[R] (⨂[R]^(na + (nb + nc)) M) :=
(linear_map.llcomp R _ _ _ ((mul _ nc).compr₂ e.to_linear_map)).comp
(mul na nb),
have lhs_eq : ∀ a b c, lhs a b c = e ((a ₜ* b) ₜ* c) := λ _ _ _, rfl,
let rhs : (⨂[R]^na M) →ₗ[R] (⨂[R]^nb M) →ₗ[R] (⨂[R]^nc M) →ₗ[R] (⨂[R]^(na + (nb + nc)) M) :=
(linear_map.llcomp R _ _ _ (linear_map.lflip R _ _ _) $
(linear_map.llcomp R _ _ _ (mul na _).flip).comp (mul nb nc)).flip,
have rhs_eq : ∀ a b c, rhs a b c = (a ₜ* (b ₜ* c)) := λ _ _ _, rfl,
suffices : lhs = rhs,
from linear_map.congr_fun (linear_map.congr_fun (linear_map.congr_fun this a) b) c,
ext a b c,
-- clean up
simp only [linear_map.comp_multilinear_map_apply, lhs_eq, rhs_eq, tprod_mul_tprod, e,
cast_tprod],
congr' with j,
rw fin.append_assoc,
refine congr_arg (fin.append a (fin.append b c)) (fin.ext _),
rw [fin.coe_cast, fin.coe_cast],
end
-- for now we just use the default for the `gnpow` field as it's easier.
instance gmonoid : graded_monoid.gmonoid (λ i, ⨂[R]^i M) :=
{ one_mul := λ a, graded_monoid_eq_of_cast (zero_add _) (one_mul _),
mul_one := λ a, graded_monoid_eq_of_cast (add_zero _) (mul_one _),
mul_assoc := λ a b c, graded_monoid_eq_of_cast (add_assoc _ _ _) (mul_assoc _ _ _),
..tensor_power.ghas_mul,
..tensor_power.ghas_one, }
/-- The canonical map from `R` to `⨂[R]^0 M` corresponding to the algebra_map of the tensor
algebra. -/
def algebra_map₀ : R ≃ₗ[R] ⨂[R]^0 M :=
linear_equiv.symm $ is_empty_equiv (fin 0)
lemma algebra_map₀_eq_smul_one (r : R) :
(algebra_map₀ r : ⨂[R]^0 M) = r • ₜ1 :=
by { simp [algebra_map₀], congr }
lemma algebra_map₀_one : (algebra_map₀ 1 : ⨂[R]^0 M) = ₜ1 :=
(algebra_map₀_eq_smul_one 1).trans (one_smul _ _)
lemma algebra_map₀_mul {n} (r : R) (a : ⨂[R]^n M) :
cast R M (zero_add _) (algebra_map₀ r ₜ* a) = r • a :=
by rw [ghas_mul_eq_coe_linear_map, algebra_map₀_eq_smul_one, linear_map.map_smul₂,
linear_equiv.map_smul, ←ghas_mul_eq_coe_linear_map, one_mul]
lemma mul_algebra_map₀ {n} (r : R) (a : ⨂[R]^n M) :
cast R M (add_zero _) (a ₜ* algebra_map₀ r) = r • a :=
by rw [ghas_mul_eq_coe_linear_map, algebra_map₀_eq_smul_one, linear_map.map_smul,
linear_equiv.map_smul, ←ghas_mul_eq_coe_linear_map, mul_one]
lemma algebra_map₀_mul_algebra_map₀ (r s : R) :
cast R M (add_zero _) (algebra_map₀ r ₜ* algebra_map₀ s) = algebra_map₀ (r * s) :=
begin
rw [←smul_eq_mul, linear_equiv.map_smul],
exact algebra_map₀_mul r (@algebra_map₀ R M _ _ _ s),
end
instance gsemiring : direct_sum.gsemiring (λ i, ⨂[R]^i M) :=
{ mul_zero := λ i j a, linear_map.map_zero _,
zero_mul := λ i j b, linear_map.map_zero₂ _ _,
mul_add := λ i j a b₁ b₂, linear_map.map_add _ _ _,
add_mul := λ i j a₁ a₂ b, linear_map.map_add₂ _ _ _ _,
nat_cast := λ n, algebra_map₀ (n : R),
nat_cast_zero := by rw [nat.cast_zero, map_zero],
nat_cast_succ := λ n, by rw [nat.cast_succ, map_add, algebra_map₀_one],
..tensor_power.gmonoid }
example : semiring (⨁ n : ℕ, ⨂[R]^n M) := by apply_instance
/-- The tensor powers form a graded algebra.
Note that this instance implies `algebra R (⨁ n : ℕ, ⨂[R]^n M)` via `direct_sum.algebra`. -/
instance galgebra : direct_sum.galgebra R (λ i, ⨂[R]^i M) :=
{ to_fun := (algebra_map₀ : R ≃ₗ[R] ⨂[R]^0 M).to_linear_map.to_add_monoid_hom,
map_one := algebra_map₀_one,
map_mul := λ r s, graded_monoid_eq_of_cast rfl begin
rw [←linear_equiv.eq_symm_apply],
have := algebra_map₀_mul_algebra_map₀ r s,
exact this.symm,
end,
commutes := λ r x, graded_monoid_eq_of_cast (add_comm _ _) begin
have := (algebra_map₀_mul r x.snd).trans (mul_algebra_map₀ r x.snd).symm,
rw [←linear_equiv.eq_symm_apply, cast_symm],
rw [←linear_equiv.eq_symm_apply, cast_symm, cast_cast] at this,
exact this,
end,
smul_def := λ r x, graded_monoid_eq_of_cast (zero_add x.fst).symm begin
rw [←linear_equiv.eq_symm_apply, cast_symm],
exact (algebra_map₀_mul r x.snd).symm,
end }
lemma galgebra_to_fun_def (r : R) :
@direct_sum.galgebra.to_fun ℕ R (λ i, ⨂[R]^i M) _ _ _ _ _ _ _ r = algebra_map₀ r := rfl
example : algebra R (⨁ n : ℕ, ⨂[R]^n M) := by apply_instance
end tensor_power
|
f2a2149db48ddc42cc83a64b8465d2dacdd6ace8 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/valuation/valuation_ring.lean | 4786cea2674b74332794e535787f9da7bd0eaf60 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 11,644 | lean | /-
Copyright (c) 2022 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Adam Topaz
-/
import ring_theory.valuation.integers
import ring_theory.ideal.local_ring
import ring_theory.localization.fraction_ring
import ring_theory.discrete_valuation_ring
import tactic.field_simp
/-!
# Valuation Rings
A valuation ring is a domain such that for every pair of elements `a b`, either `a` divides
`b` or vice-versa.
Any valuation ring induces a natural valuation on its fraction field, as we show in this file.
Namely, given the following instances:
`[comm_ring A] [is_domain A] [valuation_ring A] [field K] [algebra A K] [is_fraction_ring A K]`,
there is a natural valuation `valuation A K` on `K` with values in `value_group A K` where
the image of `A` under `algebra_map A K` agrees with `(valuation A K).integer`.
We also show that valuation rings are local and that their lattice of ideals is totally ordered.
-/
universes u v w
/-- An integral domain is called a `valuation ring` provided that for any pair
of elements `a b : A`, either `a` divides `b` or vice versa. -/
class valuation_ring (A : Type u) [comm_ring A] [is_domain A] : Prop :=
(cond [] : ∀ a b : A, ∃ c : A, a * c = b ∨ b * c = a)
namespace valuation_ring
section
variables (A : Type u) [comm_ring A]
variables (K : Type v) [field K] [algebra A K]
/-- The value group of the valuation ring `A`. -/
def value_group : Type v := quotient (mul_action.orbit_rel Aˣ K)
instance : inhabited (value_group A K) := ⟨quotient.mk' 0⟩
instance : has_le (value_group A K) := has_le.mk $ λ x y,
quotient.lift_on₂' x y (λ a b, ∃ c : A, c • b = a)
begin
rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩, ext,
split,
{ rintros ⟨e,he⟩, use ((c⁻¹ : Aˣ) * e * d),
apply_fun (λ t, c⁻¹ • t) at he,
simpa [mul_smul] using he },
{ rintros ⟨e,he⟩, dsimp,
use (d⁻¹ : Aˣ) * c * e,
erw [← he, ← mul_smul, ← mul_smul],
congr' 1,
rw mul_comm,
simp only [← mul_assoc, ← units.coe_mul, mul_inv_self, one_mul] }
end
instance : has_zero (value_group A K) := ⟨quotient.mk' 0⟩
instance : has_one (value_group A K) := ⟨quotient.mk' 1⟩
instance : has_mul (value_group A K) := has_mul.mk $ λ x y,
quotient.lift_on₂' x y (λ a b, quotient.mk' $ a * b)
begin
rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩,
apply quotient.sound',
dsimp,
use c * d,
simp only [mul_smul, algebra.smul_def, units.smul_def, ring_hom.map_mul,
units.coe_mul],
ring,
end
instance : has_inv (value_group A K) := has_inv.mk $ λ x,
quotient.lift_on' x (λ a, quotient.mk' a⁻¹)
begin
rintros _ a ⟨b,rfl⟩,
apply quotient.sound',
use b⁻¹,
dsimp,
rw [units.smul_def, units.smul_def, algebra.smul_def, algebra.smul_def,
mul_inv, ring_hom.map_units_inv],
end
variables [is_domain A] [valuation_ring A] [is_fraction_ring A K]
protected lemma le_total (a b : value_group A K) : a ≤ b ∨ b ≤ a :=
begin
rcases a with ⟨a⟩, rcases b with ⟨b⟩,
obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a,
obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b,
have : (algebra_map A K) ya ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya,
have : (algebra_map A K) yb ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya),
{ right,
use c,
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← h], congr' 1, ring },
{ left,
use c,
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← h], congr' 1, ring }
end
noncomputable
instance : linear_ordered_comm_group_with_zero (value_group A K) :=
{ le_refl := by { rintro ⟨⟩, use 1, rw one_smul },
le_trans := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ⟨e,rfl⟩ ⟨f,rfl⟩, use (e * f), rw mul_smul },
le_antisymm := begin
rintros ⟨a⟩ ⟨b⟩ ⟨e,rfl⟩ ⟨f,hf⟩,
by_cases hb : b = 0, { simp [hb] },
have : is_unit e,
{ apply is_unit_of_dvd_one,
use f, rw mul_comm,
rw [← mul_smul, algebra.smul_def] at hf,
nth_rewrite 1 ← one_mul b at hf,
rw ← (algebra_map A K).map_one at hf,
exact is_fraction_ring.injective _ _
(cancel_comm_monoid_with_zero.mul_right_cancel_of_ne_zero hb hf).symm },
apply quotient.sound',
use [this.unit, rfl],
end,
le_total := valuation_ring.le_total _ _,
decidable_le := by { classical, apply_instance },
mul_assoc := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, apply quotient.sound', rw mul_assoc, apply setoid.refl' },
one_mul := by { rintros ⟨a⟩, apply quotient.sound', rw one_mul, apply setoid.refl' },
mul_one := by { rintros ⟨a⟩, apply quotient.sound', rw mul_one, apply setoid.refl' },
mul_comm := by { rintros ⟨a⟩ ⟨b⟩, apply quotient.sound', rw mul_comm, apply setoid.refl' },
mul_le_mul_left := begin
rintros ⟨a⟩ ⟨b⟩ ⟨c,rfl⟩ ⟨d⟩,
use c, simp only [algebra.smul_def], ring,
end,
zero_mul := by { rintros ⟨a⟩, apply quotient.sound', rw zero_mul, apply setoid.refl' },
mul_zero := by { rintros ⟨a⟩, apply quotient.sound', rw mul_zero, apply setoid.refl' },
zero_le_one := ⟨0, by rw zero_smul⟩,
exists_pair_ne := begin
use [0,1],
intro c, obtain ⟨d,hd⟩ := quotient.exact' c,
apply_fun (λ t, d⁻¹ • t) at hd,
simpa using hd,
end,
inv_zero := by { apply quotient.sound', rw inv_zero, apply setoid.refl' },
mul_inv_cancel := begin
rintros ⟨a⟩ ha,
apply quotient.sound',
use 1,
simp only [one_smul],
apply (mul_inv_cancel _).symm,
contrapose ha,
simp only [not_not] at ha ⊢,
rw ha, refl,
end,
..(infer_instance : has_le (value_group A K)),
..(infer_instance : has_mul (value_group A K)),
..(infer_instance : has_inv (value_group A K)),
..(infer_instance : has_zero (value_group A K)),
..(infer_instance : has_one (value_group A K)) }
/-- Any valuation ring induces a valuation on its fraction field. -/
def valuation : valuation K (value_group A K) :=
{ to_fun := quotient.mk',
map_zero' := rfl,
map_one' := rfl,
map_mul' := λ _ _, rfl,
map_add_le_max' := begin
intros a b,
obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a,
obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b,
have : (algebra_map A K) ya ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya,
have : (algebra_map A K) yb ≠ 0 :=
is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya),
dsimp,
{ apply le_trans _ (le_max_left _ _),
use (c + 1),
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h],
congr' 1, ring },
{ apply le_trans _ (le_max_right _ _),
use (c + 1),
rw algebra.smul_def,
field_simp,
simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h],
congr' 1, ring }
end }
lemma mem_integer_iff (x : K) : x ∈ (valuation A K).integer ↔ ∃ a : A, algebra_map A K a = x :=
begin
split,
{ rintros ⟨c,rfl⟩,
use c,
rw [algebra.smul_def, mul_one] },
{ rintro ⟨c,rfl⟩,
use c,
rw [algebra.smul_def, mul_one] }
end
/-- The valuation ring `A` is isomorphic to the ring of integers of its associated valuation. -/
noncomputable def equiv_integer : A ≃+* (valuation A K).integer :=
ring_equiv.of_bijective (show A →ₙ+* (valuation A K).integer, from
{ to_fun := λ a, ⟨algebra_map A K a, (mem_integer_iff _ _ _).mpr ⟨a,rfl⟩⟩,
map_mul' := λ _ _, by { ext1, exact (algebra_map A K).map_mul _ _ },
map_zero' := by { ext1, exact (algebra_map A K).map_zero },
map_add' := λ _ _, by { ext1, exact (algebra_map A K).map_add _ _ } })
begin
split,
{ intros x y h,
apply_fun (coe : _ → K) at h,
dsimp at h,
exact is_fraction_ring.injective _ _ h },
{ rintros ⟨a,(ha : a ∈ (valuation A K).integer)⟩,
rw mem_integer_iff at ha,
obtain ⟨a,rfl⟩ := ha,
use [a, rfl] }
end
@[simp]
lemma coe_equiv_integer_apply (a : A) : (equiv_integer A K a : K) = algebra_map A K a := rfl
lemma range_algebra_map_eq : (valuation A K).integer = (algebra_map A K).range :=
by { ext, exact mem_integer_iff _ _ _ }
end
section
variables (A : Type u) [comm_ring A] [is_domain A] [valuation_ring A]
@[priority 100]
instance : local_ring A :=
local_ring.of_is_unit_or_is_unit_one_sub_self
begin
intros a,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond a (1-a),
{ left,
apply is_unit_of_mul_eq_one _ (c+1),
simp [mul_add, h] },
{ right,
apply is_unit_of_mul_eq_one _ (c+1),
simp [mul_add, h] }
end
instance [decidable_rel ((≤) : ideal A → ideal A → Prop)] : linear_order (ideal A) :=
{ le_total := begin
intros α β,
by_cases h : α ≤ β, { exact or.inl h },
erw not_forall at h,
push_neg at h,
obtain ⟨a,h₁,h₂⟩ := h,
right,
intros b hb,
obtain ⟨c,(h|h)⟩ := valuation_ring.cond a b,
{ rw ← h,
exact ideal.mul_mem_right _ _ h₁ },
{ exfalso, apply h₂, rw ← h,
apply ideal.mul_mem_right _ _ hb },
end,
decidable_le := infer_instance,
..(infer_instance : complete_lattice (ideal A)) }
end
section
variables {𝒪 : Type u} {K : Type v} {Γ : Type w}
[comm_ring 𝒪] [is_domain 𝒪] [field K] [algebra 𝒪 K]
[linear_ordered_comm_group_with_zero Γ]
(v : _root_.valuation K Γ) (hh : v.integers 𝒪)
include hh
/-- If `𝒪` satisfies `v.integers 𝒪` where `v` is a valuation on a field, then `𝒪`
is a valuation ring. -/
lemma of_integers : valuation_ring 𝒪 :=
begin
constructor,
intros a b,
cases le_total (v (algebra_map 𝒪 K a)) (v (algebra_map 𝒪 K b)),
{ obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h,
use c, exact or.inr hc.symm },
{ obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h,
use c, exact or.inl hc.symm }
end
end
section
variables (K : Type u) [field K]
/-- A field is a valuation ring. -/
@[priority 100]
instance of_field : valuation_ring K :=
begin
constructor,
intros a b,
by_cases b = 0,
{ use 0, left, simp [h] },
{ use a * b⁻¹, right, field_simp, rw mul_comm }
end
end
section
variables (A : Type u) [comm_ring A] [is_domain A] [discrete_valuation_ring A]
/-- A DVR is a valuation ring. -/
@[priority 100]
instance of_discrete_valuation_ring : valuation_ring A :=
begin
constructor,
intros a b,
by_cases ha : a = 0, { use 0, right, simp [ha] },
by_cases hb : b = 0, { use 0, left, simp [hb] },
obtain ⟨ϖ,hϖ⟩ := discrete_valuation_ring.exists_irreducible A,
obtain ⟨m,u,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible ha hϖ,
obtain ⟨n,v,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible hb hϖ,
cases le_total m n with h h,
{ use (u⁻¹ * v : Aˣ) * ϖ^(n-m), left,
simp_rw [mul_comm (u : A), units.coe_mul, ← mul_assoc, mul_assoc _ (u : A)],
simp only [units.mul_inv, mul_one, mul_comm _ (v : A), mul_assoc, ← pow_add],
congr' 2,
linarith },
{ use (v⁻¹ * u : Aˣ) * ϖ^(m-n), right,
simp_rw [mul_comm (v : A), units.coe_mul, ← mul_assoc, mul_assoc _ (v : A)],
simp only [units.mul_inv, mul_one, mul_comm _ (u : A), mul_assoc, ← pow_add],
congr' 2,
linarith }
end
end
end valuation_ring
|
5ddb7cacf166a70cf238bf0ead4f085dc7f64bbc | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/category/Module/kernels.lean | a9446745145d2c4129579afa2c141f8c3e204426 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,162 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import algebra.category.Module.basic
/-!
# The concrete (co)kernels in the category of modules are (co)kernels in the categorical sense.
-/
open category_theory
open category_theory.limits
open category_theory.limits.walking_parallel_pair
universes u v
namespace Module
variables {R : Type u} [ring R]
section
variables {M N : Module.{v} R} (f : M ⟶ N)
/-- The kernel cone induced by the concrete kernel. -/
def kernel_cone : kernel_fork f :=
kernel_fork.of_ι (as_hom f.ker.subtype) $ by tidy
/-- The kernel of a linear map is a kernel in the categorical sense. -/
def kernel_is_limit : is_limit (kernel_cone f) :=
fork.is_limit.mk _
(λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $
by { rw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition,
has_zero_morphisms.comp_zero (fork.ι s) N], refl }))
(λ s, linear_map.subtype_comp_cod_restrict _ _ _)
(λ s m h, linear_map.ext $ λ x, subtype.ext_iff_val.2 $
have h₁ : (m ≫ (kernel_cone f).π.app zero).to_fun = (s.π.app zero).to_fun,
by { congr, exact h zero },
by convert @congr_fun _ _ _ _ h₁ x )
/-- The cokernel cocone induced by the projection onto the quotient. -/
def cokernel_cocone : cokernel_cofork f :=
cokernel_cofork.of_π (as_hom f.range.mkq) $ linear_map.range_mkq_comp _
/-- The projection onto the quotient is a cokernel in the categorical sense. -/
def cokernel_is_colimit : is_colimit (cokernel_cocone f) :=
cofork.is_colimit.mk _
(λ s, f.range.liftq (cofork.π s) $ linear_map.range_le_ker_iff.2 $ cokernel_cofork.condition s)
(λ s, f.range.liftq_mkq (cofork.π s) _)
(λ s m h,
begin
haveI : epi (as_hom f.range.mkq) := epi_of_range_eq_top _ (submodule.range_mkq _),
apply (cancel_epi (as_hom f.range.mkq)).1,
convert h walking_parallel_pair.one,
exact submodule.liftq_mkq _ _ _
end)
end
/-- The category of R-modules has kernels, given by the inclusion of the kernel submodule. -/
lemma has_kernels_Module : has_kernels (Module R) :=
⟨λ X Y f, has_limit.mk ⟨_, kernel_is_limit f⟩⟩
/-- The category or R-modules has cokernels, given by the projection onto the quotient. -/
lemma has_cokernels_Module : has_cokernels (Module R) :=
⟨λ X Y f, has_colimit.mk ⟨_, cokernel_is_colimit f⟩⟩
open_locale Module
local attribute [instance] has_kernels_Module
local attribute [instance] has_cokernels_Module
variables {G H : Module.{v} R} (f : G ⟶ H)
/--
The categorical kernel of a morphism in `Module`
agrees with the usual module-theoretical kernel.
-/
noncomputable def kernel_iso_ker {G H : Module.{v} R} (f : G ⟶ H) :
kernel f ≅ Module.of R (f.ker) :=
limit.iso_limit_cone ⟨_, kernel_is_limit f⟩
-- We now show this isomorphism commutes with the inclusion of the kernel into the source.
@[simp, elementwise] lemma kernel_iso_ker_inv_kernel_ι :
(kernel_iso_ker f).inv ≫ kernel.ι f = f.ker.subtype :=
limit.iso_limit_cone_inv_π _ _
@[simp, elementwise] lemma kernel_iso_ker_hom_ker_subtype :
(kernel_iso_ker f).hom ≫ f.ker.subtype = kernel.ι f :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ (limit.is_limit _) zero
/--
The categorical cokernel of a morphism in `Module`
agrees with the usual module-theoretical quotient.
-/
noncomputable def cokernel_iso_range_quotient {G H : Module.{v} R} (f : G ⟶ H) :
cokernel f ≅ Module.of R (f.range.quotient) :=
colimit.iso_colimit_cocone ⟨_, cokernel_is_colimit f⟩
-- We now show this isomorphism commutes with the projection of target to the cokernel.
@[simp, elementwise] lemma cokernel_π_cokernel_iso_range_quotient_hom :
cokernel.π f ≫ (cokernel_iso_range_quotient f).hom = f.range.mkq :=
by { convert colimit.iso_colimit_cocone_ι_hom _ _; refl, }
@[simp, elementwise] lemma range_mkq_cokernel_iso_range_quotient_inv :
↿f.range.mkq ≫ (cokernel_iso_range_quotient f).inv = cokernel.π f :=
by { convert colimit.iso_colimit_cocone_ι_inv ⟨_, cokernel_is_colimit f⟩ _; refl, }
end Module
|
aa7a313bf571a62ec135b1585b7c9debd505d6df | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/polynomial/hasse_deriv.lean | 90350af447ece96252617307622473c8d0e58c49 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,552 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.polynomial.derivative
import data.nat.choose.vandermonde
/-!
# Hasse derivative of polynomials
The `k`th Hasse derivative of a polynomial `∑ a_i X^i` is `∑ (i.choose k) a_i X^(i-k)`.
It is a variant of the usual derivative, and satisfies `k! * (hasse_deriv k f) = derivative^[k] f`.
The main benefit is that is gives an atomic way of talking about expressions such as
`(derivative^[k] f).eval r / k!`, that occur in Taylor expansions, for example.
## Main declarations
In the following, we write `D k` for the `k`-th Hasse derivative `hasse_deriv k`.
* `polynomial.hasse_deriv`: the `k`-th Hasse derivative of a polynomial
* `polynomial.hasse_deriv_zero`: the `0`th Hasse derivative is the identity
* `polynomial.hasse_deriv_one`: the `1`st Hasse derivative is the usual derivative
* `polynomial.factorial_smul_hasse_deriv`: the identity `k! • (D k f) = derivative^[k] f`
* `polynomial.hasse_deriv_comp`: the identity `(D k).comp (D l) = (k+l).choose k • D (k+l)`
* `polynomial.hasse_deriv_mul`:
the "Leibniz rule" `D k (f * g) = ∑ ij in antidiagonal k, D ij.1 f * D ij.2 g`
For the identity principle, see `polynomial.eq_zero_of_hasse_deriv_eq_zero`
in `data/polynomial/taylor.lean`.
## Reference
https://math.fontein.de/2009/08/12/the-hasse-derivative/
-/
noncomputable theory
namespace polynomial
open_locale nat big_operators
open function nat (hiding nsmul_eq_mul)
variables {R : Type*} [semiring R] (k : ℕ) (f : polynomial R)
/-- The `k`th Hasse derivative of a polynomial `∑ a_i X^i` is `∑ (i.choose k) a_i X^(i-k)`.
It satisfies `k! * (hasse_deriv k f) = derivative^[k] f`. -/
def hasse_deriv (k : ℕ) : polynomial R →ₗ[R] polynomial R :=
lsum (λ i, (monomial (i-k)) ∘ₗ distrib_mul_action.to_linear_map R R (i.choose k))
lemma hasse_deriv_apply :
hasse_deriv k f = f.sum (λ i r, monomial (i - k) (↑(i.choose k) * r)) :=
by simpa only [← nsmul_eq_mul]
lemma hasse_deriv_coeff (n : ℕ) :
(hasse_deriv k f).coeff n = (n + k).choose k * f.coeff (n + k) :=
begin
rw [hasse_deriv_apply, coeff_sum, sum_def, finset.sum_eq_single (n + k), coeff_monomial],
{ simp only [if_true, nat.add_sub_cancel, eq_self_iff_true], },
{ intros i hi hink,
rw [coeff_monomial],
by_cases hik : i < k,
{ simp only [nat.choose_eq_zero_of_lt hik, if_t_t, nat.cast_zero, zero_mul], },
{ push_neg at hik, rw if_neg, contrapose! hink, exact (nat.sub_eq_iff_eq_add hik).mp hink, } },
{ intro h, simp only [not_mem_support_iff.mp h, monomial_zero_right, mul_zero, coeff_zero] }
end
lemma hasse_deriv_zero' : hasse_deriv 0 f = f :=
by simp only [hasse_deriv_apply, nat.sub_zero, nat.choose_zero_right,
nat.cast_one, one_mul, sum_monomial_eq]
@[simp] lemma hasse_deriv_zero : @hasse_deriv R _ 0 = linear_map.id :=
linear_map.ext $ hasse_deriv_zero'
lemma hasse_deriv_one' : hasse_deriv 1 f = derivative f :=
by simp only [hasse_deriv_apply, derivative_apply, monomial_eq_C_mul_X, nat.choose_one_right,
(nat.cast_commute _ _).eq]
@[simp] lemma hasse_deriv_one : @hasse_deriv R _ 1 = derivative :=
linear_map.ext $ hasse_deriv_one'
@[simp] lemma hasse_deriv_monomial (n : ℕ) (r : R) :
hasse_deriv k (monomial n r) = monomial (n - k) (↑(n.choose k) * r) :=
begin
ext i,
simp only [hasse_deriv_coeff, coeff_monomial],
by_cases hnik : n = i + k,
{ rw [if_pos hnik, if_pos, ← hnik], apply nat.sub_eq_of_eq_add, rwa add_comm },
{ rw [if_neg hnik, mul_zero],
by_cases hkn : k ≤ n,
{ rw [← nat.sub_eq_iff_eq_add hkn] at hnik, rw [if_neg hnik] },
{ push_neg at hkn, rw [nat.choose_eq_zero_of_lt hkn, nat.cast_zero, zero_mul, if_t_t] } }
end
lemma hasse_deriv_C (r : R) (hk : 0 < k) : hasse_deriv k (C r) = 0 :=
by rw [← monomial_zero_left, hasse_deriv_monomial, nat.choose_eq_zero_of_lt hk,
nat.cast_zero, zero_mul, monomial_zero_right]
lemma hasse_deriv_apply_one (hk : 0 < k) : hasse_deriv k (1 : polynomial R) = 0 :=
by rw [← C_1, hasse_deriv_C k _ hk]
lemma hasse_deriv_X (hk : 1 < k) : hasse_deriv k (X : polynomial R) = 0 :=
by rw [← monomial_one_one_eq_X, hasse_deriv_monomial, nat.choose_eq_zero_of_lt hk,
nat.cast_zero, zero_mul, monomial_zero_right]
lemma factorial_smul_hasse_deriv :
⇑(k! • @hasse_deriv R _ k) = ((@derivative R _)^[k]) :=
begin
induction k with k ih,
{ rw [hasse_deriv_zero, factorial_zero, iterate_zero, one_smul, linear_map.id_coe], },
ext f n : 2,
rw [iterate_succ_apply', ← ih],
simp only [linear_map.smul_apply, coeff_smul, linear_map.map_smul_of_tower, coeff_derivative,
hasse_deriv_coeff, ← @choose_symm_add _ k],
simp only [nsmul_eq_mul, factorial_succ, mul_assoc, succ_eq_add_one, ← add_assoc,
add_right_comm n 1 k, ← cast_succ],
rw ← (cast_commute (n+1) (f.coeff (n + k + 1))).eq,
simp only [← mul_assoc], norm_cast, congr' 2,
apply @cast_injective ℚ,
have h1 : n + 1 ≤ n + k + 1 := succ_le_succ le_self_add,
have h2 : k + 1 ≤ n + k + 1 := succ_le_succ le_add_self,
have H : ∀ (n : ℕ), (n! : ℚ) ≠ 0, { exact_mod_cast factorial_ne_zero },
-- why can't `field_simp` help me here?
simp only [cast_mul, cast_choose ℚ, h1, h2, -one_div, -mul_eq_zero,
succ_sub_succ_eq_sub, nat.add_sub_cancel, add_sub_cancel_left] with field_simps,
rw [eq_div_iff_mul_eq (mul_ne_zero (H _) (H _)), eq_comm, div_mul_eq_mul_div,
eq_div_iff_mul_eq (mul_ne_zero (H _) (H _))],
norm_cast,
simp only [factorial_succ, succ_eq_add_one], ring,
end
lemma hasse_deriv_comp (k l : ℕ) :
(@hasse_deriv R _ k).comp (hasse_deriv l) = (k+l).choose k • hasse_deriv (k+l) :=
begin
ext i : 2,
simp only [linear_map.smul_apply, comp_app, linear_map.coe_comp, smul_monomial,
hasse_deriv_apply, mul_one, monomial_eq_zero_iff, sum_monomial_index, mul_zero,
nat.sub_sub, add_comm l k],
rw_mod_cast nsmul_eq_mul,
congr' 2,
by_cases hikl : i < k + l,
{ rw [choose_eq_zero_of_lt hikl, mul_zero],
by_cases hil : i < l,
{ rw [choose_eq_zero_of_lt hil, mul_zero] },
{ push_neg at hil, rw [← nat.sub_lt_right_iff_lt_add hil] at hikl,
rw [choose_eq_zero_of_lt hikl , zero_mul], }, },
push_neg at hikl, apply @cast_injective ℚ,
have h1 : l ≤ i := nat.le_of_add_le_right hikl,
have h2 : k ≤ i - l := nat.le_sub_right_of_add_le hikl,
have h3 : k ≤ k + l := le_self_add,
have H : ∀ (n : ℕ), (n! : ℚ) ≠ 0, { exact_mod_cast factorial_ne_zero },
-- why can't `field_simp` help me here?
simp only [cast_mul, cast_choose ℚ, h1, h2, h3, hikl, -one_div, -mul_eq_zero,
succ_sub_succ_eq_sub, nat.add_sub_cancel, add_sub_cancel_left] with field_simps,
rw [eq_div_iff_mul_eq, eq_comm, div_mul_eq_mul_div, eq_div_iff_mul_eq, nat.sub_sub, add_comm l k],
{ ring, },
all_goals { apply_rules [mul_ne_zero, H] }
end
section
open add_monoid_hom finset.nat
lemma hasse_deriv_mul (f g : polynomial R) :
hasse_deriv k (f * g) = ∑ ij in antidiagonal k, hasse_deriv ij.1 f * hasse_deriv ij.2 g :=
begin
let D := λ k, (@hasse_deriv R _ k).to_add_monoid_hom,
let Φ := @add_monoid_hom.mul (polynomial R) _,
show (comp_hom (D k)).comp Φ f g =
∑ (ij : ℕ × ℕ) in antidiagonal k, ((comp_hom.comp ((comp_hom Φ) (D ij.1))).flip (D ij.2) f) g,
simp only [← finset_sum_apply],
congr' 2, clear f g,
ext m r n s : 4,
simp only [finset_sum_apply, coe_mul_left, coe_comp, flip_apply, comp_app,
hasse_deriv_monomial, linear_map.to_add_monoid_hom_coe, comp_hom_apply_apply, coe_mul,
monomial_mul_monomial],
have aux : ∀ (x : ℕ × ℕ), x ∈ antidiagonal k →
monomial (m - x.1 + (n - x.2)) (↑(m.choose x.1) * r * (↑(n.choose x.2) * s)) =
monomial (m + n - k) (↑(m.choose x.1) * ↑(n.choose x.2) * (r * s)),
{ intros x hx, rw [finset.nat.mem_antidiagonal] at hx, subst hx,
by_cases hm : m < x.1,
{ simp only [nat.choose_eq_zero_of_lt hm, nat.cast_zero, zero_mul, monomial_zero_right], },
by_cases hn : n < x.2,
{ simp only [nat.choose_eq_zero_of_lt hn, nat.cast_zero,
zero_mul, mul_zero, monomial_zero_right], },
push_neg at hm hn,
rw [← nat.sub_add_comm hm, ← nat.add_sub_assoc hn, nat.sub_sub, add_comm x.2 x.1, mul_assoc,
← mul_assoc r, ← (nat.cast_commute _ r).eq, mul_assoc, mul_assoc], },
conv_rhs { apply_congr, skip, rw aux _ H, },
rw_mod_cast [← linear_map.map_sum, ← finset.sum_mul, ← nat.add_choose_eq],
end
end
end polynomial
|
b9f21224bebaf87a261cf29fbfaf4f664d0a0b31 | f20db13587f4dd28a4b1fbd31953afd491691fa0 | /library/init/meta/tactic.lean | 795ae8aedc74543d2688bf1bc02fedbfacf16418 | [
"Apache-2.0"
] | permissive | AHartNtkn/lean | 9a971edfc6857c63edcbf96bea6841b9a84cf916 | 0d83a74b26541421fc1aa33044c35b03759710ed | refs/heads/master | 1,620,592,591,236 | 1,516,749,881,000 | 1,516,749,881,000 | 118,697,288 | 1 | 0 | null | 1,516,759,470,000 | 1,516,759,470,000 | null | UTF-8 | Lean | false | false | 51,618 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.function init.data.option.basic init.util
import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail
import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment
import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad
meta constant tactic_state : Type
universes u v
namespace tactic_state
/-- Create a tactic state with an empty local context and a dummy goal. -/
meta constant mk_empty : environment → options → tactic_state
meta constant env : tactic_state → environment
/-- Format the given tactic state. If `target_lhs_only` is true and the target
is of the form `lhs ~ rhs`, where `~` is a simplification relation,
then only the `lhs` is displayed.
Remark: the parameter `target_lhs_only` is a temporary hack used to implement
the `conv` monad. It will be removed in the future. -/
meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format
/-- Format expression with respect to the main goal in the tactic state.
If the tactic state does not contain any goals, then format expression
using an empty local context. -/
meta constant format_expr : tactic_state → expr → format
meta constant get_options : tactic_state → options
meta constant set_options : tactic_state → options → tactic_state
end tactic_state
meta instance : has_to_format tactic_state :=
⟨tactic_state.to_format⟩
meta instance : has_to_string tactic_state :=
⟨λ s, (to_fmt s).to_string s.get_options⟩
@[reducible] meta def tactic := interaction_monad tactic_state
@[reducible] meta def tactic_result := interaction_monad.result tactic_state
namespace tactic
export interaction_monad (hiding failed fail)
meta def failed {α : Type} : tactic α := interaction_monad.failed
meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α :=
interaction_monad.fail msg
end tactic
namespace tactic_result
export interaction_monad.result
end tactic_result
open tactic
open tactic_result
infixl ` >>=[tactic] `:2 := interaction_monad_bind
infixl ` >>[tactic] `:2 := interaction_monad_seq
meta instance : alternative tactic :=
{ failure := @interaction_monad.failed _,
orelse := @interaction_monad_orelse _,
..interaction_monad.monad }
meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) :=
λ s, match t s with
| success a s' := success (ulift.up a) s'
| exception t ref s := exception t ref s
end
meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α :=
λ s, match t s with
| success (ulift.up a) s' := success a s'
| exception t ref s := exception t ref s
end
namespace tactic
variables {α : Type u}
meta def try_core (t : tactic α) : tactic (option α) :=
λ s, result.cases_on (t s)
(λ a, success (some a))
(λ e ref s', success none s)
meta def skip : tactic unit :=
success ()
meta def try (t : tactic α) : tactic unit :=
try_core t >>[tactic] skip
meta def try_lst : list (tactic unit) → tactic unit
| [] := failed
| (tac :: tacs) := λ s,
match tac s with
| result.success _ s' := try (try_lst tacs) s'
| result.exception e p s' :=
match try_lst tacs s' with
| result.exception _ _ _ := result.exception e p s'
| r := r
end
end
meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit :=
λ s, result.cases_on (t s)
(λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s)
(λ e ref s', success () s)
meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception _ _ s') := success () s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail combinator failed, given tactic succeeded" none s
end
open nat
/-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/
meta def iterate_at_most : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := (do t, iterate_at_most n t) <|> skip
/-- (iterate_exactly n t) : execute t n times -/
meta def iterate_exactly : nat → tactic unit → tactic unit
| 0 t := skip
| (succ n) t := do t, iterate_exactly n t
meta def iterate : tactic unit → tactic unit :=
iterate_at_most 100000
meta def returnopt (e : option α) : tactic α :=
λ s, match e with
| (some a) := success a s
| none := mk_exception "failed" none s
end
meta instance opt_to_tac : has_coe (option α) (tactic α) :=
⟨returnopt⟩
/-- Decorate t's exceptions with msg -/
meta def decorate_ex (msg : format) (t : tactic α) : tactic α :=
λ s, result.cases_on (t s)
success
(λ opt_thunk,
match opt_thunk with
| some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u)))
| none := exception none
end)
@[inline] meta def write (s' : tactic_state) : tactic unit :=
λ s, success () s'
@[inline] meta def read : tactic tactic_state :=
λ s, success s s
meta def get_options : tactic options :=
do s ← read, return s.get_options
meta def set_options (o : options) : tactic unit :=
do s ← read, write (s.set_options o)
meta def save_options {α : Type} (t : tactic α) : tactic α :=
do o ← get_options,
a ← t,
set_options o,
return a
meta def returnex {α : Type} (e : exceptional α) : tactic α :=
λ s, match e with
| exceptional.success a := success a s
| exceptional.exception ._ f :=
match get_options s with
| success opt _ := exception (some (λ u, f opt)) none s
| exception _ _ _ := exception (some (λ u, f options.mk)) none s
end
end
meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) :=
⟨returnex⟩
end tactic
meta def tactic_format_expr (e : expr) : tactic format :=
do s ← tactic.read, return (tactic_state.format_expr s e)
meta class has_to_tactic_format (α : Type u) :=
(to_tactic_format : α → tactic format)
meta instance : has_to_tactic_format expr :=
⟨tactic_format_expr⟩
meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format :=
has_to_tactic_format.to_tactic_format
open tactic format
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) :=
⟨has_map.map to_fmt ∘ monad.mapm pp⟩
meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] :
has_to_tactic_format (α × β) :=
⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩
meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format
| (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")")
| none := return "none"
meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) :=
⟨option_to_tactic_format⟩
meta instance {α} (a : α) : has_to_tactic_format (reflected a) :=
⟨λ h, pp h.to_expr⟩
@[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α :=
⟨(λ x, return x) ∘ to_fmt⟩
namespace tactic
open tactic_state
meta def get_env : tactic environment :=
do s ← read,
return $ env s
meta def get_decl (n : name) : tactic declaration :=
do s ← read,
(env s).get n
meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit :=
do fmt ← pp a,
return $ _root_.trace_fmt fmt (λ u, ())
meta def trace_call_stack : tactic unit :=
assume state, _root_.trace_call_stack (success () state)
meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α :=
λ s, timeit desc (t () s)
meta def trace_state : tactic unit :=
do s ← read,
trace $ to_fmt s
inductive transparency
| all | semireducible | instances | reducible | none
export transparency (reducible semireducible)
/-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/
meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α
/-- Return the partial term/proof constructed so far. Note that the resultant expression
may contain variables that are not declarate in the current main goal. -/
meta constant result : tactic expr
/-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to
`do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect
to the current goal, and trace_result will do it with respect to the initial goal. -/
meta constant format_result : tactic format
/-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/
meta constant target : tactic expr
meta constant intro_core : name → tactic expr
meta constant intron : nat → tactic unit
/-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/
meta constant clear : expr → tactic unit
meta constant revert_lst : list expr → tactic nat
/-- Return `e` in weak head normal form with respect to the given transparency setting.
If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors
and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations
are compiled into primitive datatypes accepted by the Kernel. -/
meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr
/-- (head) eta expand the given expression -/
meta constant head_eta_expand : expr → tactic expr
/-- (head) beta reduction -/
meta constant head_beta : expr → tactic expr
/-- (head) zeta reduction -/
meta constant head_zeta : expr → tactic expr
/-- zeta reduction -/
meta constant zeta : expr → tactic expr
/-- (head) eta reduction -/
meta constant head_eta : expr → tactic expr
/-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/
meta constant unify (t s : expr) (md := semireducible) : tactic unit
/-- Similar to `unify`, but it treats metavariables as constants. -/
meta constant is_def_eq (t s : expr) (md := semireducible) : tactic unit
/-- Infer the type of the given expression.
Remark: transparency does not affect type inference -/
meta constant infer_type : expr → tactic expr
meta constant get_local : name → tactic expr
/-- Resolve a name using the current local context, environment, aliases, etc. -/
meta constant resolve_name : name → tactic pexpr
/-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/
meta constant local_context : tactic (list expr)
meta constant get_unused_name (n : name) (i : option nat := none) : tactic name
/-- Helper tactic for creating simple applications where some arguments are inferred using
type inference.
Example, given
```
rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop
nat : Type
real : Type
vec.{l} : Pi (α : Type l) (n : nat), Type.{l1}
f g : Pi (n : nat), vec real n
```
then
```
mk_app_core semireducible "rel" [f, g]
```
returns the application
```
rel.{1 2} nat (fun n : nat, vec real n) f g
```
The unification constraints due to type inference are solved using the transparency `md`.
-/
meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr
/-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit.
Example, given `(a b : nat)` then
```
mk_mapp "ite" [some (a > b), none, none, some a, some b]
```
returns the application
```
@ite.{1} (a > b) (nat.decidable_gt a b) nat a b
```
-/
meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr
/-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/
meta constant mk_congr_arg : expr → expr → tactic expr
/-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/
meta constant mk_congr_fun : expr → expr → tactic expr
/-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/
meta constant mk_congr : expr → expr → tactic expr
/-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/
meta constant mk_eq_refl : expr → tactic expr
/-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/
meta constant mk_eq_symm : expr → tactic expr
/-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/
meta constant mk_eq_trans : expr → expr → tactic expr
/-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/
meta constant mk_eq_mp : expr → expr → tactic expr
/-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/
meta constant mk_eq_mpr : expr → expr → tactic expr
/- Given a local constant t, if t has type (lhs = rhs) apply substitution.
Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t).
The tactic fails if the given expression is not a local constant. -/
meta constant subst_core : expr → tactic unit
/-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to
the target type. -/
meta constant exact (e : expr) (md := semireducible) : tactic unit
/-- Elaborate the given quoted expression with respect to the current main goal.
If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/
meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr
/-- Return true if the given expression is a type class. -/
meta constant is_class : expr → tactic bool
/-- Try to create an instance of the given type class. -/
meta constant mk_instance : expr → tactic expr
/-- Change the target of the main goal.
The input expression must be definitionally equal to the current target.
If `check` is `ff`, then the tactic does not check whether `e`
is definitionally equal to the current target. If it is not,
then the error will only be detected by the kernel type checker. -/
meta constant change (e : expr) (check : bool := tt): tactic unit
/-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/
meta constant assert_core : name → expr → tactic unit
/-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/
meta constant assertv_core : name → expr → expr → tactic unit
/-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/
meta constant define_core : name → expr → tactic unit
/-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/
meta constant definev_core : name → expr → expr → tactic unit
/-- rotate goals to the left -/
meta constant rotate_left : nat → tactic unit
meta constant get_goals : tactic (list expr)
meta constant set_goals : list expr → tactic unit
inductive new_goals
| non_dep_first | non_dep_only | all
/-- Configuration options for the `apply` tactic.
- `new_goals` is the strategy for ordering new goals.
- `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution.
- `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`.
- `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`.
- `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints.
For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration,
but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where
`?y` is a fresh metavariable.
-/
structure apply_cfg :=
(md := semireducible)
(approx := tt)
(new_goals := new_goals.non_dep_first)
(instances := tt)
(auto_param := tt)
(opt_param := tt)
(unify := tt)
/-- Apply the expression `e` to the main goal,
the unification is performed using the transparency mode in `cfg`.
If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification.
`cfg.new_goals` specifies which unassigned metavariables become new goals, and their order.
If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables.
The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`).
It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/
meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr))
/- Create a fresh meta universe variable. -/
meta constant mk_meta_univ : tactic level
/- Create a fresh meta-variable with the given type.
The scope of the new meta-variable is the local context of the main goal. -/
meta constant mk_meta_var : expr → tactic expr
/-- Return the value assigned to the given universe meta-variable.
Fail if argument is not an universe meta-variable or if it is not assigned. -/
meta constant get_univ_assignment : level → tactic level
/-- Return the value assigned to the given meta-variable.
Fail if argument is not a meta-variable or if it is not assigned. -/
meta constant get_assignment : expr → tactic expr
/-- Return true if the given meta-variable is assigned.
Fail if argument is not a meta-variable. -/
meta constant is_assigned : expr → tactic bool
meta constant mk_fresh_name : tactic name
/-- Return a hash code for expr that ignores inst_implicit arguments,
and proofs. -/
meta constant abstract_hash : expr → tactic nat
/-- Return the "weight" of the given expr while ignoring inst_implicit arguments,
and proofs. -/
meta constant abstract_weight : expr → tactic nat
meta constant abstract_eq : expr → expr → tactic bool
/-- Induction on `h` using recursor `rec`, names for the new hypotheses
are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names
in the recursor.
It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor),
a list of new hypotheses, and a list of substitutions for hypotheses
depending on `h`. The substitutions map internal names to their replacement terms. If the
replacement is again a hypothesis the user name stays the same. The internal names are only valid
in the original goal, not in the type context of the new goal.
Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of
constructor names.
If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/
meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`.
`h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of
substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the
number of constructors. Some goals may be discarded when the indices to not match.
See `induction` for information on the list of substitutions.
The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/
meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr)))
/-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/
meta constant destruct (e : expr) (md := semireducible) : tactic unit
/-- Generalizes the target with respect to `e`. -/
meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit
/-- instantiate assigned metavariables in the given expression -/
meta constant instantiate_mvars : expr → tactic expr
/-- Add the given declaration to the environment -/
meta constant add_decl : declaration → tactic unit
/-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/
meta constant set_env : environment → tactic unit
/-- (doc_string env d k) return the doc string for d (if available) -/
meta constant doc_string : name → tactic string
meta constant add_doc_string : name → string → tactic unit
/--
Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and
meta-variables. This function collects all dependencies (universe parameters, universe metavariables,
local constants (aka hypotheses) and metavariables).
It updates the environment in the tactic_state, and returns an expression of the form
(c.{l_1 ... l_n} a_1 ... a_m)
where l_i's and a_j's are the collected dependencies.
-/
meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr
meta constant module_doc_strings : tactic (list (option name × string))
/-- Set attribute `attr_name` for constant `c_name` with the given priority.
If the priority is none, then use default -/
meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit
/-- `unset_attribute attr_name c_name` -/
meta constant unset_attribute : name → name → tactic unit
/-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name`
has the attribute `attr_name`. The result is the priority. -/
meta constant has_attribute : name → name → tactic nat
/-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from
`src` to `tgt` if it is defined for `src` -/
meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit :=
try $ do
prio ← has_attribute attr_name src,
set_basic_attribute attr_name tgt p (some prio)
/-- Name of the declaration currently being elaborated. -/
meta constant decl_name : tactic name
/-- `save_type_info e ref` save (typeof e) at position associated with ref -/
meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit
meta constant save_info_thunk : pos → (unit → format) → tactic unit
/-- Return list of currently open namespaces -/
meta constant open_namespaces : tactic (list name)
/-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using
keyed matching with the given transparency setting.
We say `t` occurs in `e` by keyed matching iff there is a subterm `s`
s.t. `t` and `s` have the same head, and `is_def_eq t s md`
The main idea is to minimize the number of `is_def_eq` checks
performed. -/
meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool
/-- Abstracts all occurrences of the term `t` in `e` using keyed matching.
If `unify` is `ff`, then matching is used instead of unification.
That is, metavariables occurring in `e` are not assigned. -/
meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr
/-- Blocks the execution of the current thread for at least `msecs` milliseconds.
This tactic is used mainly for debugging purposes. -/
meta constant sleep (msecs : nat) : tactic unit
/-- Type check `e` with respect to the current goal.
Fails if `e` is not type correct. -/
meta constant type_check (e : expr) (md := semireducible) : tactic unit
open list nat
/-- Goals can be tagged using a list of names. -/
def tag : Type := list name
/-- Enable/disable goal tagging -/
meta constant enable_tags (b : bool) : tactic unit
/-- Return tt iff goal tagging is enabled. -/
meta constant tags_enabled : tactic bool
/-- Tag goal `g` with tag `t`. It does nothing is goal tagging is disabled.
Remark: `set_goal g []` removes the tag -/
meta constant set_tag (g : expr) (t : tag) : tactic unit
/-- Return tag associated with `g`. Return `[]` if there is no tag. -/
meta constant get_tag (g : expr) : tactic tag
meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit :=
induction h ns rec md >> return ()
/-- Remark: set_goals will erase any solved goal -/
meta def cleanup : tactic unit :=
get_goals >>= set_goals
/-- Auxiliary definition used to implement begin ... end blocks -/
meta def step {α : Type u} (t : tactic α) : tactic unit :=
t >>[tactic] cleanup
meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit :=
λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col
meta def is_prop (e : expr) : tactic bool :=
do t ← infer_type e,
return (t = `(Prop))
/-- Return true iff n is the name of declaration that is a proposition. -/
meta def is_prop_decl (n : name) : tactic bool :=
do env ← get_env,
d ← env.get n,
t ← return $ d.type,
is_prop t
meta def is_proof (e : expr) : tactic bool :=
infer_type e >>= is_prop
meta def whnf_no_delta (e : expr) : tactic expr :=
whnf e transparency.none
/-- Return `e` in weak head normal form with respect to the given transparency setting,
or `e` head is a generalized constructor or inductive datatype. -/
meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr :=
whnf e md ff
meta def whnf_target : tactic unit :=
target >>= whnf >>= change
meta def unsafe_change (e : expr) : tactic unit :=
change e ff
meta def intro (n : name) : tactic expr :=
do t ← target,
if expr.is_pi t ∨ expr.is_let t then intro_core n
else whnf_target >> intro_core n
meta def intro1 : tactic expr :=
intro `_
meta def intros : tactic (list expr) :=
do t ← target,
match t with
| expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs)
| _ := return []
end
meta def intro_lst : list name → tactic (list expr)
| [] := return []
| (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs)
/-- Introduces new hypotheses with forward dependencies -/
meta def intros_dep : tactic (list expr) :=
do t ← target,
let proc (b : expr) :=
if b.has_var_idx 0 then
do h ← intro1, hs ← intros_dep, return (h::hs)
else
-- body doesn't depend on new hypothesis
return [],
match t with
| expr.pi _ _ _ b := proc b
| expr.elet _ _ _ b := proc b
| _ := return []
end
meta def introv : list name → tactic (list expr)
| [] := intros_dep
| (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs')
/-- Returns n fully qualified if it refers to a constant, or else fails. -/
meta def resolve_constant (n : name) : tactic name :=
do (expr.const n _) ← resolve_name n,
pure n
meta def to_expr_strict (q : pexpr) : tactic expr :=
to_expr q
meta def revert (l : expr) : tactic nat :=
revert_lst [l]
meta def clear_lst : list name → tactic unit
| [] := skip
| (n::ns) := do H ← get_local n, clear H, clear_lst ns
meta def match_not (e : expr) : tactic expr :=
match (expr.is_not e) with
| (some a) := return a
| none := fail "expression is not a negation"
end
meta def match_and (e : expr) : tactic (expr × expr) :=
match (expr.is_and e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a conjunction"
end
meta def match_or (e : expr) : tactic (expr × expr) :=
match (expr.is_or e) with
| (some (α, β)) := return (α, β)
| none := fail "expression is not a disjunction"
end
meta def match_iff (e : expr) : tactic (expr × expr) :=
match (expr.is_iff e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an iff"
end
meta def match_eq (e : expr) : tactic (expr × expr) :=
match (expr.is_eq e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not an equality"
end
meta def match_ne (e : expr) : tactic (expr × expr) :=
match (expr.is_ne e) with
| (some (lhs, rhs)) := return (lhs, rhs)
| none := fail "expression is not a disequality"
end
meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) :=
do match (expr.is_heq e) with
| (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs)
| none := fail "expression is not a heterogeneous equality"
end
meta def match_refl_app (e : expr) : tactic (name × expr × expr) :=
do env ← get_env,
match (environment.is_refl_app env e) with
| (some (R, lhs, rhs)) := return (R, lhs, rhs)
| none := fail "expression is not an application of a reflexive relation"
end
meta def match_app_of (e : expr) (n : name) : tactic (list expr) :=
guard (expr.is_app_of e n) >> return e.get_app_args
meta def get_local_type (n : name) : tactic expr :=
get_local n >>= infer_type
meta def trace_result : tactic unit :=
format_result >>= trace
meta def rexact (e : expr) : tactic unit :=
exact e reducible
meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α
| [] := failed
| (h :: hs) := f h <|> any_hyp_aux hs
meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α :=
local_context >>= any_hyp_aux f
/-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/
meta def find_same_type : expr → list expr → tactic expr
| e [] := failed
| e (H :: Hs) :=
do t ← infer_type H,
(unify e t >> return H) <|> find_same_type e Hs
meta def find_assumption (e : expr) : tactic expr :=
do ctx ← local_context, find_same_type e ctx
meta def assumption : tactic unit :=
do { ctx ← local_context,
t ← target,
H ← find_same_type t ctx,
exact H }
<|> fail "assumption tactic failed"
meta def save_info (p : pos) : tactic unit :=
do s ← read,
tactic.save_info_thunk p (λ _, tactic_state.to_format s)
notation `‹` p `›` := (by assumption : p)
/-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/
meta def swap : tactic unit :=
do gs ← get_goals,
match gs with
| (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs)
| e := skip
end
/-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/
meta def assert (h : name) (t : expr) : tactic expr :=
do assert_core h t, swap, e ← intro h, swap, return e
/-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/
meta def assertv (h : name) (t : expr) (v : expr) : tactic expr :=
assertv_core h t v >> intro h
/-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/
meta def define (h : name) (t : expr) : tactic expr :=
do define_core h t, swap, e ← intro h, swap, return e
/-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/
meta def definev (h : name) (t : expr) (v : expr) : tactic expr :=
definev_core h t v >> intro h
/-- Add `h : t := pr` to the current goal -/
meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, definev h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Add `h : t` to the current goal, given a proof `pr : t` -/
meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr :=
let dv := λt, assertv h t pr in
option.cases_on t (infer_type pr >>= dv) dv
/-- Return the number of goals that need to be solved -/
meta def num_goals : tactic nat :=
do gs ← get_goals,
return (length gs)
/-- We have to provide the instance argument `[has_mod nat]` because
mod for nat was not defined yet -/
meta def rotate_right (n : nat) [has_mod nat] : tactic unit :=
do ng ← num_goals,
if ng = 0 then skip
else rotate_left (ng - n % ng)
meta def rotate : nat → tactic unit :=
rotate_left
private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit
| [] r := set_goals r.reverse
| (g::gs) r := do
ok ← try_core (set_goals [g] >> t),
match ok with
| none := repeat_aux gs (g::r)
| _ := do
gs' ← get_goals,
repeat_aux (gs' ++ gs) r
end
/-- This tactic is applied to each goal. If the application succeeds,
the tactic is applied recursively to all the generated subgoals until it eventually fails.
The recursion stops in a subgoal when the tactic has failed to make progress.
The tactic `repeat` never fails. -/
meta def repeat (t : tactic unit) : tactic unit :=
do gs ← get_goals, repeat_aux t gs []
/-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail.
The tactic fails if all t_i's fail. -/
meta def first {α : Type u} : list (tactic α) → tactic α
| [] := fail "first tactic failed, no more alternatives"
| (t::ts) := t <|> first ts
/-- Applies the given tactic to the main goal and fails if it is not solved. -/
meta def solve1 (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
match gs with
| [] := fail "solve1 tactic failed, there isn't any goal left to focus"
| (g::rs) :=
do set_goals [g],
tac,
gs' ← get_goals,
match gs' with
| [] := set_goals rs
| gs := fail "solve1 tactic failed, focused goal has not been solved"
end
end
/-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/
meta def solve (ts : list (tactic unit)) : tactic unit :=
first $ map solve1 ts
private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit
| [] [] rs := set_goals rs
| (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals"
| tts (g::gs) rs :=
mcond (is_assigned g) (focus_aux tts gs rs) $
do set_goals [g],
t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics",
t,
rs' ← get_goals,
focus_aux ts gs (rs ++ rs')
/-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/
meta def focus (ts : list (tactic unit)) : tactic unit :=
do gs ← get_goals, focus_aux ts gs []
meta def focus1 {α} (tac : tactic α) : tactic α :=
do g::gs ← get_goals,
match gs with
| [] := tac
| _ := do
set_goals [g],
a ← tac,
gs' ← get_goals,
set_goals (gs' ++ gs),
return a
end
private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit
| [] ac := set_goals ac
| (g :: gs) ac :=
mcond (is_assigned g) (all_goals_core gs ac) $
do set_goals [g],
tac,
new_gs ← get_goals,
all_goals_core gs (ac ++ new_gs)
/-- Apply the given tactic to all goals. -/
meta def all_goals (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
all_goals_core tac gs []
private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit
| [] ac progress := guard progress >> set_goals ac
| (g :: gs) ac progress :=
mcond (is_assigned g) (any_goals_core gs ac progress) $
do set_goals [g],
succeeded ← try_core tac,
new_gs ← get_goals,
any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress)
/-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if
tac succeeds for at least one goal. -/
meta def any_goals (tac : tactic unit) : tactic unit :=
do gs ← get_goals,
any_goals_core tac gs [] ff
/-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/
meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, all_goals tac2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit :=
do g::gs ← get_goals,
set_goals [g],
tac1, focus tacs2,
gs' ← get_goals,
set_goals (gs' ++ gs)
meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) :=
⟨seq⟩
meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) :=
⟨seq_focus⟩
meta constant is_trace_enabled_for : name → bool
/-- Execute tac only if option trace.n is set to true. -/
meta def when_tracing (n : name) (tac : tactic unit) : tactic unit :=
when (is_trace_enabled_for n = tt) tac
/-- Fail if there are no remaining goals. -/
meta def fail_if_no_goals : tactic unit :=
do n ← num_goals,
when (n = 0) (fail "tactic failed, there are no goals to be solved")
/-- Fail if there are unsolved goals. -/
meta def done : tactic unit :=
do n ← num_goals,
when (n ≠ 0) (fail "done tactic failed, there are unsolved goals")
meta def apply_opt_param : tactic unit :=
do `(opt_param %%t %%v) ← target,
exact v
meta def apply_auto_param : tactic unit :=
do `(auto_param %%type %%tac_name_expr) ← target,
change type,
tac_name ← eval_expr name tac_name_expr,
tac ← eval_expr (tactic unit) (expr.const tac_name []),
tac
meta def has_opt_auto_param (ms : list expr) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit :=
when (cfg.auto_param || cfg.opt_param) $
mwhen (has_opt_auto_param ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $
set_goals [m] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool :=
ms.mfoldl
(λ r m, do type ← infer_type m.2,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2)
ff
meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit :=
mwhen (has_opt_auto_param_for_apply ms) $ do
gs ← get_goals,
ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $
set_goals [m.2] >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) :=
do r ← apply_core e cfg,
try_apply_opt_auto_param_for_apply cfg r,
return r
meta def fapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.all}
meta def eapply (e : expr) : tactic (list (name × expr)) :=
apply e {new_goals := new_goals.non_dep_only}
/-- Try to solve the main goal using type class resolution. -/
meta def apply_instance : tactic unit :=
do tgt ← target >>= instantiate_mvars,
b ← is_class tgt,
if b then mk_instance tgt >>= exact
else fail "apply_instance tactic fail, target is not a type class"
/-- Create a list of universe meta-variables of the given size. -/
meta def mk_num_meta_univs : nat → tactic (list level)
| 0 := return []
| (succ n) := do
l ← mk_meta_univ,
ls ← mk_num_meta_univs n,
return (l::ls)
/-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/
meta def mk_const (c : name) : tactic expr :=
do env ← get_env,
decl ← env.get c,
let num := decl.univ_params.length,
ls ← mk_num_meta_univs num,
return (expr.const c ls)
/-- Apply the constant `c` -/
meta def applyc (c : name) : tactic unit :=
do c ← mk_const c, apply c, skip
meta def eapplyc (c : name) : tactic unit :=
do c ← mk_const c, eapply c, skip
meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit :=
try (do c ← mk_const n, save_type_info c ref)
/-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`,
and return metavariable `?M : ?T`.
This action can be used to create a meta-variable when
we don't know its type at creation time -/
meta def mk_mvar : tactic expr :=
do u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
mk_meta_var t
/-- Makes a sorry macro with a meta-variable as its type. -/
meta def mk_sorry : tactic expr := do
u ← mk_meta_univ,
t ← mk_meta_var (expr.sort u),
return $ expr.mk_sorry t
/-- Closes the main goal using sorry. -/
meta def admit : tactic unit :=
target >>= exact ∘ expr.mk_sorry
meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do
uniq_name ← mk_fresh_name,
return $ expr.local_const uniq_name pp_name bi type
meta def mk_local_def (pp_name : name) (type : expr) : tactic expr :=
mk_local' pp_name binder_info.default type
meta def mk_local_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
private meta def get_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_pi_arity_aux new_b,
return (r + 1)
| e := return 0
/-- Compute the arity of the given (Pi-)type -/
meta def get_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_pi_arity_aux
/-- Compute the arity of the given function -/
meta def get_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_pi_arity
meta def triv : tactic unit := mk_const `trivial >>= exact
notation `dec_trivial` := of_as_true (by tactic.triv)
meta def by_contradiction (H : option name := none) : tactic expr :=
do tgt : expr ← target,
(match_not tgt >> return ())
<|>
(mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip)
<|>
fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)",
match H with
| some n := intro n
| none := intro1
end
private meta def generalizes_aux (md : transparency) : list expr → tactic unit
| [] := skip
| (e::es) := generalize e `x md >> generalizes_aux es
meta def generalizes (es : list expr) (md := semireducible) : tactic unit :=
generalizes_aux md es
private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr)
| [] r := return r
| (h::hs) r :=
do type ← infer_type h,
d ← kdepends_on type e md,
if d then kdependencies_core hs (h::r)
else kdependencies_core hs r
/-- Return all hypotheses that depends on `e`
The dependency test is performed using `kdepends_on` with the given transparency setting. -/
meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) :=
do ctx ← local_context, kdependencies_core e md ctx []
/-- Revert all hypotheses that depend on `e` -/
meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat :=
kdependencies e md >>= revert_lst
meta def revert_kdeps (e : expr) (md := reducible) :=
revert_kdependencies e md
/-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis.
Remark, it reverts dependencies using `revert_kdeps`.
Two different transparency modes are used `md` and `dmd`.
The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`.
It returns the constructor names associated with each new goal. -/
meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list name) :=
if e.is_local_constant then
do r ← cases_core e ids md, return $ r.map (λ t, t.1)
else do
x ← mk_fresh_name,
n ← revert_kdependencies e dmd,
(tactic.generalize e x dmd)
<|>
(do t ← infer_type e,
tactic.assertv x t e,
get_local x >>= tactic.revert,
return ()),
h ← tactic.intro1,
focus1 (do r ← cases_core h ids md, all_goals (intron n), return $ r.map (λ t, t.1))
meta def refine (e : pexpr) : tactic unit :=
do tgt : expr ← target,
to_expr ``(%%e : %%tgt) tt >>= exact
meta def by_cases (e : expr) (h : name) : tactic unit :=
do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"),
inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"),
t ← target,
tm ← mk_mapp `dite [some e, some inst, some t],
seq (apply tm >> skip) (intro h >> skip)
meta def funext_core : list name → bool → tactic unit
| [] tt := return ()
| ids only_ids := try $
do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf),
applyc `funext,
id ← if ids.empty ∨ ids.head = `_ then do
(expr.lam n _ _ _) ← whnf lhs,
return n
else return ids.head,
intro id,
funext_core ids.tail only_ids
meta def funext : tactic unit :=
funext_core [] ff
meta def funext_lst (ids : list name) : tactic unit :=
funext_core ids tt
private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i :=
let n := base <.> ("_aux_" ++ repr i) in
if ¬env.contains n then n
else get_undeclared_const (i+1)
meta def new_aux_decl_name : tactic name := do
env ← get_env, n ← decl_name,
return $ get_undeclared_const env n 1
private meta def mk_aux_decl_name : option name → tactic name
| none := new_aux_decl_name
| (some suffix) := do p ← decl_name, return $ p ++ suffix
meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit :=
do fail_if_no_goals,
gs ← get_goals,
type ← if zeta_reduce then target >>= zeta else target,
is_lemma ← is_prop type,
m ← mk_meta_var type,
set_goals [m],
tac,
n ← num_goals,
when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"),
set_goals gs,
val ← instantiate_mvars m,
val ← if zeta_reduce then zeta val else return val,
c ← mk_aux_decl_name suffix,
e ← add_aux_decl c type val is_lemma,
exact e
/-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/
meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) :=
do m ← mk_meta_var type,
gs ← get_goals,
set_goals [m],
a ← tac,
set_goals gs,
return (a, m)
/-- Return tt iff 'd' is a declaration in one of the current open namespaces -/
meta def in_open_namespaces (d : name) : tactic bool :=
do ns ← open_namespaces,
env ← get_env,
return $ ns.any (λ n, n.is_prefix_of d) && env.contains d
/-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of
memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting
long running tactics. -/
meta def try_for {α} (max : nat) (tac : tactic α) : tactic α :=
λ s,
match _root_.try_for max (tac s) with
| some r := r
| none := mk_exception "try_for tactic failed, timeout" none s
end
meta def updateex_env (f : environment → exceptional environment) : tactic unit :=
do env ← get_env,
env ← returnex $ f env,
set_env env
/- Add a new inductive datatype to the environment
name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/
meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr))
(is_meta : bool := ff) : tactic unit :=
updateex_env $ λe, e.add_inductive n ls p ty is is_meta
meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit :=
add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff)
meta def rename (curr : name) (new : name) : tactic unit :=
do h ← get_local curr,
n ← revert h,
intro new,
intron (n - 1)
/--
"Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof
that (type = new_type). The tactic actually creates a new hypothesis
with the same user facing name, and (tries to) clear `h`.
The `clear` step fails if `h` has forward dependencies. In this case, the old `h`
will remain in the local context. The tactic returns the new hypothesis. -/
meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr :=
do h_type ← infer_type h,
new_h ← assert h.local_pp_name new_type,
mk_eq_mp eq_pr h >>= exact,
try $ clear h,
return new_h
meta def main_goal : tactic expr :=
do g::gs ← get_goals, return g
/- Goal tagging support -/
meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α :=
do old ← tags_enabled,
enable_tags b,
r ← t,
enable_tags old,
return r
meta def get_main_tag : tactic tag :=
main_goal >>= get_tag
meta def set_main_tag (t : tag) : tactic unit :=
do g ← main_goal, set_tag g t
meta def subst (h : expr) : tactic unit :=
(do guard h.is_local_constant,
some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h,
is_def_eq α β,
new_h_type ← mk_app `eq [lhs, rhs],
new_h_pr ← mk_app `eq_of_heq [h],
new_h ← assertv h.local_pp_name new_h_type new_h_pr,
try (clear h),
subst_core new_h)
<|> subst_core h
end tactic
notation [parsing_only] `command`:max := tactic unit
open tactic
namespace list
meta def for_each {α} : list α → (α → tactic unit) → tactic unit
| [] fn := skip
| (e::es) fn := do fn e, for_each es fn
meta def any_of {α β} : list α → (α → tactic β) → tactic β
| [] fn := failed
| (e::es) fn := do opt_b ← try_core (fn e),
match opt_b with
| some b := return b
| none := any_of es fn
end
end list
/- Install monad laws tactic and use it to prove some instances. -/
meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact
meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact
meta def unsafe_monad_from_pure_bind {m : Type u → Type v}
(pure : Π {α : Type u}, α → m α)
(bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m :=
{pure := @pure, bind := @bind,
id_map := undefined, pure_bind := undefined, bind_assoc := undefined}
meta instance : monad task :=
{map := @task.map, bind := @task.bind, pure := @task.pure,
id_map := undefined, pure_bind := undefined, bind_assoc := undefined,
bind_pure_comp_eq_map := undefined}
namespace tactic
meta def mk_id_proof (prop : expr) (pr : expr) : expr :=
expr.app (expr.app (expr.const ``id [level.zero]) prop) pr
meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr :=
do prop ← mk_app `eq [lhs, rhs],
return $ mk_id_proof prop pr
meta def replace_target (new_target : expr) (pr : expr) : tactic unit :=
do t ← target,
assert `htarget new_target, swap,
ht ← get_local `htarget,
locked_pr ← mk_id_eq t new_target pr,
mk_eq_mpr locked_pr ht >>= exact
end tactic
|
1f34f7462f85f190f5fedaeda22f0c9e45ed9baa | 6094e25ea0b7699e642463b48e51b2ead6ddc23f | /library/data/set/filter.lean | 5e2fed02dc3f23153ec864dddc01cb317a4d6a28 | [
"Apache-2.0"
] | permissive | gbaz/lean | a7835c4e3006fbbb079e8f8ffe18aacc45adebfb | a501c308be3acaa50a2c0610ce2e0d71becf8032 | refs/heads/master | 1,611,198,791,433 | 1,451,339,111,000 | 1,451,339,111,000 | 48,713,797 | 0 | 0 | null | 1,451,338,939,000 | 1,451,338,939,000 | null | UTF-8 | Lean | false | false | 11,875 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Filters, following Hölzl, Immler, and Huffman, "Type classes and filters for mathematical
analysis in Isabelle/HOL".
-/
import data.set.function logic.identities algebra.complete_lattice
namespace set
open classical
structure filter (A : Type) :=
(sets : set (set A))
(univ_mem_sets : univ ∈ sets)
(inter_closed : ∀ {a b}, a ∈ sets → b ∈ sets → a ∩ b ∈ sets)
(is_mono : ∀ {a b}, a ⊆ b → a ∈ sets → b ∈ sets)
attribute filter.sets [coercion]
namespace filter -- i.e. set.filter
variable {A : Type}
variables {P Q : A → Prop}
variables {F₁ : filter A} {F₂ : filter A} {F : filter A}
definition eventually (P : A → Prop) (F : filter A) : Prop :=
P ∈ F
-- TODO: notation for eventually?
-- notation `forallf` binders `∈` F `,` r:(scoped:1 P, P) := eventually r F
-- notation `'∀f` binders `∈` F `,` r:(scoped:1 P, P) := eventually r F
theorem eventually_true (F : filter A) : eventually (λx, true) F :=
!filter.univ_mem_sets
theorem eventually_of_forall {P : A → Prop} (F : filter A) (H : ∀ x, P x) : eventually P F :=
by rewrite [eq_univ_of_forall H]; apply eventually_true
theorem eventually_mono (H₁ : eventually P F) (H₂ : ∀x, P x → Q x) : eventually Q F :=
!filter.is_mono H₂ H₁
theorem eventually_and (H₁ : eventually P F) (H₂ : eventually Q F) :
eventually (λ x, P x ∧ Q x) F :=
!filter.inter_closed H₁ H₂
theorem eventually_mp (H₁ : eventually (λx, P x → Q x) F) (H₂ : eventually P F) :
eventually Q F :=
have ∀ x, (P x → Q x) ∧ P x → Q x, from take x, assume H, and.left H (and.right H),
eventually_mono (eventually_and H₁ H₂) this
theorem eventually_mpr (H₁ : eventually P F) (H₂ : eventually (λx, P x → Q x) F) :
eventually Q F := eventually_mp H₂ H₁
variables (P Q F)
theorem eventually_and_iff : eventually (λ x, P x ∧ Q x) F ↔ eventually P F ∧ eventually Q F :=
iff.intro
(assume H, and.intro
(eventually_mpr H (eventually_of_forall F (take x, and.left)))
(eventually_mpr H (eventually_of_forall F (take x, and.right))))
(assume H, eventually_and (and.left H) (and.right H))
variables {P Q F}
-- TODO: port eventually_ball_finite_distrib, etc.
theorem eventually_choice {B : Type} [nonemptyB : nonempty B] {R : A → B → Prop} {F : filter A}
(H : eventually (λ x, ∃ y, R x y) F) : ∃ f, eventually (λ x, R x (f x)) F :=
let f := λ x, epsilon (λ y, R x y) in
exists.intro f
(eventually_mono H
(take x, suppose ∃ y, R x y,
show R x (f x), from epsilon_spec this))
theorem exists_not_of_not_eventually (H : ¬ eventually P F) : ∃ x, ¬ P x :=
exists_not_of_not_forall (assume H', H (eventually_of_forall F H'))
theorem eventually_iff_mp (H₁ : eventually (λ x, P x ↔ Q x) F) (H₂ : eventually P F) :
eventually Q F :=
eventually_mono (eventually_and H₁ H₂) (λ x H, iff.mp (and.left H) (and.right H))
theorem eventually_iff_mpr (H₁ : eventually (λ x, P x ↔ Q x) F) (H₂ : eventually Q F) :
eventually P F :=
eventually_mono (eventually_and H₁ H₂) (λ x H, iff.mpr (and.left H) (and.right H))
theorem eventually_iff_iff (H : eventually (λ x, P x ↔ Q x) F) : eventually P F ↔ eventually Q F :=
iff.intro (eventually_iff_mp H) (eventually_iff_mpr H)
-- TODO: port frequently and properties?
/- filters form a lattice under ⊇ -/
protected theorem eq : sets F₁ = sets F₂ → F₁ = F₂ :=
begin
cases F₁ with s₁ u₁ i₁ m₁, cases F₂ with s₂ u₂ i₂ m₂, esimp,
intro eqs₁s₂, revert [u₁, i₁, m₁, u₂, i₂, m₂],
subst s₁, intros, exact rfl
end
definition weakens [reducible] (F₁ F₂ : filter A) := F₁ ⊇ F₂
infix `≼`:50 := weakens
definition refines [reducible] (F₁ F₂ : filter A) := F₁ ⊆ F₂
infix `≽`:50 := refines
theorem weakens.refl (F : filter A) : F ≼ F := subset.refl _
theorem weakens.trans {F₁ F₂ F₃ : filter A} (H₁ : F₁ ≼ F₂) (H₂ : F₂ ≼ F₃) : F₁ ≼ F₃ :=
subset.trans H₂ H₁
theorem weakens.antisymm (H₁ : F₁ ≼ F₂) (H₂ : F₂ ≼ F₁) : F₁ = F₂ :=
filter.eq (eq_of_subset_of_subset H₂ H₁)
definition bot : filter A :=
⦃ filter,
sets := univ,
univ_mem_sets := trivial,
inter_closed := λ a b Ha Hb, trivial,
is_mono := λ a b Ha Hsub, trivial
⦄
notation `⊥` := bot
definition top : filter A :=
⦃ filter,
sets := '{univ},
univ_mem_sets := !or.inl rfl,
inter_closed := abstract
λ a b Ha Hb,
by rewrite [*!mem_singleton_iff at *]; substvars; exact !inter_univ
end,
is_mono := abstract
λ a b Hsub Ha,
begin
rewrite [mem_singleton_iff at Ha], subst [Ha],
exact or.inl (eq_univ_of_univ_subset Hsub)
end
end
⦄
notation `⊤` := top
definition sup (F₁ F₂ : filter A) : filter A :=
⦃ filter,
sets := F₁ ∩ F₂,
univ_mem_sets := and.intro (filter.univ_mem_sets F₁) (filter.univ_mem_sets F₂),
inter_closed := abstract
λ a b Ha Hb,
and.intro
(filter.inter_closed F₁ (and.left Ha) (and.left Hb))
(filter.inter_closed F₂ (and.right Ha) (and.right Hb))
end,
is_mono := abstract
λ a b Hsub Ha,
and.intro
(filter.is_mono F₁ Hsub (and.left Ha))
(filter.is_mono F₂ Hsub (and.right Ha))
end
⦄
infix `⊔`:65 := sup
definition inf (F₁ F₂ : filter A) : filter A :=
⦃ filter,
sets := {r | ∃₀ s ∈ F₁, ∃₀ t ∈ F₂, r ⊇ s ∩ t},
univ_mem_sets := abstract
bounded_exists.intro (univ_mem_sets F₁)
(bounded_exists.intro (univ_mem_sets F₂)
(by rewrite univ_inter; apply subset.refl))
end,
inter_closed := abstract
λ a b Ha Hb,
obtain a₁ [a₁F₁ [a₂ [a₂F₂ (Ha' : a ⊇ a₁ ∩ a₂)]]], from Ha,
obtain b₁ [b₁F₁ [b₂ [b₂F₂ (Hb' : b ⊇ b₁ ∩ b₂)]]], from Hb,
assert a₁ ∩ b₁ ∩ (a₂ ∩ b₂) = a₁ ∩ a₂ ∩ (b₁ ∩ b₂),
by rewrite [*inter.assoc, inter.left_comm b₁],
have a ∩ b ⊇ a₁ ∩ b₁ ∩ (a₂ ∩ b₂),
begin
rewrite this,
apply subset_inter,
{apply subset.trans,
apply inter_subset_left,
exact Ha'},
apply subset.trans,
apply inter_subset_right,
exact Hb'
end,
bounded_exists.intro (inter_closed F₁ a₁F₁ b₁F₁)
(bounded_exists.intro (inter_closed F₂ a₂F₂ b₂F₂)
this)
end,
is_mono := abstract
λ a b Hsub Ha,
obtain a₁ [a₁F₁ [a₂ [a₂F₂ (Ha' : a ⊇ a₁ ∩ a₂)]]], from Ha,
bounded_exists.intro a₁F₁
(bounded_exists.intro a₂F₂ (subset.trans Ha' Hsub))
end
⦄
infix `⊓`:70 := inf
definition Sup (S : set (filter A)) : filter A :=
⦃ filter,
sets := {s | ∀₀ F ∈ S, s ∈ F},
univ_mem_sets := λ F FS, univ_mem_sets F,
inter_closed := abstract
λ a b Ha Hb F FS,
inter_closed F (Ha F FS) (Hb F FS)
end,
is_mono := abstract
λ a b asubb Ha F FS,
is_mono F asubb (Ha F FS)
end
⦄
prefix `⨆`:65 := Sup
definition Inf (S : set (filter A)) : filter A :=
Sup {F | ∀ G, G ∈ S → G ≽ F}
prefix `⨅`:70 := Inf
theorem eventually_of_refines (H₁ : eventually P F₁) (H₂ : F₁ ≽ F₂) : eventually P F₂ := H₂ H₁
theorem refines_of_forall (H : ∀ P, eventually P F₁ → eventually P F₂) : F₁ ≽ F₂ := H
theorem eventually_bot (P : A → Prop) : eventually P ⊥ := trivial
theorem refines_bot (F : filter A) : F ≽ ⊥ :=
take P, suppose eventually P F, eventually_bot P
theorem eventually_top_of_forall (H : ∀ x, P x) : eventually P ⊤ :=
by rewrite [↑eventually, ↑top, mem_singleton_iff]; exact eq_univ_of_forall H
theorem forall_of_eventually_top : eventually P ⊤ → ∀ x, P x :=
by rewrite [↑eventually, ↑top, mem_singleton_iff]; intro H x; rewrite H; exact trivial
theorem eventually_top (P : A → Prop) : eventually P top ↔ ∀ x, P x :=
iff.intro forall_of_eventually_top eventually_top_of_forall
theorem top_refines (F : filter A) : ⊤ ≽ F :=
take P, suppose eventually P top,
eventually_of_forall F (forall_of_eventually_top this)
theorem eventually_sup (P : A → Prop) (F₁ F₂ : filter A) :
eventually P (sup F₁ F₂) ↔ eventually P F₁ ∧ eventually P F₂ :=
!iff.refl
theorem sup_refines_left (F₁ F₂ : filter A) : F₁ ⊔ F₂ ≽ F₁ :=
inter_subset_left _ _
theorem sup_refines_right (F₁ F₂ : filter A) : F₁ ⊔ F₂ ≽ F₂ :=
inter_subset_right _ _
theorem refines_sup (H₁ : F ≽ F₁) (H₂ : F ≽ F₂) : F ≽ F₁ ⊔ F₂ :=
subset_inter H₁ H₂
theorem refines_inf_left (F₁ F₂ : filter A) : F₁ ≽ F₁ ⊓ F₂ :=
take s, suppose s ∈ F₁,
bounded_exists.intro `s ∈ F₁`
(bounded_exists.intro (univ_mem_sets F₂) (by rewrite inter_univ; apply subset.refl))
theorem refines_inf_right (F₁ F₂ : filter A) : F₂ ≽ F₁ ⊓ F₂ :=
take s, suppose s ∈ F₂,
bounded_exists.intro (univ_mem_sets F₁)
(bounded_exists.intro `s ∈ F₂` (by rewrite univ_inter; apply subset.refl))
theorem inf_refines (H₁ : F₁ ≽ F) (H₂ : F₂ ≽ F) : F₁ ⊓ F₂ ≽ F :=
take s : set A, suppose (#set.filter s ∈ F₁ ⊓ F₂),
obtain a₁ [a₁F₁ [a₂ [a₂F₂ (Hsub : s ⊇ a₁ ∩ a₂)]]], from this,
have a₁ ∈ F, from H₁ a₁F₁,
have a₂ ∈ F, from H₂ a₂F₂,
show s ∈ F, from is_mono F Hsub (inter_closed F `a₁ ∈ F` `a₂ ∈ F`)
theorem refines_Sup {F : filter A} {S : set (filter A)} (H : ∀₀ G ∈ S, F ≽ G) : F ≽ ⨆ S :=
λ s Fs G GS, H GS Fs
theorem Sup_refines {F : filter A} {S : set (filter A)} (FS : F ∈ S) : ⨆ S ≽ F :=
λ s sInfS, sInfS F FS
theorem Inf_refines {F : filter A} {S : set (filter A)} (H : ∀₀ G ∈ S, G ≽ F) : ⨅ S ≽ F :=
Sup_refines H
theorem refines_Inf {F : filter A} {S : set (filter A)} (FS : F ∈ S) : F ≽ ⨅ S :=
refines_Sup (λ G GS, GS F FS)
protected definition complete_lattice_Inf [reducible] [instance] : complete_lattice_Inf (filter A) :=
⦃ complete_lattice_Inf,
le := weakens,
le_refl := weakens.refl,
le_trans := @weakens.trans A,
le_antisymm := @weakens.antisymm A,
-- inf := inf,
-- le_inf := @inf_refines A,
-- inf_le_left := refines_inf_left,
-- inf_le_right := refines_inf_right,
-- sup := sup,
-- sup_le := @refines_sup A,
-- le_sup_left := sup_refines_left,
-- le_sup_right := sup_refines_right,
Inf := Inf,
Inf_le := @refines_Inf A,
le_Inf := @Inf_refines A
⦄
-- The previous instance is enough for showing that (filter A) is a complete_lattice
example {A : Type} : complete_lattice (filter A) :=
_
end filter
end set
|
6b67637c340093471756cdb789ebaeaea471f138 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/list/basic.lean | 7129974700d1329bd9c951af482ccbc674106e83 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 165,383 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import algebra.order_functions
import control.monad.basic
import data.nat.choose.basic
import order.rel_classes
/-!
# Basic properties of lists
-/
open function nat
namespace list
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
attribute [inline] list.head
instance : is_left_id (list α) has_append.append [] :=
⟨ nil_append ⟩
instance : is_right_id (list α) has_append.append [] :=
⟨ append_nil ⟩
instance : is_associative (list α) has_append.append :=
⟨ append_assoc ⟩
theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ [].
theorem cons_ne_self (a : α) (l : list α) : a::l ≠ l :=
mt (congr_arg length) (nat.succ_ne_self _)
theorem head_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → h₁ = h₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pheq)
theorem tail_eq_of_cons_eq {h₁ h₂ : α} {t₁ t₂ : list α} :
(h₁::t₁) = (h₂::t₂) → t₁ = t₂ :=
assume Peq, list.no_confusion Peq (assume Pheq Pteq, Pteq)
@[simp] theorem cons_injective {a : α} : injective (cons a) :=
assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe
theorem cons_inj (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' :=
⟨λ e, cons_injective e, congr_arg _⟩
theorem exists_cons_of_ne_nil {l : list α} (h : l ≠ nil) : ∃ b L, l = b :: L :=
by { induction l with c l', contradiction, use [c,l'], }
/-! ### mem -/
theorem mem_singleton_self (a : α) : a ∈ [a] := mem_cons_self _ _
theorem eq_of_mem_singleton {a b : α} : a ∈ [b] → a = b :=
assume : a ∈ [b], or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, this)
(assume : a ∈ [], absurd this (not_mem_nil a))
@[simp] theorem mem_singleton {a b : α} : a ∈ [b] ↔ a = b :=
⟨eq_of_mem_singleton, or.inl⟩
theorem mem_of_mem_cons_of_mem {a b : α} {l : list α} : a ∈ b::l → b ∈ l → a ∈ l :=
assume ainbl binl, or.elim (eq_or_mem_of_mem_cons ainbl)
(assume : a = b, begin subst a, exact binl end)
(assume : a ∈ l, this)
theorem eq_or_ne_mem_of_mem {a b : α} {l : list α} (h : a ∈ b :: l) : a = b ∨ (a ≠ b ∧ a ∈ l) :=
classical.by_cases or.inl $ assume : a ≠ b, h.elim or.inl $ assume h, or.inr ⟨this, h⟩
theorem not_mem_append {a : α} {s t : list α} (h₁ : a ∉ s) (h₂ : a ∉ t) : a ∉ s ++ t :=
mt mem_append.1 $ not_or_distrib.2 ⟨h₁, h₂⟩
theorem ne_nil_of_mem {a : α} {l : list α} (h : a ∈ l) : l ≠ [] :=
by intro e; rw e at h; cases h
theorem mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t :=
begin
induction l with b l ih, {cases h}, rcases h with rfl | h,
{ exact ⟨[], l, rfl⟩ },
{ rcases ih h with ⟨s, t, rfl⟩,
exact ⟨b::s, t, rfl⟩ }
end
theorem mem_of_ne_of_mem {a y : α} {l : list α} (h₁ : a ≠ y) (h₂ : a ∈ y :: l) : a ∈ l :=
or.elim (eq_or_mem_of_mem_cons h₂) (λe, absurd e h₁) (λr, r)
theorem ne_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ≠ b :=
assume nin aeqb, absurd (or.inl aeqb) nin
theorem not_mem_of_not_mem_cons {a b : α} {l : list α} : a ∉ b::l → a ∉ l :=
assume nin nainl, absurd (or.inr nainl) nin
theorem not_mem_cons_of_ne_of_not_mem {a y : α} {l : list α} : a ≠ y → a ∉ l → a ∉ y::l :=
assume p1 p2, not.intro (assume Pain, absurd (eq_or_mem_of_mem_cons Pain) (not_or p1 p2))
theorem ne_and_not_mem_of_not_mem_cons {a y : α} {l : list α} : a ∉ y::l → a ≠ y ∧ a ∉ l :=
assume p, and.intro (ne_of_not_mem_cons p) (not_mem_of_not_mem_cons p)
theorem mem_map_of_mem (f : α → β) {a : α} {l : list α} (h : a ∈ l) : f a ∈ map f l :=
begin
induction l with b l' ih,
{cases h},
{rcases h with rfl | h,
{exact or.inl rfl},
{exact or.inr (ih h)}}
end
theorem exists_of_mem_map {f : α → β} {b : β} {l : list α} (h : b ∈ map f l) :
∃ a, a ∈ l ∧ f a = b :=
begin
induction l with c l' ih,
{cases h},
{cases (eq_or_mem_of_mem_cons h) with h h,
{exact ⟨c, mem_cons_self _ _, h.symm⟩},
{rcases ih h with ⟨a, ha₁, ha₂⟩,
exact ⟨a, mem_cons_of_mem _ ha₁, ha₂⟩ }}
end
@[simp] theorem mem_map {f : α → β} {b : β} {l : list α} : b ∈ map f l ↔ ∃ a, a ∈ l ∧ f a = b :=
⟨exists_of_mem_map, λ ⟨a, la, h⟩, by rw [← h]; exact mem_map_of_mem f la⟩
theorem mem_map_of_injective {f : α → β} (H : injective f) {a : α} {l : list α} :
f a ∈ map f l ↔ a ∈ l :=
⟨λ m, let ⟨a', m', e⟩ := exists_of_mem_map m in H e ▸ m', mem_map_of_mem _⟩
lemma forall_mem_map_iff {f : α → β} {l : list α} {P : β → Prop} :
(∀ i ∈ l.map f, P i) ↔ ∀ j ∈ l, P (f j) :=
begin
split,
{ assume H j hj,
exact H (f j) (mem_map_of_mem f hj) },
{ assume H i hi,
rcases mem_map.1 hi with ⟨j, hj, ji⟩,
rw ← ji,
exact H j hj }
end
@[simp] lemma map_eq_nil {f : α → β} {l : list α} : list.map f l = [] ↔ l = [] :=
⟨by cases l; simp only [forall_prop_of_true, map, forall_prop_of_false, not_false_iff],
λ h, h.symm ▸ rfl⟩
@[simp] theorem mem_join {a : α} : ∀ {L : list (list α)}, a ∈ join L ↔ ∃ l, l ∈ L ∧ a ∈ l
| [] := ⟨false.elim, λ⟨_, h, _⟩, false.elim h⟩
| (c :: L) := by simp only [join, mem_append, @mem_join L, mem_cons_iff, or_and_distrib_right,
exists_or_distrib, exists_eq_left]
theorem exists_of_mem_join {a : α} {L : list (list α)} : a ∈ join L → ∃ l, l ∈ L ∧ a ∈ l :=
mem_join.1
theorem mem_join_of_mem {a : α} {L : list (list α)} {l} (lL : l ∈ L) (al : a ∈ l) : a ∈ join L :=
mem_join.2 ⟨l, lL, al⟩
@[simp]
theorem mem_bind {b : β} {l : list α} {f : α → list β} : b ∈ list.bind l f ↔ ∃ a ∈ l, b ∈ f a :=
iff.trans mem_join
⟨λ ⟨l', h1, h2⟩, let ⟨a, al, fa⟩ := exists_of_mem_map h1 in ⟨a, al, fa.symm ▸ h2⟩,
λ ⟨a, al, bfa⟩, ⟨f a, mem_map_of_mem _ al, bfa⟩⟩
theorem exists_of_mem_bind {b : β} {l : list α} {f : α → list β} :
b ∈ list.bind l f → ∃ a ∈ l, b ∈ f a :=
mem_bind.1
theorem mem_bind_of_mem {b : β} {l : list α} {f : α → list β} {a} (al : a ∈ l) (h : b ∈ f a) :
b ∈ list.bind l f :=
mem_bind.2 ⟨a, al, h⟩
lemma bind_map {g : α → list β} {f : β → γ} :
∀(l : list α), list.map f (l.bind g) = l.bind (λa, (g a).map f)
| [] := rfl
| (a::l) := by simp only [cons_bind, map_append, bind_map l]
/-! ### length -/
theorem length_eq_zero {l : list α} : length l = 0 ↔ l = [] :=
⟨eq_nil_of_length_eq_zero, λ h, h.symm ▸ rfl⟩
theorem length_pos_of_mem {a : α} : ∀ {l : list α}, a ∈ l → 0 < length l
| (b::l) _ := zero_lt_succ _
theorem exists_mem_of_length_pos : ∀ {l : list α}, 0 < length l → ∃ a, a ∈ l
| (b::l) _ := ⟨b, mem_cons_self _ _⟩
theorem length_pos_iff_exists_mem {l : list α} : 0 < length l ↔ ∃ a, a ∈ l :=
⟨exists_mem_of_length_pos, λ ⟨a, h⟩, length_pos_of_mem h⟩
theorem ne_nil_of_length_pos {l : list α} : 0 < length l → l ≠ [] :=
λ h1 h2, lt_irrefl 0 ((length_eq_zero.2 h2).subst h1)
theorem length_pos_of_ne_nil {l : list α} : l ≠ [] → 0 < length l :=
λ h, pos_iff_ne_zero.2 $ λ h0, h $ length_eq_zero.1 h0
theorem length_pos_iff_ne_nil {l : list α} : 0 < length l ↔ l ≠ [] :=
⟨ne_nil_of_length_pos, length_pos_of_ne_nil⟩
theorem length_eq_one {l : list α} : length l = 1 ↔ ∃ a, l = [a] :=
⟨match l with [a], _ := ⟨a, rfl⟩ end, λ ⟨a, e⟩, e.symm ▸ rfl⟩
lemma exists_of_length_succ {n} :
∀ l : list α, l.length = n + 1 → ∃ h t, l = h :: t
| [] H := absurd H.symm $ succ_ne_zero n
| (h :: t) H := ⟨h, t, rfl⟩
@[simp] lemma length_injective_iff : injective (list.length : list α → ℕ) ↔ subsingleton α :=
begin
split,
{ intro h, refine ⟨λ x y, _⟩, suffices : [x] = [y], { simpa using this }, apply h, refl },
{ intros hα l1 l2 hl, induction l1 generalizing l2; cases l2,
{ refl }, { cases hl }, { cases hl },
congr, exactI subsingleton.elim _ _, apply l1_ih, simpa using hl }
end
@[simp] lemma length_injective [subsingleton α] : injective (length : list α → ℕ) :=
length_injective_iff.mpr $ by apply_instance
/-! ### set-theoretic notation of lists -/
lemma empty_eq : (∅ : list α) = [] := by refl
lemma singleton_eq (x : α) : ({x} : list α) = [x] := rfl
lemma insert_neg [decidable_eq α] {x : α} {l : list α} (h : x ∉ l) :
has_insert.insert x l = x :: l :=
if_neg h
lemma insert_pos [decidable_eq α] {x : α} {l : list α} (h : x ∈ l) :
has_insert.insert x l = l :=
if_pos h
lemma doubleton_eq [decidable_eq α] {x y : α} (h : x ≠ y) : ({x, y} : list α) = [x, y] :=
by { rw [insert_neg, singleton_eq], rwa [singleton_eq, mem_singleton] }
/-! ### bounded quantifiers over lists -/
theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x.
@[simp] theorem forall_mem_cons' {p : α → Prop} {a : α} {l : list α} :
(∀ (x : α), x = a ∨ x ∈ l → p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [or_imp_distrib, forall_and_distrib, forall_eq]
theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} :
(∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x :=
by simp only [mem_cons_iff, forall_mem_cons']
theorem forall_mem_of_forall_mem_cons {p : α → Prop} {a : α} {l : list α}
(h : ∀ x ∈ a :: l, p x) :
∀ x ∈ l, p x :=
(forall_mem_cons.1 h).2
theorem forall_mem_singleton {p : α → Prop} {a : α} : (∀ x ∈ [a], p x) ↔ p a :=
by simp only [mem_singleton, forall_eq]
theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_append, or_imp_distrib, forall_and_distrib]
theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x.
theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) :
∃ x ∈ a :: l, p x :=
bex.intro a (mem_cons_self _ _) h
theorem exists_mem_cons_of_exists {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ l, p x) :
∃ x ∈ a :: l, p x :=
bex.elim h (λ x xl px, bex.intro x (mem_cons_of_mem _ xl) px)
theorem or_exists_of_exists_mem_cons {p : α → Prop} {a : α} {l : list α} (h : ∃ x ∈ a :: l, p x) :
p a ∨ ∃ x ∈ l, p x :=
bex.elim h (λ x xal px,
or.elim (eq_or_mem_of_mem_cons xal)
(assume : x = a, begin rw ←this, left, exact px end)
(assume : x ∈ l, or.inr (bex.intro x this px)))
theorem exists_mem_cons_iff (p : α → Prop) (a : α) (l : list α) :
(∃ x ∈ a :: l, p x) ↔ p a ∨ ∃ x ∈ l, p x :=
iff.intro or_exists_of_exists_mem_cons
(assume h, or.elim h (exists_mem_cons_of l) exists_mem_cons_of_exists)
/-! ### list subset -/
theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl
theorem subset_append_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_left _ _
theorem subset_append_of_subset_right (l l₁ l₂ : list α) : l ⊆ l₂ → l ⊆ l₁++l₂ :=
λ s, subset.trans s $ subset_append_right _ _
@[simp] theorem cons_subset {a : α} {l m : list α} :
a::l ⊆ m ↔ a ∈ m ∧ l ⊆ m :=
by simp only [subset_def, mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq]
theorem cons_subset_of_subset_of_mem {a : α} {l m : list α}
(ainm : a ∈ m) (lsubm : l ⊆ m) : a::l ⊆ m :=
cons_subset.2 ⟨ainm, lsubm⟩
theorem append_subset_of_subset_of_subset {l₁ l₂ l : list α} (l₁subl : l₁ ⊆ l) (l₂subl : l₂ ⊆ l) :
l₁ ++ l₂ ⊆ l :=
λ a h, (mem_append.1 h).elim (@l₁subl _) (@l₂subl _)
@[simp] theorem append_subset_iff {l₁ l₂ l : list α} :
l₁ ++ l₂ ⊆ l ↔ l₁ ⊆ l ∧ l₂ ⊆ l :=
begin
split,
{ intro h, simp only [subset_def] at *, split; intros; simp* },
{ rintro ⟨h1, h2⟩, apply append_subset_of_subset_of_subset h1 h2 }
end
theorem eq_nil_of_subset_nil : ∀ {l : list α}, l ⊆ [] → l = []
| [] s := rfl
| (a::l) s := false.elim $ s $ mem_cons_self a l
theorem eq_nil_iff_forall_not_mem {l : list α} : l = [] ↔ ∀ a, a ∉ l :=
show l = [] ↔ l ⊆ [], from ⟨λ e, e ▸ subset.refl _, eq_nil_of_subset_nil⟩
theorem map_subset {l₁ l₂ : list α} (f : α → β) (H : l₁ ⊆ l₂) : map f l₁ ⊆ map f l₂ :=
λ x, by simp only [mem_map, not_and, exists_imp_distrib, and_imp]; exact λ a h e, ⟨a, H h, e⟩
theorem map_subset_iff {l₁ l₂ : list α} (f : α → β) (h : injective f) :
map f l₁ ⊆ map f l₂ ↔ l₁ ⊆ l₂ :=
begin
refine ⟨_, map_subset f⟩, intros h2 x hx,
rcases mem_map.1 (h2 (mem_map_of_mem f hx)) with ⟨x', hx', hxx'⟩,
cases h hxx', exact hx'
end
/-! ### append -/
lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ L₂ := rfl
@[simp] lemma singleton_append {x : α} {l : list α} : [x] ++ l = x :: l := rfl
theorem append_ne_nil_of_ne_nil_left (s t : list α) : s ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
theorem append_ne_nil_of_ne_nil_right (s t : list α) : t ≠ [] → s ++ t ≠ [] :=
by induction s; intros; contradiction
@[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] :=
by cases p; simp only [nil_append, cons_append, eq_self_iff_true, true_and, false_and]
@[simp] lemma nil_eq_append_iff {a b : list α} : [] = a ++ b ↔ a = [] ∧ b = [] :=
by rw [eq_comm, append_eq_nil]
lemma append_eq_cons_iff {a b c : list α} {x : α} :
a ++ b = x :: c ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by cases a; simp only [and_assoc, @eq_comm _ c, nil_append, cons_append, eq_self_iff_true,
true_and, false_and, exists_false, false_or, or_false, exists_and_distrib_left, exists_eq_left']
lemma cons_eq_append_iff {a b c : list α} {x : α} :
(x :: c : list α) = a ++ b ↔ (a = [] ∧ b = x :: c) ∨ (∃a', a = x :: a' ∧ c = a' ++ b) :=
by rw [eq_comm, append_eq_cons_iff]
lemma append_eq_append_iff {a b c d : list α} :
a ++ b = c ++ d ↔ (∃a', c = a ++ a' ∧ b = a' ++ d) ∨ (∃c', a = c ++ c' ∧ d = c' ++ b) :=
begin
induction a generalizing c,
case nil { rw nil_append, split,
{ rintro rfl, left, exact ⟨_, rfl, rfl⟩ },
{ rintro (⟨a', rfl, rfl⟩ | ⟨a', H, rfl⟩), {refl}, {rw [← append_assoc, ← H], refl} } },
case cons : a as ih {
cases c,
{ simp only [cons_append, nil_append, false_and, exists_false, false_or, exists_eq_left'],
exact eq_comm },
{ simp only [cons_append, @eq_comm _ a, ih, and_assoc, and_or_distrib_left,
exists_and_distrib_left] } }
end
@[simp] theorem split_at_eq_take_drop : ∀ (n : ℕ) (l : list α), split_at n l = (take n l, drop n l)
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := by simp only [split_at, split_at_eq_take_drop n xs, take, drop]
@[simp] theorem take_append_drop : ∀ (n : ℕ) (l : list α), take n l ++ drop n l = l
| 0 a := rfl
| (succ n) [] := rfl
| (succ n) (x :: xs) := congr_arg (cons x) $ take_append_drop n xs
-- TODO(Leo): cleanup proof after arith dec proc
theorem append_inj :
∀ {s₁ s₂ t₁ t₂ : list α}, s₁ ++ t₁ = s₂ ++ t₂ → length s₁ = length s₂ → s₁ = s₂ ∧ t₁ = t₂
| [] [] t₁ t₂ h hl := ⟨rfl, h⟩
| (a::s₁) [] t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl
| [] (b::s₂) t₁ t₂ h hl := list.no_confusion $ eq_nil_of_length_eq_zero hl.symm
| (a::s₁) (b::s₂) t₁ t₂ h hl := list.no_confusion h $ λab hap,
let ⟨e1, e2⟩ := @append_inj s₁ s₂ t₁ t₂ hap (succ.inj hl) in
by rw [ab, e1, e2]; exact ⟨rfl, rfl⟩
theorem append_inj_right {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : t₁ = t₂ :=
(append_inj h hl).right
theorem append_inj_left {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length s₁ = length s₂) : s₁ = s₂ :=
(append_inj h hl).left
theorem append_inj' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂) (hl : length t₁ = length t₂) :
s₁ = s₂ ∧ t₁ = t₂ :=
append_inj h $ @nat.add_right_cancel _ (length t₁) _ $
let hap := congr_arg length h in by simp only [length_append] at hap; rwa [← hl] at hap
theorem append_inj_right' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : t₁ = t₂ :=
(append_inj' h hl).right
theorem append_inj_left' {s₁ s₂ t₁ t₂ : list α} (h : s₁ ++ t₁ = s₂ ++ t₂)
(hl : length t₁ = length t₂) : s₁ = s₂ :=
(append_inj' h hl).left
theorem append_left_cancel {s t₁ t₂ : list α} (h : s ++ t₁ = s ++ t₂) : t₁ = t₂ :=
append_inj_right h rfl
theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ :=
append_inj_left' h rfl
theorem append_right_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ :=
⟨append_left_cancel, congr_arg _⟩
theorem append_left_inj {s₁ s₂ : list α} (t) : s₁ ++ t = s₂ ++ t ↔ s₁ = s₂ :=
⟨append_right_cancel, congr_arg _⟩
theorem map_eq_append_split {f : α → β} {l : list α} {s₁ s₂ : list β}
(h : map f l = s₁ ++ s₂) : ∃ l₁ l₂, l = l₁ ++ l₂ ∧ map f l₁ = s₁ ∧ map f l₂ = s₂ :=
begin
have := h, rw [← take_append_drop (length s₁) l] at this ⊢,
rw map_append at this,
refine ⟨_, _, rfl, append_inj this _⟩,
rw [length_map, length_take, min_eq_left],
rw [← length_map f l, h, length_append],
apply nat.le_add_right
end
/-! ### repeat -/
@[simp] theorem repeat_succ (a : α) (n) : repeat a (n + 1) = a :: repeat a n := rfl
theorem eq_of_mem_repeat {a b : α} : ∀ {n}, b ∈ repeat a n → b = a
| (n+1) h := or.elim h id $ @eq_of_mem_repeat _
theorem eq_repeat_of_mem {a : α} : ∀ {l : list α}, (∀ b ∈ l, b = a) → l = repeat a l.length
| [] H := rfl
| (b::l) H := by cases forall_mem_cons.1 H with H₁ H₂;
unfold length repeat; congr; [exact H₁, exact eq_repeat_of_mem H₂]
theorem eq_repeat' {a : α} {l : list α} : l = repeat a l.length ↔ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ λ b, eq_of_mem_repeat, eq_repeat_of_mem⟩
theorem eq_repeat {a : α} {n} {l : list α} : l = repeat a n ↔ length l = n ∧ ∀ b ∈ l, b = a :=
⟨λ h, h.symm ▸ ⟨length_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_add (a : α) (m n) : repeat a (m + n) = repeat a m ++ repeat a n :=
by induction m; simp only [*, zero_add, succ_add, repeat]; split; refl
theorem repeat_subset_singleton (a : α) (n) : repeat a n ⊆ [a] :=
λ b h, mem_singleton.2 (eq_of_mem_repeat h)
@[simp] theorem map_const (l : list α) (b : β) : map (function.const α b) l = repeat b l.length :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) :
b₁ = b₂ :=
by rw map_const at h; exact eq_of_mem_repeat h
@[simp] theorem map_repeat (f : α → β) (a : α) (n) : map f (repeat a n) = repeat (f a) n :=
by induction n; [refl, simp only [*, repeat, map]]; split; refl
@[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred :=
by cases n; refl
@[simp] theorem join_repeat_nil (n : ℕ) : join (repeat [] n) = @nil α :=
by induction n; [refl, simp only [*, repeat, join, append_nil]]
/-! ### pure -/
@[simp] theorem mem_pure {α} (x y : α) :
x ∈ (pure y : list α) ↔ x = y := by simp! [pure,list.ret]
/-! ### bind -/
@[simp] theorem bind_eq_bind {α β} (f : α → list β) (l : list α) :
l >>= f = l.bind f := rfl
@[simp] theorem bind_append (f : α → list β) (l₁ l₂ : list α) :
(l₁ ++ l₂).bind f = l₁.bind f ++ l₂.bind f :=
append_bind _ _ _
@[simp] theorem bind_singleton (f : α → list β) (x : α) : [x].bind f = f x :=
append_nil (f x)
/-! ### concat -/
theorem concat_nil (a : α) : concat [] a = [a] := rfl
theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl
@[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] :=
by induction l; simp only [*, concat]; split; refl
theorem init_eq_of_concat_eq {a : α} {l₁ l₂ : list α} : concat l₁ a = concat l₂ a → l₁ = l₂ :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact append_right_cancel h
end
theorem last_eq_of_concat_eq {a b : α} {l : list α} : concat l a = concat l b → a = b :=
begin
intro h,
rw [concat_eq_append, concat_eq_append] at h,
exact head_eq_of_cons_eq (append_left_cancel h)
end
theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] :=
by simp
theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ :=
by simp
theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) :=
by simp only [concat_eq_append, length_append, length]
theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a :=
by simp
/-! ### reverse -/
@[simp] theorem reverse_nil : reverse (@nil α) = [] := rfl
local attribute [simp] reverse_core
@[simp] theorem reverse_cons (a : α) (l : list α) : reverse (a::l) = reverse l ++ [a] :=
have aux : ∀ l₁ l₂, reverse_core l₁ l₂ ++ [a] = reverse_core l₁ (l₂ ++ [a]),
by intro l₁; induction l₁; intros; [refl, simp only [*, reverse_core, cons_append]],
(aux l nil).symm
theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ :=
by induction l₁ generalizing l₂; [refl, simp only [*, reverse_core, reverse_cons, append_assoc]];
refl
theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a :=
by simp only [reverse_cons, concat_eq_append]
@[simp] theorem reverse_singleton (a : α) : reverse [a] = [a] := rfl
@[simp] theorem reverse_append (s t : list α) : reverse (s ++ t) = (reverse t) ++ (reverse s) :=
by induction s; [rw [nil_append, reverse_nil, append_nil],
simp only [*, cons_append, reverse_cons, append_assoc]]
theorem reverse_concat (l : list α) (a : α) : reverse (concat l a) = a :: reverse l :=
by rw [concat_eq_append, reverse_append, reverse_singleton, singleton_append]
@[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l :=
by induction l; [refl, simp only [*, reverse_cons, reverse_append]]; refl
@[simp] theorem reverse_injective : injective (@reverse α) :=
left_inverse.injective reverse_reverse
@[simp] theorem reverse_inj {l₁ l₂ : list α} : reverse l₁ = reverse l₂ ↔ l₁ = l₂ :=
reverse_injective.eq_iff
@[simp] theorem reverse_eq_nil {l : list α} : reverse l = [] ↔ l = [] :=
@reverse_inj _ l []
theorem concat_eq_reverse_cons (a : α) (l : list α) : concat l a = reverse (a :: reverse l) :=
by simp only [concat_eq_append, reverse_cons, reverse_reverse]
@[simp] theorem length_reverse (l : list α) : length (reverse l) = length l :=
by induction l; [refl, simp only [*, reverse_cons, length_append, length]]
@[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) :=
by induction l; [refl, simp only [*, map, reverse_cons, map_append]]
theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) :
map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) :=
by simp only [reverse_core_eq, map_append, map_reverse]
@[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l :=
by induction l; [refl, simp only [*, reverse_cons, mem_append, mem_singleton, mem_cons_iff,
not_mem_nil, false_or, or_false, or_comm]]
@[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n :=
eq_repeat.2 ⟨by simp only [length_reverse, length_repeat],
λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩
/-! ### is_nil -/
lemma is_nil_iff_eq_nil {l : list α} : l.is_nil ↔ l = [] :=
list.cases_on l (by simp [is_nil]) (by simp [is_nil])
/-! ### init -/
@[simp] theorem length_init : ∀ (l : list α), length (init l) = length l - 1
| [] := rfl
| [a] := rfl
| (a :: b :: l) :=
begin
rw init,
simp only [add_left_inj, length, succ_add_sub_one],
exact length_init (b :: l)
end
/-! ### last -/
@[simp] theorem last_cons {a : α} {l : list α} :
∀ (h₁ : a :: l ≠ nil) (h₂ : l ≠ nil), last (a :: l) h₁ = last l h₂ :=
by {induction l; intros, contradiction, reflexivity}
@[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a :=
by induction l;
[refl, simp only [cons_append, last_cons _ (λ H, cons_ne_nil _ _ (append_eq_nil.1 H).2), *]]
theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a :=
by simp only [concat_eq_append, last_append]
@[simp] theorem last_singleton (a : α) (h : [a] ≠ []) : last [a] h = a := rfl
@[simp] theorem last_cons_cons (a₁ a₂ : α) (l : list α) (h : a₁::a₂::l ≠ []) :
last (a₁::a₂::l) h = last (a₂::l) (cons_ne_nil a₂ l) := rfl
theorem init_append_last : ∀ {l : list α} (h : l ≠ []), init l ++ [last l h] = l
| [] h := absurd rfl h
| [a] h := rfl
| (a::b::l) h :=
begin
rw [init, cons_append, last_cons (cons_ne_nil _ _) (cons_ne_nil _ _)],
congr,
exact init_append_last (cons_ne_nil b l)
end
theorem last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) :
last l₁ h₁ = last l₂ h₂ :=
by subst l₁
theorem last_mem : ∀ {l : list α} (h : l ≠ []), last l h ∈ l
| [] h := absurd rfl h
| [a] h := or.inl rfl
| (a::b::l) h := or.inr $ by { rw [last_cons_cons], exact last_mem (cons_ne_nil b l) }
lemma last_repeat_succ (a m : ℕ) :
(repeat a m.succ).last (ne_nil_of_length_eq_succ
(show (repeat a m.succ).length = m.succ, by rw length_repeat)) = a :=
begin
induction m with k IH,
{ simp },
{ simpa only [repeat_succ, last] }
end
/-! ### last' -/
@[simp] theorem last'_is_none :
∀ {l : list α}, (last' l).is_none ↔ l = []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_none (b::l)]
@[simp] theorem last'_is_some : ∀ {l : list α}, l.last'.is_some ↔ l ≠ []
| [] := by simp
| [a] := by simp
| (a::b::l) := by simp [@last'_is_some (b::l)]
theorem mem_last'_eq_last : ∀ {l : list α} {x : α}, x ∈ l.last' → ∃ h, x = last l h
| [] x hx := false.elim $ by simpa using hx
| [a] x hx := have a = x, by simpa using hx, this ▸ ⟨cons_ne_nil a [], rfl⟩
| (a::b::l) x hx :=
begin
rw last' at hx,
rcases mem_last'_eq_last hx with ⟨h₁, h₂⟩,
use cons_ne_nil _ _,
rwa [last_cons]
end
theorem mem_of_mem_last' {l : list α} {a : α} (ha : a ∈ l.last') : a ∈ l :=
let ⟨h₁, h₂⟩ := mem_last'_eq_last ha in h₂.symm ▸ last_mem _
theorem init_append_last' : ∀ {l : list α} (a ∈ l.last'), init l ++ [a] = l
| [] a ha := (option.not_mem_none a ha).elim
| [a] _ rfl := rfl
| (a :: b :: l) c hc := by { rw [last'] at hc, rw [init, cons_append, init_append_last' _ hc] }
theorem ilast_eq_last' [inhabited α] : ∀ l : list α, l.ilast = l.last'.iget
| [] := by simp [ilast, arbitrary]
| [a] := rfl
| [a, b] := rfl
| [a, b, c] := rfl
| (a :: b :: c :: l) := by simp [ilast, ilast_eq_last' (c :: l)]
@[simp] theorem last'_append_cons : ∀ (l₁ : list α) (a : α) (l₂ : list α),
last' (l₁ ++ a :: l₂) = last' (a :: l₂)
| [] a l₂ := rfl
| [b] a l₂ := rfl
| (b::c::l₁) a l₂ := by rw [cons_append, cons_append, last', ← cons_append, last'_append_cons]
theorem last'_append_of_ne_nil (l₁ : list α) : ∀ {l₂ : list α} (hl₂ : l₂ ≠ []),
last' (l₁ ++ l₂) = last' l₂
| [] hl₂ := by contradiction
| (b::l₂) _ := last'_append_cons l₁ b l₂
/-! ### head(') and tail -/
theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget :=
by cases l; refl
theorem mem_of_mem_head' {x : α} : ∀ {l : list α}, x ∈ l.head' → x ∈ l
| [] h := (option.not_mem_none _ h).elim
| (a::l) h := by { simp only [head', option.mem_def] at h, exact h ▸ or.inl rfl }
@[simp] theorem head_cons [inhabited α] (a : α) (l : list α) : head (a::l) = a := rfl
@[simp] theorem tail_nil : tail (@nil α) = [] := rfl
@[simp] theorem tail_cons (a : α) (l : list α) : tail (a::l) = l := rfl
@[simp] theorem head_append [inhabited α] (t : list α) {s : list α} (h : s ≠ []) :
head (s ++ t) = head s :=
by {induction s, contradiction, refl}
theorem tail_append_singleton_of_ne_nil {a : α} {l : list α} (h : l ≠ nil) :
tail (l ++ [a]) = tail l ++ [a] :=
by { induction l, contradiction, rw [tail,cons_append,tail], }
theorem cons_head'_tail : ∀ {l : list α} {a : α} (h : a ∈ head' l), a :: tail l = l
| [] a h := by contradiction
| (b::l) a h := by { simp at h, simp [h] }
theorem head_mem_head' [inhabited α] : ∀ {l : list α} (h : l ≠ []), head l ∈ head' l
| [] h := by contradiction
| (a::l) h := rfl
theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l :=
cons_head'_tail (head_mem_head' h)
@[simp] theorem head'_map (f : α → β) (l) : head' (map f l) = (head' l).map f := by cases l; refl
/-! ### Induction from the right -/
/-- Induction principle from the right for lists: if a property holds for the empty list, and
for `l ++ [a]` if it holds for `l`, then it holds for all lists. The principle is given for
a `Sort`-valued predicate, i.e., it can also be used to construct data. -/
@[elab_as_eliminator] def reverse_rec_on {C : list α → Sort*}
(l : list α) (H0 : C [])
(H1 : ∀ (l : list α) (a : α), C l → C (l ++ [a])) : C l :=
begin
rw ← reverse_reverse l,
induction reverse l,
{ exact H0 },
{ rw reverse_cons, exact H1 _ _ ih }
end
/-- Bidirectional induction principle for lists: if a property holds for the empty list, the
singleton list, and `a :: (l ++ [b])` from `l`, then it holds for all lists. This can be used to
prove statements about palindromes. The principle is given for a `Sort`-valued predicate, i.e., it
can also be used to construct data. -/
def bidirectional_rec {C : list α → Sort*}
(H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : ∀ l, C l
| [] := H0
| [a] := H1 a
| (a :: b :: l) :=
let l' := init (b :: l), b' := last (b :: l) (cons_ne_nil _ _) in
have length l' < length (a :: b :: l), by { change _ < length l + 2, simp },
begin
rw ←init_append_last (cons_ne_nil b l),
have : C l', from bidirectional_rec l',
exact Hn a l' b' ‹C l'›
end
using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf list.length⟩] }
/-- Like `bidirectional_rec`, but with the list parameter placed first. -/
@[elab_as_eliminator] def bidirectional_rec_on {C : list α → Sort*}
(l : list α) (H0 : C []) (H1 : ∀ (a : α), C [a])
(Hn : ∀ (a : α) (l : list α) (b : α), C l → C (a :: (l ++ [b]))) : C l :=
bidirectional_rec H0 H1 Hn l
/-! ### sublists -/
@[simp] theorem nil_sublist : Π (l : list α), [] <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons _ _ a (nil_sublist l)
@[refl, simp] theorem sublist.refl : Π (l : list α), l <+ l
| [] := sublist.slnil
| (a :: l) := sublist.cons2 _ _ a (sublist.refl l)
@[trans] theorem sublist.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ <+ l₂) (h₂ : l₂ <+ l₃) : l₁ <+ l₃ :=
sublist.rec_on h₂ (λ_ s, s)
(λl₂ l₃ a h₂ IH l₁ h₁, sublist.cons _ _ _ (IH l₁ h₁))
(λl₂ l₃ a h₂ IH l₁ h₁, @sublist.cases_on _ (λl₁ l₂', l₂' = a :: l₂ → l₁ <+ a :: l₃) _ _ h₁
(λ_, nil_sublist _)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons _ _ _ (IH _ h₁) end)
(λl₁ l₂' a' h₁' e, match a', l₂', e, h₁' with ._, ._, rfl, h₁ :=
sublist.cons2 _ _ _ (IH _ h₁) end) rfl)
l₁ h₁
@[simp] theorem sublist_cons (a : α) (l : list α) : l <+ a::l :=
sublist.cons _ _ _ (sublist.refl l)
theorem sublist_of_cons_sublist {a : α} {l₁ l₂ : list α} : a::l₁ <+ l₂ → l₁ <+ l₂ :=
sublist.trans (sublist_cons a l₁)
theorem cons_sublist_cons {l₁ l₂ : list α} (a : α) (s : l₁ <+ l₂) : a::l₁ <+ a::l₂ :=
sublist.cons2 _ _ _ s
@[simp] theorem sublist_append_left : Π (l₁ l₂ : list α), l₁ <+ l₁++l₂
| [] l₂ := nil_sublist _
| (a::l₁) l₂ := cons_sublist_cons _ (sublist_append_left l₁ l₂)
@[simp] theorem sublist_append_right : Π (l₁ l₂ : list α), l₂ <+ l₁++l₂
| [] l₂ := sublist.refl _
| (a::l₁) l₂ := sublist.cons _ _ _ (sublist_append_right l₁ l₂)
theorem sublist_cons_of_sublist (a : α) {l₁ l₂ : list α} : l₁ <+ l₂ → l₁ <+ a::l₂ :=
sublist.cons _ _ _
theorem sublist_append_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ :=
s.trans $ sublist_append_left _ _
theorem sublist_append_of_sublist_right {l l₁ l₂ : list α} (s : l <+ l₂) : l <+ l₁++l₂ :=
s.trans $ sublist_append_right _ _
theorem sublist_of_cons_sublist_cons {l₁ l₂ : list α} : ∀ {a : α}, a::l₁ <+ a::l₂ → l₁ <+ l₂
| ._ (sublist.cons ._ ._ a s) := sublist_of_cons_sublist s
| ._ (sublist.cons2 ._ ._ a s) := s
theorem cons_sublist_cons_iff {l₁ l₂ : list α} {a : α} : a::l₁ <+ a::l₂ ↔ l₁ <+ l₂ :=
⟨sublist_of_cons_sublist_cons, cons_sublist_cons _⟩
@[simp] theorem append_sublist_append_left {l₁ l₂ : list α} : ∀ l, l++l₁ <+ l++l₂ ↔ l₁ <+ l₂
| [] := iff.rfl
| (a::l) := cons_sublist_cons_iff.trans (append_sublist_append_left l)
theorem sublist.append_right {l₁ l₂ : list α} (h : l₁ <+ l₂) (l) : l₁++l <+ l₂++l :=
begin
induction h with _ _ a _ ih _ _ a _ ih,
{ refl },
{ apply sublist_cons_of_sublist a ih },
{ apply cons_sublist_cons a ih }
end
theorem sublist_or_mem_of_sublist {l l₁ l₂ : list α} {a : α} (h : l <+ l₁ ++ a::l₂) :
l <+ l₁ ++ l₂ ∨ a ∈ l :=
begin
induction l₁ with b l₁ IH generalizing l,
{ cases h, { left, exact ‹l <+ l₂› }, { right, apply mem_cons_self } },
{ cases h with _ _ _ h _ _ _ h,
{ exact or.imp_left (sublist_cons_of_sublist _) (IH h) },
{ exact (IH h).imp (cons_sublist_cons _) (mem_cons_of_mem _) } }
end
theorem sublist.reverse {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse :=
begin
induction h with _ _ _ _ ih _ _ a _ ih, {refl},
{ rw reverse_cons, exact sublist_append_of_sublist_left ih },
{ rw [reverse_cons, reverse_cons], exact ih.append_right [a] }
end
@[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ :=
⟨λ h, l₁.reverse_reverse ▸ l₂.reverse_reverse ▸ h.reverse, sublist.reverse⟩
@[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ :=
⟨λ h, by simpa only [reverse_append, append_sublist_append_left, reverse_sublist_iff]
using h.reverse,
λ h, h.append_right l⟩
theorem sublist.append {l₁ l₂ r₁ r₂ : list α}
(hl : l₁ <+ l₂) (hr : r₁ <+ r₂) : l₁ ++ r₁ <+ l₂ ++ r₂ :=
(hl.append_right _).trans ((append_sublist_append_left _).2 hr)
theorem sublist.subset : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂
| ._ ._ sublist.slnil b h := h
| ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (sublist.subset s h)
| ._ ._ (sublist.cons2 l₁ l₂ a s) b h :=
match eq_or_mem_of_mem_cons h with
| or.inl h := h ▸ mem_cons_self _ _
| or.inr h := mem_cons_of_mem _ (sublist.subset s h)
end
theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l :=
⟨λ h, h.subset (mem_singleton_self _), λ h,
let ⟨s, t, e⟩ := mem_split h in e.symm ▸
(cons_sublist_cons _ (nil_sublist _)).trans (sublist_append_right _ _)⟩
theorem eq_nil_of_sublist_nil {l : list α} (s : l <+ []) : l = [] :=
eq_nil_of_subset_nil $ s.subset
theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n :=
⟨λ h, by simpa only [length_repeat] using length_le_of_sublist h,
λ h, by induction h; [refl, simp only [*, repeat_succ, sublist.cons]] ⟩
theorem eq_of_sublist_of_length_eq : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ = length l₂ → l₁ = l₂
| ._ ._ sublist.slnil h := rfl
| ._ ._ (sublist.cons l₁ l₂ a s) h :=
absurd (length_le_of_sublist s) $ not_le_of_gt $ by rw h; apply lt_succ_self
| ._ ._ (sublist.cons2 l₁ l₂ a s) h :=
by rw [length, length] at h; injection h with h; rw eq_of_sublist_of_length_eq s h
theorem eq_of_sublist_of_length_le {l₁ l₂ : list α} (s : l₁ <+ l₂) (h : length l₂ ≤ length l₁) :
l₁ = l₂ :=
eq_of_sublist_of_length_eq s (le_antisymm (length_le_of_sublist s) h)
theorem sublist.antisymm {l₁ l₂ : list α} (s₁ : l₁ <+ l₂) (s₂ : l₂ <+ l₁) : l₁ = l₂ :=
eq_of_sublist_of_length_le s₁ (length_le_of_sublist s₂)
instance decidable_sublist [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+ l₂)
| [] l₂ := is_true $ nil_sublist _
| (a::l₁) [] := is_false $ λh, list.no_confusion $ eq_nil_of_sublist_nil h
| (a::l₁) (b::l₂) :=
if h : a = b then
decidable_of_decidable_of_iff (decidable_sublist l₁ l₂) $
by rw [← h]; exact ⟨cons_sublist_cons _, sublist_of_cons_sublist_cons⟩
else decidable_of_decidable_of_iff (decidable_sublist (a::l₁) l₂)
⟨sublist_cons_of_sublist _, λs, match a, l₁, s, h with
| a, l₁, sublist.cons ._ ._ ._ s', h := s'
| ._, ._, sublist.cons2 t ._ ._ s', h := absurd rfl h
end⟩
/-! ### index_of -/
section index_of
variable [decidable_eq α]
@[simp] theorem index_of_nil (a : α) : index_of a [] = 0 := rfl
theorem index_of_cons (a b : α) (l : list α) :
index_of a (b::l) = if a = b then 0 else succ (index_of a l) := rfl
theorem index_of_cons_eq {a b : α} (l : list α) : a = b → index_of a (b::l) = 0 :=
assume e, if_pos e
@[simp] theorem index_of_cons_self (a : α) (l : list α) : index_of a (a::l) = 0 :=
index_of_cons_eq _ rfl
@[simp, priority 990]
theorem index_of_cons_ne {a b : α} (l : list α) : a ≠ b → index_of a (b::l) = succ (index_of a l) :=
assume n, if_neg n
theorem index_of_eq_length {a : α} {l : list α} : index_of a l = length l ↔ a ∉ l :=
begin
induction l with b l ih,
{ exact iff_of_true rfl (not_mem_nil _) },
simp only [length, mem_cons_iff, index_of_cons], split_ifs,
{ exact iff_of_false (by rintro ⟨⟩) (λ H, H $ or.inl h) },
{ simp only [h, false_or], rw ← ih, exact succ_inj' }
end
@[simp, priority 980]
theorem index_of_of_not_mem {l : list α} {a : α} : a ∉ l → index_of a l = length l :=
index_of_eq_length.2
theorem index_of_le_length {a : α} {l : list α} : index_of a l ≤ length l :=
begin
induction l with b l ih, {refl},
simp only [length, index_of_cons],
by_cases h : a = b, {rw if_pos h, exact nat.zero_le _},
rw if_neg h, exact succ_le_succ ih
end
theorem index_of_lt_length {a} {l : list α} : index_of a l < length l ↔ a ∈ l :=
⟨λh, by_contradiction $ λ al, ne_of_lt h $ index_of_eq_length.2 al,
λal, lt_of_le_of_ne index_of_le_length $ λ h, index_of_eq_length.1 h al⟩
end index_of
/-! ### nth element -/
theorem nth_le_of_mem : ∀ {a} {l : list α}, a ∈ l → ∃ n h, nth_le l n h = a
| a (_ :: l) (or.inl rfl) := ⟨0, succ_pos _, rfl⟩
| a (b :: l) (or.inr m) :=
let ⟨n, h, e⟩ := nth_le_of_mem m in ⟨n+1, succ_lt_succ h, e⟩
theorem nth_le_nth : ∀ {l : list α} {n} h, nth l n = some (nth_le l n h)
| (a :: l) 0 h := rfl
| (a :: l) (n+1) h := @nth_le_nth l n _
theorem nth_len_le : ∀ {l : list α} {n}, length l ≤ n → nth l n = none
| [] n h := rfl
| (a :: l) (n+1) h := nth_len_le (le_of_succ_le_succ h)
theorem nth_eq_some {l : list α} {n a} : nth l n = some a ↔ ∃ h, nth_le l n h = a :=
⟨λ e,
have h : n < length l, from lt_of_not_ge $ λ hn,
by rw nth_len_le hn at e; contradiction,
⟨h, by rw nth_le_nth h at e;
injection e with e; apply nth_le_mem⟩,
λ ⟨h, e⟩, e ▸ nth_le_nth _⟩
@[simp]
theorem nth_eq_none_iff : ∀ {l : list α} {n}, nth l n = none ↔ length l ≤ n :=
begin
intros, split,
{ intro h, by_contradiction h',
have h₂ : ∃ h, l.nth_le n h = l.nth_le n (lt_of_not_ge h') := ⟨lt_of_not_ge h', rfl⟩,
rw [← nth_eq_some, h] at h₂, cases h₂ },
{ solve_by_elim [nth_len_le] },
end
theorem nth_of_mem {a} {l : list α} (h : a ∈ l) : ∃ n, nth l n = some a :=
let ⟨n, h, e⟩ := nth_le_of_mem h in ⟨n, by rw [nth_le_nth, e]⟩
theorem nth_le_mem : ∀ (l : list α) n h, nth_le l n h ∈ l
| (a :: l) 0 h := mem_cons_self _ _
| (a :: l) (n+1) h := mem_cons_of_mem _ (nth_le_mem l _ _)
theorem nth_mem {l : list α} {n a} (e : nth l n = some a) : a ∈ l :=
let ⟨h, e⟩ := nth_eq_some.1 e in e ▸ nth_le_mem _ _ _
theorem mem_iff_nth_le {a} {l : list α} : a ∈ l ↔ ∃ n h, nth_le l n h = a :=
⟨nth_le_of_mem, λ ⟨n, h, e⟩, e ▸ nth_le_mem _ _ _⟩
theorem mem_iff_nth {a} {l : list α} : a ∈ l ↔ ∃ n, nth l n = some a :=
mem_iff_nth_le.trans $ exists_congr $ λ n, nth_eq_some.symm
lemma nth_injective {α : Type u} {xs : list α} {i j : ℕ}
(h₀ : i < xs.length)
(h₁ : nodup xs)
(h₂ : xs.nth i = xs.nth j) : i = j :=
begin
induction xs with x xs generalizing i j,
{ cases h₀ },
{ cases i; cases j,
case nat.zero nat.zero
{ refl },
case nat.succ nat.succ
{ congr, cases h₁,
apply xs_ih;
solve_by_elim [lt_of_succ_lt_succ] },
iterate 2
{ dsimp at h₂,
cases h₁ with _ _ h h',
cases h x _ rfl,
rw mem_iff_nth,
exact ⟨_, h₂.symm⟩ <|>
exact ⟨_, h₂⟩ } },
end
@[simp] theorem nth_map (f : α → β) : ∀ l n, nth (map f l) n = (nth l n).map f
| [] n := rfl
| (a :: l) 0 := rfl
| (a :: l) (n+1) := nth_map l n
theorem nth_le_map (f : α → β) {l n} (H1 H2) : nth_le (map f l) n H1 = f (nth_le l n H2) :=
option.some.inj $ by rw [← nth_le_nth, nth_map, nth_le_nth]; refl
/-- A version of `nth_le_map` that can be used for rewriting. -/
theorem nth_le_map_rev (f : α → β) {l n} (H) :
f (nth_le l n H) = nth_le (map f l) n ((length_map f l).symm ▸ H) :=
(nth_le_map f _ _).symm
@[simp] theorem nth_le_map' (f : α → β) {l n} (H) :
nth_le (map f l) n H = f (nth_le l n (length_map f l ▸ H)) :=
nth_le_map f _ _
/-- If one has `nth_le L i hi` in a formula and `h : L = L'`, one can not `rw h` in the formula as
`hi` gives `i < L.length` and not `i < L'.length`. The lemma `nth_le_of_eq` can be used to make
such a rewrite, with `rw (nth_le_of_eq h)`. -/
lemma nth_le_of_eq {L L' : list α} (h : L = L') {i : ℕ} (hi : i < L.length) :
nth_le L i hi = nth_le L' i (h ▸ hi) :=
by { congr, exact h}
@[simp] lemma nth_le_singleton (a : α) {n : ℕ} (hn : n < 1) :
nth_le [a] n hn = a :=
have hn0 : n = 0 := le_zero_iff.1 (le_of_lt_succ hn),
by subst hn0; refl
lemma nth_le_zero [inhabited α] {L : list α} (h : 0 < L.length) :
L.nth_le 0 h = L.head :=
by { cases L, cases h, simp, }
lemma nth_le_append : ∀ {l₁ l₂ : list α} {n : ℕ} (hn₁) (hn₂),
(l₁ ++ l₂).nth_le n hn₁ = l₁.nth_le n hn₂
| [] _ n hn₁ hn₂ := (not_lt_zero _ hn₂).elim
| (a::l) _ 0 hn₁ hn₂ := rfl
| (a::l) _ (n+1) hn₁ hn₂ := by simp only [nth_le, cons_append];
exact nth_le_append _ _
lemma nth_le_append_right_aux {l₁ l₂ : list α} {n : ℕ}
(h₁ : l₁.length ≤ n) (h₂ : n < (l₁ ++ l₂).length) : n - l₁.length < l₂.length :=
begin
rw list.length_append at h₂,
convert (nat.sub_lt_sub_right_iff h₁).mpr h₂,
simp,
end
lemma nth_le_append_right : ∀ {l₁ l₂ : list α} {n : ℕ} (h₁ : l₁.length ≤ n) (h₂),
(l₁ ++ l₂).nth_le n h₂ = l₂.nth_le (n - l₁.length) (nth_le_append_right_aux h₁ h₂)
| [] _ n h₁ h₂ := rfl
| (a :: l) _ (n+1) h₁ h₂ :=
begin
dsimp,
conv { to_rhs, congr, skip, rw [←nat.sub_sub, nat.sub.right_comm, nat.add_sub_cancel], },
rw nth_le_append_right (nat.lt_succ_iff.mp h₁),
end
@[simp] lemma nth_le_repeat (a : α) {n m : ℕ} (h : m < (list.repeat a n).length) :
(list.repeat a n).nth_le m h = a :=
eq_of_mem_repeat (nth_le_mem _ _ _)
lemma nth_append {l₁ l₂ : list α} {n : ℕ} (hn : n < l₁.length) :
(l₁ ++ l₂).nth n = l₁.nth n :=
have hn' : n < (l₁ ++ l₂).length := lt_of_lt_of_le hn
(by rw length_append; exact le_add_right _ _),
by rw [nth_le_nth hn, nth_le_nth hn', nth_le_append]
lemma last_eq_nth_le : ∀ (l : list α) (h : l ≠ []),
last l h = l.nth_le (l.length - 1) (sub_lt (length_pos_of_ne_nil h) one_pos)
| [] h := rfl
| [a] h := by rw [last_singleton, nth_le_singleton]
| (a :: b :: l) h := by { rw [last_cons, last_eq_nth_le (b :: l)],
refl, exact cons_ne_nil b l }
@[simp] lemma nth_concat_length : ∀ (l : list α) (a : α), (l ++ [a]).nth l.length = some a
| [] a := rfl
| (b::l) a := by rw [cons_append, length_cons, nth, nth_concat_length]
@[ext]
theorem ext : ∀ {l₁ l₂ : list α}, (∀n, nth l₁ n = nth l₂ n) → l₁ = l₂
| [] [] h := rfl
| (a::l₁) [] h := by have h0 := h 0; contradiction
| [] (a'::l₂) h := by have h0 := h 0; contradiction
| (a::l₁) (a'::l₂) h := by have h0 : some a = some a' := h 0; injection h0 with aa;
simp only [aa, ext (λn, h (n+1))]; split; refl
theorem ext_le {l₁ l₂ : list α} (hl : length l₁ = length l₂)
(h : ∀n h₁ h₂, nth_le l₁ n h₁ = nth_le l₂ n h₂) : l₁ = l₂ :=
ext $ λn, if h₁ : n < length l₁
then by rw [nth_le_nth, nth_le_nth, h n h₁ (by rwa [← hl])]
else let h₁ := le_of_not_gt h₁ in by { rw [nth_len_le h₁, nth_len_le], rwa [←hl], }
@[simp] theorem index_of_nth_le [decidable_eq α] {a : α} :
∀ {l : list α} h, nth_le l (index_of a l) h = a
| (b::l) h := by by_cases h' : a = b;
simp only [h', if_pos, if_false, index_of_cons, nth_le, @index_of_nth_le l]
@[simp] theorem index_of_nth [decidable_eq α] {a : α} {l : list α} (h : a ∈ l) :
nth l (index_of a l) = some a :=
by rw [nth_le_nth, index_of_nth_le (index_of_lt_length.2 h)]
theorem nth_le_reverse_aux1 :
∀ (l r : list α) (i h1 h2), nth_le (reverse_core l r) (i + length l) h1 = nth_le r i h2
| [] r i := λh1 h2, rfl
| (a :: l) r i :=
by rw (show i + length (a :: l) = i + 1 + length l, from add_right_comm i (length l) 1);
exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2)
lemma index_of_inj [decidable_eq α] {l : list α} {x y : α}
(hx : x ∈ l) (hy : y ∈ l) : index_of x l = index_of y l ↔ x = y :=
⟨λ h, have nth_le l (index_of x l) (index_of_lt_length.2 hx) =
nth_le l (index_of y l) (index_of_lt_length.2 hy),
by simp only [h],
by simpa only [index_of_nth_le],
λ h, by subst h⟩
theorem nth_le_reverse_aux2 : ∀ (l r : list α) (i : nat) (h1) (h2),
nth_le (reverse_core l r) (length l - 1 - i) h1 = nth_le l i h2
| [] r i h1 h2 := absurd h2 (not_lt_zero _)
| (a :: l) r 0 h1 h2 := begin
have aux := nth_le_reverse_aux1 l (a :: r) 0,
rw zero_add at aux,
exact aux _ (zero_lt_succ _)
end
| (a :: l) r (i+1) h1 h2 := begin
have aux := nth_le_reverse_aux2 l (a :: r) i,
have heq := calc length (a :: l) - 1 - (i + 1)
= length l - (1 + i) : by rw add_comm; refl
... = length l - 1 - i : by rw nat.sub_sub,
rw [← heq] at aux,
apply aux
end
@[simp] theorem nth_le_reverse (l : list α) (i : nat) (h1 h2) :
nth_le (reverse l) (length l - 1 - i) h1 = nth_le l i h2 :=
nth_le_reverse_aux2 _ _ _ _ _
lemma eq_cons_of_length_one {l : list α} (h : l.length = 1) :
l = [l.nth_le 0 (h.symm ▸ zero_lt_one)] :=
begin
refine ext_le (by convert h) (λ n h₁ h₂, _),
simp only [nth_le_singleton],
congr,
exact eq_bot_iff.mpr (nat.lt_succ_iff.mp h₂)
end
lemma modify_nth_tail_modify_nth_tail {f g : list α → list α} (m : ℕ) :
∀n (l:list α), (l.modify_nth_tail f n).modify_nth_tail g (m + n) =
l.modify_nth_tail (λl, (f l).modify_nth_tail g m) n
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_modify_nth_tail n l)
lemma modify_nth_tail_modify_nth_tail_le
{f g : list α → list α} (m n : ℕ) (l : list α) (h : n ≤ m) :
(l.modify_nth_tail f n).modify_nth_tail g m =
l.modify_nth_tail (λl, (f l).modify_nth_tail g (m - n)) n :=
begin
rcases le_iff_exists_add.1 h with ⟨m, rfl⟩,
rw [nat.add_sub_cancel_left, add_comm, modify_nth_tail_modify_nth_tail]
end
lemma modify_nth_tail_modify_nth_tail_same {f g : list α → list α} (n : ℕ) (l:list α) :
(l.modify_nth_tail f n).modify_nth_tail g n = l.modify_nth_tail (g ∘ f) n :=
by rw [modify_nth_tail_modify_nth_tail_le n n l (le_refl n), nat.sub_self]; refl
lemma modify_nth_tail_id :
∀n (l:list α), l.modify_nth_tail id n = l
| 0 l := rfl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (list.cons a) (modify_nth_tail_id n l)
theorem remove_nth_eq_nth_tail : ∀ n (l : list α), remove_nth l n = modify_nth_tail tail n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (a::l) := congr_arg (cons _) (remove_nth_eq_nth_tail _ _)
theorem update_nth_eq_modify_nth (a : α) : ∀ n (l : list α),
update_nth l n a = modify_nth (λ _, a) n l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := congr_arg (cons _) (update_nth_eq_modify_nth _ _)
theorem modify_nth_eq_update_nth (f : α → α) : ∀ n (l : list α),
modify_nth f n l = ((λ a, update_nth l n (f a)) <$> nth l n).get_or_else l
| 0 l := by cases l; refl
| (n+1) [] := rfl
| (n+1) (b::l) := (congr_arg (cons b)
(modify_nth_eq_update_nth n l)).trans $ by cases nth l n; refl
theorem nth_modify_nth (f : α → α) : ∀ n (l : list α) m,
nth (modify_nth f n l) m = (λ a, if n = m then f a else a) <$> nth l m
| n l 0 := by cases l; cases n; refl
| n [] (m+1) := by cases n; refl
| 0 (a::l) (m+1) := by cases nth l m; refl
| (n+1) (a::l) (m+1) := (nth_modify_nth n l m).trans $
by cases nth l m with b; by_cases n = m;
simp only [h, if_pos, if_true, if_false, option.map_none, option.map_some, mt succ.inj,
not_false_iff]
theorem modify_nth_tail_length (f : list α → list α) (H : ∀ l, length (f l) = length l) :
∀ n l, length (modify_nth_tail f n l) = length l
| 0 l := H _
| (n+1) [] := rfl
| (n+1) (a::l) := @congr_arg _ _ _ _ (+1) (modify_nth_tail_length _ _)
@[simp] theorem modify_nth_length (f : α → α) :
∀ n l, length (modify_nth f n l) = length l :=
modify_nth_tail_length _ (λ l, by cases l; refl)
@[simp] theorem update_nth_length (l : list α) (n) (a : α) :
length (update_nth l n a) = length l :=
by simp only [update_nth_eq_modify_nth, modify_nth_length]
@[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) :
nth (modify_nth f n l) n = f <$> nth l n :=
by simp only [nth_modify_nth, if_pos]
@[simp] theorem nth_modify_nth_ne (f : α → α) {m n} (l : list α) (h : m ≠ n) :
nth (modify_nth f m l) n = nth l n :=
by simp only [nth_modify_nth, if_neg h, id_map']
theorem nth_update_nth_eq (a : α) (n) (l : list α) :
nth (update_nth l n a) n = (λ _, a) <$> nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_eq]
theorem nth_update_nth_of_lt (a : α) {n} {l : list α} (h : n < length l) :
nth (update_nth l n a) n = some a :=
by rw [nth_update_nth_eq, nth_le_nth h]; refl
theorem nth_update_nth_ne (a : α) {m n} (l : list α) (h : m ≠ n) :
nth (update_nth l m a) n = nth l n :=
by simp only [update_nth_eq_modify_nth, nth_modify_nth_ne _ _ h]
@[simp] lemma nth_le_update_nth_eq (l : list α) (i : ℕ) (a : α)
(h : i < (l.update_nth i a).length) : (l.update_nth i a).nth_le i h = a :=
by rw [← option.some_inj, ← nth_le_nth, nth_update_nth_eq, nth_le_nth]; simp * at *
@[simp] lemma nth_le_update_nth_of_ne {l : list α} {i j : ℕ} (h : i ≠ j) (a : α)
(hj : j < (l.update_nth i a).length) :
(l.update_nth i a).nth_le j hj = l.nth_le j (by simpa using hj) :=
by rw [← option.some_inj, ← list.nth_le_nth, list.nth_update_nth_ne _ _ h, list.nth_le_nth]
lemma mem_or_eq_of_mem_update_nth : ∀ {l : list α} {n : ℕ} {a b : α}
(h : a ∈ l.update_nth n b), a ∈ l ∨ a = b
| [] n a b h := false.elim h
| (c::l) 0 a b h := ((mem_cons_iff _ _ _).1 h).elim
or.inr (or.inl ∘ mem_cons_of_mem _)
| (c::l) (n+1) a b h := ((mem_cons_iff _ _ _).1 h).elim
(λ h, h ▸ or.inl (mem_cons_self _ _))
(λ h, (mem_or_eq_of_mem_update_nth h).elim
(or.inl ∘ mem_cons_of_mem _) or.inr)
section insert_nth
variable {a : α}
@[simp] lemma insert_nth_nil (a : α) : insert_nth 0 a [] = [a] := rfl
lemma length_insert_nth : ∀n as, n ≤ length as → length (insert_nth n a as) = length as + 1
| 0 as h := rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := congr_arg nat.succ $ length_insert_nth n as (nat.le_of_succ_le_succ h)
lemma remove_nth_insert_nth (n:ℕ) (l : list α) : (l.insert_nth n a).remove_nth n = l :=
by rw [remove_nth_eq_nth_tail, insert_nth, modify_nth_tail_modify_nth_tail_same];
from modify_nth_tail_id _ _
lemma insert_nth_remove_nth_of_ge : ∀n m as, n < length as → n ≤ m →
insert_nth m a (as.remove_nth n) = (as.insert_nth (m + 1) a).remove_nth n
| 0 0 [] has _ := (lt_irrefl _ has).elim
| 0 0 (a::as) has hmn := by simp [remove_nth, insert_nth]
| 0 (m+1) (a::as) has hmn := rfl
| (n+1) (m+1) (a::as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_ge n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_remove_nth_of_le : ∀n m as, n < length as → m ≤ n →
insert_nth m a (as.remove_nth n) = (as.insert_nth m a).remove_nth (n + 1)
| n 0 (a :: as) has hmn := rfl
| (n + 1) (m + 1) (a :: as) has hmn :=
congr_arg (cons a) $
insert_nth_remove_nth_of_le n m as (nat.lt_of_succ_lt_succ has) (nat.le_of_succ_le_succ hmn)
lemma insert_nth_comm (a b : α) :
∀(i j : ℕ) (l : list α) (h : i ≤ j) (hj : j ≤ length l),
(l.insert_nth i a).insert_nth (j + 1) b = (l.insert_nth j b).insert_nth i a
| 0 j l := by simp [insert_nth]
| (i + 1) 0 l := assume h, (nat.not_lt_zero _ h).elim
| (i + 1) (j+1) [] := by simp
| (i + 1) (j+1) (c::l) :=
assume h₀ h₁,
by simp [insert_nth];
exact insert_nth_comm i j l (nat.le_of_succ_le_succ h₀) (nat.le_of_succ_le_succ h₁)
lemma mem_insert_nth {a b : α} : ∀ {n : ℕ} {l : list α} (hi : n ≤ l.length),
a ∈ l.insert_nth n b ↔ a = b ∨ a ∈ l
| 0 as h := iff.rfl
| (n+1) [] h := (nat.not_succ_le_zero _ h).elim
| (n+1) (a'::as) h := begin
dsimp [list.insert_nth],
erw [list.mem_cons_iff, mem_insert_nth (nat.le_of_succ_le_succ h), list.mem_cons_iff,
← or.assoc, or_comm (a = a'), or.assoc]
end
end insert_nth
/-! ### map -/
@[simp] lemma map_nil (f : α → β) : map f [] = [] := rfl
theorem map_eq_foldr (f : α → β) (l : list α) :
map f l = foldr (λ a bs, f a :: bs) [] l :=
by induction l; simp *
lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l
| [] _ := rfl
| (a::l) h := let ⟨h₁, h₂⟩ := forall_mem_cons.1 h in
by rw [map, map, h₁, map_congr h₂]
lemma map_eq_map_iff {f g : α → β} {l : list α} : map f l = map g l ↔ (∀ x ∈ l, f x = g x) :=
begin
refine ⟨_, map_congr⟩, intros h x hx,
rw [mem_iff_nth_le] at hx, rcases hx with ⟨n, hn, rfl⟩,
rw [nth_le_map_rev f, nth_le_map_rev g], congr, exact h
end
theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) :=
by induction l; [refl, simp only [*, concat_eq_append, cons_append, map, map_append]]; split; refl
theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l :=
by induction l; [refl, simp only [*, map]]; split; refl
theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil :=
eq_nil_of_length_eq_zero $ by rw [← length_map f l, h]; refl
@[simp] theorem map_join (f : α → β) (L : list (list α)) :
map f (join L) = join (map (map f) L) :=
by induction L; [refl, simp only [*, join, map, map_append]]
theorem bind_ret_eq_map (f : α → β) (l : list α) :
l.bind (list.ret ∘ f) = map f l :=
by unfold list.bind; induction l; simp only [map, join, list.ret, cons_append, nil_append, *];
split; refl
@[simp] theorem map_eq_map {α β} (f : α → β) (l : list α) : f <$> l = map f l := rfl
@[simp] theorem map_tail (f : α → β) (l) : map f (tail l) = tail (map f l) :=
by cases l; refl
@[simp] theorem map_injective_iff {f : α → β} : injective (map f) ↔ injective f :=
begin
split; intros h x y hxy,
{ suffices : [x] = [y], { simpa using this }, apply h, simp [hxy] },
{ induction y generalizing x, simpa using hxy,
cases x, simpa using hxy, simp at hxy, simp [y_ih hxy.2, h hxy.1] }
end
theorem map_filter_eq_foldr (f : α → β) (p : α → Prop) [decidable_pred p] (as : list α) :
map f (filter p as) = foldr (λ a bs, if p a then f a :: bs else bs) [] as :=
by { induction as, { refl }, { simp! [*, apply_ite (map f)] } }
/-! ### map₂ -/
theorem nil_map₂ (f : α → β → γ) (l : list β) : map₂ f [] l = [] :=
by cases l; refl
theorem map₂_nil (f : α → β → γ) (l : list α) : map₂ f l [] = [] :=
by cases l; refl
/-! ### take, drop -/
@[simp] theorem take_zero (l : list α) : take 0 l = [] := rfl
@[simp] theorem take_nil : ∀ n, take n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
theorem take_cons (n) (a : α) (l : list α) : take (succ n) (a::l) = a :: take n l := rfl
@[simp] theorem take_length : ∀ (l : list α), take (length l) l = l
| [] := rfl
| (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_length end
theorem take_all_of_le : ∀ {n} {l : list α}, length l ≤ n → take n l = l
| 0 [] h := rfl
| 0 (a::l) h := absurd h (not_le_of_gt (zero_lt_succ _))
| (n+1) [] h := rfl
| (n+1) (a::l) h :=
begin
change a :: take n l = a :: l,
rw [take_all_of_le (le_of_succ_le_succ h)]
end
@[simp] theorem take_left : ∀ l₁ l₂ : list α, take (length l₁) (l₁ ++ l₂) = l₁
| [] l₂ := rfl
| (a::l₁) l₂ := congr_arg (cons a) (take_left l₁ l₂)
theorem take_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take_left
theorem take_take : ∀ (n m) (l : list α), take n (take m l) = take (min n m) l
| n 0 l := by rw [min_zero, take_zero, take_nil]
| 0 m l := by rw [zero_min, take_zero, take_zero]
| (succ n) (succ m) nil := by simp only [take_nil]
| (succ n) (succ m) (a::l) := by simp only [take, min_succ_succ, take_take n m l]; split; refl
theorem take_repeat (a : α) : ∀ (n m : ℕ), take n (repeat a m) = repeat a (min n m)
| n 0 := by simp
| 0 m := by simp
| (succ n) (succ m) := by simp [min_succ_succ, take_repeat]
lemma map_take {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.take i).map f = (L.map f).take i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_take], }
lemma take_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ},
n ≤ l₁.length → (l₁ ++ l₂).take n = l₁.take n
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [list.take, list.cons_append, list.take, take_append_of_le_length (le_of_succ_le_succ hn)]
/-- Taking the first `l₁.length + i` elements in `l₁ ++ l₂` is the same as appending the first
`i` elements of `l₂` to `l₁`. -/
lemma take_append {l₁ l₂ : list α} (i : ℕ) :
take (l₁.length + i) (l₁ ++ l₂) = l₁ ++ (take i l₂) :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, take_cons, l₁_ih, eq_self_iff_true, and_self]
end
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_take (L : list α) {i j : ℕ} (hi : i < L.length) (hj : i < j) :
nth_le L i hi = nth_le (L.take j) i (by { rw length_take, exact lt_min hj hi }) :=
by { rw nth_le_of_eq (take_append_drop j L).symm hi, exact nth_le_append _ _ }
/-- The `i`-th element of a list coincides with the `i`-th element of any of its prefixes of
length `> i`. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_take' (L : list α) {i j : ℕ} (hi : i < (L.take j).length) :
nth_le (L.take j) i hi = nth_le L i (lt_of_lt_of_le hi (by simp [le_refl])) :=
by { simp at hi, rw nth_le_take L _ hi.1 }
@[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α)
| 0 := rfl
| (n+1) := rfl
lemma mem_of_mem_drop {α} {n : ℕ} {l : list α} {x : α}
(h : x ∈ l.drop n) :
x ∈ l :=
begin
induction l generalizing n,
case list.nil : n h
{ simpa using h },
case list.cons : l_hd l_tl l_ih n h
{ cases n; simp only [mem_cons_iff, drop] at h ⊢,
{ exact h },
right, apply l_ih h },
end
@[simp] theorem drop_one : ∀ l : list α, drop 1 l = tail l
| [] := rfl
| (a :: l) := rfl
theorem drop_add : ∀ m n (l : list α), drop (m + n) l = drop m (drop n l)
| m 0 l := rfl
| m (n+1) [] := (drop_nil _).symm
| m (n+1) (a::l) := drop_add m n _
@[simp] theorem drop_left : ∀ l₁ l₂ : list α, drop (length l₁) (l₁ ++ l₂) = l₂
| [] l₂ := rfl
| (a::l₁) l₂ := drop_left l₁ l₂
theorem drop_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
drop n (l₁ ++ l₂) = l₂ :=
by rw ← h; apply drop_left
theorem drop_eq_nth_le_cons : ∀ {n} {l : list α} h,
drop n l = nth_le l n h :: drop (n+1) l
| 0 (a::l) h := rfl
| (n+1) (a::l) h := @drop_eq_nth_le_cons n _ _
@[simp] lemma drop_length (l : list α) : l.drop l.length = [] :=
calc l.drop l.length = (l ++ []).drop l.length : by simp
... = [] : drop_left _ _
lemma drop_append_of_le_length : ∀ {l₁ l₂ : list α} {n : ℕ}, n ≤ l₁.length →
(l₁ ++ l₂).drop n = l₁.drop n ++ l₂
| l₁ l₂ 0 hn := by simp
| [] l₂ (n+1) hn := absurd hn dec_trivial
| (a::l₁) l₂ (n+1) hn :=
by rw [drop, cons_append, drop, drop_append_of_le_length (le_of_succ_le_succ hn)]
/-- Dropping the elements up to `l₁.length + i` in `l₁ + l₂` is the same as dropping the elements
up to `i` in `l₂`. -/
lemma drop_append {l₁ l₂ : list α} (i : ℕ) :
drop (l₁.length + i) (l₁ ++ l₂) = drop i l₂ :=
begin
induction l₁, { simp },
have : length l₁_tl + 1 + i = (length l₁_tl + i).succ,
by { rw nat.succ_eq_add_one, exact succ_add _ _ },
simp only [cons_append, length, this, drop, l₁_ih]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the big list to the small list. -/
lemma nth_le_drop (L : list α) {i j : ℕ} (h : i + j < L.length) :
nth_le L (i + j) h = nth_le (L.drop i) j
begin
have A : i < L.length := lt_of_le_of_lt (nat.le.intro rfl) h,
rw (take_append_drop i L).symm at h,
simpa only [le_of_lt A, min_eq_left, add_lt_add_iff_left, length_take, length_append] using h
end :=
begin
have A : length (take i L) = i, by simp [le_of_lt (lt_of_le_of_lt (nat.le.intro rfl) h)],
rw [nth_le_of_eq (take_append_drop i L).symm h, nth_le_append_right];
simp [A]
end
/-- The `i + j`-th element of a list coincides with the `j`-th element of the list obtained by
dropping the first `i` elements. Version designed to rewrite from the small list to the big list. -/
lemma nth_le_drop' (L : list α) {i j : ℕ} (h : j < (L.drop i).length) :
nth_le (L.drop i) j h = nth_le L (i + j) (nat.add_lt_of_lt_sub_left ((length_drop i L) ▸ h)) :=
by rw nth_le_drop
@[simp] theorem drop_drop (n : ℕ) : ∀ (m) (l : list α), drop n (drop m l) = drop (n + m) l
| m [] := by simp
| 0 l := by simp
| (m+1) (a::l) :=
calc drop n (drop (m + 1) (a :: l)) = drop n (drop m l) : rfl
... = drop (n + m) l : drop_drop m l
... = drop (n + (m + 1)) (a :: l) : rfl
theorem drop_take : ∀ (m : ℕ) (n : ℕ) (l : list α),
drop m (take (m + n) l) = take n (drop m l)
| 0 n _ := by simp
| (m+1) n nil := by simp
| (m+1) n (_::l) :=
have h: m + 1 + n = (m+n) + 1, by ac_refl,
by simpa [take_cons, h] using drop_take m n l
lemma map_drop {α β : Type*} (f : α → β) :
∀ (L : list α) (i : ℕ), (L.drop i).map f = (L.map f).drop i
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [map_drop], }
theorem modify_nth_tail_eq_take_drop (f : list α → list α) (H : f [] = []) :
∀ n l, modify_nth_tail f n l = take n l ++ f (drop n l)
| 0 l := rfl
| (n+1) [] := H.symm
| (n+1) (b::l) := congr_arg (cons b) (modify_nth_tail_eq_take_drop n l)
theorem modify_nth_eq_take_drop (f : α → α) :
∀ n l, modify_nth f n l = take n l ++ modify_head f (drop n l) :=
modify_nth_tail_eq_take_drop _ rfl
theorem modify_nth_eq_take_cons_drop (f : α → α) {n l} (h) :
modify_nth f n l = take n l ++ f (nth_le l n h) :: drop (n+1) l :=
by rw [modify_nth_eq_take_drop, drop_eq_nth_le_cons h]; refl
theorem update_nth_eq_take_cons_drop (a : α) {n l} (h : n < length l) :
update_nth l n a = take n l ++ a :: drop (n+1) l :=
by rw [update_nth_eq_modify_nth, modify_nth_eq_take_cons_drop _ h]
lemma reverse_take {α} {xs : list α} (n : ℕ)
(h : n ≤ xs.length) :
xs.reverse.take n = (xs.drop (xs.length - n)).reverse :=
begin
induction xs generalizing n; simp only [reverse_cons, drop, reverse_nil, nat.zero_sub, length, take_nil],
cases decidable.lt_or_eq_of_le h with h' h',
{ replace h' := le_of_succ_le_succ h',
rwa [take_append_of_le_length, xs_ih _ h'],
rw [show xs_tl.length + 1 - n = succ (xs_tl.length - n), from _, drop],
{ rwa [succ_eq_add_one, nat.sub_add_comm] },
{ rwa length_reverse } },
{ subst h', rw [length, nat.sub_self, drop],
rw [show xs_tl.length + 1 = (xs_tl.reverse ++ [xs_hd]).length, from _, take_length, reverse_cons],
rw [length_append, length_reverse], refl }
end
@[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] :=
by cases l; cases n; simp only [update_nth]
section take'
variable [inhabited α]
@[simp] theorem take'_length : ∀ n l, length (@take' α _ n l) = n
| 0 l := rfl
| (n+1) l := congr_arg succ (take'_length _ _)
@[simp] theorem take'_nil : ∀ n, take' n (@nil α) = repeat (default _) n
| 0 := rfl
| (n+1) := congr_arg (cons _) (take'_nil _)
theorem take'_eq_take : ∀ {n} {l : list α},
n ≤ length l → take' n l = take n l
| 0 l h := rfl
| (n+1) (a::l) h := congr_arg (cons _) $
take'_eq_take $ le_of_succ_le_succ h
@[simp] theorem take'_left (l₁ l₂ : list α) : take' (length l₁) (l₁ ++ l₂) = l₁ :=
(take'_eq_take (by simp only [length_append, nat.le_add_right])).trans (take_left _ _)
theorem take'_left' {l₁ l₂ : list α} {n} (h : length l₁ = n) :
take' n (l₁ ++ l₂) = l₁ :=
by rw ← h; apply take'_left
end take'
/-! ### foldl, foldr -/
lemma foldl_ext (f g : α → β → α) (a : α)
{l : list β} (H : ∀ a : α, ∀ b ∈ l, f a b = g a b) :
foldl f a l = foldl g a l :=
begin
induction l with hd tl ih generalizing a, {refl},
unfold foldl,
rw [ih (λ a b bin, H a b $ mem_cons_of_mem _ bin), H a hd (mem_cons_self _ _)]
end
lemma foldr_ext (f g : α → β → β) (b : β)
{l : list α} (H : ∀ a ∈ l, ∀ b : β, f a b = g a b) :
foldr f b l = foldr g b l :=
begin
induction l with hd tl ih, {refl},
simp only [mem_cons_iff, or_imp_distrib, forall_and_distrib, forall_eq] at H,
simp only [foldr, ih H.2, H.1]
end
@[simp] theorem foldl_nil (f : α → β → α) (a : α) : foldl f a [] = a := rfl
@[simp] theorem foldl_cons (f : α → β → α) (a : α) (b : β) (l : list β) :
foldl f a (b::l) = foldl f (f a b) l := rfl
@[simp] theorem foldr_nil (f : α → β → β) (b : β) : foldr f b [] = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
foldr f b (a::l) = f a (foldr f b l) := rfl
@[simp] theorem foldl_append (f : α → β → α) :
∀ (a : α) (l₁ l₂ : list β), foldl f a (l₁++l₂) = foldl f (foldl f a l₁) l₂
| a [] l₂ := rfl
| a (b::l₁) l₂ := by simp only [cons_append, foldl_cons, foldl_append (f a b) l₁ l₂]
@[simp] theorem foldr_append (f : α → β → β) :
∀ (b : β) (l₁ l₂ : list α), foldr f b (l₁++l₂) = foldr f (foldr f b l₂) l₁
| b [] l₂ := rfl
| b (a::l₁) l₂ := by simp only [cons_append, foldr_cons, foldr_append b l₁ l₂]
@[simp] theorem foldl_join (f : α → β → α) :
∀ (a : α) (L : list (list β)), foldl f a (join L) = foldl (foldl f) a L
| a [] := rfl
| a (l::L) := by simp only [join, foldl_append, foldl_cons, foldl_join (foldl f a l) L]
@[simp] theorem foldr_join (f : α → β → β) :
∀ (b : β) (L : list (list α)), foldr f b (join L) = foldr (λ l b, foldr f b l) b L
| a [] := rfl
| a (l::L) := by simp only [join, foldr_append, foldr_join a L, foldr_cons]
theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) :
foldl f a (reverse l) = foldr (λx y, f y x) a l :=
by induction l; [refl, simp only [*, reverse_cons, foldl_append, foldl_cons, foldl_nil, foldr]]
theorem foldr_reverse (f : α → β → β) (a : β) (l : list α) :
foldr f a (reverse l) = foldl (λx y, f y x) a l :=
let t := foldl_reverse (λx y, f y x) a (reverse l) in
by rw reverse_reverse l at t; rwa t
@[simp] theorem foldr_eta : ∀ (l : list α), foldr cons [] l = l
| [] := rfl
| (x::l) := by simp only [foldr_cons, foldr_eta l]; split; refl
@[simp] theorem reverse_foldl {l : list α} : reverse (foldl (λ t h, h :: t) [] l) = l :=
by rw ←foldr_reverse; simp
@[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : list β) :
foldl f a (map g l) = foldl (λx y, f x (g y)) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldl]]
@[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : list β) :
foldr f a (map g l) = foldr (f ∘ g) a l :=
by revert a; induction l; intros; [refl, simp only [*, map, foldr]]
theorem foldl_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldl f' (g a) (l.map g) = g (list.foldl f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldr_map' {α β: Type u} (g : α → β) (f : α → α → α) (f' : β → β → β)
(a : α) (l : list α) (h : ∀ x y, f' (g x) (g y) = g (f x y)) :
list.foldr f' (g a) (l.map g) = g (list.foldr f a l) :=
begin
induction l generalizing a,
{ simp }, { simp [l_ih, h] }
end
theorem foldl_hom (l : list γ) (f : α → β) (op : α → γ → α) (op' : β → γ → β) (a : α)
(h : ∀a x, f (op a x) = op' (f a) x) : foldl op' (f a) l = f (foldl op a l) :=
eq.symm $ by { revert a, induction l; intros; [refl, simp only [*, foldl]] }
theorem foldr_hom (l : list γ) (f : α → β) (op : γ → α → α) (op' : γ → β → β) (a : α)
(h : ∀x a, f (op x a) = op' x (f a)) : foldr op' (f a) l = f (foldr op a l) :=
by { revert a, induction l; intros; [refl, simp only [*, foldr]] }
lemma injective_foldl_comp {α : Type*} {l : list (α → α)} {f : α → α}
(hl : ∀ f ∈ l, function.injective f) (hf : function.injective f):
function.injective (@list.foldl (α → α) (α → α) function.comp f l) :=
begin
induction l generalizing f,
{ exact hf },
{ apply l_ih (λ _ h, hl _ (list.mem_cons_of_mem _ h)),
apply function.injective.comp hf,
apply hl _ (list.mem_cons_self _ _) }
end
/- scanl -/
lemma length_scanl {β : Type*} {f : α → β → α} :
∀ a l, length (scanl f a l) = l.length + 1
| a [] := rfl
| a (x :: l) := by erw [length_cons, length_cons, length_scanl]
/- scanr -/
@[simp] theorem scanr_nil (f : α → β → β) (b : β) : scanr f b [] = [b] := rfl
@[simp] theorem scanr_aux_cons (f : α → β → β) (b : β) : ∀ (a : α) (l : list α),
scanr_aux f b (a::l) = (foldr f b (a::l), scanr f b l)
| a [] := rfl
| a (x::l) := let t := scanr_aux_cons x l in
by simp only [scanr, scanr_aux, t, foldr_cons]
@[simp] theorem scanr_cons (f : α → β → β) (b : β) (a : α) (l : list α) :
scanr f b (a::l) = foldr f b (a::l) :: scanr f b l :=
by simp only [scanr, scanr_aux_cons, foldr_cons]; split; refl
section foldl_eq_foldr
-- foldl and foldr coincide when f is commutative and associative
variables {f : α → α → α} (hcomm : commutative f) (hassoc : associative f)
include hassoc
theorem foldl1_eq_foldr1 : ∀ a b l, foldl f a (l++[b]) = foldr f b (a::l)
| a b nil := rfl
| a b (c :: l) :=
by simp only [cons_append, foldl_cons, foldr_cons, foldl1_eq_foldr1 _ _ l]; rw hassoc
include hcomm
theorem foldl_eq_of_comm_of_assoc : ∀ a b l, foldl f a (b::l) = f b (foldl f a l)
| a b nil := hcomm a b
| a b (c::l) := by simp only [foldl_cons];
rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; refl
theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l
| a nil := rfl
| a (b :: l) :=
by simp only [foldr_cons, foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l)
end foldl_eq_foldr
section foldl_eq_foldlr'
variables {f : α → β → α}
variables hf : ∀ a b c, f (f a b) c = f (f a c) b
include hf
theorem foldl_eq_of_comm' : ∀ a b l, foldl f a (b::l) = f (foldl f a l) b
| a b [] := rfl
| a b (c :: l) := by rw [foldl,foldl,foldl,← foldl_eq_of_comm',foldl,hf]
theorem foldl_eq_foldr' : ∀ a l, foldl f a l = foldr (flip f) a l
| a [] := rfl
| a (b :: l) := by rw [foldl_eq_of_comm' hf,foldr,foldl_eq_foldr']; refl
end foldl_eq_foldlr'
section foldl_eq_foldlr'
variables {f : α → β → β}
variables hf : ∀ a b c, f a (f b c) = f b (f a c)
include hf
theorem foldr_eq_of_comm' : ∀ a b l, foldr f a (b::l) = foldr f (f b a) l
| a b [] := rfl
| a b (c :: l) := by rw [foldr,foldr,foldr,hf,← foldr_eq_of_comm']; refl
end foldl_eq_foldlr'
section
variables {op : α → α → α} [ha : is_associative α op] [hc : is_commutative α op]
local notation a * b := op a b
local notation l <*> a := foldl op a l
include ha
lemma foldl_assoc : ∀ {l : list α} {a₁ a₂}, l <*> (a₁ * a₂) = a₁ * (l <*> a₂)
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ :=
calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp only [foldl_cons, ha.assoc]
... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc, foldl_cons]
lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂
| [] a₁ a₂ := rfl
| (a :: l) a₁ a₂ := by simp only [foldl_cons, foldr_cons, foldl_assoc, ha.assoc];
rw [foldl_op_eq_op_foldr_assoc]
include hc
lemma foldl_assoc_comm_cons {l : list α} {a₁ a₂} : (a₁ :: l) <*> a₂ = a₁ * (l <*> a₂) :=
by rw [foldl_cons, hc.comm, foldl_assoc]
end
/-! ### mfoldl, mfoldr -/
section mfoldl_mfoldr
variables {m : Type v → Type w} [monad m]
@[simp] theorem mfoldl_nil (f : β → α → m β) {b} : mfoldl f b [] = pure b := rfl
@[simp] theorem mfoldr_nil (f : α → β → m β) {b} : mfoldr f b [] = pure b := rfl
@[simp] theorem mfoldl_cons {f : β → α → m β} {b a l} :
mfoldl f b (a :: l) = f b a >>= λ b', mfoldl f b' l := rfl
@[simp] theorem mfoldr_cons {f : α → β → m β} {b a l} :
mfoldr f b (a :: l) = mfoldr f b l >>= f a := rfl
theorem mfoldr_eq_foldr (f : α → β → m β) (b l) :
mfoldr f b l = foldr (λ a mb, mb >>= f a) (pure b) l :=
by induction l; simp *
variables [is_lawful_monad m]
theorem mfoldl_eq_foldl (f : β → α → m β) (b l) :
mfoldl f b l = foldl (λ mb a, mb >>= λ b, f b a) (pure b) l :=
begin
suffices h : ∀ (mb : m β),
(mb >>= λ b, mfoldl f b l) = foldl (λ mb a, mb >>= λ b, f b a) mb l,
by simp [←h (pure b)],
induction l; intro,
{ simp },
{ simp only [mfoldl, foldl, ←l_ih] with monad_norm }
end
@[simp] theorem mfoldl_append {f : β → α → m β} : ∀ {b l₁ l₂},
mfoldl f b (l₁ ++ l₂) = mfoldl f b l₁ >>= λ x, mfoldl f x l₂
| _ [] _ := by simp only [nil_append, mfoldl_nil, pure_bind]
| _ (_::_) _ := by simp only [cons_append, mfoldl_cons, mfoldl_append, bind_assoc]
@[simp] theorem mfoldr_append {f : α → β → m β} : ∀ {b l₁ l₂},
mfoldr f b (l₁ ++ l₂) = mfoldr f b l₂ >>= λ x, mfoldr f x l₁
| _ [] _ := by simp only [nil_append, mfoldr_nil, bind_pure]
| _ (_::_) _ := by simp only [mfoldr_cons, cons_append, mfoldr_append, bind_assoc]
end mfoldl_mfoldr
/-! ### prod and sum -/
-- list.sum was already defined in defs.lean, but we couldn't tag it with `to_additive` yet.
attribute [to_additive] list.prod
section monoid
variables [monoid α] {l l₁ l₂ : list α} {a : α}
@[simp, to_additive]
theorem prod_nil : ([] : list α).prod = 1 := rfl
@[to_additive]
theorem prod_singleton : [a].prod = a := one_mul a
@[simp, to_additive]
theorem prod_cons : (a::l).prod = a * l.prod :=
calc (a::l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one]
... = _ : foldl_assoc
@[simp, to_additive]
theorem prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod :=
calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod]
... = l₁.prod * l₂.prod : foldl_assoc
@[simp, to_additive]
theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod :=
by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]]
theorem prod_ne_zero {R : Type*} [domain R] {L : list R} :
(∀ x ∈ L, (x : _) ≠ 0) → L.prod ≠ 0 :=
list.rec_on L (λ _, one_ne_zero) $ λ hd tl ih H,
by { rw forall_mem_cons at H, rw prod_cons, exact mul_ne_zero H.1 (ih H.2) }
@[to_additive]
theorem prod_eq_foldr : l.prod = foldr (*) 1 l :=
list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl]
@[to_additive]
theorem prod_hom_rel {α β γ : Type*} [monoid β] [monoid γ] (l : list α) {r : β → γ → Prop}
{f : α → β} {g : α → γ} (h₁ : r 1 1) (h₂ : ∀⦃a b c⦄, r b c → r (f a * b) (g a * c)) :
r (l.map f).prod (l.map g).prod :=
list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl])
@[to_additive]
theorem prod_hom [monoid β] (l : list α) (f : α →* β) :
(l.map f).prod = f l.prod :=
by { simp only [prod, foldl_map, f.map_one.symm],
exact l.foldl_hom _ _ _ 1 f.map_mul }
-- `to_additive` chokes on the next few lemmas, so we do them by hand below
@[simp]
lemma prod_take_mul_prod_drop :
∀ (L : list α) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop], }
@[simp]
lemma prod_take_succ :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc], }
/-- A list with product not one must have positive length. -/
lemma length_pos_of_prod_ne_one (L : list α) (h : L.prod ≠ 1) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
end monoid
@[simp]
lemma sum_take_add_sum_drop [add_monoid α] :
∀ (L : list α) (i : ℕ), (L.take i).sum + (L.drop i).sum = L.sum
| [] i := by simp
| L 0 := by simp
| (h :: t) (n+1) := by { dsimp, rw [sum_cons, sum_cons, add_assoc, sum_take_add_sum_drop], }
@[simp]
lemma sum_take_succ [add_monoid α] :
∀ (L : list α) (i : ℕ) (p), (L.take (i + 1)).sum = (L.take i).sum + L.nth_le i p
| [] i p := by cases p
| (h :: t) 0 _ := by simp
| (h :: t) (n+1) _ := by { dsimp, rw [sum_cons, sum_cons, sum_take_succ, add_assoc], }
lemma eq_of_sum_take_eq [add_left_cancel_monoid α] {L L' : list α} (h : L.length = L'.length)
(h' : ∀ i ≤ L.length, (L.take i).sum = (L'.take i).sum) : L = L' :=
begin
apply ext_le h (λ i h₁ h₂, _),
have : (L.take (i + 1)).sum = (L'.take (i + 1)).sum := h' _ (nat.succ_le_of_lt h₁),
rw [sum_take_succ L i h₁, sum_take_succ L' i h₂, h' i (le_of_lt h₁)] at this,
exact add_left_cancel this
end
lemma monotone_sum_take [canonically_ordered_add_monoid α] (L : list α) :
monotone (λ i, (L.take i).sum) :=
begin
apply monotone_of_monotone_nat (λ n, _),
by_cases h : n < L.length,
{ rw sum_take_succ _ _ h,
exact le_add_right (le_refl _) },
{ push_neg at h,
simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] }
end
/-- A list with sum not zero must have positive length. -/
lemma length_pos_of_sum_ne_zero [add_monoid α] (L : list α) (h : L.sum ≠ 0) : 0 < L.length :=
by { cases L, { simp at h, cases h, }, { simp, }, }
/-- If all elements in a list are bounded below by `1`, then the length of the list is bounded
by the sum of the elements. -/
lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum :=
begin
induction L with j L IH h, { simp },
rw [sum_cons, length, add_comm],
exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi)))
end
-- Now we tie those lemmas back to their multiplicative versions.
attribute [to_additive] prod_take_mul_prod_drop prod_take_succ length_pos_of_prod_ne_one
/-- A list with positive sum must have positive length. -/
-- This is an easy consequence of `length_pos_of_sum_ne_zero`, but often useful in applications.
lemma length_pos_of_sum_pos [ordered_cancel_add_comm_monoid α] (L : list α) (h : 0 < L.sum) :
0 < L.length :=
length_pos_of_sum_ne_zero L (ne_of_gt h)
@[simp, to_additive]
theorem prod_erase [decidable_eq α] [comm_monoid α] {a} :
Π {l : list α}, a ∈ l → a * (l.erase a).prod = l.prod
| (b::l) h :=
begin
rcases eq_or_ne_mem_of_mem h with rfl | ⟨ne, h⟩,
{ simp only [list.erase, if_pos, prod_cons] },
{ simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] }
end
lemma dvd_prod [comm_monoid α] {a} {l : list α} (ha : a ∈ l) : a ∣ l.prod :=
let ⟨s, t, h⟩ := mem_split ha in
by rw [h, prod_append, prod_cons, mul_left_comm]; exact dvd_mul_right _ _
@[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n :=
by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]]
theorem dvd_sum [comm_semiring α] {a} {l : list α} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum :=
begin
induction l with x l ih,
{ exact dvd_zero _ },
{ rw [list.sum_cons],
exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) }
end
@[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) :=
by induction L; [refl, simp only [*, join, map, sum_cons, length_append]]
@[simp] theorem length_bind (l : list α) (f : α → list β) :
length (list.bind l f) = sum (map (length ∘ f) l) :=
by rw [list.bind, length_join, map_map]
lemma exists_lt_of_sum_lt [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α}
(f g : α → β) (h : (l.map f).sum < (l.map g).sum) : ∃ x ∈ l, f x < g x :=
begin
induction l with x l,
{ exfalso, exact lt_irrefl _ h },
{ by_cases h' : f x < g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases l_ih _ with ⟨y, h1y, h2y⟩, refine ⟨y, mem_cons_of_mem x h1y, h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_lt_of_le h $ add_le_add_right (le_of_not_gt h') _) }
end
lemma exists_le_of_sum_le [decidable_linear_ordered_cancel_add_comm_monoid β] {l : list α}
(hl : l ≠ []) (f g : α → β) (h : (l.map f).sum ≤ (l.map g).sum) : ∃ x ∈ l, f x ≤ g x :=
begin
cases l with x l,
{ contradiction },
{ by_cases h' : f x ≤ g x, exact ⟨x, mem_cons_self _ _, h'⟩,
rcases exists_lt_of_sum_lt f g _ with ⟨y, h1y, h2y⟩,
exact ⟨y, mem_cons_of_mem x h1y, le_of_lt h2y⟩, simp at h,
exact lt_of_add_lt_add_left (lt_of_le_of_lt h $ add_lt_add_right (lt_of_not_ge h') _) }
end
-- Several lemmas about sum/head/tail for `list ℕ`.
-- These are hard to generalize well, as they rely on the fact that `default ℕ = 0`.
-- We'd like to state this as `L.head * L.tail.prod = L.prod`,
-- but because `L.head` relies on an inhabited instances and
-- returns a garbage value for the empty list, this is not possible.
-- Instead we write the statement in terms of `(L.nth 0).get_or_else 1`,
-- and below, restate the lemma just for `ℕ`.
@[to_additive]
lemma head_mul_tail_prod' [monoid α] (L : list α) :
(L.nth 0).get_or_else 1 * L.tail.prod = L.prod :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum :=
by { cases L, { simp, refl, }, { simp, }, }
lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum :=
nat.le.intro (head_add_tail_sum L)
lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head :=
by rw [← head_add_tail_sum L, add_comm, nat.add_sub_cancel]
section
variables {G : Type*} [comm_group G]
attribute [to_additive] alternating_prod
@[simp, to_additive] lemma alternating_prod_nil :
alternating_prod ([] : list G) = 1 := rfl
@[simp, to_additive] lemma alternating_prod_singleton (g : G) :
alternating_prod [g] = g := rfl
@[simp, to_additive alternating_sum_cons_cons']
lemma alternating_prod_cons_cons (g h : G) (l : list G) :
alternating_prod (g :: h :: l) = g * h⁻¹ * alternating_prod l := rfl
lemma alternating_sum_cons_cons {G : Type*} [add_comm_group G] (g h : G) (l : list G) :
alternating_sum (g :: h :: l) = g - h + alternating_sum l := rfl
end
/-! ### join -/
attribute [simp] join
theorem join_eq_nil : ∀ {L : list (list α)}, join L = [] ↔ ∀ l ∈ L, l = []
| [] := iff_of_true rfl (forall_mem_nil _)
| (l::L) := by simp only [join, append_eq_nil, join_eq_nil, forall_mem_cons]
@[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ :=
by induction L₁; [refl, simp only [*, join, cons_append, append_assoc]]
lemma join_join (l : list (list (list α))) : l.join.join = (l.map join).join :=
by { induction l, simp, simp [l_ih] }
/-- In a join, taking the first elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join of the first `i` sublists. -/
lemma take_sum_join (L : list (list α)) (i : ℕ) :
L.join.take ((L.map length).take i).sum = (L.take i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [take_append, L_ih]
end
/-- In a join, dropping all the elements up to an index which is the sum of the lengths of the
first `i` sublists, is the same as taking the join after dropping the first `i` sublists. -/
lemma drop_sum_join (L : list (list α)) (i : ℕ) :
L.join.drop ((L.map length).take i).sum = (L.drop i).join :=
begin
induction L generalizing i, { simp },
cases i, { simp },
simp [drop_append, L_ih],
end
/-- Taking only the first `i+1` elements in a list, and then dropping the first `i` ones, one is
left with a list of length `1` made of the `i`-th element of the original list. -/
lemma drop_take_succ_eq_cons_nth_le (L : list α) {i : ℕ} (hi : i < L.length) :
(L.take (i+1)).drop i = [nth_le L i hi] :=
begin
induction L generalizing i,
{ simp only [length] at hi, exact (nat.not_succ_le_zero i hi).elim },
cases i, { simp },
have : i < L_tl.length,
{ simp at hi,
exact nat.lt_of_succ_lt_succ hi },
simp [L_ih this],
refl
end
/-- In a join of sublists, taking the slice between the indices `A` and `B - 1` gives back the
original sublist of index `i` if `A` is the sum of the lenghts of sublists of index `< i`, and
`B` is the sum of the lengths of sublists of index `≤ i`. -/
lemma drop_take_succ_join_eq_nth_le (L : list (list α)) {i : ℕ} (hi : i < L.length) :
(L.join.take ((L.map length).take (i+1)).sum).drop ((L.map length).take i).sum = nth_le L i hi :=
begin
have : (L.map length).take i = ((L.take (i+1)).map length).take i, by simp [map_take, take_take],
simp [take_sum_join, this, drop_sum_join, drop_take_succ_eq_cons_nth_le _ hi]
end
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt1 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < ((L.map length).take (i+1)).sum :=
by simp [hi, sum_take_succ, hj]
/-- Auxiliary lemma to control elements in a join. -/
lemma sum_take_map_length_lt2 (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
((L.map length).take i).sum + j < L.join.length :=
begin
convert lt_of_lt_of_le (sum_take_map_length_lt1 L hi hj) (monotone_sum_take _ hi),
have : L.length = (L.map length).length, by simp,
simp [this, -length_map]
end
/-- The `n`-th element in a join of sublists is the `j`-th element of the `i`th sublist,
where `n` can be obtained in terms of `i` and `j` by adding the lengths of all the sublists
of index `< i`, and adding `j`. -/
lemma nth_le_join (L : list (list α)) {i j : ℕ}
(hi : i < L.length) (hj : j < (nth_le L i hi).length) :
nth_le L.join (((L.map length).take i).sum + j) (sum_take_map_length_lt2 L hi hj) =
nth_le (nth_le L i hi) j hj :=
by rw [nth_le_take L.join (sum_take_map_length_lt2 L hi hj) (sum_take_map_length_lt1 L hi hj),
nth_le_drop, nth_le_of_eq (drop_take_succ_join_eq_nth_le L hi)]
/-- Two lists of sublists are equal iff their joins coincide, as well as the lengths of the
sublists. -/
theorem eq_iff_join_eq (L L' : list (list α)) :
L = L' ↔ L.join = L'.join ∧ map length L = map length L' :=
begin
refine ⟨λ H, by simp [H], _⟩,
rintros ⟨join_eq, length_eq⟩,
apply ext_le,
{ have : length (map length L) = length (map length L'), by rw length_eq,
simpa using this },
{ assume n h₁ h₂,
rw [← drop_take_succ_join_eq_nth_le, ← drop_take_succ_join_eq_nth_le, join_eq, length_eq] }
end
/-! ### lexicographic ordering -/
/-- Given a strict order `<` on `α`, the lexicographic strict order on `list α`, for which
`[a0, ..., an] < [b0, ..., b_k]` if `a0 < b0` or `a0 = b0` and `[a1, ..., an] < [b1, ..., bk]`.
The definition is given for any relation `r`, not only strict orders. -/
inductive lex (r : α → α → Prop) : list α → list α → Prop
| nil {a l} : lex [] (a :: l)
| cons {a l₁ l₂} (h : lex l₁ l₂) : lex (a :: l₁) (a :: l₂)
| rel {a₁ l₁ a₂ l₂} (h : r a₁ a₂) : lex (a₁ :: l₁) (a₂ :: l₂)
namespace lex
theorem cons_iff {r : α → α → Prop} [is_irrefl α r] {a l₁ l₂} :
lex r (a :: l₁) (a :: l₂) ↔ lex r l₁ l₂ :=
⟨λ h, by cases h with _ _ _ _ _ h _ _ _ _ h;
[exact h, exact (irrefl_of r a h).elim], lex.cons⟩
@[simp] theorem not_nil_right (r : α → α → Prop) (l : list α) : ¬ lex r l [].
instance is_order_connected (r : α → α → Prop)
[is_order_connected α r] [is_trichotomous α r] :
is_order_connected (list α) (lex r) :=
⟨λ l₁, match l₁ with
| _, [], c::l₃, nil := or.inr nil
| _, [], c::l₃, rel _ := or.inr nil
| _, [], c::l₃, cons _ := or.inr nil
| _, b::l₂, c::l₃, nil := or.inl nil
| a::l₁, b::l₂, c::l₃, rel h :=
(is_order_connected.conn _ b _ h).imp rel rel
| a::l₁, b::l₂, _::l₃, cons h := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match _ l₂ _ h).imp cons cons },
{ exact or.inr (rel ab) }
end
end⟩
instance is_trichotomous (r : α → α → Prop) [is_trichotomous α r] :
is_trichotomous (list α) (lex r) :=
⟨λ l₁, match l₁ with
| [], [] := or.inr (or.inl rfl)
| [], b::l₂ := or.inl nil
| a::l₁, [] := or.inr (or.inr nil)
| a::l₁, b::l₂ := begin
rcases trichotomous_of r a b with ab | rfl | ab,
{ exact or.inl (rel ab) },
{ exact (_match l₁ l₂).imp cons
(or.imp (congr_arg _) cons) },
{ exact or.inr (or.inr (rel ab)) }
end
end⟩
instance is_asymm (r : α → α → Prop)
[is_asymm α r] : is_asymm (list α) (lex r) :=
⟨λ l₁, match l₁ with
| a::l₁, b::l₂, lex.rel h₁, lex.rel h₂ := asymm h₁ h₂
| a::l₁, b::l₂, lex.rel h₁, lex.cons h₂ := asymm h₁ h₁
| a::l₁, b::l₂, lex.cons h₁, lex.rel h₂ := asymm h₂ h₂
| a::l₁, b::l₂, lex.cons h₁, lex.cons h₂ :=
by exact _match _ _ h₁ h₂
end⟩
instance is_strict_total_order (r : α → α → Prop)
[is_strict_total_order' α r] : is_strict_total_order' (list α) (lex r) :=
{..is_strict_weak_order_of_is_order_connected}
instance decidable_rel [decidable_eq α] (r : α → α → Prop)
[decidable_rel r] : decidable_rel (lex r)
| l₁ [] := is_false $ λ h, by cases h
| [] (b::l₂) := is_true lex.nil
| (a::l₁) (b::l₂) := begin
haveI := decidable_rel l₁ l₂,
refine decidable_of_iff (r a b ∨ a = b ∧ lex r l₁ l₂) ⟨λ h, _, λ h, _⟩,
{ rcases h with h | ⟨rfl, h⟩,
{ exact lex.rel h },
{ exact lex.cons h } },
{ rcases h with _|⟨_,_,_,h⟩|⟨_,_,_,_,h⟩,
{ exact or.inr ⟨rfl, h⟩ },
{ exact or.inl h } }
end
theorem append_right (r : α → α → Prop) :
∀ {s₁ s₂} t, lex r s₁ s₂ → lex r s₁ (s₂ ++ t)
| _ _ t nil := nil
| _ _ t (cons h) := cons (append_right _ h)
| _ _ t (rel r) := rel r
theorem append_left (R : α → α → Prop) {t₁ t₂} (h : lex R t₁ t₂) :
∀ s, lex R (s ++ t₁) (s ++ t₂)
| [] := h
| (a::l) := cons (append_left l)
theorem imp {r s : α → α → Prop} (H : ∀ a b, r a b → s a b) :
∀ l₁ l₂, lex r l₁ l₂ → lex s l₁ l₂
| _ _ nil := nil
| _ _ (cons h) := cons (imp _ _ h)
| _ _ (rel r) := rel (H _ _ r)
theorem to_ne : ∀ {l₁ l₂ : list α}, lex (≠) l₁ l₂ → l₁ ≠ l₂
| _ _ (cons h) e := to_ne h (list.cons.inj e).2
| _ _ (rel r) e := r (list.cons.inj e).1
theorem ne_iff {l₁ l₂ : list α} (H : length l₁ ≤ length l₂) :
lex (≠) l₁ l₂ ↔ l₁ ≠ l₂ :=
⟨to_ne, λ h, begin
induction l₁ with a l₁ IH generalizing l₂; cases l₂ with b l₂,
{ contradiction },
{ apply nil },
{ exact (not_lt_of_ge H).elim (succ_pos _) },
{ cases classical.em (a = b) with ab ab,
{ subst b, apply cons,
exact IH (le_of_succ_le_succ H) (mt (congr_arg _) h) },
{ exact rel ab } }
end⟩
end lex
--Note: this overrides an instance in core lean
instance has_lt' [has_lt α] : has_lt (list α) := ⟨lex (<)⟩
theorem nil_lt_cons [has_lt α] (a : α) (l : list α) : [] < a :: l :=
lex.nil
instance [linear_order α] : linear_order (list α) :=
linear_order_of_STO' (lex (<))
--Note: this overrides an instance in core lean
instance has_le' [linear_order α] : has_le (list α) :=
preorder.to_has_le _
instance [decidable_linear_order α] : decidable_linear_order (list α) :=
decidable_linear_order_of_STO' (lex (<))
/-! ### all & any -/
@[simp] theorem all_nil (p : α → bool) : all [] p = tt := rfl
@[simp] theorem all_cons (p : α → bool) (a : α) (l : list α) :
all (a::l) p = (p a && all l p) := rfl
theorem all_iff_forall {p : α → bool} {l : list α} : all l p ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
simp only [all_cons, band_coe_iff, ih, forall_mem_cons]
end
theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p]
{l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a :=
by simp only [all_iff_forall, bool.of_to_bool_iff]
@[simp] theorem any_nil (p : α → bool) : any [] p = ff := rfl
@[simp] theorem any_cons (p : α → bool) (a : α) (l : list α) :
any (a::l) p = (p a || any l p) := rfl
theorem any_iff_exists {p : α → bool} {l : list α} : any l p ↔ ∃ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_false bool.not_ff (not_exists_mem_nil _) },
simp only [any_cons, bor_coe_iff, ih, exists_mem_cons_iff]
end
theorem any_iff_exists_prop {p : α → Prop} [decidable_pred p]
{l : list α} : any l (λ a, p a) ↔ ∃ a ∈ l, p a :=
by simp [any_iff_exists]
theorem any_of_mem {p : α → bool} {a : α} {l : list α} (h₁ : a ∈ l) (h₂ : p a) : any l p :=
any_iff_exists.2 ⟨_, h₁, h₂⟩
@[priority 500] instance decidable_forall_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∀ x ∈ l, p x) :=
decidable_of_iff _ all_iff_forall_prop
instance decidable_exists_mem {p : α → Prop} [decidable_pred p] (l : list α) :
decidable (∃ x ∈ l, p x) :=
decidable_of_iff _ any_iff_exists_prop
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {p : α → Prop} (f : Π a, p a → β) : Π l : list α, (∀ a ∈ l, p a) → list β
| [] H := []
| (a::l) H := f a (forall_mem_cons.1 H).1 :: pmap l (forall_mem_cons.1 H).2
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new list
with the same elements but in the type `{x // x ∈ l}`. -/
def attach (l : list α) : list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {l : list α} (hx : x ∈ l) :
sizeof x < sizeof l :=
begin
induction l with h t ih; cases hx,
{ rw hx, exact lt_add_of_lt_of_nonneg (lt_one_add _) (nat.zero_le _) },
{ exact lt_add_of_pos_of_le (zero_lt_one_add _) (le_of_lt (ih hx)) }
end
theorem pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) :
@pmap _ _ p (λ a _, f a) l H = map f l :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(l : list α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f l H₁ = pmap g l H₂ :=
by induction l with _ _ ih; [refl, rw [pmap, pmap, h, ih]]
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(l H) : map g (pmap f l H) = pmap (λ a h, g (f a h)) l H :=
by induction l; [refl, simp only [*, pmap, map]]; split; refl
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(l H) : pmap f l H = l.attach.map (λ x, f x.1 (H _ x.2)) :=
by rw [attach, map_pmap]; exact pmap_congr l (λ a h₁ h₂, rfl)
theorem attach_map_val (l : list α) : l.attach.map subtype.val = l :=
by rw [attach, map_pmap]; exact (pmap_eq_map _ _ _ _).trans (map_id l)
@[simp] theorem mem_attach (l : list α) : ∀ x, x ∈ l.attach | ⟨a, h⟩ :=
by have := mem_map.1 (by rw [attach_map_val]; exact h);
{ rcases this with ⟨⟨_, _⟩, m, rfl⟩, exact m }
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{l H b} : b ∈ pmap f l H ↔ ∃ a (h : a ∈ l), f a (H a h) = b :=
by simp only [pmap_eq_map_attach, mem_map, mem_attach, true_and, subtype.exists]
@[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β}
{l H} : length (pmap f l H) = length l :=
by induction l; [refl, simp only [*, pmap, length]]
@[simp] lemma length_attach (L : list α) : L.attach.length = L.length := length_pmap
/-! ### find -/
section find
variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α}
@[simp] theorem find_nil (p : α → Prop) [decidable_pred p] : find p [] = none :=
rfl
@[simp] theorem find_cons_of_pos (l) (h : p a) : find p (a::l) = some a :=
if_pos h
@[simp] theorem find_cons_of_neg (l) (h : ¬ p a) : find p (a::l) = find p l :=
if_neg h
@[simp] theorem find_eq_none : find p l = none ↔ ∀ x ∈ l, ¬ p x :=
begin
induction l with a l IH,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases h : p a,
{ simp only [find_cons_of_pos _ h, h, not_true, false_and] },
{ rwa [find_cons_of_neg _ h, iff_true_intro h, true_and] }
end
theorem find_some (H : find p l = some a) : p a :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, exact h },
{ rw find_cons_of_neg _ h at H, exact IH H }
end
@[simp] theorem find_mem (H : find p l = some a) : a ∈ l :=
begin
induction l with b l IH, {contradiction},
by_cases h : p b,
{ rw find_cons_of_pos _ h at H, cases H, apply mem_cons_self },
{ rw find_cons_of_neg _ h at H, exact mem_cons_of_mem _ (IH H) }
end
end find
/-! ### lookmap -/
section lookmap
variables (f : α → option α)
@[simp] theorem lookmap_nil : [].lookmap f = [] := rfl
@[simp] theorem lookmap_cons_none {a : α} (l : list α) (h : f a = none) :
(a :: l).lookmap f = a :: l.lookmap f :=
by simp [lookmap, h]
@[simp] theorem lookmap_cons_some {a b : α} (l : list α) (h : f a = some b) :
(a :: l).lookmap f = b :: l :=
by simp [lookmap, h]
theorem lookmap_some : ∀ l : list α, l.lookmap some = l
| [] := rfl
| (a::l) := rfl
theorem lookmap_none : ∀ l : list α, l.lookmap (λ _, none) = l
| [] := rfl
| (a::l) := congr_arg (cons a) (lookmap_none l)
theorem lookmap_congr {f g : α → option α} :
∀ {l : list α}, (∀ a ∈ l, f a = g a) → l.lookmap f = l.lookmap g
| [] H := rfl
| (a::l) H := begin
cases forall_mem_cons.1 H with H₁ H₂,
cases h : g a with b,
{ simp [h, H₁.trans h, lookmap_congr H₂] },
{ simp [lookmap_cons_some _ _ h, lookmap_cons_some _ _ (H₁.trans h)] }
end
theorem lookmap_of_forall_not {l : list α} (H : ∀ a ∈ l, f a = none) : l.lookmap f = l :=
(lookmap_congr H).trans (lookmap_none l)
theorem lookmap_map_eq (g : α → β) (h : ∀ a (b ∈ f a), g a = g b) :
∀ l : list α, map g (l.lookmap f) = map g l
| [] := rfl
| (a::l) := begin
cases h' : f a with b,
{ simp [h', lookmap_map_eq] },
{ simp [lookmap_cons_some _ _ h', h _ _ h'] }
end
theorem lookmap_id' (h : ∀ a (b ∈ f a), a = b) (l : list α) : l.lookmap f = l :=
by rw [← map_id (l.lookmap f), lookmap_map_eq, map_id]; exact h
theorem length_lookmap (l : list α) : length (l.lookmap f) = length l :=
by rw [← length_map, lookmap_map_eq _ (λ _, ()), length_map]; simp
end lookmap
/-! ### filter_map -/
@[simp] theorem filter_map_nil (f : α → option β) : filter_map f [] = [] := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (l : list α) (h : f a = none) :
filter_map f (a :: l) = filter_map f l :=
by simp only [filter_map, h]
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (l : list α) {b : β} (h : f a = some b) :
filter_map f (a :: l) = b :: filter_map f l :=
by simp only [filter_map, h]; split; refl
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
begin
funext l,
induction l with a l IH, {refl},
simp only [filter_map_cons_some (some ∘ f) _ _ rfl, IH, map_cons], split; refl
end
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
begin
funext l,
induction l with a l IH, {refl},
by_cases pa : p a,
{ simp only [filter_map, option.guard, IH, if_pos pa, filter_cons_of_pos _ pa], split; refl },
{ simp only [filter_map, option.guard, IH, if_neg pa, filter_cons_of_neg _ pa] }
end
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (l : list α) :
filter_map g (filter_map f l) = filter_map (λ x, (f x).bind g) l :=
begin
induction l with a l IH, {refl},
cases h : f a with b,
{ rw [filter_map_cons_none _ _ h, filter_map_cons_none, IH],
simp only [h, option.none_bind'] },
rw filter_map_cons_some _ _ _ h,
cases h' : g b with c;
[ rw [filter_map_cons_none _ _ h', filter_map_cons_none, IH],
rw [filter_map_cons_some _ _ _ h', filter_map_cons_some, IH] ];
simp only [h, h', option.some_bind']
end
theorem map_filter_map (f : α → option β) (g : β → γ) (l : list α) :
map g (filter_map f l) = filter_map (λ x, (f x).map g) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_map_map (f : α → β) (g : β → option γ) (l : list α) :
filter_map g (map f l) = filter_map (g ∘ f) l :=
by rw [← filter_map_eq_map, filter_map_filter_map]; refl
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (l : list α) :
filter p (filter_map f l) = filter_map (λ x, (f x).filter p) l :=
by rw [← filter_map_eq_filter, filter_map_filter_map]; refl
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (l : list α) :
filter_map f (filter p l) = filter_map (λ x, if p x then f x else none) l :=
begin
rw [← filter_map_eq_filter, filter_map_filter_map], congr,
funext x,
show (option.guard p x).bind f = ite (p x) (f x) none,
by_cases h : p x,
{ simp only [option.guard, if_pos h, option.some_bind'] },
{ simp only [option.guard, if_neg h, option.none_bind'] }
end
@[simp] theorem filter_map_some (l : list α) : filter_map some l = l :=
by rw filter_map_eq_map; apply map_id
@[simp] theorem mem_filter_map (f : α → option β) (l : list α) {b : β} :
b ∈ filter_map f l ↔ ∃ a, a ∈ l ∧ f a = some b :=
begin
induction l with a l IH,
{ split, { intro H, cases H }, { rintro ⟨_, H, _⟩, cases H } },
cases h : f a with b',
{ have : f a ≠ some b, {rw h, intro, contradiction},
simp only [filter_map_cons_none _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, exists_eq_left, this, false_or] },
{ have : f a = some b ↔ b = b',
{ split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} },
simp only [filter_map_cons_some _ _ _ h, IH, mem_cons_iff,
or_and_distrib_right, exists_or_distrib, this, exists_eq_left] }
end
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (l : list α) :
map g (filter_map f l) = l :=
by simp only [map_filter_map, H, filter_map_some]
theorem sublist.filter_map (f : α → option β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : filter_map f l₁ <+ filter_map f l₂ :=
by induction s with l₁ l₂ a s IH l₁ l₂ a s IH;
simp only [filter_map]; cases f a with b;
simp only [filter_map, IH, sublist.cons, sublist.cons2]
theorem sublist.map (f : α → β) {l₁ l₂ : list α}
(s : l₁ <+ l₂) : map f l₁ <+ map f l₂ :=
filter_map_eq_map f ▸ s.filter_map _
/-! ### filter -/
section filter
variables {p : α → Prop} [decidable_pred p]
theorem filter_eq_foldr (p : α → Prop) [decidable_pred p] (l : list α) :
filter p l = foldr (λ a out, if p a then a :: out else out) [] l :=
by induction l; simp [*, filter]
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
: ∀ {l : list α}, (∀ x ∈ l, p x ↔ q x) → filter p l = filter q l
| [] _ := rfl
| (a::l) h := by rw forall_mem_cons at h; by_cases pa : p a;
[simp only [filter_cons_of_pos _ pa, filter_cons_of_pos _ (h.1.1 pa), filter_congr h.2],
simp only [filter_cons_of_neg _ pa, filter_cons_of_neg _ (mt h.1.2 pa), filter_congr h.2]];
split; refl
@[simp] theorem filter_subset (l : list α) : filter p l ⊆ l :=
(filter_sublist l).subset
theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a
| (b::l) ain :=
if pb : p b then
have a ∈ b :: filter p l, by simpa only [filter_cons_of_pos _ pb] using ain,
or.elim (eq_or_mem_of_mem_cons this)
(assume : a = b, begin rw [← this] at pb, exact pb end)
(assume : a ∈ filter p l, of_mem_filter this)
else
begin simp only [filter_cons_of_neg _ pb] at ain, exact (of_mem_filter ain) end
theorem mem_of_mem_filter {a : α} {l} (h : a ∈ filter p l) : a ∈ l :=
filter_subset l h
theorem mem_filter_of_mem {a : α} : ∀ {l}, a ∈ l → p a → a ∈ filter p l
| (_::l) (or.inl rfl) pa := by rw filter_cons_of_pos _ pa; apply mem_cons_self
| (b::l) (or.inr ain) pa := if pb : p b
then by rw [filter_cons_of_pos _ pb]; apply mem_cons_of_mem; apply mem_filter_of_mem ain pa
else by rw [filter_cons_of_neg _ pb]; apply mem_filter_of_mem ain pa
@[simp] theorem mem_filter {a : α} {l} : a ∈ filter p l ↔ a ∈ l ∧ p a :=
⟨λ h, ⟨mem_of_mem_filter h, of_mem_filter h⟩, λ ⟨h₁, h₂⟩, mem_filter_of_mem h₁ h₂⟩
theorem filter_eq_self {l} : filter p l = l ↔ ∀ a ∈ l, p a :=
begin
induction l with a l ih,
{ exact iff_of_true rfl (forall_mem_nil _) },
rw forall_mem_cons, by_cases p a,
{ rw [filter_cons_of_pos _ h, cons_inj, ih, and_iff_right h] },
{ rw [filter_cons_of_neg _ h],
refine iff_of_false _ (mt and.left h), intro e,
have := filter_sublist l, rw e at this,
exact not_lt_of_ge (length_le_of_sublist this) (lt_succ_self _) }
end
theorem filter_eq_nil {l} : filter p l = [] ↔ ∀ a ∈ l, ¬p a :=
by simp only [eq_nil_iff_forall_not_mem, mem_filter, not_and]
theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ :=
filter_map_eq_filter p ▸ s.filter_map _
theorem filter_of_map (f : β → α) (l) : filter p (map f l) = map f (filter (p ∘ f) l) :=
by rw [← filter_map_eq_map, filter_filter_map, filter_map_filter]; refl
@[simp] theorem filter_filter {q} [decidable_pred q] : ∀ l,
filter p (filter q l) = filter (λ a, p a ∧ q a) l
| [] := rfl
| (a :: l) := by by_cases hp : p a; by_cases hq : q a; simp only [hp, hq, filter, if_true, if_false,
true_and, false_and, filter_filter l, eq_self_iff_true]
@[simp] lemma filter_true {h : decidable_pred (λ a : α, true)} (l : list α) :
@filter α (λ _, true) h l = l :=
by convert filter_eq_self.2 (λ _ _, trivial)
@[simp] lemma filter_false {h : decidable_pred (λ a : α, false)} (l : list α) :
@filter α (λ _, false) h l = [] :=
by convert filter_eq_nil.2 (λ _ _, id)
@[simp] theorem span_eq_take_drop (p : α → Prop) [decidable_pred p] :
∀ (l : list α), span p l = (take_while p l, drop_while p l)
| [] := rfl
| (a::l) :=
if pa : p a then by simp only [span, if_pos pa, span_eq_take_drop l, take_while, drop_while]
else by simp only [span, take_while, drop_while, if_neg pa]
@[simp] theorem take_while_append_drop (p : α → Prop) [decidable_pred p] :
∀ (l : list α), take_while p l ++ drop_while p l = l
| [] := rfl
| (a::l) := if pa : p a then by rw [take_while, drop_while, if_pos pa, if_pos pa, cons_append,
take_while_append_drop l]
else by rw [take_while, drop_while, if_neg pa, if_neg pa, nil_append]
@[simp] theorem countp_nil (p : α → Prop) [decidable_pred p] : countp p [] = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (l) (pa : p a) : countp p (a::l) = countp p l + 1 :=
if_pos pa
@[simp] theorem countp_cons_of_neg {a : α} (l) (pa : ¬ p a) : countp p (a::l) = countp p l :=
if_neg pa
theorem countp_eq_length_filter (l) : countp p l = length (filter p l) :=
by induction l with x l ih; [refl, by_cases (p x)];
[simp only [filter_cons_of_pos _ h, countp, ih, if_pos h],
simp only [countp_cons_of_neg _ h, ih, filter_cons_of_neg _ h]]; refl
local attribute [simp] countp_eq_length_filter
@[simp] theorem countp_append (l₁ l₂) : countp p (l₁ ++ l₂) = countp p l₁ + countp p l₂ :=
by simp only [countp_eq_length_filter, filter_append, length_append]
theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a :=
by simp only [countp_eq_length_filter, length_pos_iff_exists_mem, mem_filter, exists_prop]
theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ :=
by simpa only [countp_eq_length_filter] using length_le_of_sublist (filter_sublist_filter s)
@[simp] theorem countp_filter {q} [decidable_pred q] (l : list α) :
countp p (filter q l) = countp (λ a, p a ∧ q a) l :=
by simp only [countp_eq_length_filter, filter_filter]
end filter
/-! ### count -/
section count
variable [decidable_eq α]
@[simp] theorem count_nil (a : α) : count a [] = 0 := rfl
theorem count_cons (a b : α) (l : list α) :
count a (b :: l) = if a = b then succ (count a l) else count a l := rfl
theorem count_cons' (a b : α) (l : list α) :
count a (b :: l) = count a l + (if a = b then 1 else 0) :=
begin rw count_cons, split_ifs; refl end
@[simp] theorem count_cons_self (a : α) (l : list α) : count a (a::l) = succ (count a l) :=
if_pos rfl
@[simp, priority 990]
theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l :=
if_neg h
theorem count_tail : Π (l : list α) (a : α) (h : 0 < l.length),
l.tail.count a = l.count a - ite (a = list.nth_le l 0 h) 1 0
| (_ :: _) a h := by { rw [count_cons], split_ifs; simp }
theorem count_le_of_sublist (a : α) {l₁ l₂} : l₁ <+ l₂ → count a l₁ ≤ count a l₂ :=
countp_le_of_sublist
theorem count_le_count_cons (a b : α) (l : list α) : count a l ≤ count a (b :: l) :=
count_le_of_sublist _ (sublist_cons _ _)
theorem count_singleton (a : α) : count a [a] = 1 := if_pos rfl
@[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ :=
countp_append
theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) :=
by simp [-add_comm]
theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l :=
by simp only [count, countp_pos, exists_prop, exists_eq_right']
@[simp, priority 980]
theorem count_eq_zero_of_not_mem {a : α} {l : list α} (h : a ∉ l) : count a l = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem not_mem_of_count_eq_zero {a : α} {l : list α} (h : count a l = 0) : a ∉ l :=
λ h', ne_of_gt (count_pos.2 h') h
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by rw [count, countp_eq_length_filter, filter_eq_self.2, length_repeat];
exact λ b m, (eq_of_mem_repeat m).symm
theorem le_count_iff_repeat_sublist {a : α} {l : list α} {n : ℕ} :
n ≤ count a l ↔ repeat a n <+ l :=
⟨λ h, ((repeat_sublist_repeat a).2 h).trans $
have filter (eq a) l = repeat a (count a l), from eq_repeat.2
⟨by simp only [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩,
by rw ← this; apply filter_sublist,
λ h, by simpa only [count_repeat] using count_le_of_sublist a h⟩
theorem repeat_count_eq_of_count_eq_length {a : α} {l : list α} (h : count a l = length l) :
repeat a (count a l) = l :=
eq_of_sublist_of_length_eq (le_count_iff_repeat_sublist.mp (le_refl (count a l)))
(eq.trans (length_repeat a (count a l)) h)
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {l : list α} (h : p a) : count a (filter p l) = count a l :=
by simp only [count, countp_filter]; congr; exact
set.ext (λ b, and_iff_left_of_imp (λ e, e ▸ h))
end count
/-! ### prefix, suffix, infix -/
@[simp] theorem prefix_append (l₁ l₂ : list α) : l₁ <+: l₁ ++ l₂ := ⟨l₂, rfl⟩
@[simp] theorem suffix_append (l₁ l₂ : list α) : l₂ <:+ l₁ ++ l₂ := ⟨l₁, rfl⟩
theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩
@[simp] theorem infix_append' (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ (l₂ ++ l₃) :=
by rw ← list.append_assoc; apply infix_append
theorem nil_prefix (l : list α) : [] <+: l := ⟨l, rfl⟩
theorem nil_suffix (l : list α) : [] <:+ l := ⟨l, append_nil _⟩
@[refl] theorem prefix_refl (l : list α) : l <+: l := ⟨[], append_nil _⟩
@[refl] theorem suffix_refl (l : list α) : l <:+ l := ⟨[], rfl⟩
@[simp] theorem suffix_cons (a : α) : ∀ l, l <:+ a :: l := suffix_append [a]
theorem prefix_concat (a : α) (l) : l <+: concat l a := by simp
theorem infix_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨[], t, h⟩
theorem infix_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <:+: l₂ :=
λ⟨t, h⟩, ⟨t, [], by simp only [h, append_nil]⟩
@[refl] theorem infix_refl (l : list α) : l <:+: l := infix_of_prefix $ prefix_refl l
theorem nil_infix (l : list α) : [] <:+: l := infix_of_prefix $ nil_prefix l
theorem infix_cons {L₁ L₂ : list α} {x : α} : L₁ <:+: L₂ → L₁ <:+: x :: L₂ :=
λ⟨LP, LS, H⟩, ⟨x :: LP, LS, H ▸ rfl⟩
@[trans] theorem is_prefix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <+: l₂ → l₂ <+: l₃ → l₁ <+: l₃
| l ._ ._ ⟨r₁, rfl⟩ ⟨r₂, rfl⟩ := ⟨r₁ ++ r₂, (append_assoc _ _ _).symm⟩
@[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃
| l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, append_assoc _ _ _⟩
@[trans] theorem is_infix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+: l₂ → l₂ <:+: l₃ → l₁ <:+: l₃
| l ._ ._ ⟨l₁, r₁, rfl⟩ ⟨l₂, r₂, rfl⟩ := ⟨l₂ ++ l₁, r₁ ++ r₂, by simp only [append_assoc]⟩
theorem sublist_of_infix {l₁ l₂ : list α} : l₁ <:+: l₂ → l₁ <+ l₂ :=
λ⟨s, t, h⟩, by rw [← h]; exact (sublist_append_right _ _).trans (sublist_append_left _ _)
theorem sublist_of_prefix {l₁ l₂ : list α} : l₁ <+: l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_prefix
theorem sublist_of_suffix {l₁ l₂ : list α} : l₁ <:+ l₂ → l₁ <+ l₂ :=
sublist_of_infix ∘ infix_of_suffix
theorem reverse_suffix {l₁ l₂ : list α} : reverse l₁ <:+ reverse l₂ ↔ l₁ <+: l₂ :=
⟨λ ⟨r, e⟩, ⟨reverse r,
by rw [← reverse_reverse l₁, ← reverse_append, e, reverse_reverse]⟩,
λ ⟨r, e⟩, ⟨reverse r, by rw [← reverse_append, e]⟩⟩
theorem reverse_prefix {l₁ l₂ : list α} : reverse l₁ <+: reverse l₂ ↔ l₁ <:+ l₂ :=
by rw ← reverse_suffix; simp only [reverse_reverse]
theorem length_le_of_infix {l₁ l₂ : list α} (s : l₁ <:+: l₂) : length l₁ ≤ length l₂ :=
length_le_of_sublist $ sublist_of_infix s
theorem eq_nil_of_infix_nil {l : list α} (s : l <:+: []) : l = [] :=
eq_nil_of_sublist_nil $ sublist_of_infix s
theorem eq_nil_of_prefix_nil {l : list α} (s : l <+: []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_prefix s
theorem eq_nil_of_suffix_nil {l : list α} (s : l <:+ []) : l = [] :=
eq_nil_of_infix_nil $ infix_of_suffix s
theorem infix_iff_prefix_suffix (l₁ l₂ : list α) : l₁ <:+: l₂ ↔ ∃ t, l₁ <+: t ∧ t <:+ l₂ :=
⟨λ⟨s, t, e⟩, ⟨l₁ ++ t, ⟨_, rfl⟩, by rw [← e, append_assoc]; exact ⟨_, rfl⟩⟩,
λ⟨._, ⟨t, rfl⟩, ⟨s, e⟩⟩, ⟨s, t, by rw append_assoc; exact e⟩⟩
theorem eq_of_infix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_infix s
theorem eq_of_prefix_of_length_eq {l₁ l₂ : list α} (s : l₁ <+: l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_prefix s
theorem eq_of_suffix_of_length_eq {l₁ l₂ : list α} (s : l₁ <:+ l₂) :
length l₁ = length l₂ → l₁ = l₂ :=
eq_of_sublist_of_length_eq $ sublist_of_suffix s
theorem prefix_of_prefix_length_le : ∀ {l₁ l₂ l₃ : list α},
l₁ <+: l₃ → l₂ <+: l₃ → length l₁ ≤ length l₂ → l₁ <+: l₂
| [] l₂ l₃ h₁ h₂ _ := nil_prefix _
| (a::l₁) (b::l₂) _ ⟨r₁, rfl⟩ ⟨r₂, e⟩ ll := begin
injection e with _ e', subst b,
rcases prefix_of_prefix_length_le ⟨_, rfl⟩ ⟨_, e'⟩
(le_of_succ_le_succ ll) with ⟨r₃, rfl⟩,
exact ⟨r₃, rfl⟩
end
theorem prefix_or_prefix_of_prefix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <+: l₃) (h₂ : l₂ <+: l₃) : l₁ <+: l₂ ∨ l₂ <+: l₁ :=
(le_total (length l₁) (length l₂)).imp
(prefix_of_prefix_length_le h₁ h₂)
(prefix_of_prefix_length_le h₂ h₁)
theorem suffix_of_suffix_length_le {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) (ll : length l₁ ≤ length l₂) : l₁ <:+ l₂ :=
reverse_prefix.1 $ prefix_of_prefix_length_le
(reverse_prefix.2 h₁) (reverse_prefix.2 h₂) (by simp [ll])
theorem suffix_or_suffix_of_suffix {l₁ l₂ l₃ : list α}
(h₁ : l₁ <:+ l₃) (h₂ : l₂ <:+ l₃) : l₁ <:+ l₂ ∨ l₂ <:+ l₁ :=
(prefix_or_prefix_of_prefix (reverse_prefix.2 h₁) (reverse_prefix.2 h₂)).imp
reverse_prefix.1 reverse_prefix.1
theorem infix_of_mem_join : ∀ {L : list (list α)} {l}, l ∈ L → l <:+: join L
| (_ :: L) l (or.inl rfl) := infix_append [] _ _
| (l' :: L) l (or.inr h) :=
is_infix.trans (infix_of_mem_join h) $ infix_of_suffix $ suffix_append _ _
theorem prefix_append_right_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ :=
exists_congr $ λ r, by rw [append_assoc, append_right_inj]
theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ :=
prefix_append_right_inj [a]
theorem take_prefix (n) (l : list α) : take n l <+: l := ⟨_, take_append_drop _ _⟩
theorem drop_suffix (n) (l : list α) : drop n l <:+ l := ⟨_, take_append_drop _ _⟩
theorem tail_suffix (l : list α) : tail l <:+ l := by rw ← drop_one; apply drop_suffix
theorem tail_subset (l : list α) : tail l ⊆ l := (sublist_of_suffix (tail_suffix l)).subset
theorem prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ :=
⟨by rintros ⟨r, rfl⟩; rw drop_left, λ e, ⟨_, e⟩⟩
theorem suffix_iff_eq_append {l₁ l₂ : list α} :
l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ :=
⟨by rintros ⟨r, rfl⟩; simp only [length_append, nat.add_sub_cancel, take_left], λ e, ⟨_, e⟩⟩
theorem prefix_iff_eq_take {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ = take (length l₁) l₂ :=
⟨λ h, append_right_cancel $
(prefix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ take_prefix _ _⟩
theorem suffix_iff_eq_drop {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ l₁ = drop (length l₂ - length l₁) l₂ :=
⟨λ h, append_left_cancel $
(suffix_iff_eq_append.1 h).trans (take_append_drop _ _).symm,
λ e, e.symm ▸ drop_suffix _ _⟩
instance decidable_prefix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <+: l₂)
| [] l₂ := is_true ⟨l₂, rfl⟩
| (a::l₁) [] := is_false $ λ ⟨t, te⟩, list.no_confusion te
| (a::l₁) (b::l₂) :=
if h : a = b then
@decidable_of_iff _ _ (by rw [← h, prefix_cons_inj])
(decidable_prefix l₁ l₂)
else
is_false $ λ ⟨t, te⟩, h $ by injection te
-- Alternatively, use mem_tails
instance decidable_suffix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+ l₂)
| [] l₂ := is_true ⟨l₂, append_nil _⟩
| (a::l₁) [] := is_false $ mt (length_le_of_sublist ∘ sublist_of_suffix) dec_trivial
| l₁ l₂ := let len1 := length l₁, len2 := length l₂ in
if hl : len1 ≤ len2 then
decidable_of_iff' (l₁ = drop (len2-len1) l₂) suffix_iff_eq_drop
else is_false $ λ h, hl $ length_le_of_sublist $ sublist_of_suffix h
@[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t
| s [] := suffices s = nil ↔ s <+: nil, by simpa only [inits, mem_singleton],
⟨λh, h.symm ▸ prefix_refl [], eq_nil_of_prefix_nil⟩
| s (a::t) :=
suffices (s = nil ∨ ∃ l ∈ inits t, a :: l = s) ↔ s <+: a :: t, by simpa,
⟨λo, match s, o with
| ._, or.inl rfl := ⟨_, rfl⟩
| s, or.inr ⟨r, hr, hs⟩ := let ⟨s, ht⟩ := (mem_inits _ _).1 hr in
by rw [← hs, ← ht]; exact ⟨s, rfl⟩
end, λmi, match s, mi with
| [], ⟨._, rfl⟩ := or.inl rfl
| (b::s), ⟨r, hr⟩ := list.no_confusion hr $ λba (st : s++r = t), or.inr $
by rw ba; exact ⟨_, (mem_inits _ _).2 ⟨_, st⟩, rfl⟩
end⟩
@[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t
| s [] := by simp only [tails, mem_singleton];
exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩
| s (a::t) := by simp only [tails, mem_cons_iff, mem_tails s t];
exact show s = a :: t ∨ s <:+ t ↔ s <:+ a :: t, from
⟨λo, match s, t, o with
| ._, t, or.inl rfl := suffix_refl _
| s, ._, or.inr ⟨l, rfl⟩ := ⟨a::l, rfl⟩
end, λe, match s, t, e with
| ._, t, ⟨[], rfl⟩ := or.inl rfl
| s, t, ⟨b::l, he⟩ := list.no_confusion he (λab lt, or.inr ⟨l, lt⟩)
end⟩
instance decidable_infix [decidable_eq α] : ∀ (l₁ l₂ : list α), decidable (l₁ <:+: l₂)
| [] l₂ := is_true ⟨[], l₂, rfl⟩
| (a::l₁) [] := is_false $ λ⟨s, t, te⟩, absurd te $ append_ne_nil_of_ne_nil_left _ _ $
append_ne_nil_of_ne_nil_right _ _ $ λh, list.no_confusion h
| l₁ l₂ := decidable_of_decidable_of_iff (list.decidable_bex (λt, l₁ <+: t) (tails l₂)) $
by refine (exists_congr (λt, _)).trans (infix_iff_prefix_suffix _ _).symm;
exact ⟨λ⟨h1, h2⟩, ⟨h2, (mem_tails _ _).1 h1⟩, λ⟨h2, h1⟩, ⟨(mem_tails _ _).2 h1, h2⟩⟩
/-! ### sublists -/
@[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl
@[simp, priority 1100] theorem sublists'_singleton (a : α) : sublists' [a] = [[], [a]] := rfl
theorem map_sublists'_aux (g : list β → list γ) (l : list α) (f r) :
map g (sublists'_aux l f r) = sublists'_aux l (g ∘ f) (map g r) :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_append (r' : list (list β)) (l : list α) (f r) :
sublists'_aux l f (r ++ r') = sublists'_aux l f r ++ r' :=
by induction l generalizing f r; [refl, simp only [*, sublists'_aux]]
theorem sublists'_aux_eq_sublists' (l f r) :
@sublists'_aux α β l f r = map f (sublists' l) ++ r :=
by rw [sublists', map_sublists'_aux, ← sublists'_aux_append]; refl
@[simp] theorem sublists'_cons (a : α) (l : list α) :
sublists' (a :: l) = sublists' l ++ map (cons a) (sublists' l) :=
by rw [sublists', sublists'_aux]; simp only [sublists'_aux_eq_sublists', map_id, append_nil]; refl
@[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t :=
begin
induction t with a t IH generalizing s,
{ simp only [sublists'_nil, mem_singleton],
exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ },
simp only [sublists'_cons, mem_append, IH, mem_map],
split; intro h, rcases h with h | ⟨s, h, rfl⟩,
{ exact sublist_cons_of_sublist _ h },
{ exact cons_sublist_cons _ h },
{ cases h with _ _ _ h s _ _ h,
{ exact or.inl h },
{ exact or.inr ⟨s, h, rfl⟩ } }
end
@[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l
| [] := rfl
| (a::l) := by simp only [sublists'_cons, length_append, length_sublists' l, length_map,
length, pow_succ', mul_succ, mul_zero, zero_add]
@[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl
@[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl
theorem sublists_aux₁_eq_sublists_aux : ∀ l (f : list α → list β),
sublists_aux₁ l f = sublists_aux l (λ ys r, f ys ++ r)
| [] f := rfl
| (a::l) f := by rw [sublists_aux₁, sublists_aux]; simp only [*, append_assoc]
theorem sublists_aux_cons_eq_sublists_aux₁ (l : list α) :
sublists_aux l cons = sublists_aux₁ l (λ x, [x]) :=
by rw [sublists_aux₁_eq_sublists_aux]; refl
theorem sublists_aux_eq_foldr.aux {a : α} {l : list α}
(IH₁ : ∀ (f : list α → list β → list β), sublists_aux l f = foldr f [] (sublists_aux l cons))
(IH₂ : ∀ (f : list α → list (list α) → list (list α)),
sublists_aux l f = foldr f [] (sublists_aux l cons))
(f : list α → list β → list β) : sublists_aux (a::l) f = foldr f [] (sublists_aux (a::l) cons) :=
begin
simp only [sublists_aux, foldr_cons], rw [IH₂, IH₁], congr' 1,
induction sublists_aux l cons with _ _ ih, {refl},
simp only [ih, foldr_cons]
end
theorem sublists_aux_eq_foldr (l : list α) : ∀ (f : list α → list β → list β),
sublists_aux l f = foldr f [] (sublists_aux l cons) :=
suffices _ ∧ ∀ f : list α → list (list α) → list (list α),
sublists_aux l f = foldr f [] (sublists_aux l cons),
from this.1,
begin
induction l with a l IH, {split; intro; refl},
exact ⟨sublists_aux_eq_foldr.aux IH.1 IH.2,
sublists_aux_eq_foldr.aux IH.2 IH.2⟩
end
theorem sublists_aux_cons_cons (l : list α) (a : α) :
sublists_aux (a::l) cons = [a] :: foldr (λys r, ys :: (a :: ys) :: r) [] (sublists_aux l cons) :=
by rw [← sublists_aux_eq_foldr]; refl
theorem sublists_aux₁_append : ∀ (l₁ l₂ : list α) (f : list α → list β),
sublists_aux₁ (l₁ ++ l₂) f = sublists_aux₁ l₁ f ++
sublists_aux₁ l₂ (λ x, f x ++ sublists_aux₁ l₁ (f ∘ (++ x)))
| [] l₂ f := by simp only [sublists_aux₁, nil_append, append_nil]
| (a::l₁) l₂ f := by simp only [sublists_aux₁, cons_append, sublists_aux₁_append l₁, append_assoc];
refl
theorem sublists_aux₁_concat (l : list α) (a : α) (f : list α → list β) :
sublists_aux₁ (l ++ [a]) f = sublists_aux₁ l f ++
f [a] ++ sublists_aux₁ l (λ x, f (x ++ [a])) :=
by simp only [sublists_aux₁_append, sublists_aux₁, append_assoc, append_nil]
theorem sublists_aux₁_bind : ∀ (l : list α)
(f : list α → list β) (g : β → list γ),
(sublists_aux₁ l f).bind g = sublists_aux₁ l (λ x, (f x).bind g)
| [] f g := rfl
| (a::l) f g := by simp only [sublists_aux₁, bind_append, sublists_aux₁_bind l]
theorem sublists_aux_cons_append (l₁ l₂ : list α) :
sublists_aux (l₁ ++ l₂) cons = sublists_aux l₁ cons ++
(do x ← sublists_aux l₂ cons, (++ x) <$> sublists l₁) :=
begin
simp only [sublists, sublists_aux_cons_eq_sublists_aux₁, sublists_aux₁_append, bind_eq_bind,
sublists_aux₁_bind],
congr, funext x, apply congr_arg _,
rw [← bind_ret_eq_map, sublists_aux₁_bind], exact (append_nil _).symm
end
theorem sublists_append (l₁ l₂ : list α) :
sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) :=
by simp only [map, sublists, sublists_aux_cons_append, map_eq_map, bind_eq_bind,
cons_bind, map_id', append_nil, cons_append, map_id' (λ _, rfl)]; split; refl
@[simp] theorem sublists_concat (l : list α) (a : α) :
sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) :=
by rw [sublists_append, sublists_singleton, bind_eq_bind, cons_bind, cons_bind, nil_bind,
map_eq_map, map_eq_map, map_id' (append_nil), append_nil]
theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) :=
by induction l with hd tl ih; [refl,
simp only [reverse_cons, sublists_append, sublists'_cons, map_append, ih, sublists_singleton,
map_eq_map, bind_eq_bind, map_map, cons_bind, append_nil, nil_bind, (∘)]]
theorem sublists_eq_sublists' (l : list α) : sublists l = map reverse (sublists' (reverse l)) :=
by rw [← sublists_reverse, reverse_reverse]
theorem sublists'_reverse (l : list α) : sublists' (reverse l) = map reverse (sublists l) :=
by simp only [sublists_eq_sublists', map_map, map_id' (reverse_reverse)]
theorem sublists'_eq_sublists (l : list α) : sublists' l = map reverse (sublists (reverse l)) :=
by rw [← sublists'_reverse, reverse_reverse]
theorem sublists_aux_ne_nil : ∀ (l : list α), [] ∉ sublists_aux l cons
| [] := id
| (a::l) := begin
rw [sublists_aux_cons_cons],
refine not_mem_cons_of_ne_of_not_mem (cons_ne_nil _ _).symm _,
have := sublists_aux_ne_nil l, revert this,
induction sublists_aux l cons; intro, {rwa foldr},
simp only [foldr, mem_cons_iff, false_or, not_or_distrib],
exact ⟨ne_of_not_mem_cons this, ih (not_mem_of_not_mem_cons this)⟩
end
@[simp] theorem mem_sublists {s t : list α} : s ∈ sublists t ↔ s <+ t :=
by rw [← reverse_sublist_iff, ← mem_sublists',
sublists'_reverse, mem_map_of_injective reverse_injective]
@[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l :=
by simp only [sublists_eq_sublists', length_map, length_sublists', length_reverse]
theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l :=
reverse_rec_on l (nil_sublist _) $
λ l a IH, by simp only [map, map_append, sublists_concat]; exact
((append_sublist_append_left _).2 $ singleton_sublist.2 $
mem_map.2 ⟨[], mem_sublists.2 (nil_sublist _), by refl⟩).trans
((append_sublist_append_right _).2 IH)
/-! ### sublists_len -/
/-- Auxiliary function to construct the list of all sublists of a given length. Given an
integer `n`, a list `l`, a function `f` and an auxiliary list `L`, it returns the list made of
of `f` applied to all sublists of `l` of length `n`, concatenated with `L`. -/
def sublists_len_aux {α β : Type*} : ℕ → list α → (list α → β) → list β → list β
| 0 l f r := f [] :: r
| (n+1) [] f r := r
| (n+1) (a::l) f r := sublists_len_aux (n + 1) l f
(sublists_len_aux n l (f ∘ list.cons a) r)
/-- The list of all sublists of a list `l` that are of length `n`. For instance, for
`l = [0, 1, 2, 3]` and `n = 2`, one gets
`[[2, 3], [1, 3], [1, 2], [0, 3], [0, 2], [0, 1]]`. -/
def sublists_len {α : Type*} (n : ℕ) (l : list α) : list (list α) :=
sublists_len_aux n l id []
lemma sublists_len_aux_append {α β γ : Type*} :
∀ (n : ℕ) (l : list α) (f : list α → β) (g : β → γ) (r : list β) (s : list γ),
sublists_len_aux n l (g ∘ f) (r.map g ++ s) =
(sublists_len_aux n l f r).map g ++ s
| 0 l f g r s := rfl
| (n+1) [] f g r s := rfl
| (n+1) (a::l) f g r s := begin
unfold sublists_len_aux,
rw [show ((g ∘ f) ∘ list.cons a) = (g ∘ f ∘ list.cons a), by refl,
sublists_len_aux_append, sublists_len_aux_append]
end
lemma sublists_len_aux_eq {α β : Type*} (l : list α) (n) (f : list α → β) (r) :
sublists_len_aux n l f r = (sublists_len n l).map f ++ r :=
by rw [sublists_len, ← sublists_len_aux_append]; refl
lemma sublists_len_aux_zero {α : Type*} (l : list α) (f : list α → β) (r) :
sublists_len_aux 0 l f r = f [] :: r := by cases l; refl
@[simp] lemma sublists_len_zero {α : Type*} (l : list α) :
sublists_len 0 l = [[]] := sublists_len_aux_zero _ _ _
@[simp] lemma sublists_len_succ_nil {α : Type*} (n) :
sublists_len (n+1) (@nil α) = [] := rfl
@[simp] lemma sublists_len_succ_cons {α : Type*} (n) (a : α) (l) :
sublists_len (n + 1) (a::l) =
sublists_len (n + 1) l ++ (sublists_len n l).map (cons a) :=
by rw [sublists_len, sublists_len_aux, sublists_len_aux_eq,
sublists_len_aux_eq, map_id, append_nil]; refl
@[simp] lemma length_sublists_len {α : Type*} : ∀ n (l : list α),
length (sublists_len n l) = nat.choose (length l) n
| 0 l := by simp
| (n+1) [] := by simp
| (n+1) (a::l) := by simp [-add_comm, nat.choose, *]; apply add_comm
lemma sublists_len_sublist_sublists' {α : Type*} : ∀ n (l : list α),
sublists_len n l <+ sublists' l
| 0 l := singleton_sublist.2 (mem_sublists'.2 (nil_sublist _))
| (n+1) [] := nil_sublist _
| (n+1) (a::l) := begin
rw [sublists_len_succ_cons, sublists'_cons],
exact (sublists_len_sublist_sublists' _ _).append
((sublists_len_sublist_sublists' _ _).map _)
end
lemma sublists_len_sublist_of_sublist
{α : Type*} (n) {l₁ l₂ : list α} (h : l₁ <+ l₂) : sublists_len n l₁ <+ sublists_len n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction h with l₁ l₂ a s IH l₁ l₂ a s IH, {refl},
{ refine IH.trans _,
rw sublists_len_succ_cons,
apply sublist_append_left },
{ simp [sublists_len_succ_cons],
exact IH.append ((IHn s).map _) }
end
lemma length_of_sublists_len {α : Type*} : ∀ {n} {l l' : list α},
l' ∈ sublists_len n l → length l' = n
| 0 l l' (or.inl rfl) := rfl
| (n+1) (a::l) l' h := begin
rw [sublists_len_succ_cons, mem_append, mem_map] at h,
rcases h with h | ⟨l', h, rfl⟩,
{ exact length_of_sublists_len h },
{ exact congr_arg (+1) (length_of_sublists_len h) },
end
lemma mem_sublists_len_self {α : Type*} {l l' : list α}
(h : l' <+ l) : l' ∈ sublists_len (length l') l :=
begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH,
{ exact or.inl rfl },
{ cases l₁ with b l₁,
{ exact or.inl rfl },
{ rw [length, sublists_len_succ_cons],
exact mem_append_left _ IH } },
{ rw [length, sublists_len_succ_cons],
exact mem_append_right _ (mem_map.2 ⟨_, IH, rfl⟩) }
end
@[simp] lemma mem_sublists_len {α : Type*} {n} {l l' : list α} :
l' ∈ sublists_len n l ↔ l' <+ l ∧ length l' = n :=
⟨λ h, ⟨mem_sublists'.1
((sublists_len_sublist_sublists' _ _).subset h),
length_of_sublists_len h⟩,
λ ⟨h₁, h₂⟩, h₂ ▸ mem_sublists_len_self h₁⟩
/-! ### permutations -/
section permutations
@[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] theorem permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
end permutations
/-! ### insert -/
section insert
variable [decidable_eq α]
@[simp] theorem insert_nil (a : α) : insert a nil = [a] := rfl
theorem insert.def (a : α) (l : list α) : insert a l = if a ∈ l then l else a :: l := rfl
@[simp, priority 980]
theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l :=
by simp only [insert.def, if_pos h]
@[simp, priority 970]
theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l :=
by simp only [insert.def, if_neg h]; split; refl
@[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l :=
begin
by_cases h' : b ∈ l,
{ simp only [insert_of_mem h'],
apply (or_iff_right_of_imp _).symm,
exact λ e, e.symm ▸ h' },
simp only [insert_of_not_mem h', mem_cons_iff]
end
@[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l :=
by by_cases a ∈ l; [simp only [insert_of_mem h], simp only [insert_of_not_mem h, suffix_cons]]
@[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l :=
mem_insert_iff.2 (or.inl rfl)
theorem mem_insert_of_mem {a b : α} {l : list α} (h : a ∈ l) : a ∈ insert b l :=
mem_insert_iff.2 (or.inr h)
theorem eq_or_mem_of_mem_insert {a b : α} {l : list α} (h : a ∈ insert b l) : a = b ∨ a ∈ l :=
mem_insert_iff.1 h
@[simp] theorem length_insert_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (insert a l) = length l :=
by rw insert_of_mem h
@[simp] theorem length_insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) :
length (insert a l) = length l + 1 :=
by rw insert_of_not_mem h; refl
end insert
/-! ### erasep -/
section erasep
variables {p : α → Prop} [decidable_pred p]
@[simp] theorem erasep_nil : [].erasep p = [] := rfl
theorem erasep_cons (a : α) (l : list α) :
(a :: l).erasep p = if p a then l else a :: l.erasep p := rfl
@[simp] theorem erasep_cons_of_pos {a : α} {l : list α} (h : p a) : (a :: l).erasep p = l :=
by simp [erasep_cons, h]
@[simp] theorem erasep_cons_of_neg {a : α} {l : list α} (h : ¬ p a) :
(a::l).erasep p = a :: l.erasep p :=
by simp [erasep_cons, h]
theorem erasep_of_forall_not {l : list α}
(h : ∀ a ∈ l, ¬ p a) : l.erasep p = l :=
by induction l with _ _ ih; [refl,
simp [h _ (or.inl rfl), ih (forall_mem_of_forall_mem_cons h)]]
theorem exists_of_erasep {l : list α} {a} (al : a ∈ l) (pa : p a) :
∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
induction l with b l IH, {cases al},
by_cases pb : p b,
{ exact ⟨b, [], l, forall_mem_nil _, pb, by simp [pb]⟩ },
{ rcases al with rfl | al, {exact pb.elim pa},
rcases IH al with ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
exact ⟨c, b::l₁, l₂, forall_mem_cons.2 ⟨pb, h₁⟩,
h₂, by rw h₃; refl, by simp [pb, h₄]⟩ }
end
theorem exists_or_eq_self_of_erasep (p : α → Prop) [decidable_pred p] (l : list α) :
l.erasep p = l ∨ ∃ a l₁ l₂, (∀ b ∈ l₁, ¬ p b) ∧ p a ∧ l = l₁ ++ a :: l₂ ∧ l.erasep p = l₁ ++ l₂ :=
begin
by_cases h : ∃ a ∈ l, p a,
{ rcases h with ⟨a, ha, pa⟩,
exact or.inr (exists_of_erasep ha pa) },
{ simp at h, exact or.inl (erasep_of_forall_not h) }
end
@[simp] theorem length_erasep_of_mem {l : list α} {a} (al : a ∈ l) (pa : p a) :
length (l.erasep p) = pred (length l) :=
by rcases exists_of_erasep al pa with ⟨_, l₁, l₂, _, _, e₁, e₂⟩;
rw e₂; simp [-add_comm, e₁]; refl
theorem erasep_append_left {a : α} (pa : p a) :
∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erasep p = l₁.erasep p ++ l₂
| (x::xs) l₂ h := begin
by_cases h' : p x; simp [h'],
rw erasep_append_left l₂ (mem_of_ne_of_mem (mt _ h') h),
rintro rfl, exact pa
end
theorem erasep_append_right :
∀ {l₁ : list α} (l₂), (∀ b ∈ l₁, ¬ p b) → (l₁++l₂).erasep p = l₁ ++ l₂.erasep p
| [] l₂ h := rfl
| (x::xs) l₂ h := by simp [(forall_mem_cons.1 h).1,
erasep_append_right _ (forall_mem_cons.1 h).2]
theorem erasep_sublist (l : list α) : l.erasep p <+ l :=
by rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩;
[rw h, {rw [h₄, h₃], simp}]
theorem erasep_subset (l : list α) : l.erasep p ⊆ l :=
(erasep_sublist l).subset
theorem sublist.erasep {l₁ l₂ : list α} (s : l₁ <+ l₂) : l₁.erasep p <+ l₂.erasep p :=
begin
induction s,
case list.sublist.slnil { refl },
case list.sublist.cons : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [IH.trans (erasep_sublist _), IH.cons _ _ _] },
case list.sublist.cons2 : l₁ l₂ a s IH {
by_cases h : p a; simp [h],
exacts [s, IH.cons2 _ _ _] }
end
theorem mem_of_mem_erasep {a : α} {l : list α} : a ∈ l.erasep p → a ∈ l :=
@erasep_subset _ _ _ _ _
@[simp] theorem mem_erasep_of_neg {a : α} {l : list α} (pa : ¬ p a) : a ∈ l.erasep p ↔ a ∈ l :=
⟨mem_of_mem_erasep, λ al, begin
rcases exists_or_eq_self_of_erasep p l with h | ⟨c, l₁, l₂, h₁, h₂, h₃, h₄⟩,
{ rwa h },
{ rw h₄, rw h₃ at al,
have : a ≠ c, {rintro rfl, exact pa.elim h₂},
simpa [this] using al }
end⟩
theorem erasep_map (f : β → α) :
∀ (l : list β), (map f l).erasep p = map f (l.erasep (p ∘ f))
| [] := rfl
| (b::l) := by by_cases p (f b); simp [h, erasep_map l]
@[simp] theorem extractp_eq_find_erasep :
∀ l : list α, extractp p l = (find p l, erasep p l)
| [] := rfl
| (a::l) := by by_cases pa : p a; simp [extractp, pa, extractp_eq_find_erasep l]
end erasep
/-! ### erase -/
section erase
variable [decidable_eq α]
@[simp] theorem erase_nil (a : α) : [].erase a = [] := rfl
theorem erase_cons (a b : α) (l : list α) :
(b :: l).erase a = if b = a then l else b :: l.erase a := rfl
@[simp] theorem erase_cons_head (a : α) (l : list α) : (a :: l).erase a = l :=
by simp only [erase_cons, if_pos rfl]
@[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) :
(b::l).erase a = b :: l.erase a :=
by simp only [erase_cons, if_neg h]; split; refl
theorem erase_eq_erasep (a : α) (l : list α) : l.erase a = l.erasep (eq a) :=
by { induction l with b l, {refl},
by_cases a = b; [simp [h], simp [h, ne.symm h, *]] }
@[simp, priority 980]
theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l :=
by rw [erase_eq_erasep, erasep_of_forall_not]; rintro b h' rfl; exact h h'
theorem exists_erase_eq {a : α} {l : list α} (h : a ∈ l) :
∃ l₁ l₂, a ∉ l₁ ∧ l = l₁ ++ a :: l₂ ∧ l.erase a = l₁ ++ l₂ :=
by rcases exists_of_erasep h rfl with ⟨_, l₁, l₂, h₁, rfl, h₂, h₃⟩;
rw erase_eq_erasep; exact ⟨l₁, l₂, λ h, h₁ _ h rfl, h₂, h₃⟩
@[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) :
length (l.erase a) = pred (length l) :=
by rw erase_eq_erasep; exact length_erasep_of_mem h rfl
theorem erase_append_left {a : α} {l₁ : list α} (l₂) (h : a ∈ l₁) :
(l₁++l₂).erase a = l₁.erase a ++ l₂ :=
by simp [erase_eq_erasep]; exact erasep_append_left (by refl) l₂ h
theorem erase_append_right {a : α} {l₁ : list α} (l₂) (h : a ∉ l₁) :
(l₁++l₂).erase a = l₁ ++ l₂.erase a :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_append_right];
rintro b h' rfl; exact h h'
theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l :=
by rw erase_eq_erasep; apply erasep_sublist
theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l :=
(erase_sublist a l).subset
theorem sublist.erase (a : α) {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.erase a <+ l₂.erase a :=
by simp [erase_eq_erasep]; exact sublist.erasep h
theorem mem_of_mem_erase {a b : α} {l : list α} : a ∈ l.erase b → a ∈ l :=
@erase_subset _ _ _ _ _
@[simp] theorem mem_erase_of_ne {a b : α} {l : list α} (ab : a ≠ b) : a ∈ l.erase b ↔ a ∈ l :=
by rw erase_eq_erasep; exact mem_erasep_of_neg ab.symm
theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a :=
if ab : a = b then by rw ab else
if ha : a ∈ l then
if hb : b ∈ l then match l, l.erase a, exists_erase_eq ha, hb with
| ._, ._, ⟨l₁, l₂, ha', rfl, rfl⟩, hb :=
if h₁ : b ∈ l₁ then
by rw [erase_append_left _ h₁, erase_append_left _ h₁,
erase_append_right _ (mt mem_of_mem_erase ha'), erase_cons_head]
else
by rw [erase_append_right _ h₁, erase_append_right _ h₁, erase_append_right _ ha',
erase_cons_tail _ ab, erase_cons_head]
end
else by simp only [erase_of_not_mem hb, erase_of_not_mem (mt mem_of_mem_erase hb)]
else by simp only [erase_of_not_mem ha, erase_of_not_mem (mt mem_of_mem_erase ha)]
theorem map_erase [decidable_eq β] {f : α → β} (finj : injective f) {a : α}
(l : list α) : map f (l.erase a) = (map f l).erase (f a) :=
by rw [erase_eq_erasep, erase_eq_erasep, erasep_map]; congr;
ext b; simp [finj.eq_iff]
theorem map_foldl_erase [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (foldl list.erase l₁ l₂) = foldl (λ l a, l.erase (f a)) (map f l₁) l₂ :=
by induction l₂ generalizing l₁; [refl,
simp only [foldl_cons, map_erase finj, *]]
@[simp] theorem count_erase_self (a : α) :
∀ (s : list α), count a (list.erase s a) = pred (count a s)
| [] := by simp
| (h :: t) :=
begin
rw erase_cons,
by_cases p : h = a,
{ rw [if_pos p, count_cons', if_pos p.symm], simp },
{ rw [if_neg p, count_cons', count_cons', if_neg (λ x : a = h, p x.symm), count_erase_self],
simp, }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) :
∀ (s : list α), count a (list.erase s b) = count a s
| [] := by simp
| (x :: xs) :=
begin
rw erase_cons,
split_ifs with h,
{ rw [count_cons', h, if_neg ab], simp },
{ rw [count_cons', count_cons', count_erase_of_ne] }
end
end erase
/-! ### diff -/
section diff
variable [decidable_eq α]
@[simp] theorem diff_nil (l : list α) : l.diff [] = l := rfl
@[simp] theorem diff_cons (l₁ l₂ : list α) (a : α) : l₁.diff (a::l₂) = (l₁.erase a).diff l₂ :=
if h : a ∈ l₁ then by simp only [list.diff, if_pos h]
else by simp only [list.diff, if_neg h, erase_of_not_mem h]
@[simp] theorem nil_diff (l : list α) : [].diff l = [] :=
by induction l; [refl, simp only [*, diff_cons, erase_of_not_mem (not_mem_nil _)]]
theorem diff_eq_foldl : ∀ (l₁ l₂ : list α), l₁.diff l₂ = foldl list.erase l₁ l₂
| l₁ [] := rfl
| l₁ (a::l₂) := (diff_cons l₁ l₂ a).trans (diff_eq_foldl _ _)
@[simp] theorem diff_append (l₁ l₂ l₃ : list α) : l₁.diff (l₂ ++ l₃) = (l₁.diff l₂).diff l₃ :=
by simp only [diff_eq_foldl, foldl_append]
@[simp] theorem map_diff [decidable_eq β] {f : α → β} (finj : injective f) {l₁ l₂ : list α} :
map f (l₁.diff l₂) = (map f l₁).diff (map f l₂) :=
by simp only [diff_eq_foldl, foldl_map, map_foldl_erase finj]
theorem diff_sublist : ∀ l₁ l₂ : list α, l₁.diff l₂ <+ l₁
| l₁ [] := sublist.refl _
| l₁ (a::l₂) := calc l₁.diff (a :: l₂) = (l₁.erase a).diff l₂ : diff_cons _ _ _
... <+ l₁.erase a : diff_sublist _ _
... <+ l₁ : list.erase_sublist _ _
theorem diff_subset (l₁ l₂ : list α) : l₁.diff l₂ ⊆ l₁ :=
(diff_sublist _ _).subset
theorem mem_diff_of_mem {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁ → a ∉ l₂ → a ∈ l₁.diff l₂
| l₁ [] h₁ h₂ := h₁
| l₁ (b::l₂) h₁ h₂ := by rw diff_cons; exact
mem_diff_of_mem ((mem_erase_of_ne (ne_of_not_mem_cons h₂)).2 h₁) (not_mem_of_not_mem_cons h₂)
theorem sublist.diff_right : ∀ {l₁ l₂ l₃: list α}, l₁ <+ l₂ → l₁.diff l₃ <+ l₂.diff l₃
| l₁ l₂ [] h := h
| l₁ l₂ (a::l₃) h := by simp only
[diff_cons, (h.erase _).diff_right]
theorem erase_diff_erase_sublist_of_sublist {a : α} : ∀ {l₁ l₂ : list α},
l₁ <+ l₂ → (l₂.erase a).diff (l₁.erase a) <+ l₂.diff l₁
| [] l₂ h := erase_sublist _ _
| (b::l₁) l₂ h := if heq : b = a then by simp only [heq, erase_cons_head, diff_cons]
else by simpa only [erase_cons_head, erase_cons_tail _ heq, diff_cons,
erase_comm a b l₂]
using erase_diff_erase_sublist_of_sublist (h.erase b)
end diff
/-! ### enum -/
theorem length_enum_from : ∀ n (l : list α), length (enum_from n l) = length l
| n [] := rfl
| n (a::l) := congr_arg nat.succ (length_enum_from _ _)
theorem length_enum : ∀ (l : list α), length (enum l) = length l := length_enum_from _
@[simp] theorem enum_from_nth : ∀ n (l : list α) m,
nth (enum_from n l) m = (λ a, (n + m, a)) <$> nth l m
| n [] m := rfl
| n (a :: l) 0 := rfl
| n (a :: l) (m+1) := (enum_from_nth (n+1) l m).trans $
by rw [add_right_comm]; refl
@[simp] theorem enum_nth : ∀ (l : list α) n,
nth (enum l) n = (λ a, (n, a)) <$> nth l n :=
by simp only [enum, enum_from_nth, zero_add]; intros; refl
@[simp] theorem enum_from_map_snd : ∀ n (l : list α),
map prod.snd (enum_from n l) = l
| n [] := rfl
| n (a :: l) := congr_arg (cons _) (enum_from_map_snd _ _)
@[simp] theorem enum_map_snd : ∀ (l : list α),
map prod.snd (enum l) = l := enum_from_map_snd _
theorem mem_enum_from {x : α} {i : ℕ} :
∀ {j : ℕ} (xs : list α), (i, x) ∈ xs.enum_from j → j ≤ i ∧ i < j + xs.length ∧ x ∈ xs
| j [] := by simp [enum_from]
| j (y :: ys) :=
suffices i = j ∧ x = y ∨ (i, x) ∈ enum_from (j + 1) ys →
j ≤ i ∧ i < j + (length ys + 1) ∧ (x = y ∨ x ∈ ys),
by simpa [enum_from, mem_enum_from ys],
begin
rintro (h|h),
{ refine ⟨le_of_eq h.1.symm,h.1 ▸ _,or.inl h.2⟩,
apply nat.lt_add_of_pos_right; simp },
{ obtain ⟨hji, hijlen, hmem⟩ := mem_enum_from _ h,
refine ⟨_, _, _⟩,
{ exact le_trans (nat.le_succ _) hji },
{ convert hijlen using 1, ac_refl },
{ simp [hmem] } }
end
/-! ### product -/
@[simp] theorem nil_product (l : list β) : product (@nil α) l = [] := rfl
@[simp] theorem product_cons (a : α) (l₁ : list α) (l₂ : list β)
: product (a::l₁) l₂ = map (λ b, (a, b)) l₂ ++ product l₁ l₂ := rfl
@[simp] theorem product_nil : ∀ (l : list α), product l (@nil β) = []
| [] := rfl
| (a::l) := by rw [product_cons, product_nil]; refl
@[simp] theorem mem_product {l₁ : list α} {l₂ : list β} {a : α} {b : β} :
(a, b) ∈ product l₁ l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ :=
by simp only [product, mem_bind, mem_map, prod.ext_iff, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, exists_eq_right]
theorem length_product (l₁ : list α) (l₂ : list β) :
length (product l₁ l₂) = length l₁ * length l₂ :=
by induction l₁ with x l₁ IH; [exact (zero_mul _).symm,
simp only [length, product_cons, length_append, IH,
right_distrib, one_mul, length_map, add_comm]]
/-! ### sigma -/
section
variable {σ : α → Type*}
@[simp] theorem nil_sigma (l : Π a, list (σ a)) : (@nil α).sigma l = [] := rfl
@[simp] theorem sigma_cons (a : α) (l₁ : list α) (l₂ : Π a, list (σ a))
: (a::l₁).sigma l₂ = map (sigma.mk a) (l₂ a) ++ l₁.sigma l₂ := rfl
@[simp] theorem sigma_nil : ∀ (l : list α), l.sigma (λ a, @nil (σ a)) = []
| [] := rfl
| (a::l) := by rw [sigma_cons, sigma_nil]; refl
@[simp] theorem mem_sigma {l₁ : list α} {l₂ : Π a, list (σ a)} {a : α} {b : σ a} :
sigma.mk a b ∈ l₁.sigma l₂ ↔ a ∈ l₁ ∧ b ∈ l₂ a :=
by simp only [list.sigma, mem_bind, mem_map, exists_prop, exists_and_distrib_left,
and.left_comm, exists_eq_left, heq_iff_eq, exists_eq_right]
theorem length_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
length (l₁.sigma l₂) = (l₁.map (λ a, length (l₂ a))).sum :=
by induction l₁ with x l₁ IH; [refl,
simp only [map, sigma_cons, length_append, length_map, IH, sum_cons]]
end
/-! ### disjoint -/
section disjoint
theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁
| a i₂ i₁ := d i₁ i₂
theorem disjoint_comm {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ disjoint l₂ l₁ :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₁ → a ∉ l₂ := iff.rfl
theorem disjoint_right {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ {a}, a ∈ l₂ → a ∉ l₁ :=
disjoint_comm
theorem disjoint_iff_ne {l₁ l₂ : list α} : disjoint l₁ l₂ ↔ ∀ a ∈ l₁, ∀ b ∈ l₂, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {l₁ l₂ l : list α} (ss : l₁ ⊆ l) (d : disjoint l l₂) :
disjoint l₁ l₂
| x m₁ := d (ss m₁)
theorem disjoint_of_subset_right {l₁ l₂ l : list α} (ss : l₂ ⊆ l) (d : disjoint l₁ l) :
disjoint l₁ l₂
| x m m₁ := d m (ss m₁)
theorem disjoint_of_disjoint_cons_left {a : α} {l₁ l₂} : disjoint (a::l₁) l₂ → disjoint l₁ l₂ :=
disjoint_of_subset_left (list.subset_cons _ _)
theorem disjoint_of_disjoint_cons_right {a : α} {l₁ l₂} : disjoint l₁ (a::l₂) → disjoint l₁ l₂ :=
disjoint_of_subset_right (list.subset_cons _ _)
@[simp] theorem disjoint_nil_left (l : list α) : disjoint [] l
| a := (not_mem_nil a).elim
@[simp] theorem disjoint_nil_right (l : list α) : disjoint l [] :=
by rw disjoint_comm; exact disjoint_nil_left _
@[simp, priority 1100] theorem singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l :=
by simp only [disjoint, mem_singleton, forall_eq]; refl
@[simp, priority 1100] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l :=
by rw disjoint_comm; simp only [singleton_disjoint]
@[simp] theorem disjoint_append_left {l₁ l₂ l : list α} :
disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l :=
by simp only [disjoint, mem_append, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_append_right {l₁ l₂ l : list α} :
disjoint l (l₁++l₂) ↔ disjoint l l₁ ∧ disjoint l l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {l₁ l₂ : list α} :
disjoint (a::l₁) l₂ ↔ a ∉ l₂ ∧ disjoint l₁ l₂ :=
(@disjoint_append_left _ [a] l₁ l₂).trans $ by simp only [singleton_disjoint]
@[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} :
disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ :=
disjoint_comm.trans $ by simp only [disjoint_comm, disjoint_cons_left]
theorem disjoint_of_disjoint_append_left_left {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₁ l :=
(disjoint_append_left.1 d).1
theorem disjoint_of_disjoint_append_left_right {l₁ l₂ l : list α} (d : disjoint (l₁++l₂) l) :
disjoint l₂ l :=
(disjoint_append_left.1 d).2
theorem disjoint_of_disjoint_append_right_left {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₁ :=
(disjoint_append_right.1 d).1
theorem disjoint_of_disjoint_append_right_right {l₁ l₂ l : list α} (d : disjoint l (l₁++l₂)) :
disjoint l l₂ :=
(disjoint_append_right.1 d).2
theorem disjoint_take_drop {l : list α} {m n : ℕ} (hl : l.nodup) (h : m ≤ n) :
disjoint (l.take m) (l.drop n) :=
begin
induction l generalizing m n,
case list.nil : m n
{ simp },
case list.cons : x xs xs_ih m n
{ cases m; cases n; simp only [disjoint_cons_left, mem_cons_iff, disjoint_cons_right, drop,
true_or, eq_self_iff_true, not_true, false_and,
disjoint_nil_left, take],
{ cases h },
cases hl with _ _ h₀ h₁, split,
{ intro h, exact h₀ _ (mem_of_mem_drop h) rfl, },
solve_by_elim [le_of_succ_le_succ] { max_depth := 4 } },
end
end disjoint
/-! ### union -/
section union
variable [decidable_eq α]
@[simp] theorem nil_union (l : list α) : [] ∪ l = l := rfl
@[simp] theorem cons_union (l₁ l₂ : list α) (a : α) : a :: l₁ ∪ l₂ = insert a (l₁ ∪ l₂) := rfl
@[simp] theorem mem_union {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∪ l₂ ↔ a ∈ l₁ ∨ a ∈ l₂ :=
by induction l₁; simp only [nil_union, not_mem_nil, false_or, cons_union, mem_insert_iff,
mem_cons_iff, or_assoc, *]
theorem mem_union_left {a : α} {l₁ : list α} (h : a ∈ l₁) (l₂ : list α) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inl h)
theorem mem_union_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ∪ l₂ :=
mem_union.2 (or.inr h)
theorem sublist_suffix_of_union : ∀ l₁ l₂ : list α, ∃ t, t <+ l₁ ∧ t ++ l₂ = l₁ ∪ l₂
| [] l₂ := ⟨[], by refl, rfl⟩
| (a::l₁) l₂ := let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
if h : a ∈ l₁ ∪ l₂
then ⟨t, sublist_cons_of_sublist _ s, by simp only [e, cons_union, insert_of_mem h]⟩
else ⟨a::t, cons_sublist_cons _ s, by simp only [cons_append, cons_union, e, insert_of_not_mem h];
split; refl⟩
theorem suffix_union_right (l₁ l₂ : list α) : l₂ <:+ l₁ ∪ l₂ :=
(sublist_suffix_of_union l₁ l₂).imp (λ a, and.right)
theorem union_sublist_append (l₁ l₂ : list α) : l₁ ∪ l₂ <+ l₁ ++ l₂ :=
let ⟨t, s, e⟩ := sublist_suffix_of_union l₁ l₂ in
e ▸ (append_sublist_append_right _).2 s
theorem forall_mem_union {p : α → Prop} {l₁ l₂ : list α} :
(∀ x ∈ l₁ ∪ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) :=
by simp only [mem_union, or_imp_distrib, forall_and_distrib]
theorem forall_mem_of_forall_mem_union_left {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₁, p x :=
(forall_mem_union.1 h).1
theorem forall_mem_of_forall_mem_union_right {p : α → Prop} {l₁ l₂ : list α}
(h : ∀ x ∈ l₁ ∪ l₂, p x) : ∀ x ∈ l₂, p x :=
(forall_mem_union.1 h).2
end union
/-! ### inter -/
section inter
variable [decidable_eq α]
@[simp] theorem inter_nil (l : list α) : [] ∩ l = [] := rfl
@[simp] theorem inter_cons_of_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) :
(a::l₁) ∩ l₂ = a :: (l₁ ∩ l₂) :=
if_pos h
@[simp] theorem inter_cons_of_not_mem {a : α} (l₁ : list α) {l₂ : list α} (h : a ∉ l₂) :
(a::l₁) ∩ l₂ = l₁ ∩ l₂ :=
if_neg h
theorem mem_of_mem_inter_left {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₁ :=
mem_of_mem_filter
theorem mem_of_mem_inter_right {l₁ l₂ : list α} {a : α} : a ∈ l₁ ∩ l₂ → a ∈ l₂ :=
of_mem_filter
theorem mem_inter_of_mem_of_mem {l₁ l₂ : list α} {a : α} : a ∈ l₁ → a ∈ l₂ → a ∈ l₁ ∩ l₂ :=
mem_filter_of_mem
@[simp] theorem mem_inter {a : α} {l₁ l₂ : list α} : a ∈ l₁ ∩ l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ :=
mem_filter
theorem inter_subset_left (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₁ :=
filter_subset _
theorem inter_subset_right (l₁ l₂ : list α) : l₁ ∩ l₂ ⊆ l₂ :=
λ a, mem_of_mem_inter_right
theorem subset_inter {l l₁ l₂ : list α} (h₁ : l ⊆ l₁) (h₂ : l ⊆ l₂) : l ⊆ l₁ ∩ l₂ :=
λ a h, mem_inter.2 ⟨h₁ h, h₂ h⟩
theorem inter_eq_nil_iff_disjoint {l₁ l₂ : list α} : l₁ ∩ l₂ = [] ↔ disjoint l₁ l₂ :=
by simp only [eq_nil_iff_forall_not_mem, mem_inter, not_and]; refl
theorem forall_mem_inter_of_forall_left {p : α → Prop} {l₁ : list α} (h : ∀ x ∈ l₁, p x)
(l₂ : list α) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_left) h
theorem forall_mem_inter_of_forall_right {p : α → Prop} (l₁ : list α) {l₂ : list α}
(h : ∀ x ∈ l₂, p x) :
∀ x, x ∈ l₁ ∩ l₂ → p x :=
ball.imp_left (λ x, mem_of_mem_inter_right) h
@[simp] lemma inter_reverse {xs ys : list α} :
xs.inter ys.reverse = xs.inter ys :=
by simp only [list.inter, mem_reverse]; congr
end inter
section choose
variables (p : α → Prop) [decidable_pred p] (l : list α)
lemma choose_spec (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃ a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃ a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
-- A jumble of lost lemmas:
theorem ilast'_mem : ∀ a l, @ilast' α a l ∈ a :: l
| a [] := or.inl rfl
| a (b::l) := or.inr (ilast'_mem b l)
@[simp] lemma nth_le_attach (L : list α) (i) (H : i < L.attach.length) :
(L.attach.nth_le i H).1 = L.nth_le i (length_attach L ▸ H) :=
calc (L.attach.nth_le i H).1
= (L.attach.map subtype.val).nth_le i (by simpa using H) : by rw nth_le_map'
... = L.nth_le i _ : by congr; apply attach_map_val
end list
@[to_additive]
theorem monoid_hom.map_list_prod {α β : Type*} [monoid α] [monoid β] (f : α →* β) (l : list α) :
f l.prod = (l.map f).prod :=
(l.prod_hom f).symm
namespace list
@[to_additive]
theorem prod_map_hom {α β γ : Type*} [monoid β] [monoid γ] (L : list α) (f : α → β) (g : β →* γ) :
(L.map (g ∘ f)).prod = g ((L.map f).prod) :=
by {rw g.map_list_prod, exact congr_arg _ (map_map _ _ _).symm}
theorem sum_map_mul_left {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, r * f b)).sum = r * (L.map f).sum :=
sum_map_hom L f $ add_monoid_hom.mul_left r
theorem sum_map_mul_right {α : Type*} [semiring α] {β : Type*} (L : list β)
(f : β → α) (r : α) :
(L.map (λ b, f b * r)).sum = (L.map f).sum * r :=
sum_map_hom L f $ add_monoid_hom.mul_right r
universes u v
@[simp]
theorem mem_map_swap {α : Type u} {β : Type v} (x : α) (y : β) (xs : list (α × β)) :
(y, x) ∈ map prod.swap xs ↔ (x, y) ∈ xs :=
begin
induction xs with x xs,
{ simp only [not_mem_nil, map_nil] },
{ cases x with a b,
simp only [mem_cons_iff, prod.mk.inj_iff, map, prod.swap_prod_mk, prod.exists, xs_ih],
tauto! },
end
lemma slice_eq {α} (xs : list α) (n m : ℕ) :
slice n m xs = xs.take n ++ xs.drop (n+m) :=
begin
induction n generalizing xs,
{ simp [slice] },
{ cases xs; simp [slice, *, nat.succ_add], }
end
lemma sizeof_slice_lt {α} [has_sizeof α] (i j : ℕ) (hj : 0 < j) (xs : list α) (hi : i < xs.length) :
sizeof (list.slice i j xs) < sizeof xs :=
begin
induction xs generalizing i j,
case list.nil : i j h
{ cases hi },
case list.cons : x xs xs_ih i j h
{ cases i; simp only [-slice_eq, list.slice],
{ cases j, cases h,
dsimp only [drop], unfold_wf,
apply @lt_of_le_of_lt _ _ _ xs.sizeof,
{ clear_except,
induction xs generalizing j; unfold_wf,
case list.nil : j
{ refl },
case list.cons : xs_hd xs_tl xs_ih j
{ cases j; unfold_wf, refl,
transitivity, apply xs_ih,
simp }, },
unfold_wf, apply zero_lt_one_add, },
{ unfold_wf, apply xs_ih _ _ h,
apply lt_of_succ_lt_succ hi, } },
end
end list
|
55acc7b6f65a507a77fc82c1a5428a6987f28f6f | 96e44fc78cabfc9d646dc37d0e756189b6b79181 | /library/init/meta/simp_tactic.lean | 39392d2986cfbe06c5f9357de492c8df04ea6581 | [
"Apache-2.0"
] | permissive | TwoFX/lean | 23c73c10a340f5a381f6abf27a27f53f1fb7e2e3 | 7e3f336714055869690b7309b6bb651fbc67e76e | refs/heads/master | 1,612,504,908,183 | 1,594,641,622,000 | 1,594,641,622,000 | 243,750,847 | 0 | 0 | Apache-2.0 | 1,582,890,661,000 | 1,582,890,661,000 | null | UTF-8 | Lean | false | false | 26,954 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.meta.attribute init.meta.constructor_tactic
import init.meta.relation_tactics init.meta.occurrences
import init.data.option.basic
open tactic
def simp.default_max_steps := 10000000
/-- Prefix the given `attr_name` with `"simp_attr"`. -/
meta constant mk_simp_attr_decl_name (attr_name : name) : name
/-- Simp lemmas are used by the "simplifier" family of tactics.
`simp_lemmas` is essentially a pair of tables `rb_map (expr_type × name) (priority_list simp_lemma)`.
One of the tables is for congruences and one is for everything else.
An individual simp lemma is:
- A kind which can be `Refl`, `Simp` or `Congr`.
- A pair of `expr`s `l ~> r`. The rb map is indexed by the name of `get_app_fn(l)`.
- A proof that `l = r` or `l ↔ r`.
- A list of the metavariables that must be filled before the proof can be applied.
- A priority number
-/
meta constant simp_lemmas : Type
/-- Make a new table of simp lemmas -/
meta constant simp_lemmas.mk : simp_lemmas
/-- Merge the simp_lemma tables. -/
meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas
/-- Remove the given lemmas from the table. Use the names of the lemmas. -/
meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas
/-- Makes the default simp_lemmas table which is composed of all lemmas tagged with `simp`. -/
meta constant simp_lemmas.mk_default : tactic simp_lemmas
/-- Add a simplification lemma by an expression `p`. Some conditions on `p` must hold for it to be added, see list below.
If your lemma is not being added, you can see the reasons by setting `set_option trace.simp_lemmas true`.
- `p` must have the type `Π (h₁ : _) ... (hₙ : _), LHS ~ RHS` for some reflexive, transitive relation (usually `=`).
- Any of the hypotheses `hᵢ` should either be present in `LHS` or otherwise a `Prop` or a typeclass instance.
- `LHS` should not occur within `RHS`.
- `LHS` should not occur within a hypothesis `hᵢ`.
-/
meta constant simp_lemmas.add (s : simp_lemmas) (e : expr) (symm : bool := false) : tactic simp_lemmas
/-- Add a simplification lemma by it's declaration name. See `simp_lemmas.add` for more information.-/
meta constant simp_lemmas.add_simp (s : simp_lemmas) (id : name) (symm : bool := false) : tactic simp_lemmas
/-- Adds a congruence simp lemma to simp_lemmas.
A congruence simp lemma is a lemma that breaks the simplification down into separate problems.
For example, to simplify `a ∧ b` to `c ∧ d`, we should try to simp `a` to `c` and `b` to `d`.
For examples of congruence simp lemmas look for lemmas with the `@[congr]` attribute.
```lean
lemma if_simp_congr ... (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := ...
lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := ...
lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := ...
```
-/
meta constant simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas
/-- Add expressions to a set of simp lemmas using `simp_lemmas.add`.
This is the new version of `simp_lemmas.append`,
which also allows you to set the `symm` flag.
-/
meta def simp_lemmas.append_with_symm (s : simp_lemmas) (hs : list (expr × bool)) :
tactic simp_lemmas :=
hs.mfoldl (λ s h, simp_lemmas.add s h.fst h.snd) s
/-- Add expressions to a set of simp lemmas using `simp_lemmas.add`.
This is the backwards-compatibility version of `simp_lemmas.append_with_symm`,
and sets all `symm` flags to `ff`.
-/
meta def simp_lemmas.append (s : simp_lemmas) (hs : list expr) : tactic simp_lemmas :=
hs.mfoldl (λ s h, simp_lemmas.add s h ff) s
/-- `simp_lemmas.rewrite s e prove R` apply a simplification lemma from 's'
- 'e' is the expression to be "simplified"
- 'prove' is used to discharge proof obligations.
- 'r' is the equivalence relation being used (e.g., 'eq', 'iff')
- 'md' is the transparency; how aggresively should the simplifier perform reductions.
Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/
meta constant simp_lemmas.rewrite (s : simp_lemmas) (e : expr)
(prove : tactic unit := failed) (r : name := `eq) (md := reducible)
: tactic (expr × expr)
meta constant simp_lemmas.rewrites (s : simp_lemmas) (e : expr)
(prove : tactic unit := failed) (r : name := `eq) (md := reducible)
: tactic $ list (expr × expr)
/-- `simp_lemmas.drewrite s e` tries to rewrite 'e' using only refl lemmas in 's' -/
meta constant simp_lemmas.drewrite (s : simp_lemmas) (e : expr) (md := reducible) : tactic expr
meta constant is_valid_simp_lemma_cnst : name → tactic bool
meta constant is_valid_simp_lemma : expr → tactic bool
meta constant simp_lemmas.pp : simp_lemmas → tactic format
meta instance : has_to_tactic_format simp_lemmas :=
⟨simp_lemmas.pp⟩
namespace tactic
/- Remark: `transform` should not change the target. -/
/-- Revert a local constant, change its type using `transform`. -/
meta def revert_and_transform (transform : expr → tactic expr) (h : expr) : tactic unit :=
do num_reverted : ℕ ← revert h,
t ← target,
match t with
| expr.pi n bi d b :=
do h_simp ← transform d,
unsafe_change $ expr.pi n bi h_simp b
| expr.elet n g e f :=
do h_simp ← transform g,
unsafe_change $ expr.elet n h_simp e f
| _ := fail "reverting hypothesis created neither a pi nor an elet expr (unreachable?)"
end,
intron num_reverted
/-- `get_eqn_lemmas_for deps d` returns the automatically generated equational lemmas for definition d.
If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/
meta def get_eqn_lemmas_for (deps : bool) (d : name) : tactic (list name) := do
env ← get_env,
pure $ if deps then env.get_ext_eqn_lemmas_for d else env.get_eqn_lemmas_for d
structure dsimp_config :=
(md := reducible) -- reduction mode: how aggressively constants are replaced with their definitions.
(max_steps : nat := simp.default_max_steps) -- The maximum number of steps allowed before failing.
(canonize_instances : bool := tt) -- See the documentation in `src/library/defeq_canonizer.h`
(single_pass : bool := ff) -- Visit each subterm no more than once.
(fail_if_unchanged := tt) -- Don't throw if dsimp didn't do anything.
(eta := tt) -- allow eta-equivalence: `(λ x, F $ x) ↝ F`
(zeta : bool := tt) -- do zeta-reductions: `let x : a := b in c ↝ c[x/b]`.
(beta : bool := tt) -- do beta-reductions: `(λ x, E) $ (y) ↝ E[x/y]`.
(proj : bool := tt) -- reduce projections: `⟨a,b⟩.1 ↝ a`.
(iota : bool := tt) -- reduce recursors for inductive datatypes: eg `nat.rec_on (succ n) Z R ↝ R n $ nat.rec_on n Z R`
(unfold_reducible := ff) -- if tt, definitions with `reducible` transparency will be unfolded (delta-reduced)
(memoize := tt) -- Perform caching of dsimps of subterms.
end tactic
/-- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas.
The resulting expression is definitionally equal to the input.
The list `u` contains defintions to be delta-reduced, and projections to be reduced.-/
meta constant simp_lemmas.dsimplify (s : simp_lemmas) (u : list name := []) (e : expr) (cfg : tactic.dsimp_config := {}) : tactic expr
namespace tactic
/- Remark: the configuration parameters `cfg.md` and `cfg.eta` are ignored by this tactic. -/
meta constant dsimplify_core
/- The user state type. -/
{α : Type}
/- Initial user data -/
(a : α)
/- (pre a e) is invoked before visiting the children of subterm 'e',
if it succeeds the result (new_a, new_e, flag) where
- 'new_a' is the new value for the user data
- 'new_e' is a new expression that must be definitionally equal to 'e',
- 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/
(pre : α → expr → tactic (α × expr × bool))
/- (post a e) is invoked after visiting the children of subterm 'e',
The output is similar to (pre a e), but the 'flag' indicates whether
the new expression should be revisited or not. -/
(post : α → expr → tactic (α × expr × bool))
(e : expr)
(cfg : dsimp_config := {})
: tactic (α × expr)
meta def dsimplify
(pre : expr → tactic (expr × bool))
(post : expr → tactic (expr × bool))
: expr → tactic expr :=
λ e, do (a, new_e) ← dsimplify_core ()
(λ u e, do r ← pre e, return (u, r))
(λ u e, do r ← post e, return (u, r)) e,
return new_e
meta def get_simp_lemmas_or_default : option simp_lemmas → tactic simp_lemmas
| none := simp_lemmas.mk_default
| (some s) := return s
meta def dsimp_target (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit :=
do
s ← get_simp_lemmas_or_default s,
t ← target >>= instantiate_mvars,
s.dsimplify u t cfg >>= unsafe_change
meta def dsimp_hyp (h : expr) (s : option simp_lemmas := none) (u : list name := []) (cfg : dsimp_config := {}) : tactic unit :=
do s ← get_simp_lemmas_or_default s, revert_and_transform (λ e, s.dsimplify u e cfg) h
/- Remark: we use transparency.instances by default to make sure that we
can unfold projections of type classes. Example:
(@has_add.add nat nat.has_add a b)
-/
/-- Tries to unfold `e` if it is a constant or a constant application.
Remark: this is not a recursive procedure. -/
meta constant dunfold_head (e : expr) (md := transparency.instances) : tactic expr
structure dunfold_config extends dsimp_config :=
(md := transparency.instances)
/- Remark: in principle, dunfold can be implemented on top of dsimp. We don't do it for
performance reasons. -/
meta constant dunfold (cs : list name) (e : expr) (cfg : dunfold_config := {}) : tactic expr
meta def dunfold_target (cs : list name) (cfg : dunfold_config := {}) : tactic unit :=
do t ← target, dunfold cs t cfg >>= unsafe_change
meta def dunfold_hyp (cs : list name) (h : expr) (cfg : dunfold_config := {}) : tactic unit :=
revert_and_transform (λ e, dunfold cs e cfg) h
structure delta_config :=
(max_steps := simp.default_max_steps)
(visit_instances := tt)
private meta def is_delta_target (e : expr) (cs : list name) : bool :=
cs.any (λ c,
if e.is_app_of c then tt /- Exact match -/
else let f := e.get_app_fn in
/- f is an auxiliary constant generated when compiling c -/
f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c))
/-- Delta reduce the given constant names -/
meta def delta (cs : list name) (e : expr) (cfg : delta_config := {}) : tactic expr :=
let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do
guard (is_delta_target e cs),
(expr.const f_name f_lvls) ← return e.get_app_fn,
env ← get_env,
decl ← env.get f_name,
new_f ← decl.instantiate_value_univ_params f_lvls,
new_e ← head_beta (expr.mk_app new_f e.get_app_args),
return (u, new_e, tt)
in do (c, new_e) ← dsimplify_core () (λ c e, failed) unfold e {max_steps := cfg.max_steps, canonize_instances := cfg.visit_instances},
return new_e
meta def delta_target (cs : list name) (cfg : delta_config := {}) : tactic unit :=
do t ← target, delta cs t cfg >>= unsafe_change
meta def delta_hyp (cs : list name) (h : expr) (cfg : delta_config := {}) :tactic unit :=
revert_and_transform (λ e, delta cs e cfg) h
structure unfold_proj_config extends dsimp_config :=
(md := transparency.instances)
/-- If `e` is a projection application, try to unfold it, otherwise fail. -/
meta constant unfold_proj (e : expr) (md := transparency.instances) : tactic expr
meta def unfold_projs (e : expr) (cfg : unfold_proj_config := {}) : tactic expr :=
let unfold (changed : bool) (e : expr) : tactic (bool × expr × bool) := do
new_e ← unfold_proj e cfg.md,
return (tt, new_e, tt)
in do (tt, new_e) ← dsimplify_core ff (λ c e, failed) unfold e cfg.to_dsimp_config | fail "no projections to unfold",
return new_e
meta def unfold_projs_target (cfg : unfold_proj_config := {}) : tactic unit :=
do t ← target, unfold_projs t cfg >>= unsafe_change
meta def unfold_projs_hyp (h : expr) (cfg : unfold_proj_config := {}) : tactic unit :=
revert_and_transform (λ e, unfold_projs e cfg) h
structure simp_config :=
(max_steps : nat := simp.default_max_steps)
(contextual : bool := ff)
(lift_eq : bool := tt)
(canonize_instances : bool := tt)
(canonize_proofs : bool := ff)
(use_axioms : bool := tt)
(zeta : bool := tt)
(beta : bool := tt)
(eta : bool := tt)
(proj : bool := tt) -- reduce projections
(iota : bool := tt)
(iota_eqn : bool := ff) -- reduce using all equation lemmas generated by equation/pattern-matching compiler
(constructor_eq : bool := tt)
(single_pass : bool := ff)
(fail_if_unchanged := tt)
(memoize := tt)
/--
`simplify s e cfg r prove` simplify `e` using `s` using bottom-up traversal.
`discharger` is a tactic for dischaging new subgoals created by the simplifier.
If it fails, the simplifier tries to discharge the subgoal by simplifying it to `true`.
The parameter `to_unfold` specifies definitions that should be delta-reduced,
and projection applications that should be unfolded.
-/
meta constant simplify (s : simp_lemmas) (to_unfold : list name := []) (e : expr) (cfg : simp_config := {}) (r : name := `eq)
(discharger : tactic unit := failed) : tactic (expr × expr)
meta def simp_target (s : simp_lemmas) (to_unfold : list name := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit :=
do t ← target >>= instantiate_mvars,
(new_t, pr) ← simplify s to_unfold t cfg `eq discharger,
replace_target new_t pr
meta def simp_hyp (s : simp_lemmas) (to_unfold : list name := []) (h : expr) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic expr :=
do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"),
htype ← infer_type h,
(h_new_type, pr) ← simplify s to_unfold htype cfg `eq discharger,
replace_hyp h h_new_type pr
/--
`ext_simplify_core a c s discharger pre post r e`:
- `a : α` - initial user data
- `c : simp_config` - simp configuration options
- `s : simp_lemmas` - the set of simp_lemmas to use. Remark: the simplification lemmas are not applied automatically like in the simplify tactic. The caller must use them at pre/post.
- `discharger : α → tactic α` - tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user data.
- `pre a s r p e` is invoked before visiting the children of subterm 'e'.
+ arguments:
- `a` is the current user data
- `s` is the updated set of lemmas if 'contextual' is `tt`,
- `r` is the simplification relation being used,
- `p` is the "parent" expression (if there is one).
- `e` is the current subexpression in question.
+ if it succeeds the result is `(new_a, new_e, new_pr, flag)` where
- `new_a` is the new value for the user data
- `new_e` is a new expression s.t. `r e new_e`
- `new_pr` is a proof for `e r new_e`, If it is none, the proof is assumed to be by reflexivity
- `flag` if tt `new_e` children should be visited, and `post` invoked.
- `(post a s r p e)` is invoked after visiting the children of subterm `e`,
The output is similar to `(pre a r s p e)`, but the 'flag' indicates whether the new expression should be revisited or not.
- `r` is the simplification relation. Usually `=` or `↔`.
- `e` is the input expression to be simplified.
The method returns `(a,e,pr)` where
- `a` is the final user data
- `e` is the new expression
- `pr` is the proof that the given expression equals the input expression.
-/
meta constant ext_simplify_core
{α : Type}
(a : α)
(c : simp_config)
(s : simp_lemmas)
(discharger : α → tactic α)
(pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool))
(post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool))
(r : name) :
expr → tactic (α × expr × expr)
private meta def is_equation : expr → bool
| (expr.pi n bi d b) := is_equation b
| e := match (expr.is_eq e) with (some a) := tt | none := ff end
meta def collect_ctx_simps : tactic (list expr) :=
local_context
section simp_intros
meta def intro1_aux : bool → list name → tactic expr
| ff _ := intro1
| tt (n::ns) := intro n
| _ _ := failed
structure simp_intros_config extends simp_config :=
(use_hyps := ff)
meta def simp_intros_aux (cfg : simp_config) (use_hyps : bool) (to_unfold : list name) : simp_lemmas → bool → list name → tactic simp_lemmas
| S tt [] := try (simp_target S to_unfold cfg) >> return S
| S use_ns ns := do
t ← target,
if t.is_napp_of `not 1 then
intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail
else if t.is_arrow then
do {
d ← return t.binding_domain,
(new_d, h_d_eq_new_d) ← simplify S to_unfold d cfg,
h_d ← intro1_aux use_ns ns,
h_new_d ← mk_eq_mp h_d_eq_new_d h_d,
assertv_core h_d.local_pp_name new_d h_new_d,
clear h_d,
h_new ← intro1,
new_S ← if use_hyps then mcond (is_prop new_d) (S.add h_new ff) (return S)
else return S,
simp_intros_aux new_S use_ns ns.tail
}
<|>
-- failed to simplify... we just introduce and continue
(intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail)
else if t.is_pi || t.is_let then
intro1_aux use_ns ns >> simp_intros_aux S use_ns ns.tail
else do
new_t ← whnf t reducible,
if new_t.is_pi then unsafe_change new_t >> simp_intros_aux S use_ns ns
else
try (simp_target S to_unfold cfg) >>
mcond (expr.is_pi <$> target)
(simp_intros_aux S use_ns ns)
(if use_ns ∧ ¬ns.empty then failed else return S)
meta def simp_intros (s : simp_lemmas) (to_unfold : list name := []) (ids : list name := []) (cfg : simp_intros_config := {}) : tactic unit :=
step $ simp_intros_aux cfg.to_simp_config cfg.use_hyps to_unfold s (bnot ids.empty) ids
end simp_intros
meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit :=
do (lhs, rhs) ← target >>= match_eq,
(new_rhs, heq) ← simp_ext lhs,
unify rhs new_rhs,
exact heq
/- Simp attribute support -/
meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas
| S [] := return S
| S (n::ns) := do S' ← S.add_simp n ff, to_simp_lemmas S' ns
meta def mk_simp_attr (attr_name : name) (attr_deps : list name := []) : command :=
do let t := `(user_attribute simp_lemmas),
let v := `({name := attr_name,
descr := "simplifier attribute",
cache_cfg := {
mk_cache := λ ns, do {
s ← tactic.to_simp_lemmas simp_lemmas.mk ns,
s ← attr_deps.mfoldl
(λ s attr_name, do
ns ← attribute.get_instances attr_name,
to_simp_lemmas s ns)
s,
return s },
dependencies := `reducibility :: attr_deps}} : user_attribute simp_lemmas),
let n := mk_simp_attr_decl_name attr_name,
add_decl (declaration.defn n [] t v reducibility_hints.abbrev ff),
attribute.register n
/--
### Example usage:
```lean
-- make a new simp attribute called "my_reduction"
run_cmd mk_simp_attr `my_reduction
-- Add "my_reduction" attributes to these if-reductions
attribute [my_reduction] if_pos if_neg dif_pos dif_neg
-- will return the simp_lemmas with the `my_reduction` attribute.
#eval get_user_simp_lemmas `my_reduction
```
-/
meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas :=
if attr_name = `default then simp_lemmas.mk_default
else get_attribute_cache_dyn (mk_simp_attr_decl_name attr_name)
meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas
| S [] := return S
| S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R
meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas :=
if no_dflt then
join_user_simp_lemmas_core simp_lemmas.mk attrs
else do
s ← simp_lemmas.mk_default,
join_user_simp_lemmas_core s attrs
/-- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral,
and pr is a proof that the input argument is equal to n. -/
meta constant norm_num : expr → tactic (expr × expr)
meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) :=
ext_simplify_core a cfg simp_lemmas.mk (λ _, failed)
(λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt))
(λ _ _ _ _ _, failed)
`eq e
meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit :=
do t ← target,
(_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg,
replace_target new_target pr
meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) :=
ext_simplify_core a cfg simp_lemmas.mk (λ _, failed)
(λ _ _ _ _ _, failed)
(λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt))
`eq e
meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit :=
do t ← target,
(_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg,
replace_target new_target pr
private meta def remove_deps (s : name_set) (h : expr) : name_set :=
if s.empty then s
else h.fold s (λ e o s, if e.is_local_constant then s.erase e.local_uniq_name else s)
/- Return the list of hypothesis that are propositions and do not have
forward dependencies. -/
meta def non_dep_prop_hyps : tactic (list expr) :=
do
ctx ← local_context,
s ← ctx.mfoldl (λ s h, do
h_type ← infer_type h,
let s := remove_deps s h_type,
h_val ← head_zeta h,
let s := if h_val =ₐ h then s else remove_deps s h_val,
mcond (is_prop h_type)
(return $ s.insert h.local_uniq_name)
(return s)) mk_name_set,
t ← target,
let s := remove_deps s t,
return $ ctx.filter (λ h, s.contains h.local_uniq_name)
section simp_all
meta structure simp_all_entry :=
(h : expr) -- hypothesis
(new_type : expr) -- new type
(pr : option expr) -- proof that type of h is equal to new_type
(s : simp_lemmas) -- simplification lemmas for simplifying new_type
private meta def update_simp_lemmas (es : list simp_all_entry) (h : expr) : tactic (list simp_all_entry) :=
es.mmap $ λ e, do new_s ← e.s.add h ff, return {s := new_s, ..e}
/- Helper tactic for `init`.
Remark: the following tactic is quadratic on the length of list expr (the list of non dependent propositions).
We can make it more efficient as soon as we have an efficient simp_lemmas.erase. -/
private meta def init_aux : list expr → simp_lemmas → list simp_all_entry → tactic (simp_lemmas × list simp_all_entry)
| [] s r := return (s, r)
| (h::hs) s r := do
new_r ← update_simp_lemmas r h,
new_s ← s.add h ff,
h_type ← infer_type h,
init_aux hs new_s (⟨h, h_type, none, s⟩::new_r)
private meta def init (s : simp_lemmas) (hs : list expr) : tactic (simp_lemmas × list simp_all_entry) :=
init_aux hs s []
private meta def add_new_hyps (es : list simp_all_entry) : tactic unit :=
es.mmap' $ λ e,
match e.pr with
| none := return ()
| some pr :=
assert e.h.local_pp_name e.new_type >>
mk_eq_mp pr e.h >>= exact
end
private meta def clear_old_hyps (es : list simp_all_entry) : tactic unit :=
es.mmap' $ λ e, when (e.pr ≠ none) (try (clear e.h))
private meta def join_pr : option expr → expr → tactic expr
| none pr₂ := return pr₂
| (some pr₁) pr₂ := mk_eq_trans pr₁ pr₂
private meta def loop (cfg : simp_config) (discharger : tactic unit) (to_unfold : list name)
: list simp_all_entry → list simp_all_entry → simp_lemmas → bool → tactic unit
| [] r s m :=
if m then loop r [] s ff
else do
add_new_hyps r,
target_changed ← (simp_target s to_unfold cfg discharger >> return tt) <|> return ff,
guard (cfg.fail_if_unchanged = ff ∨ target_changed ∨ r.any (λ e, e.pr ≠ none)) <|> fail "simp_all tactic failed to simplify",
clear_old_hyps r
| (e::es) r s m := do
let ⟨h, h_type, h_pr, s'⟩ := e,
(new_h_type, new_pr) ← simplify s' to_unfold h_type {fail_if_unchanged := ff, ..cfg} `eq discharger,
if h_type =ₐ new_h_type then loop es (e::r) s m
else do
new_pr ← join_pr h_pr new_pr,
new_fact_pr ← mk_eq_mp new_pr h,
if new_h_type = `(false) then do
tgt ← target,
to_expr ``(@false.rec %%tgt %%new_fact_pr) >>= exact
else do
h0_type ← infer_type h,
let new_fact_pr := mk_id_proof new_h_type new_fact_pr,
new_es ← update_simp_lemmas es new_fact_pr,
new_r ← update_simp_lemmas r new_fact_pr,
let new_r := {new_type := new_h_type, pr := new_pr, ..e} :: new_r,
new_s ← s.add new_fact_pr ff,
loop new_es new_r new_s tt
meta def simp_all (s : simp_lemmas) (to_unfold : list name) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic unit :=
do hs ← non_dep_prop_hyps,
(s, es) ← init s hs,
loop cfg discharger to_unfold es [] s ff
end simp_all
/- debugging support for algebraic normalizer -/
meta constant trace_algebra_info : expr → tactic unit
end tactic
export tactic (mk_simp_attr)
run_cmd mk_simp_attr `norm [`simp]
|
b62f2699863b67dff194c74afe5d4b6b91ce3608 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /archive/100-theorems-list/16_abel_ruffini.lean | 942ec9ff38921c1ba499d44158c3c71e06f14f83 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,838 | lean | /-
Copyright (c) 2021 Thomas Browning. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning
-/
import field_theory.abel_ruffini
import analysis.calculus.local_extr
/-!
Construction of an algebraic number that is not solvable by radicals.
The main ingredients are:
* `solvable_by_rad.is_solvable'` in `field_theory/abel_ruffini` :
an irreducible polynomial with an `is_solvable_by_rad` root has solvable Galois group
* `gal_action_hom_bijective_of_prime_degree'` in `field_theory/polynomial_galois_group` :
an irreducible polynomial of prime degree with 1-3 non-real roots has full Galois group
* `equiv.perm.not_solvable` in `group_theory/solvable` : the symmetric group is not solvable
Then all that remains is the construction of a specific polynomial satisfying the conditions of
`gal_action_hom_bijective_of_prime_degree'`, which is done in this file.
-/
namespace abel_ruffini
open function polynomial polynomial.gal ideal
local attribute [instance] splits_ℚ_ℂ
variables (R : Type*) [comm_ring R] (a b : ℕ)
/-- A quintic polynomial that we will show is irreducible -/
noncomputable def Φ : polynomial R := X ^ 5 - C ↑a * X + C ↑b
variables {R}
@[simp] lemma map_Phi {S : Type*} [comm_ring S] (f : R →+* S) : (Φ R a b).map f = Φ S a b :=
by simp [Φ]
@[simp] lemma coeff_zero_Phi : (Φ R a b).coeff 0 = ↑b :=
by simp [Φ, coeff_X_pow]
@[simp] lemma coeff_five_Phi : (Φ R a b).coeff 5 = 1 :=
by simp [Φ, coeff_X, coeff_C, -C_eq_nat_cast, -ring_hom.map_nat_cast]
variables [nontrivial R]
lemma degree_Phi : (Φ R a b).degree = ↑5 :=
begin
suffices : degree (X ^ 5 - C ↑a * X) = ↑5,
{ rwa [Φ, degree_add_eq_left_of_degree_lt],
convert degree_C_le.trans_lt (with_bot.coe_lt_coe.mpr (nat.zero_lt_bit1 2)) },
rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow,
exact (degree_C_mul_X_le _).trans_lt (with_bot.coe_lt_coe.mpr (nat.one_lt_bit1 two_ne_zero)),
end
lemma nat_degree_Phi : (Φ R a b).nat_degree = 5 :=
nat_degree_eq_of_degree_eq_some (degree_Phi a b)
lemma leading_coeff_Phi : (Φ R a b).leading_coeff = 1 :=
by rw [polynomial.leading_coeff, nat_degree_Phi, coeff_five_Phi]
lemma monic_Phi : (Φ R a b).monic :=
leading_coeff_Phi a b
lemma irreducible_Phi (p : ℕ) (hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) :
irreducible (Φ ℚ a b) :=
begin
rw [←map_Phi a b (int.cast_ring_hom ℚ), ←is_primitive.int.irreducible_iff_irreducible_map_cast],
apply irreducible_of_eisenstein_criterion,
{ rwa [span_singleton_prime (int.coe_nat_ne_zero.mpr hp.ne_zero), int.prime_iff_nat_abs_prime] },
{ rw [leading_coeff_Phi, mem_span_singleton],
exact_mod_cast mt nat.dvd_one.mp (hp.ne_one) },
{ intros n hn,
rw mem_span_singleton,
rw [degree_Phi, with_bot.coe_lt_coe] at hn,
interval_cases n with hn;
simp [Φ, coeff_X_pow, coeff_C, int.coe_nat_dvd.mpr, hpb, hpa, -ring_hom.eq_int_cast] },
{ simp only [degree_Phi, ←with_bot.coe_zero, with_bot.coe_lt_coe, nat.succ_pos'] },
{ rw [coeff_zero_Phi, span_singleton_pow, mem_span_singleton, int.nat_cast_eq_coe_nat],
exact mt int.coe_nat_dvd.mp hp2b },
all_goals { exact monic.is_primitive (monic_Phi a b) },
end
lemma real_roots_Phi_le : fintype.card ((Φ ℚ a b).root_set ℝ) ≤ 3 :=
begin
rw [←map_Phi a b (algebra_map ℤ ℚ), Φ, ←one_mul (X ^ 5), ←C_1],
refine (card_root_set_le_derivative _).trans
(nat.succ_le_succ ((card_root_set_le_derivative _).trans (nat.succ_le_succ _))),
suffices : ((C ((algebra_map ℤ ℚ) 20) * X ^ 3).root_set ℝ).subsingleton,
{ norm_num [fintype.card_le_one_iff_subsingleton, ← mul_assoc, *] at * },
rw root_set_C_mul_X_pow; norm_num,
end
lemma real_roots_Phi_ge_aux (hab : b < a) :
∃ x y : ℝ, x ≠ y ∧ aeval x (Φ ℚ a b) = 0 ∧ aeval y (Φ ℚ a b) = 0 :=
begin
let f := λ x : ℝ, aeval x (Φ ℚ a b),
have hf : f = λ x, x ^ 5 - a * x + b := by simp [f, Φ],
have hc : ∀ s : set ℝ, continuous_on f s := λ s, (Φ ℚ a b).continuous_on_aeval,
have ha : (1 : ℝ) ≤ a := nat.one_le_cast.mpr (nat.one_le_of_lt hab),
have hle : (0 : ℝ) ≤ 1 := zero_le_one,
have hf0 : 0 ≤ f 0 := by norm_num [hf],
by_cases hb : (1 : ℝ) - a + b < 0,
{ have hf1 : f 1 < 0 := by norm_num [hf, hb],
have hfa : 0 ≤ f a,
{ simp_rw [hf, ←sq],
refine add_nonneg (sub_nonneg.mpr (pow_le_pow ha _)) _; norm_num },
obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Ico' hle (hc _) (set.mem_Ioc.mpr ⟨hf1, hf0⟩),
obtain ⟨y, ⟨hy1, -⟩, hy2⟩ := intermediate_value_Ioc ha (hc _) (set.mem_Ioc.mpr ⟨hf1, hfa⟩),
exact ⟨x, y, (hx1.trans hy1).ne, hx2, hy2⟩ },
{ replace hb : (b : ℝ) = a - 1 := by linarith [show (b : ℝ) + 1 ≤ a, by exact_mod_cast hab],
have hf1 : f 1 = 0 := by norm_num [hf, hb],
have hfa := calc f (-a) = a ^ 2 - a ^ 5 + b : by norm_num [hf, ← sq]
... ≤ a ^ 2 - a ^ 3 + (a - 1) : by refine add_le_add (sub_le_sub_left
(pow_le_pow ha _) _) _; linarith
... = -(a - 1) ^ 2 * (a + 1) : by ring
... ≤ 0 : by nlinarith,
have ha' := neg_nonpos.mpr (hle.trans ha),
obtain ⟨x, ⟨-, hx1⟩, hx2⟩ := intermediate_value_Icc ha' (hc _) (set.mem_Icc.mpr ⟨hfa, hf0⟩),
exact ⟨x, 1, (hx1.trans_lt zero_lt_one).ne, hx2, hf1⟩ },
end
lemma real_roots_Phi_ge (hab : b < a) : 2 ≤ fintype.card ((Φ ℚ a b).root_set ℝ) :=
begin
have q_ne_zero : Φ ℚ a b ≠ 0 := (monic_Phi a b).ne_zero,
obtain ⟨x, y, hxy, hx, hy⟩ := real_roots_Phi_ge_aux a b hab,
have key : ↑({x, y} : finset ℝ) ⊆ (Φ ℚ a b).root_set ℝ,
{ simp [set.insert_subset, mem_root_set q_ne_zero, hx, hy] },
replace key := fintype.card_le_of_embedding (set.embedding_of_subset _ _ key),
rwa [fintype.card_coe, finset.card_insert_of_not_mem, finset.card_singleton] at key,
rwa finset.mem_singleton,
end
lemma complex_roots_Phi (h : (Φ ℚ a b).separable) : fintype.card ((Φ ℚ a b).root_set ℂ) = 5 :=
(card_root_set_eq_nat_degree h (is_alg_closed.splits_codomain _)).trans (nat_degree_Phi a b)
lemma gal_Phi (hab : b < a) (h_irred : irreducible (Φ ℚ a b)) :
bijective (gal_action_hom (Φ ℚ a b) ℂ) :=
begin
apply gal_action_hom_bijective_of_prime_degree' h_irred,
{ norm_num [nat_degree_Phi] },
{ rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff],
exact (real_roots_Phi_le a b).trans (nat.le_succ 3) },
{ simp_rw [complex_roots_Phi a b h_irred.separable, nat.succ_le_succ_iff],
exact real_roots_Phi_ge a b hab },
end
theorem not_solvable_by_rad (p : ℕ) (x : ℂ) (hx : aeval x (Φ ℚ a b) = 0) (hab : b < a)
(hp : p.prime) (hpa : p ∣ a) (hpb : p ∣ b) (hp2b : ¬ p ^ 2 ∣ b) :
¬ is_solvable_by_rad ℚ x :=
begin
have h_irred := irreducible_Phi a b p hp hpa hpb hp2b,
apply mt (solvable_by_rad.is_solvable' h_irred hx),
introI h,
refine equiv.perm.not_solvable _ (le_of_eq _)
(solvable_of_surjective (gal_Phi a b hab h_irred).2),
rw_mod_cast [cardinal.fintype_card, complex_roots_Phi a b h_irred.separable],
end
theorem not_solvable_by_rad' (x : ℂ) (hx : aeval x (Φ ℚ 4 2) = 0) :
¬ is_solvable_by_rad ℚ x :=
by apply not_solvable_by_rad 4 2 2 x hx; norm_num
theorem exists_not_solvable_by_rad : ∃ x : ℂ, is_algebraic ℚ x ∧ ¬ is_solvable_by_rad ℚ x :=
begin
obtain ⟨x, hx⟩ := exists_root_of_splits (algebra_map ℚ ℂ)
(is_alg_closed.splits_codomain (Φ ℚ 4 2))
(ne_of_eq_of_ne (degree_Phi 4 2) (mt with_bot.coe_eq_coe.mp (nat.bit1_ne_zero 2))),
exact ⟨x, ⟨Φ ℚ 4 2, (monic_Phi 4 2).ne_zero, hx⟩, not_solvable_by_rad' x hx⟩,
end
end abel_ruffini
|
d51e8e1d85943ffd577b742ac329d9e8d138dfbd | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/data/matrix/notation.lean | 545bf3ee80d009bb584b65bce90e24d89a1f6eff | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,557 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
Notation for vectors and matrices
-/
import data.fintype.card
import data.matrix.basic
import tactic.fin_cases
/-!
# 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 a matrix, so `![![a, b], ![c, d]] : matrix (fin 2) (fin 2) α`.
This file includes `simp` lemmas for applying operations in
`data.matrix.basic` to values built out of this notation.
## Main definitions
* `vec_empty` is the empty vector (or `0` by `n` matrix) `![]`
* `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)`
## Implementation notes
The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`.
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.
## Notations
The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`.
## Examples
Examples of usage can be found in the `test/matrix.lean` file.
-/
namespace matrix
universe u
variables {α : Type u}
open_locale matrix
section matrix_notation
/-- `![]` is the vector with no entries. -/
def vec_empty : fin 0 → α :=
fin_zero_elim
/-- `vec_cons h t` prepends an entry `h` to a vector `t`.
The inverse functions are `vec_head` and `vec_tail`.
The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`.
-/
def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α :=
fin.cons h t
notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l
/-- `vec_head v` gives the first entry of the vector `v` -/
def vec_head {n : ℕ} (v : fin n.succ → α) : α :=
v 0
/-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/
def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α :=
v ∘ fin.succ
variables {m n : ℕ}
/-- Use `![...]` notation for displaying a vector `fin n → α`, for example:
```
#eval ![1, 2] + ![3, 4] -- ![4, 6]
```
-/
instance [has_repr α] : has_repr (fin n → α) :=
{ repr := λ f, "![" ++ (string.intercalate ", " ((list.fin_range n).map (λ n, repr (f n)))) ++ "]" }
/-- Use `![...]` notation for displaying a `fin`-indexed matrix, for example:
```
#eval ![![1, 2], ![3, 4]] + ![![3, 4], ![5, 6]] -- ![![4, 6], ![8, 10]]
```
-/
instance [has_repr α] : has_repr (matrix (fin m) (fin n) α) :=
(by apply_instance : has_repr (fin m → fin n → α))
end matrix_notation
variables {m n o : ℕ} {m' n' o' : Type*}
lemma empty_eq (v : fin 0 → α) : v = ![] :=
by { ext i, fin_cases i }
section val
@[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl
@[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl
lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) :
vec_cons x u ⟨0, h⟩ = x :=
rfl
@[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) :
vec_cons x u i.succ = u i :=
by simp [vec_cons]
@[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) :
vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ :=
by simp only [vec_cons, fin.cons, fin.cases_succ']
@[simp] lemma head_cons (x : α) (u : fin m → α) :
vec_head (vec_cons x u) = x :=
rfl
@[simp] lemma tail_cons (x : α) (u : fin m → α) :
vec_tail (vec_cons x u) = u :=
by { ext, simp [vec_tail] }
@[simp] lemma empty_val' {n' : Type*} (j : n') :
(λ i, (![] : fin 0 → n' → α) i j) = ![] :=
empty_eq _
@[simp] lemma cons_val' (v : n' → α) (B : matrix (fin m) n' α) (i j) :
vec_cons v B i j = vec_cons (v j) (λ i, B i j) i :=
by { refine fin.cases _ _ i; simp }
@[simp] lemma head_val' (B : matrix (fin m.succ) n' α) (j : n') :
vec_head (λ i, B i j) = vec_head B j := rfl
@[simp] lemma tail_val' (B : matrix (fin m.succ) n' α) (j : n') :
vec_tail (λ i, B i j) = λ i, vec_tail B i j :=
by { ext, simp [vec_tail] }
@[simp] lemma cons_head_tail (u : fin m.succ → α) :
vec_cons (vec_head u) (vec_tail u) = u :=
fin.cons_self_tail _
@[simp] lemma range_cons (x : α) (u : fin n → α) :
set.range (vec_cons x u) = {x} ∪ set.range u :=
set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm]
@[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ :=
set.range_eq_empty _
/-- `![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] lemma cons_val_one (x : α) (u : fin m.succ → α) :
vec_cons x u 1 = vec_head u :=
by { rw [← fin.succ_zero_eq_one, cons_val_succ], refl }
@[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) :
vec_cons x u i = x :=
by { fin_cases i, refl }
lemma cons_fin_one (x : α) (u : fin 0 → α) : vec_cons x u = (λ _, x) :=
funext (cons_val_fin_one x u)
/-! ### Numeral (`bit0` and `bit1`) indices
The following definitions and `simp` lemmas are to allow any
numeral-indexed element of a vector given with matrix notation to
be extracted by `simp` (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`).
-/
@[simp] lemma empty_append (v : fin n → α) : fin.append (zero_add _).symm ![] v = v :=
by { ext, simp [fin.append] }
@[simp] lemma cons_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) :
fin.append ho (vec_cons x u) v =
vec_cons x (fin.append (by rwa [add_assoc, add_comm 1, ←add_assoc,
add_right_cancel_iff] at ho) u v) :=
begin
ext i,
simp_rw [fin.append],
split_ifs with h,
{ rcases i with ⟨⟨⟩ | i, hi⟩,
{ simp },
{ simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h,
simp [h] } },
{ rcases i with ⟨⟨⟩ | i, hi⟩,
{ simpa using h },
{ rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h,
simp [h] } }
end
/-- `vec_alt0 v` gives a vector with half the length of `v`, with
only alternate elements (even-numbered). -/
def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α :=
v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩
/-- `vec_alt1 v` gives a vector with half the length of `v`, with
only alternate elements (odd-numbered). -/
def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α :=
v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩
lemma vec_alt0_append (v : fin n → α) : vec_alt0 rfl (fin.append rfl v v) = v ∘ bit0 :=
begin
ext i,
simp_rw [function.comp, bit0, vec_alt0, fin.append],
split_ifs with h; congr,
{ rw fin.coe_mk at h,
simp only [fin.ext_iff, fin.coe_add, fin.coe_mk],
exact (nat.mod_eq_of_lt h).symm },
{ rw [fin.coe_mk, not_lt] at h,
simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h],
refine (nat.mod_eq_of_lt _).symm,
rw nat.sub_lt_left_iff_lt_add h,
exact add_lt_add i.property i.property }
end
lemma vec_alt1_append (v : fin (n + 1) → α) : vec_alt1 rfl (fin.append rfl v v) = v ∘ bit1 :=
begin
ext i,
simp_rw [function.comp, vec_alt1, fin.append],
cases n,
{ simp, congr },
{ split_ifs with h; simp_rw [bit1, bit0]; congr,
{ simp only [fin.ext_iff, fin.coe_add, fin.coe_mk],
rw fin.coe_mk at h,
rw fin.coe_one,
rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h),
rw nat.mod_eq_of_lt h },
{ rw [fin.coe_mk, not_lt] at h,
simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one,
nat.mod_eq_sub_mod h],
refine (nat.mod_eq_of_lt _).symm,
rw nat.sub_lt_left_iff_lt_add h,
exact nat.add_succ_lt_add i.property i.property } }
end
@[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) :
vec_head (vec_alt0 hm v) = v 0 := rfl
@[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) :
vec_head (vec_alt1 hm v) = v 1 :=
by simp [vec_head, vec_alt1]
@[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) :
vec_cons x u (bit0 i) = vec_alt0 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i :=
by rw vec_alt0_append
@[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) :
vec_cons x u (bit1 i) = vec_alt1 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i :=
by rw vec_alt1_append
@[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) :
vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0
(by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff,
add_right_cancel_iff] at h) u) :=
begin
ext i,
simp_rw [vec_alt0],
rcases i with ⟨⟨⟩ | i, hi⟩,
{ refl },
{ simp [vec_alt0, nat.add_succ, nat.succ_add] }
end
-- Although proved by simp, extracting element 8 of a five-element
-- vector does not work by simp unless this lemma is present.
@[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] :=
by simp
@[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) :
vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1
(by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff,
add_right_cancel_iff] at h) u) :=
begin
ext i,
simp_rw [vec_alt1],
rcases i with ⟨⟨⟩ | i, hi⟩,
{ refl },
{ simp [vec_alt1, nat.add_succ, nat.succ_add] }
end
-- Although proved by simp, extracting element 9 of a five-element
-- vector does not work by simp unless this lemma is present.
@[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] :=
by simp
end val
section dot_product
variables [add_comm_monoid α] [has_mul α]
@[simp] lemma dot_product_empty (v w : fin 0 → α) :
dot_product v w = 0 := finset.sum_empty
@[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) :
dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) :=
by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail]
@[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) :
dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w :=
by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail]
end dot_product
section col_row
@[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty :=
empty_eq _
@[simp] lemma col_cons (x : α) (u : fin m → α) :
col (vec_cons x u) = vec_cons (λ _, x) (col u) :=
by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] }
@[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty :=
by { ext, refl }
@[simp] lemma row_cons (x : α) (u : fin m → α) :
row (vec_cons x u) = λ _, vec_cons x u :=
by { ext, refl }
end col_row
section transpose
@[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = ![] := empty_eq _
@[simp] lemma transpose_empty_cols : (![] : matrix (fin 0) m' α)ᵀ = λ i, ![] :=
funext (λ i, empty_eq _)
@[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) :
(vec_cons v A)ᵀ = λ i, vec_cons (v i) (Aᵀ i) :=
by { ext i j, refine fin.cases _ _ j; simp }
@[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (Aᵀ) = vec_head ∘ A :=
rfl
@[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (Aᵀ) = (vec_tail ∘ A)ᵀ :=
by { ext i j, refl }
end transpose
section mul
variables [semiring α]
@[simp] lemma empty_mul [fintype n'] (A : matrix (fin 0) n' α) (B : matrix n' o' α) :
A ⬝ B = ![] :=
empty_eq _
@[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) :
A ⬝ B = 0 :=
rfl
@[simp] lemma mul_empty [fintype n'] (A : matrix m' n' α) (B : matrix n' (fin 0) α) :
A ⬝ B = λ _, ![] :=
funext (λ _, empty_eq _)
lemma mul_val_succ [fintype n']
(A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') :
(A ⬝ B) i.succ j = (vec_tail A ⬝ B) i j := rfl
@[simp] lemma cons_mul [fintype n'] (v : n' → α) (A : matrix (fin m) n' α) (B : matrix n' o' α) :
vec_cons v A ⬝ B = vec_cons (vec_mul v B) (A ⬝ B) :=
by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ] }
end mul
section vec_mul
variables [semiring α]
@[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) :
vec_mul v B = 0 :=
rfl
@[simp] lemma vec_mul_empty [fintype n'] (v : n' → α) (B : matrix n' (fin 0) α) :
vec_mul v B = ![] :=
empty_eq _
@[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : matrix (fin n.succ) o' α) :
vec_mul (vec_cons x v) B = x • (vec_head B) + vec_mul v (vec_tail B) :=
by { ext i, simp [vec_mul] }
@[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : matrix (fin n) o' α) :
vec_mul v (vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) B :=
by { ext i, simp [vec_mul] }
end vec_mul
section mul_vec
variables [semiring α]
@[simp] lemma empty_mul_vec [fintype n'] (A : matrix (fin 0) n' α) (v : n' → α) :
mul_vec A v = ![] :=
empty_eq _
@[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) :
mul_vec A v = 0 :=
rfl
@[simp] lemma cons_mul_vec [fintype n'] (v : n' → α) (A : fin m → n' → α) (w : n' → α) :
mul_vec (vec_cons v A) w = vec_cons (dot_product v w) (mul_vec A w) :=
by { ext i, refine fin.cases _ _ i; simp [mul_vec] }
@[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α)
(v : fin n → α) :
mul_vec A (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (vec_tail ∘ A) v :=
by { ext i, simp [mul_vec, mul_comm] }
end mul_vec
section vec_mul_vec
variables [semiring α]
@[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) :
vec_mul_vec v w = ![] :=
empty_eq _
@[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) :
vec_mul_vec v w = λ _, ![] :=
funext (λ i, empty_eq _)
@[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) :
vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) :=
by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] }
@[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) :
vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w :=
by { ext i j, simp [vec_mul_vec]}
end vec_mul_vec
section smul
variables [semiring α]
@[simp] lemma smul_empty (x : α) (v : fin 0 → α) : x • v = ![] := empty_eq _
@[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _
@[simp] lemma smul_cons (x y : α) (v : fin n → α) :
x • vec_cons y v = vec_cons (x * y) (x • v) :=
by { ext i, refine fin.cases _ _ i; simp }
@[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : matrix (fin m) n' α) :
x • vec_cons v A = vec_cons (x • v) (x • A) :=
by { ext i, refine fin.cases _ _ i; simp }
end smul
section add
variables [has_add α]
@[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _
@[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) :
vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) :=
by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] }
@[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) :
v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) :=
by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] }
@[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl
@[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl
end add
section sub
variables [has_sub α]
@[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _
@[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) :
vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) :=
by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] }
@[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) :
v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) :=
by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] }
@[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl
@[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl
end sub
section zero
variables [has_zero α]
@[simp] lemma zero_empty : (0 : fin 0 → α) = ![] :=
empty_eq _
@[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 :=
by { ext i j, refine fin.cases _ _ i, { refl }, simp }
@[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl
@[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl
@[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} :
vec_cons x v = 0 ↔ x = 0 ∧ v = 0 :=
⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩,
λ ⟨hx, hv⟩, by simp [hx, hv] ⟩
open_locale classical
lemma cons_nonzero_iff {v : fin n → α} {x : α} :
vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) :=
⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr),
λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩
end zero
section neg
variables [has_neg α]
@[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _
@[simp] lemma neg_cons (x : α) (v : fin n → α) :
-(vec_cons x v) = vec_cons (-x) (-v) :=
by { ext i, refine fin.cases _ _ i; simp }
@[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl
@[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl
end neg
section minor
@[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') :
minor A row col = ![] :=
empty_eq _
@[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') :
minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) :=
by { ext i j, refine fin.cases _ _ i; simp [minor] }
end minor
end matrix
|
1fdeef7d1c6adf3b5861e1e0e9853a1def0dc9b8 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/propositional_logic/precedence/rules_of_reasoning.lean | 3dc9fe463b8a307e7f544cc0bba87d5f9055892f | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,963 | lean | --import .prop_logic
import .propositional_logic_syntax_and_semantics
open pExp
/-
Here are three propositional variables,
P, Q, and R.
-/
def P := pVar (var.mk 0)
def Q := pVar (var.mk 1)
def R := pVar (var.mk 2)
/-
Below are 20+ formulae in propositional
logic. Your job is to classify each as
valid or not valid. To do this you will
produe a truth table for each one. It is
good that we have an automatic evaluator
as that makes the job easy. For each of
the formulae that is not valid, give an
English language counterexample: some
scenario that shows that the formula is
not always true.
To do this assignment, produce a truth table
for each formula and use the result to tell
if a formula is valid or not. Remember that
each row of a truth table corresponds to one
interpretation and gives the value of such a
formula under that specific interpretation.
Some of the formulae contain only one variable.
We will always use P in these cases. You will
need two interpretations in these cases. Call
them Pt and Pf. Some formula have two variables,
P and Q. You will need four interpretations in
these cases. Call them PtQt, PtQf, etc. Finally
some formula use three variables. Call the
interpretations for these cases PtQtRt, etc.
Define your interpretations, for formulae with
one, two, and three variables, respectively, here.
-/
-- Answer
/-
Beneath each formula, below, evaluate it under
each of its possible interpretations. Hint: use
pEval!
The results will tell you whether the formula
is valid or not. It'll also tell you under
which of the interpretations, if any, it is
not true.
From the results, you can then decide whether
each formula is valid or not.
-/
def true_intro : pExp := pTrue
-- truth table here (some number of pEvals)
-- classification here (valid or not)
def false_elim := pFalse >> P
-- answer here
#eval pEval false_elim _
#eval pEval false_elim _
def true_imp := pTrue >> P
-- etc
def and_intro := P >> Q >> P ∧ Q
def and_elim_left := P ∧ Q >> P
def and_elim_right := P ∧ Q >> Q
def or_intro_left := P >> P ∨ Q
def or_intro_right := Q >> P ∨ Q
def or_elim := P ∨ Q >> (P >> R) >> (Q >> R) >> R
def iff_intro := (P >> Q) >> (Q >> P) >> (P ↔ Q)
def iff_intro' := (P >> Q) ∧ (Q >> P) >> (P ↔ Q)
def iff_elim_left := (P ↔ Q) >> (P >> Q)
def iff_elim_right := (P ↔ Q) >> (Q >> P)
def arrow_elim := (P >> Q) >> (P >> Q)
def resolution := (P ∨ Q) >> (¬ Q ∨ R) >> (P ∨ R)
def unit_resolution := (P ∨ Q) >> ((¬ Q) >> P)
def syllogism := (P >> Q) >> (Q >> R) >> (P >> R)
def modus_tollens := (P >> Q) >> (¬ Q >> ¬ P)
def neg_elim := (¬ ¬ P) >> P
def excluded_middle := P ∨ (¬ P)
def neg_intro := (P >> pFalse) >> (¬ P)
def affirm_consequence := (P >> Q) >> (Q >> P)
-- fallacy
/-
Counterexample. Just because I know that if it's raining the streets are wet,
I don't necessarily know that if the streets wet it's raining, because there
could be other causes for the street to be wet.
-/
def affirm_disjunct := (P ∨ Q) >> (P >> ¬ Q)
def deny_antecedent := (P >> Q) >> (¬ P >> ¬ Q)
axioms A B : Prop
#check A ∨ B ∧ B ∨ A
#check (A ∨ B) ∧ (B ∨ A)
#check A ∨ (B ∧ B) ∨ A
#check A ∨ B → B ∨ A
#check (A ∨ B) → (B ∨ A)
#check A ∨ (B → B) ∨ A
#check A → B ↔ B → A
#check (A → B) ↔ (B → A)
#check A → (B ↔ B) → A
#check A ↔ B ∨ B ↔ A
#check (A ↔ B) ∨ (B ↔ A)
#check A ↔ (B ∨ B) ↔ A
#check A → B ∨ B → A
#check (A → B) ∨ (B → A)
#check A → (B ∨ B) → A
/-
Study the valid rules and learn their names.
These rules, which, here, we are validating
"semantically" (by the method of truth tables)
will become fundamental "rules of inference",
for reasoning "syntactically" when we get to
predicate logic. There is not much memorizing
in this class, but this is one case where you
will find it important to learn the names and
definitions of these rules.
-/ |
36fdb1294f3a8370c7ae1b3a2cd911d2752f61a6 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/order/basic.lean | dfbae895f965a467c92e559bc5689d66d8392328 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 17,312 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro
-/
import data.subtype
import data.prod
open function
/-!
# Basic definitions about `≤` and `<`
## Definitions
### Predicates on functions
- `monotone f`: a function between two types equipped with `≤` is monotone
if `a ≤ b` implies `f a ≤ f b`.
- `strict_mono f` : a function between two types equipped with `<` is strictly monotone
if `a < b` implies `f a < f b`.
- `order_dual α` : a type tag reversing the meaning of all inequalities.
### Transfering orders
- `order.preimage`, `preorder.lift`: transfer a (pre)order on `β` to an order on `α`
using a function `f : α → β`.
- `partial_order.lift`, `linear_order.lift`, `decidable_linear_order.lift`:
transfer a partial (resp., linear, decidable linear) order on `β` to a partial
(resp., linear, decidable linear) order on `α` using an injective function `f`.
### Extra classes
- `no_top_order`, `no_bot_order`: an order without a maximal/minimal element.
- `densely_ordered`: an order with no gaps, i.e. for any two elements `a<b` there exists
`c`, `a<c<b`.
## Main theorems
- `monotone_of_monotone_nat`: if `f : ℕ → α` and `f n ≤ f (n + 1)` for all `n`, then
`f` is monotone;
- `strict_mono.nat`: if `f : ℕ → α` and `f n < f (n + 1)` for all `n`, then f is strictly monotone.
## TODO
- expand module docs
- automatic construction of dual definitions / theorems
## See also
- `algebra.order` for basic lemmas about orders, and projection notation for orders
## Tags
preorder, order, partial order, linear order, monotone, strictly monotone
-/
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop}
theorem preorder.ext {α} {A B : preorder α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
casesI A, casesI B, congr,
{ funext x y, exact propext (H x y) },
{ funext x y,
dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H,
simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] },
end
theorem partial_order.ext {α} {A B : partial_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { haveI this := preorder.ext H,
casesI A, casesI B, injection this, congr' }
theorem linear_order.ext {α} {A B : linear_order α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
by { haveI this := partial_order.ext H,
casesI A, casesI B, injection this, congr' }
/-- Given a relation `R` on `β` and a function `f : α → β`,
the preimage relation on `α` is defined by `x ≤ y ↔ f x ≤ f y`.
It is the unique relation on `α` making `f` a `rel_embedding`
(assuming `f` is injective). -/
@[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y)
infix ` ⁻¹'o `:80 := order.preimage
/-- The preimage of a decidable order is decidable. -/
instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] :
decidable_rel (f ⁻¹'o s) :=
λ x y, H _ _
section monotone
variables [preorder α] [preorder β] [preorder γ]
/-- A function between preorders is monotone if
`a ≤ b` implies `f a ≤ f b`. -/
def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b
theorem monotone_id : @monotone α α _ _ id := assume x y h, h
theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b
protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) :
monotone (g ∘ f) :=
assume a b h, m_g (m_f h)
protected theorem monotone.iterate {f : α → α} (hf : monotone f) (n : ℕ) : monotone (f^[n]) :=
nat.rec_on n monotone_id (λ n ihn, ihn.comp hf)
lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) :
monotone f | n m h :=
begin
induction h,
{ refl },
{ transitivity, assumption, exact hf _ }
end
lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f)
{x x' : α} (h : f x < f x') : x < x' :=
by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' }
end monotone
/-- A function `f` is strictly monotone if `a < b` implies `f a < f b`. -/
def strict_mono [has_lt α] [has_lt β] (f : α → β) : Prop :=
∀ ⦃a b⦄, a < b → f a < f b
lemma strict_mono_id [has_lt α] : strict_mono (id : α → α) := λ a b, id
/-- A function `f` is strictly monotone increasing on `t` if `x < y` for `x,y ∈ t` implies
`f x < f y`. -/
def strict_mono_incr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop :=
∀ (x ∈ t) (y ∈ t), x < y → f x < f y
/-- A function `f` is strictly monotone decreasing on `t` if `x < y` for `x,y ∈ t` implies
`f y < f x`. -/
def strict_mono_decr_on [has_lt α] [has_lt β] (f : α → β) (t : set α) : Prop :=
∀ (x ∈ t) (y ∈ t), x < y → f y < f x
namespace strict_mono
open ordering function
lemma comp [has_lt α] [has_lt β] [has_lt γ] {g : β → γ} {f : α → β}
(hg : strict_mono g) (hf : strict_mono f) :
strict_mono (g ∘ f) :=
λ a b h, hg (hf h)
protected theorem iterate [has_lt α] {f : α → α} (hf : strict_mono f) (n : ℕ) :
strict_mono (f^[n]) :=
nat.rec_on n strict_mono_id (λ n ihn, ihn.comp hf)
lemma id_le {φ : ℕ → ℕ} (h : strict_mono φ) : ∀ n, n ≤ φ n :=
λ n, nat.rec_on n (nat.zero_le _) (λ n hn, nat.succ_le_of_lt (lt_of_le_of_lt hn $ h $ nat.lt_succ_self n))
section
variables [linear_order α] [preorder β] {f : α → β}
lemma lt_iff_lt (H : strict_mono f) {a b} :
f a < f b ↔ a < b :=
⟨λ h, ((lt_trichotomy b a)
.resolve_left $ λ h', lt_asymm h $ H h')
.resolve_left $ λ e, ne_of_gt h $ congr_arg _ e, @H _ _⟩
lemma injective (H : strict_mono f) : injective f
| a b e := ((lt_trichotomy a b)
.resolve_left $ λ h, ne_of_lt (H h) e)
.resolve_right $ λ h, ne_of_gt (H h) e
theorem compares (H : strict_mono f) {a b} :
∀ {o}, compares o (f a) (f b) ↔ compares o a b
| lt := H.lt_iff_lt
| eq := ⟨λ h, H.injective h, congr_arg _⟩
| gt := H.lt_iff_lt
lemma le_iff_le (H : strict_mono f) {a b} :
f a ≤ f b ↔ a ≤ b :=
⟨λ h, le_of_not_gt $ λ h', not_le_of_lt (H h') h,
λ h, (lt_or_eq_of_le h).elim (λ h', le_of_lt (H h')) (λ h', h' ▸ le_refl _)⟩
lemma top_preimage_top (H : strict_mono f) {a} (h_top : ∀ p, p ≤ f a) (x : α) : x ≤ a :=
H.le_iff_le.mp (h_top (f x))
lemma bot_preimage_bot (H : strict_mono f) {a} (h_bot : ∀ p, f a ≤ p) (x : α) : a ≤ x :=
H.le_iff_le.mp (h_bot (f x))
end
protected lemma nat {β} [preorder β] {f : ℕ → β} (h : ∀n, f n < f (n+1)) : strict_mono f :=
by { intros n m hnm, induction hnm with m' hnm' ih, apply h, exact ih.trans (h _) }
-- `preorder α` isn't strong enough: if the preorder on α is an equivalence relation,
-- then `strict_mono f` is vacuously true.
lemma monotone [partial_order α] [preorder β] {f : α → β} (H : strict_mono f) : monotone f :=
λ a b h, (lt_or_eq_of_le h).rec (le_of_lt ∘ (@H _ _)) (by rintro rfl; refl)
end strict_mono
section
open function
lemma injective_of_lt_imp_ne [linear_order α] {f : α → β} (h : ∀ x y, x < y → f x ≠ f y) : injective f :=
begin
intros x y k,
contrapose k,
rw [←ne.def, ne_iff_lt_or_gt] at k,
cases k,
{ apply h _ _ k },
{ rw eq_comm,
apply h _ _ k }
end
lemma strict_mono_of_monotone_of_injective [partial_order α] [partial_order β] {f : α → β}
(h₁ : monotone f) (h₂ : injective f) : strict_mono f :=
λ a b h,
begin
rw lt_iff_le_and_ne at ⊢ h,
exact ⟨h₁ h.1, λ e, h.2 (h₂ e)⟩
end
lemma strict_mono_of_le_iff_le [preorder α] [preorder β] {f : α → β}
(h : ∀ x y, x ≤ y ↔ f x ≤ f y) : strict_mono f :=
λ a b, by simp [lt_iff_le_not_le, h] {contextual := tt}
end
/-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/
def order_dual (α : Type*) := α
namespace order_dual
instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h
instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩
instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩
-- `dual_le` and `dual_lt` should not be simp lemmas:
-- they cause a loop since `α` and `order_dual α` are definitionally equal
lemma dual_le [has_le α] {a b : α} :
@has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl
lemma dual_lt [has_lt α] {a b : α} :
@has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl
instance (α : Type*) [preorder α] : preorder (order_dual α) :=
{ le_refl := le_refl,
le_trans := assume a b c hab hbc, hbc.trans hab,
lt_iff_le_not_le := λ _ _, lt_iff_le_not_le,
.. order_dual.has_le α,
.. order_dual.has_lt α }
instance (α : Type*) [partial_order α] : partial_order (order_dual α) :=
{ le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α }
instance (α : Type*) [linear_order α] : linear_order (order_dual α) :=
{ le_total := assume a b:α, le_total b a, .. order_dual.partial_order α }
instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) :=
{ decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance,
decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance,
.. order_dual.linear_order α }
instance : Π [inhabited α], inhabited (order_dual α) := id
end order_dual
/- order instances on the function space -/
instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) :=
{ le := λx y, ∀i, x i ≤ y i,
le_refl := assume a i, le_refl (a i),
le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) }
instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] :
partial_order (Πi, α i) :=
{ le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)),
..pi.preorder }
theorem comp_le_comp_left_of_monotone [preorder α] [preorder β]
{f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) :
has_le.le.{max w u} (f ∘ g) (f ∘ h) :=
assume x, m_f (le_gh x)
section monotone
variables [preorder α] [preorder γ]
protected theorem monotone.order_dual {f : α → γ} (hf : monotone f) :
@monotone (order_dual α) (order_dual γ) _ _ f :=
λ x y hxy, hf hxy
theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f :=
assume a a' h b, m b h
theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) :=
assume a a' h, m h b
end monotone
theorem strict_mono.order_dual [has_lt α] [has_lt β] {f : α → β} (hf : strict_mono f) :
@strict_mono (order_dual α) (order_dual β) _ _ f :=
λ x y hxy, hf hxy
/-- Transfer a `preorder` on `β` to a `preorder` on `α` using a function `f : α → β`. -/
def preorder.lift {α β} [preorder β] (f : α → β) : preorder α :=
{ le := λx y, f x ≤ f y,
le_refl := λ a, le_refl _,
le_trans := λ a b c, le_trans,
lt := λx y, f x < f y,
lt_iff_le_not_le := λ a b, lt_iff_le_not_le }
/-- Transfer a `partial_order` on `β` to a `partial_order` on `α` using an injective
function `f : α → β`. -/
def partial_order.lift {α β} [partial_order β] (f : α → β) (inj : injective f) :
partial_order α :=
{ le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f }
/-- Transfer a `linear_order` on `β` to a `linear_order` on `α` using an injective
function `f : α → β`. -/
def linear_order.lift {α β} [linear_order β] (f : α → β) (inj : injective f) :
linear_order α :=
{ le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj }
/-- Transfer a `decidable_linear_order` on `β` to a `decidable_linear_order` on `α` using
an injective function `f : α → β`. -/
def decidable_linear_order.lift {α β} [decidable_linear_order β] (f : α → β) (inj : injective f) :
decidable_linear_order α :=
{ decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance,
decidable_lt := λ x y, show decidable (f x < f y), by apply_instance,
decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩,
.. linear_order.lift f inj }
instance subtype.preorder {α} [preorder α] (p : α → Prop) : preorder (subtype p) :=
preorder.lift subtype.val
instance subtype.partial_order {α} [partial_order α] (p : α → Prop) :
partial_order (subtype p) :=
partial_order.lift subtype.val subtype.val_injective
instance subtype.linear_order {α} [linear_order α] (p : α → Prop) : linear_order (subtype p) :=
linear_order.lift subtype.val subtype.val_injective
instance subtype.decidable_linear_order {α} [decidable_linear_order α] (p : α → Prop) :
decidable_linear_order (subtype p) :=
decidable_linear_order.lift subtype.val subtype.val_injective
instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) :=
⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩
instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) :=
{ le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩,
le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩,
⟨le_trans hac hce, le_trans hbd hdf⟩,
.. prod.has_le α β }
/-- The pointwise partial order on a product.
(The lexicographic ordering is defined in order/lexicographic.lean, and the instances are
available via the type synonym `lex α β = α × β`.) -/
instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] :
partial_order (α × β) :=
{ le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩,
prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb),
.. prod.preorder α β }
/-!
### Additional order classes
-/
/-- order without a top element; somtimes called cofinal -/
class no_top_order (α : Type u) [preorder α] : Prop :=
(no_top : ∀a:α, ∃a', a < a')
lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' :=
no_top_order.no_top
instance nonempty_gt {α : Type u} [preorder α] [no_top_order α] (a : α) :
nonempty {x // a < x} :=
nonempty_subtype.2 (no_top a)
/-- order without a bottom element; somtimes called coinitial or dense -/
class no_bot_order (α : Type u) [preorder α] : Prop :=
(no_bot : ∀a:α, ∃a', a' < a)
lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a :=
no_bot_order.no_bot
instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] :
no_top_order (order_dual α) :=
⟨λ a, @no_bot α _ _ a⟩
instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] :
no_bot_order (order_dual α) :=
⟨λ a, @no_top α _ _ a⟩
instance nonempty_lt {α : Type u} [preorder α] [no_bot_order α] (a : α) :
nonempty {x // x < a} :=
nonempty_subtype.2 (no_bot a)
/-- An order is dense if there is an element between any pair of distinct elements. -/
class densely_ordered (α : Type u) [preorder α] : Prop :=
(dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂)
lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ :=
densely_ordered.dense
instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] :
densely_ordered (order_dual α) :=
⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩
lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h : ∀a₃>a₂, a₁ ≤ a₃) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›)
lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ :=
le_antisymm (le_of_forall_le_of_dense h₂) h₁
lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h : ∀a₃<a₁, a₃ ≤ a₂) :
a₁ ≤ a₂ :=
le_of_not_gt $ assume ha,
let ⟨a, ha₁, ha₂⟩ := dense ha in
lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a›
lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}
(h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₃ ≤ a₂) : a₁ = a₂ :=
le_antisymm (le_of_forall_ge_of_dense h₂) h₁
lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) :
(∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a₂ ≤ a) ∧ (∀a<a₂, a ≤ a₁)) :=
or_iff_not_imp_left.2 $ assume h,
⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩,
assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩
variables {s : β → β → Prop} {t : γ → γ → Prop}
/-- Any `linear_order` is a noncomputable `decidable_linear_order`. This is not marked
as an instance to avoid a loop. -/
noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α :=
{ decidable_le := classical.dec_rel _, ..LO }
|
2c59fff7fc3a29742f37ae681463e40ba0e80753 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/reflects_isomorphisms.lean | c700299b0b8074b91d65cfaac929e8e48c9e836e | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,409 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.fully_faithful
import Mathlib.PostPort
universes v₁ v₂ u₁ u₂ l
namespace Mathlib
namespace category_theory
/--
Define what it means for a functor `F : C ⥤ D` to reflect isomorphisms: for any
morphism `f : A ⟶ B`, if `F.map f` is an isomorphism then `f` is as well.
Note that we do not assume or require that `F` is faithful.
-/
class reflects_isomorphisms {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D)
where
reflects : {A B : C} → (f : A ⟶ B) → [_inst_3 : is_iso (functor.map F f)] → is_iso f
/-- If `F` reflects isos and `F.map f` is an iso, then `f` is an iso. -/
def is_iso_of_reflects_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {A : C} {B : C} (f : A ⟶ B) (F : C ⥤ D) [is_iso (functor.map F f)] [reflects_isomorphisms F] : is_iso f :=
reflects_isomorphisms.reflects F f
protected instance of_full_and_faithful {C : Type u₁} [category C] {D : Type u₂} [category D] (F : C ⥤ D) [full F] [faithful F] : reflects_isomorphisms F :=
reflects_isomorphisms.mk
fun (X Y : C) (f : X ⟶ Y) (i : is_iso (functor.map F f)) => is_iso.mk (functor.preimage F (inv (functor.map F f)))
|
4b4ba2389d8ddfb835c807f4ef43ea1e6b770fba | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/locally_convex/bounded.lean | d26f8bcfcdcaa01469da94f69b754710bd71f0fd | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 10,007 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll
-/
import analysis.locally_convex.basic
import analysis.locally_convex.balanced_core_hull
import analysis.seminorm
import topology.bornology.basic
import topology.algebra.uniform_group
import topology.uniform_space.cauchy
/-!
# Von Neumann Boundedness
This file defines natural or von Neumann bounded sets and proves elementary properties.
## Main declarations
* `bornology.is_vonN_bounded`: A set `s` is von Neumann-bounded if every neighborhood of zero
absorbs `s`.
* `bornology.vonN_bornology`: The bornology made of the von Neumann-bounded sets.
## Main results
* `bornology.is_vonN_bounded.of_topological_space_le`: A coarser topology admits more
von Neumann-bounded sets.
* `bornology.is_vonN_bounded.image`: A continuous linear image of a bounded set is bounded.
## References
* [Bourbaki, *Topological Vector Spaces*][bourbaki1987]
-/
variables {𝕜 𝕜' E E' F ι : Type*}
open filter
open_locale topological_space pointwise
namespace bornology
section semi_normed_ring
section has_zero
variables (𝕜)
variables [semi_normed_ring 𝕜] [has_smul 𝕜 E] [has_zero E]
variables [topological_space E]
/-- A set `s` is von Neumann bounded if every neighborhood of 0 absorbs `s`. -/
def is_vonN_bounded (s : set E) : Prop := ∀ ⦃V⦄, V ∈ 𝓝 (0 : E) → absorbs 𝕜 V s
variables (E)
@[simp] lemma is_vonN_bounded_empty : is_vonN_bounded 𝕜 (∅ : set E) :=
λ _ _, absorbs_empty
variables {𝕜 E}
lemma is_vonN_bounded_iff (s : set E) : is_vonN_bounded 𝕜 s ↔ ∀ V ∈ 𝓝 (0 : E), absorbs 𝕜 V s :=
iff.rfl
lemma _root_.filter.has_basis.is_vonN_bounded_basis_iff {q : ι → Prop} {s : ι → set E} {A : set E}
(h : (𝓝 (0 : E)).has_basis q s) :
is_vonN_bounded 𝕜 A ↔ ∀ i (hi : q i), absorbs 𝕜 (s i) A :=
begin
refine ⟨λ hA i hi, hA (h.mem_of_mem hi), λ hA V hV, _⟩,
rcases h.mem_iff.mp hV with ⟨i, hi, hV⟩,
exact (hA i hi).mono_left hV,
end
/-- Subsets of bounded sets are bounded. -/
lemma is_vonN_bounded.subset {s₁ s₂ : set E} (h : s₁ ⊆ s₂) (hs₂ : is_vonN_bounded 𝕜 s₂) :
is_vonN_bounded 𝕜 s₁ :=
λ V hV, (hs₂ hV).mono_right h
/-- The union of two bounded sets is bounded. -/
lemma is_vonN_bounded.union {s₁ s₂ : set E} (hs₁ : is_vonN_bounded 𝕜 s₁)
(hs₂ : is_vonN_bounded 𝕜 s₂) :
is_vonN_bounded 𝕜 (s₁ ∪ s₂) :=
λ V hV, (hs₁ hV).union (hs₂ hV)
end has_zero
end semi_normed_ring
section multiple_topologies
variables [semi_normed_ring 𝕜] [add_comm_group E] [module 𝕜 E]
/-- If a topology `t'` is coarser than `t`, then any set `s` that is bounded with respect to
`t` is bounded with respect to `t'`. -/
lemma is_vonN_bounded.of_topological_space_le {t t' : topological_space E} (h : t ≤ t') {s : set E}
(hs : @is_vonN_bounded 𝕜 E _ _ _ t s) : @is_vonN_bounded 𝕜 E _ _ _ t' s :=
λ V hV, hs $ (le_iff_nhds t t').mp h 0 hV
end multiple_topologies
section image
variables {𝕜₁ 𝕜₂ : Type*} [normed_division_ring 𝕜₁] [normed_division_ring 𝕜₂]
[add_comm_group E] [module 𝕜₁ E] [add_comm_group F] [module 𝕜₂ F]
[topological_space E] [topological_space F]
/-- A continuous linear image of a bounded set is bounded. -/
lemma is_vonN_bounded.image {σ : 𝕜₁ →+* 𝕜₂} [ring_hom_surjective σ] [ring_hom_isometric σ]
{s : set E} (hs : is_vonN_bounded 𝕜₁ s) (f : E →SL[σ] F) :
is_vonN_bounded 𝕜₂ (f '' s) :=
begin
let σ' := ring_equiv.of_bijective σ ⟨σ.injective, σ.is_surjective⟩,
have σ_iso : isometry σ := add_monoid_hom_class.isometry_of_norm σ
(λ x, ring_hom_isometric.is_iso),
have σ'_symm_iso : isometry σ'.symm := σ_iso.right_inv σ'.right_inv,
have f_tendsto_zero := f.continuous.tendsto 0,
rw map_zero at f_tendsto_zero,
intros V hV,
rcases hs (f_tendsto_zero hV) with ⟨r, hrpos, hr⟩,
refine ⟨r, hrpos, λ a ha, _⟩,
rw ← σ'.apply_symm_apply a,
have hanz : a ≠ 0 := norm_pos_iff.mp (hrpos.trans_le ha),
have : σ'.symm a ≠ 0 := (map_ne_zero σ'.symm.to_ring_hom).mpr hanz,
change _ ⊆ σ _ • _,
rw [set.image_subset_iff, preimage_smul_setₛₗ _ _ _ f this.is_unit],
refine hr (σ'.symm a) _,
rwa σ'_symm_iso.norm_map_of_map_zero (map_zero _)
end
end image
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
variables [topological_space E] [has_continuous_smul 𝕜 E]
/-- Singletons are bounded. -/
lemma is_vonN_bounded_singleton (x : E) : is_vonN_bounded 𝕜 ({x} : set E) :=
λ V hV, (absorbent_nhds_zero hV).absorbs
/-- The union of all bounded set is the whole space. -/
lemma is_vonN_bounded_covers : ⋃₀ (set_of (is_vonN_bounded 𝕜)) = (set.univ : set E) :=
set.eq_univ_iff_forall.mpr (λ x, set.mem_sUnion.mpr
⟨{x}, is_vonN_bounded_singleton _, set.mem_singleton _⟩)
variables (𝕜 E)
/-- The von Neumann bornology defined by the von Neumann bounded sets.
Note that this is not registered as an instance, in order to avoid diamonds with the
metric bornology.-/
@[reducible] -- See note [reducible non-instances]
def vonN_bornology : bornology E :=
bornology.of_bounded (set_of (is_vonN_bounded 𝕜)) (is_vonN_bounded_empty 𝕜 E)
(λ _ hs _ ht, hs.subset ht) (λ _ hs _, hs.union) is_vonN_bounded_singleton
variables {E}
@[simp] lemma is_bounded_iff_is_vonN_bounded {s : set E} :
@is_bounded _ (vonN_bornology 𝕜 E) s ↔ is_vonN_bounded 𝕜 s :=
is_bounded_of_bounded_iff _
end normed_field
end bornology
section uniform_add_group
variables (𝕜) [nontrivially_normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
variables [uniform_space E] [uniform_add_group E] [has_continuous_smul 𝕜 E]
lemma totally_bounded.is_vonN_bounded {s : set E} (hs : totally_bounded s) :
bornology.is_vonN_bounded 𝕜 s :=
begin
rw totally_bounded_iff_subset_finite_Union_nhds_zero at hs,
intros U hU,
have h : filter.tendsto (λ (x : E × E), x.fst + x.snd) (𝓝 (0,0)) (𝓝 ((0 : E) + (0 : E))) :=
tendsto_add,
rw add_zero at h,
have h' := (nhds_basis_balanced 𝕜 E).prod (nhds_basis_balanced 𝕜 E),
simp_rw [←nhds_prod_eq, id.def] at h',
rcases h.basis_left h' U hU with ⟨x, hx, h''⟩,
rcases hs x.snd hx.2.1 with ⟨t, ht, hs⟩,
refine absorbs.mono_right _ hs,
rw ht.absorbs_Union,
have hx_fstsnd : x.fst + x.snd ⊆ U,
{ intros z hz,
rcases set.mem_add.mp hz with ⟨z1, z2, hz1, hz2, hz⟩,
have hz' : (z1, z2) ∈ x.fst ×ˢ x.snd := ⟨hz1, hz2⟩,
simpa only [hz] using h'' hz' },
refine λ y hy, absorbs.mono_left _ hx_fstsnd,
rw [←set.singleton_vadd, vadd_eq_add],
exact (absorbent_nhds_zero hx.1.1).absorbs.add hx.2.2.absorbs_self,
end
end uniform_add_group
section vonN_bornology_eq_metric
variables (𝕜 E) [nontrivially_normed_field 𝕜] [seminormed_add_comm_group E] [normed_space 𝕜 E]
namespace normed_space
lemma is_vonN_bounded_ball (r : ℝ) :
bornology.is_vonN_bounded 𝕜 (metric.ball (0 : E) r) :=
begin
rw [metric.nhds_basis_ball.is_vonN_bounded_basis_iff, ← ball_norm_seminorm 𝕜 E],
exact λ ε hε, (norm_seminorm 𝕜 E).ball_zero_absorbs_ball_zero hε
end
lemma is_vonN_bounded_closed_ball (r : ℝ) :
bornology.is_vonN_bounded 𝕜 (metric.closed_ball (0 : E) r) :=
(is_vonN_bounded_ball 𝕜 E (r+1)).subset (metric.closed_ball_subset_ball $ by linarith)
lemma is_vonN_bounded_iff (s : set E) :
bornology.is_vonN_bounded 𝕜 s ↔ bornology.is_bounded s :=
begin
rw [← metric.bounded_iff_is_bounded, metric.bounded_iff_subset_ball (0 : E)],
split,
{ intros h,
rcases h (metric.ball_mem_nhds 0 zero_lt_one) with ⟨ρ, hρ, hρball⟩,
rcases normed_field.exists_lt_norm 𝕜 ρ with ⟨a, ha⟩,
specialize hρball a ha.le,
rw [← ball_norm_seminorm 𝕜 E, seminorm.smul_ball_zero (hρ.trans ha),
ball_norm_seminorm, mul_one] at hρball,
exact ⟨‖a‖, hρball.trans metric.ball_subset_closed_ball⟩ },
{ exact λ ⟨C, hC⟩, (is_vonN_bounded_closed_ball 𝕜 E C).subset hC }
end
lemma is_vonN_bounded_iff' (s : set E) :
bornology.is_vonN_bounded 𝕜 s ↔ ∃ r : ℝ, ∀ (x : E) (hx : x ∈ s), ‖x‖ ≤ r :=
by rw [normed_space.is_vonN_bounded_iff, ←metric.bounded_iff_is_bounded, bounded_iff_forall_norm_le]
lemma image_is_vonN_bounded_iff (f : E' → E) (s : set E') :
bornology.is_vonN_bounded 𝕜 (f '' s) ↔ ∃ r : ℝ, ∀ (x : E') (hx : x ∈ s), ‖f x‖ ≤ r :=
by simp_rw [is_vonN_bounded_iff', set.ball_image_iff]
/-- In a normed space, the von Neumann bornology (`bornology.vonN_bornology`) is equal to the
metric bornology. -/
lemma vonN_bornology_eq : bornology.vonN_bornology 𝕜 E = pseudo_metric_space.to_bornology :=
begin
rw bornology.ext_iff_is_bounded,
intro s,
rw bornology.is_bounded_iff_is_vonN_bounded,
exact is_vonN_bounded_iff 𝕜 E s
end
variable (𝕜)
lemma is_bounded_iff_subset_smul_ball {s : set E} :
bornology.is_bounded s ↔ ∃ a : 𝕜, s ⊆ a • metric.ball 0 1 :=
begin
rw ← is_vonN_bounded_iff 𝕜,
split,
{ intros h,
rcases h (metric.ball_mem_nhds 0 zero_lt_one) with ⟨ρ, hρ, hρball⟩,
rcases normed_field.exists_lt_norm 𝕜 ρ with ⟨a, ha⟩,
exact ⟨a, hρball a ha.le⟩ },
{ rintros ⟨a, ha⟩,
exact ((is_vonN_bounded_ball 𝕜 E 1).image (a • 1 : E →L[𝕜] E)).subset ha }
end
lemma is_bounded_iff_subset_smul_closed_ball {s : set E} :
bornology.is_bounded s ↔ ∃ a : 𝕜, s ⊆ a • metric.closed_ball 0 1 :=
begin
split,
{ rw is_bounded_iff_subset_smul_ball 𝕜,
exact exists_imp_exists
(λ a ha, ha.trans $ set.smul_set_mono $ metric.ball_subset_closed_ball) },
{ rw ← is_vonN_bounded_iff 𝕜,
rintros ⟨a, ha⟩,
exact ((is_vonN_bounded_closed_ball 𝕜 E 1).image (a • 1 : E →L[𝕜] E)).subset ha }
end
end normed_space
end vonN_bornology_eq_metric
|
ab4a0eb648e750fca6822795061cb1936877fe42 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/analysis/normed_space/completion.lean | bac77e02d11220a37bdd12c6826bf49a2e12087d | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 3,709 | lean | /-
Copyright (c) 2022 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.normed.group.completion
import analysis.normed_space.operator_norm
import topology.algebra.uniform_ring
/-!
# Normed space structure on the completion of a normed space
If `E` is a normed space over `𝕜`, then so is `uniform_space.completion E`. In this file we provide
necessary instances and define `uniform_space.completion.to_complₗᵢ` - coercion
`E → uniform_space.completion E` as a bundled linear isometry.
We also show that if `A` is a normed algebra over `𝕜`, then so is `uniform_space.completion A`.
TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`.
-/
noncomputable theory
namespace uniform_space
namespace completion
variables (𝕜 E : Type*) [normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E]
@[priority 100]
instance normed_space.to_has_uniform_continuous_const_smul :
has_uniform_continuous_const_smul 𝕜 E :=
⟨λ c, (lipschitz_with_smul c).uniform_continuous⟩
instance : normed_space 𝕜 (completion E) :=
{ smul := (•),
norm_smul_le := λ c x, induction_on x
(is_closed_le (continuous_const_smul _).norm (continuous_const.mul continuous_norm)) $
λ y, by simp only [← coe_smul, norm_coe, norm_smul],
.. completion.module }
variables {𝕜 E}
/-- Embedding of a normed space to its completion as a linear isometry. -/
def to_complₗᵢ : E →ₗᵢ[𝕜] completion E :=
{ to_fun := coe,
map_smul' := coe_smul,
norm_map' := norm_coe,
.. to_compl }
@[simp] lemma coe_to_complₗᵢ : ⇑(to_complₗᵢ : E →ₗᵢ[𝕜] completion E) = coe := rfl
/-- Embedding of a normed space to its completion as a continuous linear map. -/
def to_complL : E →L[𝕜] completion E :=
to_complₗᵢ.to_continuous_linear_map
@[simp] lemma coe_to_complL : ⇑(to_complL : E →L[𝕜] completion E) = coe := rfl
@[simp] lemma norm_to_complL {𝕜 E : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E]
[normed_space 𝕜 E] [nontrivial E] : ‖(to_complL : E →L[𝕜] completion E)‖ = 1 :=
(to_complₗᵢ : E →ₗᵢ[𝕜] completion E).norm_to_continuous_linear_map
section algebra
variables (𝕜) (A : Type*)
instance [semi_normed_ring A] : normed_ring (completion A) :=
{ dist_eq := λ x y,
begin
apply completion.induction_on₂ x y; clear x y,
{ refine is_closed_eq (completion.uniform_continuous_extension₂ _).continuous _,
exact continuous.comp completion.continuous_extension continuous_sub },
{ intros x y,
rw [← completion.coe_sub, norm_coe, completion.dist_eq, dist_eq_norm] }
end,
norm_mul := λ x y,
begin
apply completion.induction_on₂ x y; clear x y,
{ exact is_closed_le (continuous.comp (continuous_norm) continuous_mul) (continuous.comp
real.continuous_mul (continuous.prod_map continuous_norm continuous_norm)) },
{ intros x y,
simp only [← coe_mul, norm_coe], exact norm_mul_le x y, }
end,
..completion.ring,
..completion.metric_space }
instance [semi_normed_comm_ring A] [normed_algebra 𝕜 A] [has_uniform_continuous_const_smul 𝕜 A] :
normed_algebra 𝕜 (completion A) :=
{ norm_smul_le := λ r x,
begin
apply completion.induction_on x; clear x,
{ exact is_closed_le (continuous.comp (continuous_norm) (continuous_const_smul r))
(continuous.comp (continuous_mul_left _) continuous_norm), },
{ intros x,
simp only [← coe_smul, norm_coe], exact norm_smul_le r x }
end,
..completion.algebra A 𝕜}
end algebra
end completion
end uniform_space
|
79ad0422ff8251f509c48d636e64d6a308fd7b05 | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/myring/polynomial_ring.lean | 3d8f6a397c6fd62fc33848714b8278ae1dc8c578 | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 8,337 | lean | import .basic
import ..logic
import ..sequence
import ..mynat.max
namespace hidden
namespace myring
structure polynomial (α : Type) [myring α] :=
(seq : sequence α)
(eventually_zero : ∃ N, ∀ n, N ≤ n → seq n = 0)
namespace polynomial
variables {α : Type} [myring α]
theorem polyext (a b : polynomial α) : (∀ n, a.seq n = b.seq n) → a = b :=
begin
assume h,
cases a,
cases b,
dsimp at h,
simp,
apply funext,
assumption,
end
def add : polynomial α → polynomial α → polynomial α :=
λ a b, ⟨a.seq + b.seq, begin
cases a.eventually_zero with N hN,
cases b.eventually_zero with M hM,
existsi (mynat.max N M),
intros n hn,
change a.seq n + b.seq n = 0,
suffices h₁ : a.seq n = 0,
suffices h₂ : b.seq n = 0,
rw [h₁, h₂, add_zero],
apply hM,
apply @mynat.max_le_cancel_right N M n,
assumption,
apply hN,
apply @mynat.max_le_cancel_left N M n,
assumption,
end⟩
instance: has_add (polynomial α) := ⟨add⟩
instance: has_zero (polynomial α) := ⟨⟨λ n, 0, begin
existsi (0 : mynat),
intros n hn,
refl,
end⟩⟩
def neg : polynomial α → polynomial α :=
λ a, ⟨λ n, -a.seq n, begin
cases a.eventually_zero with N hN,
existsi N,
intros n hn,
symmetry,
rw [←neg_unique, zero_add],
apply hN,
assumption,
end⟩
instance: has_neg (polynomial α) := ⟨neg⟩
-- Same formula for power series ring
-- term_collection a b m n = a_m b_n + a_{m + 1} b_{n-1} + ... + a_{m + n} b_0
private def term_collection (seq₁ : sequence α) (seq₂ : sequence α) : mynat → mynat → α
| m 0 := seq₁ m * seq₂ 0
| m (mynat.succ n) := seq₁ m * seq₂ (n.succ) + (term_collection m.succ n)
private lemma term_collection_zero (seq₁ seq₂ : sequence α) (m n N : mynat)
(h : ∀ a b, N ≤ a + b → seq₁ a * seq₂ b = 0) :
(N ≤ m + n → term_collection seq₁ seq₂ m n = 0) :=
begin
assume hmnN,
-- Holy fuck it took me ages to remember `generalizing`
induction n with n hn generalizing m, {
rw mynat.zz at *,
unfold term_collection,
apply h,
assumption,
}, {
unfold term_collection,
rw [h m n.succ hmnN, zero_add],
rw mynat.add_succ at hmnN,
apply hn,
rwa mynat.succ_add,
},
end
private lemma term_collection_succ (a b : sequence α) (m n : mynat) :
term_collection a b m.succ n = term_collection a b m n.succ + -(a m * b n.succ) :=
begin
apply add_cancel_right _ _ (a m * b n.succ),
rw [add_assoc, neg_add, add_zero],
dsimp only [term_collection],
rw add_comm,
end
-- Formula for what happens if you swap a and b.
private lemma term_collection_swap_args_lemma (a b : sequence α) (m n : mynat) :
term_collection b a m.succ n + term_collection a b n.succ m = term_collection a b 0 (m + n).succ :=
begin
induction n with n hn generalizing m, {
rw [mynat.zz, mynat.add_zero],
dsimp only [term_collection],
rw mul_comm,
}, {
rw [mynat.add_succ],
have := hn m.succ,
rw mynat.succ_add at this,
rw this.symm,
conv {
congr,
congr,
skip,
rw term_collection_succ,
skip,
congr,
rw term_collection_succ,
skip,
skip,
},
ac_refl,
},
end
private theorem term_collection_swap_args (a b : sequence α) (m n : mynat) :
term_collection b a m.succ n = term_collection a b 0 (m + n).succ + -term_collection a b n.succ m :=
begin
apply add_cancel_right _ _ (term_collection a b n.succ m),
rw [add_assoc, neg_add, add_zero, term_collection_swap_args_lemma],
end
open classical
-- Move to mynat? Prove in ordered_myring?
-- This is a slightly strange method of proof
private lemma sum_lemma {m n M N : mynat} : M + N ≤ m + n → M ≤ m ∨ N ≤ n :=
begin
assume h,
by_cases hm: M ≤ m,
left, assumption,
right,
change m < M at hm,
by_contradiction hn,
change n < N at hn,
rw ←@not_not (M + N ≤ m + n) at h,
change ¬(m + n < M + N) at h,
apply h,
apply mynat.lt_comb; assumption,
end
def mul : polynomial α → polynomial α → polynomial α :=
λ a b, ⟨λ n, term_collection a.seq b.seq 0 n, begin
cases a.eventually_zero with N hN,
cases b.eventually_zero with M hM,
existsi N + M,
intros n hNMn,
apply term_collection_zero _ _ _ _ (N + M),
intros i j hij,
suffices: N ≤ i ∨ M ≤ j,
suffices h₁: a.seq i = 0 ∨ b.seq j = 0,
cases h₁ with h₁a h₁b,
rw [h₁a, zero_mul],
rw [h₁b, mul_zero],
cases this,
left,
apply hN,
assumption,
right,
apply hM,
assumption,
apply sum_lemma,
assumption,
rwa mynat.zero_add,
end⟩
instance: has_mul (polynomial α) := ⟨mul⟩
instance: has_one (polynomial α) := ⟨⟨λ n, if n = 0 then 1 else 0, begin
existsi (1 : mynat),
intro n,
assume h2n,
change (0 : mynat).succ ≤ n at h2n,
rw ←mynat.lt_iff_succ_le at h2n,
apply if_neg,
assume hn0,
apply @mynat.lt_impl_neq 0 n,
assumption,
symmetry, assumption,
end⟩⟩
private lemma term_collection_one_zero (a : sequence α) (m n : mynat) :
term_collection (1 : polynomial α).seq a m.succ n = 0 :=
begin
induction n with n hn generalizing m, {
rw mynat.zz,
dsimp only [term_collection],
change (ite (m.succ = 0) 1 0) * a 0 = 0,
rw [if_neg mynat.succ_ne_zero, zero_mul],
}, {
dsimp only [term_collection],
conv {
congr, congr,
change (ite (m.succ = 0) 1 0) * a n.succ,
},
rw [if_neg (mynat.succ_ne_zero), zero_mul, zero_add],
apply hn,
},
end
private lemma term_collection_distr (a b c : sequence α) (m n : mynat) :
term_collection a (b + c) m n = term_collection a b m n + term_collection a c m n :=
begin
induction n with n hn generalizing m, {
rw mynat.zz,
dsimp only [term_collection],
change a m * (b 0 + c 0)= a m * b 0 + a m * c 0,
rw mul_add,
}, {
dsimp only [term_collection],
rw hn m.succ,
conv {
congr, congr,
change a m * (b n.succ + c n.succ),
rw mul_add,
},
ac_refl,
},
end
variables a b c : polynomial α
private theorem poly_add_assoc : a + b + c = a + (b + c) :=
begin
apply polyext,
intro n,
change a.seq n + b.seq n + c.seq n = a.seq n + (b.seq n + c.seq n),
rw add_assoc,
end
private theorem poly_add_zero : a + 0 = a :=
begin
apply polyext,
intro n,
change a.seq n + 0 = a.seq n,
rw add_zero,
end
private theorem poly_add_neg : a + -a = 0 :=
begin
apply polyext,
intro n,
change a.seq n + -(a.seq n) = 0,
rw add_neg,
end
-- Presumably impossible
private theorem poly_mul_assoc : a * b * c = a * (b * c) :=
begin
sorry,
end
private theorem poly_mul_comm : a * b = b * a :=
begin
apply polyext,
intro n,
change term_collection a.seq b.seq 0 n = term_collection b.seq a.seq 0 n,
cases n,
rw mynat.zz,
dsimp only [term_collection],
rw mul_comm,
conv {
to_lhs,
dsimp only [term_collection],
rw [term_collection_swap_args, mynat.zero_add],
dsimp only [term_collection],
congr,
rw mul_comm,
skip,
rw add_comm,
},
rw [←add_assoc, add_neg, zero_add],
refl,
end
private theorem poly_mul_one : a * 1 = a :=
begin
apply polyext,
intro n,
change term_collection a.seq (1 : polynomial α).seq 0 n = a.seq n,
cases n,
rw mynat.zz,
dsimp only [term_collection],
change a.seq 0 * (ite (0 = 0) 1 0) = a.seq 0,
rw [if_pos rfl, mul_one],
dsimp only [term_collection],
rw [term_collection_swap_args],
conv {
congr, congr,
change a.seq 0 * (ite (n.succ = 0) 1 0),
rw [if_neg mynat.succ_ne_zero, mul_zero],
},
rw [zero_add, mynat.zero_add, term_collection_one_zero, neg_zero, add_zero],
dsimp only [term_collection],
rw [term_collection_one_zero, add_zero],
change (ite (0 = 0) 1 0) * a.seq n.succ = a.seq n.succ,
rw [if_pos rfl, one_mul],
end
-- Nice and easy :)
private theorem poly_mul_add : a * (b + c) = a * b + a * c :=
begin
apply polyext,
intro n,
change term_collection a.seq (b.seq + c.seq) 0 n =
term_collection a.seq b.seq 0 n + term_collection a.seq c.seq 0 n,
rw term_collection_distr,
end
instance: myring (polynomial α) :=
⟨poly_add_assoc, poly_add_zero, poly_add_neg,
poly_mul_assoc, poly_mul_comm, poly_mul_one, poly_mul_add⟩
end polynomial
end myring
end hidden
|
dbc674ad23dce121b47d7692ec38bcfb02381b16 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/simp_ite.lean | 282dff8175a18739f20fdeea66062bb38d35ff5d | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 562 | lean | -- in older versions, this would get stuck on the equality
-- `decidable_of_decidable_of_iff dec_p p_iff_p' = dec_p'`
constants (p p' : Prop) (p_iff_p' : p ↔ p')
attribute [simp] p_iff_p'
example (a b : ℕ) [dec_p : decidable p] [dec_p' : decidable p'] :
(if p then a else b) = (if p' then a else b) :=
by simp
-- `simp` shouldn't try rewrite `p` to `p'` without the instance, but still rewrite `a` to `a'`
constants (a a' b : ℕ) (a_eq_a' : a = a')
attribute [simp] a_eq_a'
example [decidable p] : (if p then a else b) = (if p then a' else b) := by simp
|
1e3d336c26f02c74b9c7f9623deca0e73e5d73a8 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/polynomial/cyclotomic/eval.lean | 88595c50e62bb964d7fcd837c79de41dc8399739 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 15,914 | lean | /-
Copyright (c) 2021 Eric Rodriguez. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Rodriguez
-/
import ring_theory.polynomial.cyclotomic.basic
import tactic.by_contra
import topology.algebra.polynomial
import number_theory.padics.padic_val
import analysis.complex.arg
/-!
# Evaluating cyclotomic polynomials
This file states some results about evaluating cyclotomic polynomials in various different ways.
## Main definitions
* `polynomial.eval(₂)_one_cyclotomic_prime(_pow)`: `eval 1 (cyclotomic p^k R) = p`.
* `polynomial.eval_one_cyclotomic_not_prime_pow`: Otherwise, `eval 1 (cyclotomic n R) = 1`.
* `polynomial.cyclotomic_pos` : `∀ x, 0 < eval x (cyclotomic n R)` if `2 < n`.
-/
namespace polynomial
open finset nat
open_locale big_operators
@[simp] lemma eval_one_cyclotomic_prime {R : Type*} [comm_ring R] {p : ℕ} [hn : fact p.prime] :
eval 1 (cyclotomic p R) = p :=
by simp only [cyclotomic_eq_geom_sum hn.out, geom_sum_def, eval_X, one_pow, sum_const, eval_pow,
eval_finset_sum, card_range, smul_one_eq_coe]
@[simp] lemma eval₂_one_cyclotomic_prime {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S)
{p : ℕ} [fact p.prime] : eval₂ f 1 (cyclotomic p R) = p :=
by simp
@[simp] lemma eval_one_cyclotomic_prime_pow {R : Type*} [comm_ring R] {p : ℕ} (k : ℕ)
[hn : fact p.prime] : eval 1 (cyclotomic (p ^ (k + 1)) R) = p :=
by simp only [cyclotomic_prime_pow_eq_geom_sum hn.out, geom_sum_def, eval_X, one_pow, sum_const,
eval_pow, eval_finset_sum, card_range, smul_one_eq_coe]
@[simp] lemma eval₂_one_cyclotomic_prime_pow {R S : Type*} [comm_ring R] [semiring S] (f : R →+* S)
{p : ℕ} (k : ℕ) [fact p.prime] : eval₂ f 1 (cyclotomic (p ^ (k + 1)) R) = p :=
by simp
private lemma cyclotomic_neg_one_pos {n : ℕ} (hn : 2 < n) {R} [linear_ordered_comm_ring R] :
0 < eval (-1 : R) (cyclotomic n R) :=
begin
haveI := ne_zero.of_gt hn,
rw [←map_cyclotomic_int, ←int.cast_one, ←int.cast_neg, eval_int_cast_map,
int.coe_cast_ring_hom, int.cast_pos],
suffices : 0 < eval ↑(-1 : ℤ) (cyclotomic n ℝ),
{ rw [←map_cyclotomic_int n ℝ, eval_int_cast_map, int.coe_cast_ring_hom] at this,
exact_mod_cast this },
simp only [int.cast_one, int.cast_neg],
have h0 := cyclotomic_coeff_zero ℝ hn.le,
rw coeff_zero_eq_eval_zero at h0,
by_contra' hx,
have := intermediate_value_univ (-1) 0 (cyclotomic n ℝ).continuous,
obtain ⟨y, hy : is_root _ y⟩ := this (show (0 : ℝ) ∈ set.Icc _ _, by simpa [h0] using hx),
rw is_root_cyclotomic_iff at hy,
rw hy.eq_order_of at hn,
exact hn.not_le linear_ordered_ring.order_of_le_two,
end
lemma cyclotomic_pos {n : ℕ} (hn : 2 < n) {R} [linear_ordered_comm_ring R] (x : R) :
0 < eval x (cyclotomic n R) :=
begin
induction n using nat.strong_induction_on with n ih,
have hn' : 0 < n := pos_of_gt hn,
have hn'' : 1 < n := one_lt_two.trans hn,
dsimp at ih,
have := prod_cyclotomic_eq_geom_sum hn' R,
apply_fun eval x at this,
rw [divisors_eq_proper_divisors_insert_self_of_pos hn', insert_sdiff_of_not_mem,
prod_insert, eval_mul, eval_geom_sum] at this,
rotate,
{ simp only [lt_self_iff_false, mem_sdiff, not_false_iff, mem_proper_divisors, and_false,
false_and]},
{ simpa only [mem_singleton] using hn''.ne' },
rcases lt_trichotomy 0 (geom_sum x n) with h | h | h,
{ apply pos_of_mul_pos_right,
{ rwa this },
rw eval_prod,
refine prod_nonneg (λ i hi, _),
simp only [mem_sdiff, mem_proper_divisors, mem_singleton] at hi,
rw geom_sum_pos_iff hn'' at h,
cases h with hk hx,
{ refine (ih _ hi.1.2 (nat.two_lt_of_ne _ hi.2 _)).le; rintro rfl,
{ exact hn'.ne' (zero_dvd_iff.mp hi.1.1) },
{ exact even_iff_not_odd.mp (even_iff_two_dvd.mpr hi.1.1) hk } },
{ rcases eq_or_ne i 2 with rfl | hk,
{ simpa only [eval_X, eval_one, cyclotomic_two, eval_add] using hx.le },
refine (ih _ hi.1.2 (nat.two_lt_of_ne _ hi.2 hk)).le,
rintro rfl,
exact (hn'.ne' $ zero_dvd_iff.mp hi.1.1) } },
{ rw [eq_comm, geom_sum_eq_zero_iff_neg_one hn''] at h,
exact h.1.symm ▸ cyclotomic_neg_one_pos hn },
{ apply pos_of_mul_neg_left,
{ rwa this },
rw [geom_sum_neg_iff hn''] at h,
have h2 : {2} ⊆ n.proper_divisors \ {1},
{ rw [singleton_subset_iff, mem_sdiff, mem_proper_divisors, not_mem_singleton],
exact ⟨⟨even_iff_two_dvd.mp h.1, hn⟩, (nat.one_lt_bit0 one_ne_zero).ne'⟩ },
rw [eval_prod, ←prod_sdiff h2, prod_singleton]; try { apply_instance },
apply mul_nonpos_of_nonneg_of_nonpos,
{ refine prod_nonneg (λ i hi, le_of_lt _),
simp only [mem_sdiff, mem_proper_divisors, mem_singleton] at hi,
refine ih _ hi.1.1.2 (nat.two_lt_of_ne _ hi.1.2 hi.2),
rintro rfl,
rw zero_dvd_iff at hi,
exact hn'.ne' hi.1.1.1 },
{ simpa only [eval_X, eval_one, cyclotomic_two, eval_add] using h.right.le } }
end
lemma cyclotomic_pos_and_nonneg (n : ℕ) {R} [linear_ordered_comm_ring R] (x : R) :
(1 < x → 0 < eval x (cyclotomic n R)) ∧ (1 ≤ x → 0 ≤ eval x (cyclotomic n R)) :=
begin
rcases n with _ | _ | _ | n;
simp only [cyclotomic_zero, cyclotomic_one, cyclotomic_two, succ_eq_add_one,
eval_X, eval_one, eval_add, eval_sub, sub_nonneg, sub_pos,
zero_lt_one, zero_le_one, implies_true_iff, imp_self, and_self],
{ split; intro; linarith, },
{ have : 2 < n + 3 := dec_trivial,
split; intro; [skip, apply le_of_lt]; apply cyclotomic_pos this, },
end
/-- Cyclotomic polynomials are always positive on inputs larger than one.
Similar to `cyclotomic_pos` but with the condition on the input rather than index of the
cyclotomic polynomial. -/
lemma cyclotomic_pos' (n : ℕ) {R} [linear_ordered_comm_ring R] {x : R} (hx : 1 < x) :
0 < eval x (cyclotomic n R) :=
(cyclotomic_pos_and_nonneg n x).1 hx
/-- Cyclotomic polynomials are always nonnegative on inputs one or more. -/
lemma cyclotomic_nonneg (n : ℕ) {R} [linear_ordered_comm_ring R] {x : R} (hx : 1 ≤ x) :
0 ≤ eval x (cyclotomic n R) :=
(cyclotomic_pos_and_nonneg n x).2 hx
lemma eval_one_cyclotomic_not_prime_pow {R : Type*} [comm_ring R] {n : ℕ}
(h : ∀ {p : ℕ}, p.prime → ∀ k : ℕ, p ^ k ≠ n) : eval 1 (cyclotomic n R) = 1 :=
begin
rcases n.eq_zero_or_pos with rfl | hn',
{ simp },
have hn : 1 < n := one_lt_iff_ne_zero_and_ne_one.mpr ⟨hn'.ne', (h nat.prime_two 0).symm⟩,
suffices : eval 1 (cyclotomic n ℤ) = 1 ∨ eval 1 (cyclotomic n ℤ) = -1,
{ cases this with h h,
{ have := eval_int_cast_map (int.cast_ring_hom R) (cyclotomic n ℤ) 1,
simpa only [map_cyclotomic, int.cast_one, h, ring_hom.eq_int_cast] using this },
{ exfalso,
linarith [cyclotomic_nonneg n (le_refl (1 : ℤ))] }, },
rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_one, nat.eq_one_iff_not_exists_prime_dvd],
intros p hp hpe,
haveI := fact.mk hp,
have hpn : p ∣ n,
{ apply hpe.trans,
nth_rewrite 1 ←int.nat_abs_of_nat n,
rw [int.nat_abs_dvd_iff_dvd, ←int.nat_cast_eq_coe_nat,
←one_geom_sum, ←eval_geom_sum, ←prod_cyclotomic_eq_geom_sum hn'],
apply eval_dvd,
apply finset.dvd_prod_of_mem,
simpa using and.intro hn'.ne' hn.ne' },
have := prod_cyclotomic_eq_geom_sum hn' ℤ,
apply_fun eval 1 at this,
rw [eval_geom_sum, one_geom_sum, eval_prod, eq_comm,
←finset.prod_sdiff $ range_pow_padic_val_nat_subset_divisors' p, finset.prod_image] at this,
simp_rw [eval_one_cyclotomic_prime_pow, finset.prod_const, finset.card_range, mul_comm] at this,
rw [←finset.prod_sdiff $ show {n} ⊆ _, from _] at this,
any_goals {apply_instance},
swap,
{ simp only [not_exists, true_and, exists_prop, dvd_rfl, finset.mem_image, finset.mem_range,
finset.mem_singleton, finset.singleton_subset_iff, finset.mem_sdiff, nat.mem_divisors, not_and],
exact ⟨⟨hn'.ne', hn.ne'⟩, λ t _, h hp _⟩ },
rw [←int.nat_abs_of_nat p, int.nat_abs_dvd_iff_dvd] at hpe,
obtain ⟨t, ht⟩ := hpe,
rw [finset.prod_singleton, ht, mul_left_comm, mul_comm, ←mul_assoc, mul_assoc] at this,
simp only [int.nat_cast_eq_coe_nat] at *,
have : (p ^ (padic_val_nat p n) * p : ℤ) ∣ n := ⟨_, this⟩,
simp only [←pow_succ', ←int.nat_abs_dvd_iff_dvd, int.nat_abs_of_nat, int.nat_abs_pow] at this,
exact pow_succ_padic_val_nat_not_dvd hn' this,
{ rintro x - y - hxy,
apply nat.succ_injective,
exact nat.pow_right_injective hp.two_le hxy }
end
lemma sub_one_pow_totient_lt_cyclotomic_eval {n : ℕ} {q : ℝ} (hn' : 2 ≤ n) (hq' : 1 < q) :
(q - 1) ^ totient n < (cyclotomic n ℝ).eval q :=
begin
have hn : 0 < n := pos_of_gt hn',
have hq := zero_lt_one.trans hq',
have hfor : ∀ ζ' ∈ primitive_roots n ℂ, q - 1 ≤ ∥↑q - ζ'∥,
{ intros ζ' hζ',
rw mem_primitive_roots hn at hζ',
convert norm_sub_norm_le (↑q) ζ',
{ rw [complex.norm_real, real.norm_of_nonneg hq.le], },
{ rw [hζ'.norm'_eq_one hn.ne'] } },
let ζ := complex.exp (2 * ↑real.pi * complex.I / ↑n),
have hζ : is_primitive_root ζ n := complex.is_primitive_root_exp n hn.ne',
have hex : ∃ ζ' ∈ primitive_roots n ℂ, q - 1 < ∥↑q - ζ'∥,
{ refine ⟨ζ, (mem_primitive_roots hn).mpr hζ, _⟩,
suffices : ¬ same_ray ℝ (q : ℂ) ζ,
{ convert lt_norm_sub_of_not_same_ray this;
simp [real.norm_of_nonneg hq.le, hζ.norm'_eq_one hn.ne'] },
rw complex.same_ray_iff,
push_neg,
refine ⟨by exact_mod_cast hq.ne', hζ.ne_zero hn.ne', _⟩,
rw [complex.arg_of_real_of_nonneg hq.le, ne.def, eq_comm, hζ.arg_eq_zero_iff hn.ne'],
clear_value ζ,
rintro rfl,
linarith [hζ.unique is_primitive_root.one] },
have : ¬eval ↑q (cyclotomic n ℂ) = 0,
{ erw cyclotomic.eval_apply q n (algebra_map ℝ ℂ),
simpa using (cyclotomic_pos' n hq').ne' },
suffices : (units.mk0 (real.to_nnreal (q - 1)) (by simp [hq'])) ^ totient n
< units.mk0 (∥(cyclotomic n ℂ).eval q∥₊) (by simp [this]),
{ simp only [←units.coe_lt_coe, units.coe_pow, units.coe_mk0, ← nnreal.coe_lt_coe, hq'.le,
real.to_nnreal_lt_to_nnreal_iff_of_nonneg, coe_nnnorm, complex.norm_eq_abs,
nnreal.coe_pow, real.coe_to_nnreal', max_eq_left, sub_nonneg] at this,
convert this,
erw [(cyclotomic.eval_apply q n (algebra_map ℝ ℂ)), eq_comm],
simp [cyclotomic_nonneg n hq'.le], },
simp only [cyclotomic_eq_prod_X_sub_primitive_roots hζ, eval_prod, eval_C,
eval_X, eval_sub, nnnorm_prod, units.mk0_prod],
convert prod_lt_prod' _ _,
swap, { exact λ _, units.mk0 (real.to_nnreal (q - 1)) (by simp [hq']) },
{ simp [complex.card_primitive_roots] },
{ simp only [subtype.coe_mk, mem_attach, forall_true_left, subtype.forall, ←units.coe_le_coe,
← nnreal.coe_le_coe, complex.abs_nonneg, hq'.le, units.coe_mk0, real.coe_to_nnreal',
coe_nnnorm, complex.norm_eq_abs, max_le_iff, tsub_le_iff_right],
intros x hx,
simpa using hfor x hx, },
{ simp only [subtype.coe_mk, mem_attach, exists_true_left, subtype.exists,
← nnreal.coe_lt_coe, ← units.coe_lt_coe, units.coe_mk0 _, coe_nnnorm],
simpa [hq'.le] using hex, },
end
lemma cyclotomic_eval_lt_sub_one_pow_totient {n : ℕ} {q : ℝ} (hn' : 3 ≤ n) (hq' : 1 < q) :
(cyclotomic n ℝ).eval q < (q + 1) ^ totient n :=
begin
have hn : 0 < n := pos_of_gt hn',
have hq := zero_lt_one.trans hq',
have hfor : ∀ ζ' ∈ primitive_roots n ℂ, ∥↑q - ζ'∥ ≤ q + 1,
{ intros ζ' hζ',
rw mem_primitive_roots hn at hζ',
convert norm_sub_le (↑q) ζ',
{ rw [complex.norm_real, real.norm_of_nonneg (zero_le_one.trans_lt hq').le], },
{ rw [hζ'.norm'_eq_one hn.ne'] }, },
let ζ := complex.exp (2 * ↑real.pi * complex.I / ↑n),
have hζ : is_primitive_root ζ n := complex.is_primitive_root_exp n hn.ne',
have hex : ∃ ζ' ∈ primitive_roots n ℂ, ∥↑q - ζ'∥ < q + 1,
{ refine ⟨ζ, (mem_primitive_roots hn).mpr hζ, _⟩,
suffices : ¬ same_ray ℝ (q : ℂ) (-ζ),
{ convert norm_add_lt_of_not_same_ray this;
simp [real.norm_of_nonneg hq.le, hζ.norm'_eq_one hn.ne', -complex.norm_eq_abs] },
rw complex.same_ray_iff,
push_neg,
refine ⟨by exact_mod_cast hq.ne', neg_ne_zero.mpr $ hζ.ne_zero hn.ne', _⟩,
rw [complex.arg_of_real_of_nonneg hq.le, ne.def, eq_comm],
intro h,
rw [complex.arg_eq_zero_iff, complex.neg_re, neg_nonneg, complex.neg_im, neg_eq_zero] at h,
have hζ₀ : ζ ≠ 0,
{ clear_value ζ,
rintro rfl,
exact hn.ne' (hζ.unique is_primitive_root.zero) },
have : ζ.re < 0 ∧ ζ.im = 0 := ⟨h.1.lt_of_ne _, h.2⟩,
rw [←complex.arg_eq_pi_iff, hζ.arg_eq_pi_iff hn.ne'] at this,
rw this at hζ,
linarith [hζ.unique $ is_primitive_root.neg_one 0 two_ne_zero.symm],
{ contrapose! hζ₀,
ext; simp [hζ₀, h.2] } },
have : ¬eval ↑q (cyclotomic n ℂ) = 0,
{ erw cyclotomic.eval_apply q n (algebra_map ℝ ℂ),
simp only [complex.coe_algebra_map, complex.of_real_eq_zero],
exact (cyclotomic_pos' n hq').ne.symm, },
suffices : units.mk0 (∥(cyclotomic n ℂ).eval q∥₊) (by simp [this])
< (units.mk0 (real.to_nnreal (q + 1)) (by simp; linarith)) ^ totient n,
{ simp only [←units.coe_lt_coe, units.coe_pow, units.coe_mk0, ← nnreal.coe_lt_coe, hq'.le,
real.to_nnreal_lt_to_nnreal_iff_of_nonneg, coe_nnnorm, complex.norm_eq_abs,
nnreal.coe_pow, real.coe_to_nnreal', max_eq_left, sub_nonneg] at this,
convert this,
{ erw [(cyclotomic.eval_apply q n (algebra_map ℝ ℂ)), eq_comm],
simp [cyclotomic_nonneg n hq'.le] },
rw [eq_comm, max_eq_left_iff],
linarith },
simp only [cyclotomic_eq_prod_X_sub_primitive_roots hζ, eval_prod, eval_C,
eval_X, eval_sub, nnnorm_prod, units.mk0_prod],
convert prod_lt_prod' _ _,
swap, { exact λ _, units.mk0 (real.to_nnreal (q + 1)) (by simp; linarith only [hq']) },
{ simp [complex.card_primitive_roots], },
{ simp only [subtype.coe_mk, mem_attach, forall_true_left, subtype.forall, ←units.coe_le_coe,
← nnreal.coe_le_coe, complex.abs_nonneg, hq'.le, units.coe_mk0, real.coe_to_nnreal,
coe_nnnorm, complex.norm_eq_abs, max_le_iff],
intros x hx,
have : complex.abs _ ≤ _ := hfor x hx,
simp [this], },
{ simp only [subtype.coe_mk, mem_attach, exists_true_left, subtype.exists,
← nnreal.coe_lt_coe, ← units.coe_lt_coe, units.coe_mk0 _, coe_nnnorm],
obtain ⟨ζ, hζ, hhζ : complex.abs _ < _⟩ := hex,
exact ⟨ζ, hζ, by simp [hhζ]⟩ },
end
lemma sub_one_lt_nat_abs_cyclotomic_eval {n : ℕ} {q : ℕ} (hn' : 1 < n) (hq' : q ≠ 1) :
q - 1 < ((cyclotomic n ℤ).eval ↑q).nat_abs :=
begin
rcases q with _ | _ | q,
iterate 2
{ rw [pos_iff_ne_zero, ne.def, int.nat_abs_eq_zero],
intro h,
have := degree_eq_one_of_irreducible_of_root (cyclotomic.irreducible (pos_of_gt hn')) h,
rw [degree_cyclotomic, with_top.coe_eq_one, totient_eq_one_iff] at this,
rcases this with rfl|rfl; simpa using h },
suffices : (q.succ : ℝ) < (eval (↑q + 1 + 1) (cyclotomic n ℤ)).nat_abs,
{ exact_mod_cast this },
calc _ ≤ ((q + 2 - 1) ^ n.totient : ℝ) : _
... < _ : _,
{ norm_num,
convert pow_mono (by simp : 1 ≤ (q : ℝ) + 1) (totient_pos (pos_of_gt hn') : 1 ≤ n.totient),
{ simp },
{ ring }, },
convert sub_one_pow_totient_lt_cyclotomic_eval (show 2 ≤ n, by linarith)
(show (1 : ℝ) < q + 2, by {norm_cast, linarith}),
norm_cast,
erw cyclotomic.eval_apply (q + 2 : ℤ) n (algebra_map ℤ ℝ),
simp only [int.coe_nat_succ, ring_hom.eq_int_cast],
norm_cast,
rw [int.coe_nat_abs_eq_normalize, int.normalize_of_nonneg],
simp only [int.coe_nat_succ],
exact cyclotomic_nonneg n (by linarith),
end
end polynomial
|
ba1349e1cb274be4fbfe2ba9f3b2621aaf9dad18 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/classical.lean | a0b1c7478ce965391d84eb7a1b75467b275da396 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 267 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: classical
Author: Jeremy Avigad
The standard library together with the classical axioms.
-/
import standard logic.axioms.classical
|
8d01bbb662573144858c14ba4731ab71cd8e47c4 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Meta/Tactic/AC/Main.lean | 3a5fe8cc1b018566a0918f3800477094b1fcab57 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 6,148 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dany Fabian
-/
import Lean.Meta.AppBuilder
import Lean.Meta.Tactic.Refl
import Lean.Meta.Tactic.Simp.Main
import Lean.Elab.Tactic.Rewrite
namespace Lean.Meta.AC
open Lean.Data.AC
open Lean.Elab.Tactic
abbrev ACExpr := Lean.Data.AC.Expr
structure PreContext where
id : Nat
op : Expr
assoc : Expr
comm : Option Expr
idem : Option Expr
deriving Inhabited
instance : ContextInformation (PreContext × Array Bool) where
isComm ctx := ctx.1.comm.isSome
isIdem ctx := ctx.1.idem.isSome
isNeutral ctx x := ctx.2[x]!
instance : EvalInformation PreContext ACExpr where
arbitrary _ := Data.AC.Expr.var 0
evalOp _ := Data.AC.Expr.op
evalVar _ x := Data.AC.Expr.var x
def getInstance (cls : Name) (exprs : Array Expr) : MetaM (Option Expr) := do
try
let app ← mkAppM cls exprs
trace[Meta.AC] "trying: {indentExpr app}"
let inst ← synthInstance app
trace[Meta.AC] "got instance"
return some inst
catch
| _ => return none
def preContext (expr : Expr) : MetaM (Option PreContext) := do
if let some assoc := ←getInstance ``IsAssociative #[expr] then
return some
{ assoc,
op := expr
id := 0
comm := ←getInstance ``IsCommutative #[expr]
idem := ←getInstance ``IsIdempotent #[expr] }
return none
inductive PreExpr
| op (lhs rhs : PreExpr)
| var (e : Expr)
@[matchPattern] def bin (op l r : Expr) :=
Expr.app (Expr.app op l) r
def toACExpr (op l r : Expr) : MetaM (Array Expr × ACExpr) := do
let (preExpr, vars) ←
toPreExpr (mkApp2 op l r)
|>.run HashSet.empty
let vars := vars.toArray.insertionSort Expr.lt
let varMap := vars.foldl (fun xs x => xs.insert x xs.size) HashMap.empty |>.find!
return (vars, toACExpr varMap preExpr)
where
toPreExpr : Expr → StateT ExprSet MetaM PreExpr
| e@(bin op₂ l r) => do
if ←isDefEq op op₂ then
return PreExpr.op (←toPreExpr l) (←toPreExpr r)
modify fun vars => vars.insert e
return PreExpr.var e
| e => do
modify fun vars => vars.insert e
return PreExpr.var e
toACExpr (varMap : Expr → Nat) : PreExpr → ACExpr
| PreExpr.op l r => Data.AC.Expr.op (toACExpr varMap l) (toACExpr varMap r)
| PreExpr.var x => Data.AC.Expr.var (varMap x)
def buildNormProof (preContext : PreContext) (l r : Expr) : MetaM (Lean.Expr × Lean.Expr) := do
let (vars, acExpr) ← toACExpr preContext.op l r
let α ← inferType vars[0]!
let u ← getLevel α
let (isNeutrals, context) ← mkContext α u vars
let acExprNormed := Data.AC.evalList ACExpr preContext $ Data.AC.norm (preContext, isNeutrals) acExpr
let tgt := convertTarget vars acExprNormed
let lhs := convert acExpr
let rhs := convert acExprNormed
let proof := mkAppN (mkConst ``Context.eq_of_norm [u]) #[α, context, lhs, rhs, ←mkEqRefl (mkConst ``Bool.true)]
return (proof, tgt)
where
mkContext (α : Expr) (u : Level) (vars : Array Expr) : MetaM (Array Bool × Expr) := do
let arbitrary := vars[0]!
let zero := mkLevelZeroEx ()
let noneE := mkApp (mkConst ``Option.none [zero])
let someE := mkApp2 (mkConst ``Option.some [zero])
let vars ← vars.mapM fun x => do
let isNeutral :=
let isNeutralClass := mkApp3 (mkConst ``IsNeutral [u]) α preContext.op x
match ←getInstance ``IsNeutral #[preContext.op, x] with
| none => (false, noneE isNeutralClass)
| some isNeutral => (true, someE isNeutralClass isNeutral)
return (isNeutral.1, mkApp4 (mkConst ``Variable.mk [u]) α preContext.op x isNeutral.2)
let (isNeutrals, vars) := vars.unzip
let vars := vars.toList
let vars ← mkListLit (mkApp2 (mkConst ``Variable [u]) α preContext.op) vars
let comm :=
let commClass := mkApp2 (mkConst ``IsCommutative [u]) α preContext.op
match preContext.comm with
| none => noneE commClass
| some comm => someE commClass comm
let idem :=
let idemClass := mkApp2 (mkConst ``IsIdempotent [u]) α preContext.op
match preContext.idem with
| none => noneE idemClass
| some idem => someE idemClass idem
return (isNeutrals, mkApp7 (mkConst ``Lean.Data.AC.Context.mk [u]) α preContext.op preContext.assoc comm idem vars arbitrary)
convert : ACExpr → Expr
| Data.AC.Expr.op l r => mkApp2 (mkConst ``Data.AC.Expr.op) (convert l) (convert r)
| Data.AC.Expr.var x => mkApp (mkConst ``Data.AC.Expr.var) $ mkNatLit x
convertTarget (vars : Array Expr) : ACExpr → Expr
| Data.AC.Expr.op l r => mkApp2 preContext.op (convertTarget vars l) (convertTarget vars r)
| Data.AC.Expr.var x => vars[x]!
def rewriteUnnormalized (mvarId : MVarId) : MetaM Unit := do
let simpCtx :=
{
simpTheorems := {}
congrTheorems := (← getSimpCongrTheorems)
config := Simp.neutralConfig
}
let tgt ← instantiateMVars (← mvarId.getType)
let (res, _) ← Simp.main tgt simpCtx (methods := { post })
let newGoal ← applySimpResultToTarget mvarId tgt res
newGoal.refl
where
post (e : Expr) : SimpM Simp.Step := do
let ctx ← read
match e, ctx.parent? with
| bin op₁ l r, some (bin op₂ _ _) =>
if ←isDefEq op₁ op₂ then
return Simp.Step.done { expr := e }
match ←preContext op₁ with
| some pc =>
let (proof, newTgt) ← buildNormProof pc l r
return Simp.Step.done { expr := newTgt, proof? := proof }
| none => return Simp.Step.done { expr := e }
| bin op l r, _ =>
match ←preContext op with
| some pc =>
let (proof, newTgt) ← buildNormProof pc l r
return Simp.Step.done { expr := newTgt, proof? := proof }
| none => return Simp.Step.done { expr := e }
| e, _ => return Simp.Step.done { expr := e }
@[builtinTactic acRfl] def acRflTactic : Lean.Elab.Tactic.Tactic := fun _ => do
let goal ← getMainGoal
goal.withContext <| rewriteUnnormalized goal
builtin_initialize
registerTraceClass `Meta.AC
end Lean.Meta.AC
|
76d3bd1ccbe042df31fdeb451a586348daa2c77a | 41ebf3cb010344adfa84907b3304db00e02db0a6 | /uexp/src/uexp/meta/ucongr.lean | 8c99bcbf0cf620402c5c4dfa7b42407b5b48cbf8 | [
"BSD-2-Clause"
] | permissive | ReinierKoops/Cosette | e061b2ba58b26f4eddf4cd052dcf7abd16dfe8fb | eb8dadd06ee05fe7b6b99de431dd7c4faef5cb29 | refs/heads/master | 1,686,483,953,198 | 1,624,293,498,000 | 1,624,293,498,000 | 378,997,885 | 0 | 0 | BSD-2-Clause | 1,624,293,485,000 | 1,624,293,484,000 | null | UTF-8 | Lean | false | false | 10,682 | lean | import ..u_semiring
import .cosette_lemmas .cosette_tactics
/- congruence procedure for u-semiring -/
open tactic
private meta def flip_ueq : expr → tactic unit
| `(%%a * %%b) := flip_ueq a >> flip_ueq b
| `(%%t₁ ≃ %%t₂) :=
if t₁ > t₂ then return ()
else do h ← to_expr ``(eq_symm %%t₁ %%t₂),
try $ rewrite_target h,
return ()
| _ := return ()
-- walk the product and normalize equal pred,
-- we maintain an invariant, a ≃ b (a > b)
meta def unify_ueq : tactic unit := do
t ← tactic.target,
match t with
| `(%%a = %%b) := flip_ueq a >> flip_ueq b
| _ := failed
end
-- collect ueq (equality predicate) from prod
meta def collect_ueq : expr → tactic (list expr)
| `(%%a * %%b) :=
do l ← collect_ueq a,
r ← collect_ueq b,
return (l ++ r)
| e := match e with
| `(%%a ≃ %%b) := return [e]
| _ := return []
end
-- collect ueq from lhs of goal
meta def collect_lhs_ueq : tactic (list expr) :=
target >>= λ e,
match e with
| `(%%a = _ ) := collect_ueq a
| _ := return []
end
-- make sure all product is right assoc
meta def right_assoc :=
`[repeat {rewrite time_assoc}]
-- make sure ueq is in front of relation
private meta def ueq_right_order : list expr → bool
| [x] := tt
| (a :: b :: xs) :=
if ((¬(is_ueq a)) && (is_ueq b)) then ff
else ueq_right_order (b::xs)
| [] := tt
-- find the index of relation that is behind ueq
private meta def idx_of_bad : nat → list expr → tactic nat :=
λ pos l,
match l with
| [x] := failure
| (a :: b :: xs) :=
if ((¬(is_ueq a)) && (is_ueq b)) then return (pos+1)
else idx_of_bad (pos+1) (b::xs)
| []:= failure
end
private meta def all_ueq (l: list expr) : tactic bool :=
list.foldl (λ v e, do v' ← v, return $ v' && (is_ueq e)) (return tt) l
private meta def no_ueq (l: list expr) : tactic bool :=
list.foldl (λ v e, do v' ← v, return $ v' && ¬ (is_ueq e)) (return tt) l
meta def add_unit_if_needed : tactic unit := do
lhs ← get_lhs,
l ← ra_product_to_repr lhs,
all_u ← all_ueq l,
no_u ← no_ueq l,
if all_u then applyc `add_unit -- add unit when there is no relation expr
else if no_u then applyc `add_unit_l -- add unit when there is no ueq
else return ()
meta def move_ueq_step : tactic unit := do
lhs ← get_lhs,
l ← ra_product_to_repr lhs,
if ueq_right_order l then do
failed
else do
idx ← idx_of_bad 0 l,
swap_element_forward (idx - 1) l
-- move ueq, TODO: revisit here to get general SPNF form
meta def move_ueq: tactic unit :=
`[right_assoc,
add_unit_if_needed,
repeat {move_ueq_step},
repeat {apply ueq_left_assoc_lem},
repeat {apply ueq_right_assoc_lem},
repeat {apply ueq_right_assoc_lem'},
apply ueq_symm,
repeat {move_ueq_step},
repeat {apply ueq_left_assoc_lem},
repeat {apply ueq_right_assoc_lem},
repeat {apply ueq_right_assoc_lem'}
]
meta def rw_trans : tactic unit :=
do
ueq_dict ← collect_lhs_ueq,
t ← get_lhs,
match t with
| `(((%%a ≃ %%b) * ((%%c ≃ %%d) * _)) * _ * _ ) :=
if (b = c) then
if (a > d) then do
ne ← to_expr ``(%%a ≃ %%d),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_1
else fail "fail to apply ueq_trans_1"
else if (a = c) then
if (b > d) then do
ne ← to_expr ``(%%b ≃ %%d),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_2_g
else if (d > b) then do
ne ← to_expr ``(%%d ≃ %%b),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_2_l
else fail "fail to apply ueq_trans_2_l"
else if (b = d) then
if (a > c) then do
ne ← to_expr ``(%%a ≃ %%c),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_3_g
else if (c > a) then do
ne ← to_expr ``(%%c ≃ %%a),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_3_l
else fail "fail to apply ueq_trans_3_l"
else if (a = d) then
if (c > b) then do
ne ← to_expr ``(%%c ≃ %%b),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_4
else fail "fail to apply ueq_trans_4"
else return () -- do nothing if cannot use trans of ueq
| `((%%a ≃ %%b) * (%%c ≃ %%d) * _ * _) :=
if (b = c) then
if (a > d) then do
ne ← to_expr ``(%%a ≃ %%d),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_1'
else fail "fail to apply ueq_trans_1'"
else if (a = c) then
if (b > d) then do
ne ← to_expr ``(%%b ≃ %%d),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_2_g'
else if (d > b) then do
ne ← to_expr ``(%%d ≃ %%b),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_2_l'
else fail "fail to apply ueq_trans_2_l'"
else if (b = d) then
if (a > c) then do
ne ← to_expr ``(%%a ≃ %%c),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_3_g'
else if (c > a) then do
ne ← to_expr ``(%%c ≃ %%a),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_3_l'
else fail "fail to apply ueq_trans_3_l'"
else if (a = d) then
if (c > b) then do
ne ← to_expr ``(%%c ≃ %%b),
if expr_in ne ueq_dict then return ()
else applyc `ueq_trans_4'
else fail "fail to apply ueq_trans_4'"
else return () -- do nothing if cannot use trans of ueq
| _ := fail "rw_trans fail"
end
meta def ucongr_step : tactic unit := do
repr ← get_lhs_repr1,
let l := list.length repr in
let inner_loop : nat → tactic unit → tactic unit :=
λ iter_num next_iter, do
next_iter,
forward_i_to_j_lhs (1+iter_num) 1,
rw_trans in
let outter_loop : nat → tactic unit → tactic unit :=
λ iter_num next_iter, do
next_iter,
forward_i_to_j_lhs iter_num 0,
nat.repeat inner_loop (l-1) $ return ()
in do nat.repeat outter_loop l $ return ()
meta def ucongr_lhs : tactic unit := do
ucongr_step,
new_ueq ← get_lhs_repr2,
repeat $ applyc `move_ueq_between_com,
if list.length new_ueq > 1 then do -- progress!
ucongr_lhs
else return ()
meta def subst_step : tactic unit := do
l ← get_lhs,
match l with
| `((%%a ≃ %%b) * %%c * %%d * %%e) := do
ty ← infer_type a,
let body := expr.subst_var a e,
let em : expr := (expr.lam `x binder_info.default ty body),
lem ← to_expr ``(@ueq_subst_in_spnf _ %%a %%b %%c %%d %%em),
try $ rewrite_target lem,
l' ← get_lhs_expr3,
beta_reduction l'
| `((%%a ≃ %%b) * %%c * %%e) := do
ty ← infer_type a,
let body := expr.subst_var a e,
let em : expr := (expr.lam `x binder_info.default ty body),
lem ← to_expr ``(@ueq_subst_in_spnf' _ %%a %%b %%c %%em),
try $ rewrite_target lem,
l' ← get_lhs_expr3,
beta_reduction l'
| _ := return ()
end
private meta def ueq_toporder (e₁ e₂: expr) : bool :=
match e₁ with
| `(%%a ≃ %%b) := match e₂ with
| `(%%c ≃ %%d) := if (d > a) || (d = a) then ff else tt
| _ := tt
end
| _ := tt
end
-- topology sort ueqs, so that we can do a single pass of substition
meta def topsort_lhs : tactic unit := do
repr ← get_lhs_repr1,
sorted ← return $ list.qsort ueq_toporder repr,
origin ← repr_to_product repr,
new ← repr_to_product sorted,
eq_lemma ← to_expr ``(%%origin = %%new),
eq_lemma_name ← mk_fresh_name,
tactic.assert eq_lemma_name eq_lemma,
try ac_refl,
eq_lemma ← resolve_name eq_lemma_name >>= to_expr,
rewrite_target eq_lemma,
clear eq_lemma
meta def subst_lhs : tactic unit := do
topsort_lhs,
repr ← get_lhs_repr1,
let l := list.length repr in
let loop : nat → tactic unit:=
λ iter_num, do
forward_i_to_j_lhs iter_num 0,
subst_step in
repeat_or_sol loop l
private meta def remove_dup_step : tactic unit :=
`[repeat {rw ueq_dedup<|> rw ueq_dedup'}]
-- assuming LHS and RHS are already in SPNF
meta def remove_dup_ueq : tactic unit := do
repr ← get_lhs_repr1,
sorted ← return $ list.qsort (λ x y, x > y) repr,
origin ← repr_to_product repr,
new ← repr_to_product sorted,
eq_lemma ← to_expr ``(%%origin = %%new),
eq_lemma_name ← mk_fresh_name,
tactic.assert eq_lemma_name eq_lemma,
try ac_refl,
eq_lemma ← resolve_name eq_lemma_name >>= to_expr,
rewrite_target eq_lemma,
clear eq_lemma,
r2 ← get_lhs_repr1,
remove_dup_step
private meta def remove_pred_step : tactic unit :=
`[repeat {rw pred_cancel <|> rw pred_cancel'}]
meta def remove_dup_pred : tactic unit := do
repr ← get_lhs_repr3,
sorted ← return $ list.qsort (λ x y, x > y) repr,
origin ← repr_to_product repr,
new ← repr_to_product sorted,
eq_lemma ← to_expr ``(%%origin = %%new),
eq_lemma_name ← mk_fresh_name,
tactic.assert eq_lemma_name eq_lemma,
try ac_refl,
eq_lemma ← resolve_name eq_lemma_name >>= to_expr,
rewrite_target eq_lemma,
clear eq_lemma,
remove_pred_step
meta def ucongr : tactic unit := do
solved_or_continue $ (do split_pairs,
solved_or_continue $ (do unify_ueq,
move_ueq,
applyc `add_unit_m,
remove_dup_ueq,
solved_or_continue $ (do applyc `ueq_symm,
remove_dup_ueq,
solved_or_continue $ (do ucongr_lhs,
solved_or_continue $ (do applyc `ueq_symm,
ucongr_lhs,
solved_or_continue $ (do subst_lhs,
solved_or_continue $ (do applyc `ueq_symm,
subst_lhs,
solved_or_continue $ (do remove_dup_pred,
solved_or_continue $ (do applyc `ueq_symm,
remove_dup_pred,
solved_or_continue ac_refl)))))))))
|
91befaa2d6ca4dd2169f5aaa005a11159d6b92a6 | f09e92753b1d3d2eb3ce2cfb5288a7f5d1d4bd89 | /src/perfectoid_space.lean | 1deefcc2e3ba35369e2a0794da826348ec7e0f9d | [
"Apache-2.0"
] | permissive | PatrickMassot/lean-perfectoid-spaces | 7f63c581db26461b5a92d968e7563247e96a5597 | 5f70b2020b3c6d508431192b18457fa988afa50d | refs/heads/master | 1,625,797,721,782 | 1,547,308,357,000 | 1,547,309,364,000 | 136,658,414 | 0 | 1 | Apache-2.0 | 1,528,486,100,000 | 1,528,486,100,000 | null | UTF-8 | Lean | false | false | 862 | lean | -- definitions of adic_space, preadic_space, Huber_pair etc
import analysis.topology.topological_groups
import adic_space
import Tate_ring
import power_bounded
--notation
postfix `ᵒ` : 66 := power_bounded_subring
local attribute [instance] topological_add_group.to_uniform_space
open nat.Prime power_bounded
variable [nat.Prime] -- fix a prime p
/-- A perfectoid ring, following Fontaine Sem Bourb-/
class perfectoid_ring (R : Type*) extends Tate_ring R :=
(complete : is_complete_hausdorff R)
(uniform : is_uniform R)
(ramified : ∃ ϖ : pseudo_uniformizer R, (ϖ^p : Rᵒ) ∣ p)
(Frob : ∀ a : Rᵒ, ∃ b : Rᵒ, (p : Rᵒ) ∣ (b^p - a : Rᵒ))
class perfectoid_space (X : Type*) extends adic_space X :=
(perfectoid_cover : ∀ x : X, ∃ (U : opens X) (A : Huber_pair) [perfectoid_ring A.R],
(x ∈ U) ∧ is_preadic_space_equiv U (Spa A))
|
0061dc28a095ad7706bf136950855d4ba4a7a435 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /library/theories/number_theory/primes.lean | c329d00490d5fc8640ef293b78b664417a7f3ea5 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 10,246 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad
Prime numbers.
-/
import data.nat logic.identities
open bool subtype
namespace nat
open decidable
definition prime [reducible] (p : nat) := p ≥ 2 ∧ ∀ m, m ∣ p → m = 1 ∨ m = p
definition prime_ext (p : nat) := p ≥ 2 ∧ ∀ m, m ≤ p → m ∣ p → m = 1 ∨ m = p
local attribute prime_ext [reducible]
lemma prime_ext_iff_prime (p : nat) : prime_ext p ↔ prime p :=
iff.intro
begin
intro h, cases h with h₁ h₂, constructor, assumption,
intro m d, exact h₂ m (le_of_dvd (lt_of_succ_le (le_of_succ_le h₁)) d) d
end
begin
intro h, cases h with h₁ h₂, constructor, assumption,
intro m l d, exact h₂ m d
end
definition decidable_prime [instance] (p : nat) : decidable (prime p) :=
decidable_of_decidable_of_iff _ (prime_ext_iff_prime p)
lemma ge_two_of_prime {p : nat} : prime p → p ≥ 2 :=
suppose prime p, obtain h₁ h₂, from this,
h₁
theorem gt_one_of_prime {p : ℕ} (primep : prime p) : p > 1 :=
lt_of_succ_le (ge_two_of_prime primep)
theorem pos_of_prime {p : ℕ} (primep : prime p) : p > 0 :=
lt.trans zero_lt_one (gt_one_of_prime primep)
lemma not_prime_zero : ¬ prime 0 :=
λ h, absurd (ge_two_of_prime h) dec_trivial
lemma not_prime_one : ¬ prime 1 :=
λ h, absurd (ge_two_of_prime h) dec_trivial
lemma prime_two : prime 2 :=
dec_trivial
lemma prime_three : prime 3 :=
dec_trivial
lemma pred_prime_pos {p : nat} : prime p → pred p > 0 :=
suppose prime p,
have p ≥ 2, from ge_two_of_prime this,
show pred p > 0, from lt_of_succ_le (pred_le_pred this)
lemma succ_pred_prime {p : nat} : prime p → succ (pred p) = p :=
assume h, succ_pred_of_pos (pos_of_prime h)
lemma eq_one_or_eq_self_of_prime_of_dvd {p m : nat} : prime p → m ∣ p → m = 1 ∨ m = p :=
assume h d, obtain h₁ h₂, from h, h₂ m d
lemma gt_one_of_pos_of_prime_dvd {i p : nat} : prime p → 0 < i → i % p = 0 → 1 < i :=
assume ipp pos h,
have p ≥ 2, from ge_two_of_prime ipp,
have p ∣ i, from dvd_of_mod_eq_zero h,
have p ≤ i, from le_of_dvd pos this,
lt_of_succ_le (le.trans `2 ≤ p` this)
definition sub_dvd_of_not_prime {n : nat} : n ≥ 2 → ¬ prime n → {m | m ∣ n ∧ m ≠ 1 ∧ m ≠ n} :=
assume h₁ h₂,
have ¬ prime_ext n, from iff.mpr (not_iff_not_of_iff !prime_ext_iff_prime) h₂,
have ¬ n ≥ 2 ∨ ¬ (∀ m, m ≤ n → m ∣ n → m = 1 ∨ m = n), from iff.mp !not_and_iff_not_or_not this,
have ¬ (∀ m, m ≤ n → m ∣ n → m = 1 ∨ m = n), from or_resolve_right this (not_not_intro h₁),
have ¬ (∀ m, m < succ n → m ∣ n → m = 1 ∨ m = n), from
assume h, absurd (λ m hl hd, h m (lt_succ_of_le hl) hd) this,
have {m | m < succ n ∧ ¬(m ∣ n → m = 1 ∨ m = n)}, from bsub_not_of_not_ball this,
obtain m hlt (h₃ : ¬(m ∣ n → m = 1 ∨ m = n)), from this,
obtain `m ∣ n` (h₅ : ¬ (m = 1 ∨ m = n)), from iff.mp !not_implies_iff_and_not h₃,
have ¬ m = 1 ∧ ¬ m = n, from iff.mp !not_or_iff_not_and_not h₅,
subtype.tag m (and.intro `m ∣ n` this)
theorem exists_dvd_of_not_prime {n : nat} : n ≥ 2 → ¬ prime n → ∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n :=
assume h₁ h₂, exists_of_subtype (sub_dvd_of_not_prime h₁ h₂)
definition sub_dvd_of_not_prime2 {n : nat} : n ≥ 2 → ¬ prime n → {m | m ∣ n ∧ m ≥ 2 ∧ m < n} :=
assume h₁ h₂,
have n ≠ 0, from assume h, begin subst n, exact absurd h₁ dec_trivial end,
obtain m m_dvd_n m_ne_1 m_ne_n, from sub_dvd_of_not_prime h₁ h₂,
have m_ne_0 : m ≠ 0, from assume h, begin subst m, exact absurd (eq_zero_of_zero_dvd m_dvd_n) `n ≠ 0` end,
begin
existsi m, split, assumption,
split,
{cases m with m, exact absurd rfl m_ne_0,
cases m with m, exact absurd rfl m_ne_1, exact succ_le_succ (succ_le_succ (zero_le _))},
{have m_le_n : m ≤ n, from le_of_dvd (pos_of_ne_zero `n ≠ 0`) m_dvd_n,
exact lt_of_le_of_ne m_le_n m_ne_n}
end
theorem exists_dvd_of_not_prime2 {n : nat} : n ≥ 2 → ¬ prime n → ∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n :=
assume h₁ h₂, exists_of_subtype (sub_dvd_of_not_prime2 h₁ h₂)
definition sub_prime_and_dvd {n : nat} : n ≥ 2 → {p | prime p ∧ p ∣ n} :=
nat.strong_rec_on n
(take n,
assume ih : ∀ m, m < n → m ≥ 2 → {p | prime p ∧ p ∣ m},
suppose n ≥ 2,
by_cases
(suppose prime n, subtype.tag n (and.intro this (dvd.refl n)))
(suppose ¬ prime n,
obtain m m_dvd_n m_ge_2 m_lt_n, from sub_dvd_of_not_prime2 `n ≥ 2` this,
obtain p (hp : prime p) (p_dvd_m : p ∣ m), from ih m m_lt_n m_ge_2,
have p ∣ n, from dvd.trans p_dvd_m m_dvd_n,
subtype.tag p (and.intro hp this)))
lemma exists_prime_and_dvd {n : nat} : n ≥ 2 → ∃ p, prime p ∧ p ∣ n :=
assume h, exists_of_subtype (sub_prime_and_dvd h)
open eq.ops
definition infinite_primes (n : nat) : {p | p ≥ n ∧ prime p} :=
let m := fact (n + 1) in
have m ≥ 1, from le_of_lt_succ (succ_lt_succ (fact_pos _)),
have m + 1 ≥ 2, from succ_le_succ this,
obtain p `prime p` `p ∣ m + 1`, from sub_prime_and_dvd this,
have p ≥ 2, from ge_two_of_prime `prime p`,
have p > 0, from lt_of_succ_lt (lt_of_succ_le `p ≥ 2`),
have p ≥ n, from by_contradiction
(suppose ¬ p ≥ n,
have p < n, from lt_of_not_ge this,
have p ≤ n + 1, from le_of_lt (lt.step this),
have p ∣ m, from dvd_fact `p > 0` this,
have p ∣ 1, from dvd_of_dvd_add_right (!add.comm ▸ `p ∣ m + 1`) this,
have p ≤ 1, from le_of_dvd zero_lt_one this,
show false, from absurd (le.trans `2 ≤ p` `p ≤ 1`) dec_trivial),
subtype.tag p (and.intro this `prime p`)
lemma exists_infinite_primes (n : nat) : ∃ p, p ≥ n ∧ prime p :=
exists_of_subtype (infinite_primes n)
lemma odd_of_prime {p : nat} : prime p → p > 2 → odd p :=
λ pp p_gt_2, by_contradiction (λ hn,
have even p, from even_of_not_odd hn,
obtain k `p = 2*k`, from exists_of_even this,
have 2 ∣ p, by rewrite [`p = 2*k`]; apply dvd_mul_right,
or.elim (eq_one_or_eq_self_of_prime_of_dvd pp this)
(suppose 2 = 1, absurd this dec_trivial)
(suppose 2 = p, by subst this; exact absurd p_gt_2 !lt.irrefl))
theorem dvd_of_prime_of_not_coprime {p n : ℕ} (primep : prime p) (nc : ¬ coprime p n) : p ∣ n :=
have H : gcd p n = 1 ∨ gcd p n = p, from eq_one_or_eq_self_of_prime_of_dvd primep !gcd_dvd_left,
or_resolve_right H nc ▸ !gcd_dvd_right
theorem coprime_of_prime_of_not_dvd {p n : ℕ} (primep : prime p) (npdvdn : ¬ p ∣ n) :
coprime p n :=
by_contradiction (suppose ¬ coprime p n, npdvdn (dvd_of_prime_of_not_coprime primep this))
theorem not_dvd_of_prime_of_coprime {p n : ℕ} (primep : prime p) (cop : coprime p n) : ¬ p ∣ n :=
suppose p ∣ n,
have p ∣ gcd p n, from dvd_gcd !dvd.refl this,
have p ≤ gcd p n, from le_of_dvd (!gcd_pos_of_pos_left (pos_of_prime primep)) this,
have 2 ≤ 1, from le.trans (ge_two_of_prime primep) (cop ▸ this),
show false, from !not_succ_le_self this
theorem not_coprime_of_prime_dvd {p n : ℕ} (primep : prime p) (pdvdn : p ∣ n) : ¬ coprime p n :=
assume cop, not_dvd_of_prime_of_coprime primep cop pdvdn
theorem dvd_of_prime_of_dvd_mul_left {p m n : ℕ} (primep : prime p)
(Hmn : p ∣ m * n) (Hm : ¬ p ∣ m) :
p ∣ n :=
have coprime p m, from coprime_of_prime_of_not_dvd primep Hm,
show p ∣ n, from dvd_of_coprime_of_dvd_mul_left this Hmn
theorem dvd_of_prime_of_dvd_mul_right {p m n : ℕ} (primep : prime p)
(Hmn : p ∣ m * n) (Hn : ¬ p ∣ n) :
p ∣ m :=
dvd_of_prime_of_dvd_mul_left primep (!mul.comm ▸ Hmn) Hn
theorem not_dvd_mul_of_prime {p m n : ℕ} (primep : prime p) (Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) :
¬ p ∣ m * n :=
assume Hmn, Hm (dvd_of_prime_of_dvd_mul_right primep Hmn Hn)
lemma dvd_or_dvd_of_prime_of_dvd_mul {p m n : nat} : prime p → p ∣ m * n → p ∣ m ∨ p ∣ n :=
λ h₁ h₂, by_cases
(suppose p ∣ m, or.inl this)
(suppose ¬ p ∣ m, or.inr (dvd_of_prime_of_dvd_mul_left h₁ h₂ this))
lemma dvd_of_prime_of_dvd_pow {p m : nat} : ∀ {n}, prime p → p ∣ m^n → p ∣ m
| 0 hp hd :=
have p = 1, from eq_one_of_dvd_one hd,
have (1:nat) ≥ 2, begin rewrite -this at {1}, apply ge_two_of_prime hp end,
absurd this dec_trivial
| (succ n) hp hd :=
have p ∣ (m^n)*m, by rewrite [pow_succ' at hd]; exact hd,
or.elim (dvd_or_dvd_of_prime_of_dvd_mul hp this)
(suppose p ∣ m^n, dvd_of_prime_of_dvd_pow hp this)
(suppose p ∣ m, this)
lemma coprime_pow_of_prime_of_not_dvd {p m a : nat} : prime p → ¬ p ∣ a → coprime a (p^m) :=
λ h₁ h₂, coprime_pow_right m (coprime_swap (coprime_of_prime_of_not_dvd h₁ h₂))
lemma coprime_primes {p q : nat} : prime p → prime q → p ≠ q → coprime p q :=
λ hp hq hn,
have gcd p q ∣ p, from !gcd_dvd_left,
or.elim (eq_one_or_eq_self_of_prime_of_dvd hp this)
(suppose gcd p q = 1, this)
(assume h : gcd p q = p,
have gcd p q ∣ q, from !gcd_dvd_right,
have p ∣ q, by rewrite -h; exact this,
or.elim (eq_one_or_eq_self_of_prime_of_dvd hq this)
(suppose p = 1, by subst p; exact absurd hp not_prime_one)
(suppose p = q, by contradiction))
lemma coprime_pow_primes {p q : nat} (n m : nat) : prime p → prime q → p ≠ q → coprime (p^n) (q^m) :=
λ hp hq hn, coprime_pow_right m (coprime_pow_left n (coprime_primes hp hq hn))
lemma coprime_or_dvd_of_prime {p} (Pp : prime p) (i : nat) : coprime p i ∨ p ∣ i :=
by_cases
(suppose p ∣ i, or.inr this)
(suppose ¬ p ∣ i, or.inl (coprime_of_prime_of_not_dvd Pp this))
lemma eq_one_or_dvd_of_dvd_prime_pow {p : nat} : ∀ {m i : nat}, prime p → i ∣ (p^m) → i = 1 ∨ p ∣ i
| 0 := take i, assume Pp, begin rewrite [pow_zero], intro Pdvd, apply or.inl (eq_one_of_dvd_one Pdvd) end
| (succ m) := take i, assume Pp, or.elim (coprime_or_dvd_of_prime Pp i)
(λ Pcp, begin
rewrite [pow_succ'], intro Pdvd,
apply eq_one_or_dvd_of_dvd_prime_pow Pp,
apply dvd_of_coprime_of_dvd_mul_right,
apply coprime_swap Pcp, exact Pdvd
end)
(λ Pdvd, assume P, or.inr Pdvd)
end nat
|
d0f85a5e108a368fcbfc7f94071593e9ac75de41 | 88892181780ff536a81e794003fe058062f06758 | /src/100_theorems/t039.lean | 1372254e3d9a4bd9129c021efbd9a2c3c793ee2c | [] | no_license | AtnNn/lean-sandbox | fe2c44280444e8bb8146ab8ac391c82b480c0a2e | 8c68afbdc09213173aef1be195da7a9a86060a97 | refs/heads/master | 1,623,004,395,876 | 1,579,969,507,000 | 1,579,969,507,000 | 146,666,368 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 256 | lean | import number_theory.pell
-- Solutions to Pell’s Equation
open pell
theorem t039 {a x y : ℕ} : Π (a1 : a > 1), (x*x - (a * a - 1) * y * y = 1) → ∃n, x = xn a1 n ∧ y = yn a1 n
:= begin
intros,
refine eq_pell _ _,
rw ← a_1,
ring,
end
|
0168c87d9d396161bbd9102fc224f937d4df0744 | 8f67b34bba98f894155dedf263bc8d61c31e89cd | /2ltt/facts.lean | 2b1eb5244382f1d0b01c8ceb12669f75863380f1 | [] | no_license | 5HT/two-level | 3b1523db242cba819681b862fbc8f490d9571a66 | 370f5a91311db3b463b10a31891370721e2476e2 | refs/heads/master | 1,648,254,367,420 | 1,576,269,550,000 | 1,576,269,550,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,083 | lean | import data.equiv
open equiv equiv.ops eq eq.ops
-- some definitions and facts about equality and equivalence
-- which we could not find in standard library
namespace eq
definition ap {A B : Type}(f : A → B){a a' : A}
(p : a = a') : f a = f a' := p ▹ eq.refl _
definition apd {A : Type}{B : A → Type}(f : Π (a : A), B a)
{a a' : A}(p : a = a') : p ▹ f a = f a' :=
eq.drec (eq.refl _) p
definition naturality_subst {X Y : Type}{x x' : X}{P : Y → Type}
(f : X → Y)(p : x = x')(u : P (f x)) : ap f p ▹ u = p ▹ u :=
eq.drec (eq.refl _) p
definition transport_concat [simp] {A : Type } {a b c: A} (P : A → Type)
(p : a = b) (q : b = c) (u : P a) : q ▹ (p ▹ u) = p ⬝ q ▹ u := begin cases p, cases q, reflexivity end
definition concat_inv {A : Type } {a b : A} {P : A → Type}
(p : a = b) (u : P a) : #eq.ops p ⬝ p⁻¹ ▹ u = u := by cases p; reflexivity
end eq
open eq
namespace equiv
open eq.ops sigma.ops function
variables {A A' : Type}
definition pi_congr₁ [instance] {F' : A' → Type} [φ : A ≃ A']
: (Π (a : A), F' (φ ∙ a)) ≃ (Π (a : A'), F' a) :=
match φ with mk f g l r :=
mk (λ k x', r x' ▹ k (g x'))
(λ h x, h (f x))
(λ k, funext (λ x,
calc r (f x) ▹ k (g (f x))
= ap f (l x) ▹ k (g (f x)) : proof_irrel (r (f x)) (ap f (l x))
... = l x ▹ k (g (f x)) : naturality_subst f (l x) (k (g (f x)))
... = k x : apd k (l x)))
(λ h, funext (λ x', apd h (r x')))
end
definition pi_congr₂ [instance] {F G : A → Type} [φ : Π a, F a ≃ G a]
: (Π (a : A), F a) ≃ (Π (a : A), G a) :=
equiv.mk
(λ x a, (φ a) ∙ x a)
(λ x a, inv (x a))
(λ x, funext (λ a, (left_inv _ (G a) _) ▹ rfl))
(λ x, funext (λ a, (right_inv (F a) _ _) ▹ rfl))
definition pi_congr [instance] {F : A → Type} {F' : A' → Type} [φ : A ≃ A'] [φ' : Π a, F a ≃ F' (φ ∙ a)] :=
equiv.trans (@pi_congr₂ _ _ _ φ') (@pi_congr₁ _ _ _ φ)
definition sigma_eq_congr {A: Type} {F : A → Type} {a a': A} {b : F a} {b' : F a'} :
(Σ (p : a = a'), ((p ▹ b) = b')) → ⟨ a, b ⟩ = ⟨a', b'⟩ :=
begin intro p, cases p with [p₁, p₂], cases p₁, cases p₂, esimp end
definition sigma_congr₁ [instance] {A B: Type} {F : B → Type} [φ : A ≃ B]:
(Σ a : A, F (φ ∙ a)) ≃ Σ b : B, F b :=
equiv.mk
(λ x , ⟨ φ ∙ x.1, x.2 ⟩ )
(λ x, ⟨ inv x.1, begin unfold fn, unfold inv, rewrite right_inv, apply x.2 end⟩ )
(λ x, begin
unfold fn at *,
cases φ with [f, g, l, r], esimp at *, unfold fn,
cases x with [x₁, x₂],
unfold function.right_inverse at *, unfold function.left_inverse at *, unfold inv, esimp,
apply sigma_eq_congr, refine ⟨l x₁,_⟩,
calc
(l x₁ ▹ ((r (f x₁))⁻¹ ▹ x₂))
= (l x₁ ▹ (eq.symm (ap f (l x₁)) ▹ x₂)) : rfl
... = (l x₁ ▹ (eq.symm (l x₁) ▹ x₂)) : naturality_subst
... = ((l x₁ ⬝ (eq.symm (l x₁))) ▹ x₂) : transport_concat
... = x₂ : concat_inv (l x₁)
end)
begin
intro x, cases x with [x₁, x₂],
cases φ with [f, g, l, r], unfold function.right_inverse at *, unfold function.left_inverse at *, esimp at *,
apply sigma_eq_congr, refine ⟨_,_⟩, apply r,
calc
#eq.ops
r x₁ ▹ (r x₁)⁻¹ ▹ x₂
= r x₁ ⬝ (r x₁)⁻¹ ▹ x₂ : transport_concat
... = x₂ : concat_inv (r x₁)
end
definition sigma_congr₂ [instance] {A : Type} {F G : A → Type} [φ : Π a : A, F a ≃ G a] :
(Σ a, F a) ≃ Σ a, G a :=
equiv.mk
(λ x, ⟨x.1, (φ x.1) ∙ x.2⟩)
(λ x, ⟨x.1, inv x.2⟩)
begin
unfold left_inverse, intros,
cases x with [p₁, p₂], esimp,
congruence, unfold fn, unfold inv,
rewrite left_inv
end
begin
unfold right_inverse, unfold left_inverse, intros,
cases x with [p₁, p₂], congruence, unfold fn, unfold inv,
rewrite right_inv
end
definition sigma_congr {A B : Type} {F : A → Type} {G : B → Type}
[φ : A ≃ B] [φ' : Π a : A, F a ≃ G (φ ∙ a)] :
(Σ a, F a) ≃ Σ a, G a := equiv.trans sigma_congr₂ sigma_congr₁
definition sigma_swap {A B : Type} {F : A → B → Type} :
(Σ (a : A) (b : B), F a b) ≃ Σ (b : B) (a : A), F a b :=
equiv.mk (λ x, ⟨x.2.1,⟨x.1,x.2.2⟩⟩)
(λ x, ⟨x.2.1,⟨x.1,x.2.2⟩⟩)
(λ x, by cases x with [p1,p2]; cases p2; reflexivity)
(λ x, by cases x with [p1,p2]; cases p2; reflexivity)
definition iff_impl_equiv {A B : Prop} (Hiff : A ↔ B) : A ≃ B :=
match Hiff with
| iff.intro f g := equiv.mk f g (λx, proof_irrel _ _) (λx, proof_irrel _ _)
end
end equiv
namespace function
definition happly {A B : Type} {f g : A → B} : f = g -> ∀ x, f x = g x :=
begin
intros H x, rewrite H
end
end function
|
3e59211c585886bbd7e4ad5cc6913dc9d5e66e72 | 6e9cd8d58e550c481a3b45806bd34a3514c6b3e0 | /src/algebra/field.lean | 5d3a9d80e2ff20f48111a874f1470ceabf7e3065 | [
"Apache-2.0"
] | permissive | sflicht/mathlib | 220fd16e463928110e7b0a50bbed7b731979407f | 1b2048d7195314a7e34e06770948ee00f0ac3545 | refs/heads/master | 1,665,934,056,043 | 1,591,373,803,000 | 1,591,373,803,000 | 269,815,267 | 0 | 0 | Apache-2.0 | 1,591,402,068,000 | 1,591,402,067,000 | null | UTF-8 | Lean | false | false | 15,868 | lean | /-
Copyright (c) 2014 Robert Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Lewis, Leonardo de Moura, Johannes Hölzl, Mario Carneiro
-/
import algebra.ring
import algebra.group_with_zero
open set
set_option default_priority 100 -- see Note [default priority]
set_option old_structure_cmd true
universe u
variables {α : Type u}
@[protect_proj, ancestor ring has_inv]
class division_ring (α : Type u) extends ring α, has_inv α :=
(mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1)
(inv_mul_cancel : ∀ {a : α}, a ≠ 0 → a⁻¹ * a = 1)
(inv_zero : (0 : α)⁻¹ = 0)
(zero_ne_one : (0 : α) ≠ 1)
section division_ring
variables [division_ring α] {a b : α}
instance division_ring.to_nonzero : nonzero α :=
⟨division_ring.zero_ne_one⟩
protected definition algebra.div (a b : α) : α :=
a * b⁻¹
instance division_ring_has_div : has_div α :=
⟨algebra.div⟩
lemma division_def (a b : α) : a / b = a * b⁻¹ :=
rfl
@[simp] lemma mul_inv_cancel (h : a ≠ 0) : a * a⁻¹ = 1 :=
division_ring.mul_inv_cancel h
@[simp] lemma inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
division_ring.inv_mul_cancel h
@[simp] lemma one_div_eq_inv (a : α) : 1 / a = a⁻¹ := one_mul a⁻¹
@[field_simps] lemma inv_eq_one_div (a : α) : a⁻¹ = 1 / a := by simp
/-- Every division ring is a `group_with_zero`. -/
@[priority 10] -- see Note [lower instance priority]
instance division_ring.to_group_with_zero :
group_with_zero α :=
{ mul_inv_cancel := λ _, mul_inv_cancel,
.. ‹division_ring α›,
.. (by apply_instance : semiring α) }
local attribute [simp]
division_def mul_comm mul_assoc
mul_left_comm mul_inv_cancel inv_mul_cancel
lemma div_eq_mul_one_div (a b : α) : a / b = a * (1 / b) := by simp
lemma mul_one_div_cancel (h : a ≠ 0) : a * (1 / a) = 1 := by simp [h]
lemma one_div_mul_cancel (h : a ≠ 0) : (1 / a) * a = 1 := by simp [h]
@[simp] lemma div_self (h : a ≠ 0) : a / a = 1 := by simp [h]
lemma one_div_one : 1 / 1 = (1:α) :=
div_self (ne.symm zero_ne_one)
theorem inv_one : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one]
lemma mul_div_assoc (a b c : α) : (a * b) / c = a * (b / c) := by simp
@[field_simps] lemma mul_div_assoc' (a b c : α) : a * (b / c) = (a * b) / c :=
by simp [mul_div_assoc]
lemma one_div_ne_zero (h : a ≠ 0) : 1 / a ≠ 0 :=
assume : 1 / a = 0,
have 0 = (1:α), from eq.symm (by rw [← mul_one_div_cancel h, this, mul_zero]),
absurd this zero_ne_one
lemma ne_zero_of_one_div_ne_zero (h : 1 / a ≠ 0) : a ≠ 0 :=
assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end
lemma inv_ne_zero (h : a ≠ 0) : a⁻¹ ≠ 0 :=
by rw inv_eq_one_div; exact one_div_ne_zero h
lemma eq_zero_of_one_div_eq_zero (h : 1 / a = 0) : a = 0 :=
classical.by_cases
(assume ha, ha)
(assume ha, false.elim ((one_div_ne_zero ha) h))
lemma one_inv_eq : 1⁻¹ = (1:α) :=
calc 1⁻¹ = 1 * 1⁻¹ : by rw [one_mul]
... = (1:α) : by simp
local attribute [simp] one_inv_eq
lemma div_one (a : α) : a / 1 = a := by simp
lemma zero_div (a : α) : 0 / a = 0 := by simp
-- note: integral domain has a "mul_ne_zero". a commutative division ring is an integral
-- domain, but let's not define that class for now.
lemma division_ring.mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 :=
assume : a * b = 0,
have a * 1 = 0, by rw [← mul_one_div_cancel hb, ← mul_assoc, this, zero_mul],
have a = 0, by rwa mul_one at this,
absurd this ha
lemma mul_ne_zero_comm (h : a * b ≠ 0) : b * a ≠ 0 :=
have h₁ : a ≠ 0, from ne_zero_of_mul_ne_zero_right h,
have h₂ : b ≠ 0, from ne_zero_of_mul_ne_zero_left h,
division_ring.mul_ne_zero h₂ h₁
lemma eq_one_div_of_mul_eq_one (h : a * b = 1) : b = 1 / a :=
have a ≠ 0, from
assume : a = 0,
have 0 = (1:α), by rwa [this, zero_mul] at h,
absurd this zero_ne_one,
have b = (1 / a) * a * b, by rw [one_div_mul_cancel this, one_mul],
show b = 1 / a, by rwa [mul_assoc, h, mul_one] at this
lemma eq_one_div_of_mul_eq_one_left (h : b * a = 1) : b = 1 / a :=
have a ≠ 0, from
assume : a = 0,
have 0 = (1:α), by rwa [this, mul_zero] at h,
absurd this zero_ne_one,
by rw [← h, mul_div_assoc, div_self this, mul_one]
lemma division_ring.one_div_mul_one_div : (1 / a) * (1 / b) = 1 / (b * a) :=
match classical.em (a = 0), classical.em (b = 0) with
| or.inr ha, or.inr hb :=
have (b * a) * ((1 / a) * (1 / b)) = 1,
by rw [mul_assoc, ← mul_assoc a, mul_one_div_cancel ha, one_mul, mul_one_div_cancel hb],
eq_one_div_of_mul_eq_one this
| or.inl ha, _ := by simp [ha]
| _ , or.inl hb := by simp [hb]
end
lemma one_div_neg_one_eq_neg_one : (1:α) / (-1) = -1 :=
have (-1) * (-1) = (1:α), by rw [neg_mul_neg, one_mul],
eq.symm (eq_one_div_of_mul_eq_one this)
lemma one_div_neg_eq_neg_one_div (a : α) : 1 / (- a) = - (1 / a) :=
calc
1 / (- a) = 1 / ((-1) * a) : by rw neg_eq_neg_one_mul
... = (1 / a) * (1 / (- 1)) : by rw division_ring.one_div_mul_one_div
... = (1 / a) * (-1) : by rw one_div_neg_one_eq_neg_one
... = - (1 / a) : by rw [mul_neg_eq_neg_mul_symm, mul_one]
lemma div_neg_eq_neg_div (a b : α) : b / (- a) = - (b / a) :=
calc
b / (- a) = b * (1 / (- a)) : by rw [← inv_eq_one_div, division_def]
... = b * -(1 / a) : by rw one_div_neg_eq_neg_one_div
... = -(b * (1 / a)) : by rw neg_mul_eq_mul_neg
... = - (b * a⁻¹) : by rw inv_eq_one_div
lemma neg_div (a b : α) : (-b) / a = - (b / a) :=
by rw [neg_eq_neg_one_mul, mul_div_assoc, ← neg_eq_neg_one_mul]
@[field_simps] lemma neg_div' {α : Type*} [division_ring α] (a b : α) : - (b / a) = (-b) / a :=
by simp [neg_div]
lemma neg_div_neg_eq (a b : α) : (-a) / (-b) = a / b :=
by rw [div_neg_eq_neg_div, neg_div, neg_neg]
lemma one_div_one_div (a : α) : 1 / (1 / a) = a :=
match classical.em (a = 0) with
| or.inl h := by simp [h]
| or.inr h := eq.symm (eq_one_div_of_mul_eq_one_left (mul_one_div_cancel h))
end
lemma eq_of_one_div_eq_one_div (h : 1 / a = 1 / b) : a = b :=
by rw [← one_div_one_div a, h,one_div_one_div]
lemma mul_inv' (a b : α) : (b * a)⁻¹ = a⁻¹ * b⁻¹ :=
eq.symm $ calc
a⁻¹ * b⁻¹ = (1 / a) * (1 / b) : by simp
... = (1 / (b * a)) : division_ring.one_div_mul_one_div
... = (b * a)⁻¹ : by simp
lemma one_div_div (a b : α) : 1 / (a / b) = b / a :=
by rw [one_div_eq_inv, division_def, mul_inv',
inv_inv', division_def]
lemma div_helper (b : α) (h : a ≠ 0) : (1 / (a * b)) * a = 1 / b :=
by simp only [division_def, mul_inv', one_mul, mul_assoc, inv_mul_cancel h, mul_one]
lemma mul_div_cancel (a : α) {b : α} (hb : b ≠ 0) : a * b / b = a :=
by simp [hb]
lemma div_mul_cancel (a : α) {b : α} (hb : b ≠ 0) : a / b * b = a :=
by simp [hb]
@[field_simps] lemma div_div_eq_mul_div (a b c : α) : a / (b / c) = (a * c) / b :=
by rw [div_eq_mul_one_div, one_div_div, ← mul_div_assoc]
lemma div_mul_left (hb : b ≠ 0) : b / (a * b) = 1 / a :=
by simp only [division_def, mul_inv', ← mul_assoc, mul_inv_cancel hb]
lemma mul_div_mul_right (a : α) (b : α) {c : α} (hc : c ≠ 0) :
(a * c) / (b * c) = a / b :=
by rw [mul_div_assoc, div_mul_left hc, ← mul_div_assoc, mul_one]
@[field_simps] lemma div_add_div_same (a b c : α) : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma div_sub_div_same (a b c : α) : (a / c) - (b / c) = (a - b) / c :=
by rw [sub_eq_add_neg, ← neg_div, div_add_div_same, sub_eq_add_neg]
lemma neg_inv : - a⁻¹ = (- a)⁻¹ :=
by rw [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div]
lemma add_div (a b c : α) : (a + b) / c = a / c + b / c :=
(div_add_div_same _ _ _).symm
lemma sub_div (a b c : α) : (a - b) / c = a / c - b / c :=
(div_sub_div_same _ _ _).symm
lemma division_ring.inv_inj : a⁻¹ = b⁻¹ ↔ a = b :=
inv_inj'' _ _
lemma division_ring.inv_eq_iff : a⁻¹ = b ↔ b⁻¹ = a :=
inv_eq_iff
lemma div_neg (a : α) : a / -b = -(a / b) :=
by rw [← div_neg_eq_neg_div]
lemma inv_neg : (-a)⁻¹ = -(a⁻¹) :=
by rw neg_inv
lemma one_div_mul_add_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) :
(1 / a) * (a + b) * (1 / b) = 1 / a + 1 / b :=
by rw [(left_distrib (1 / a)), (one_div_mul_cancel ha), right_distrib, one_mul,
mul_assoc, (mul_one_div_cancel hb), mul_one, add_comm]
lemma one_div_mul_sub_mul_one_div_eq_one_div_add_one_div (ha : a ≠ 0) (hb : b ≠ 0) :
(1 / a) * (b - a) * (1 / b) = 1 / a - 1 / b :=
by rw [(mul_sub_left_distrib (1 / a)), (one_div_mul_cancel ha), mul_sub_right_distrib,
one_mul, mul_assoc, (mul_one_div_cancel hb), mul_one]
lemma div_eq_one_iff_eq (a : α) {b : α} (hb : b ≠ 0) : a / b = 1 ↔ a = b :=
iff.intro
(assume : a / b = 1, calc
a = a / b * b : by simp [hb]
... = 1 * b : by rw this
... = b : by simp)
(assume : a = b, by simp [this, hb])
lemma eq_of_div_eq_one (a : α) {b : α} (Hb : b ≠ 0) : a / b = 1 → a = b :=
iff.mp $ div_eq_one_iff_eq a Hb
lemma eq_div_iff_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a = b / c ↔ a * c = b :=
iff.intro
(assume : a = b / c, by rw [this, (div_mul_cancel _ hc)])
(assume : a * c = b, by rw [← this, mul_div_cancel _ hc])
lemma eq_div_of_mul_eq (a b : α) {c : α} (hc : c ≠ 0) : a * c = b → a = b / c :=
iff.mpr $ eq_div_iff_mul_eq a b hc
lemma mul_eq_of_eq_div (a b: α) {c : α} (hc : c ≠ 0) : a = b / c → a * c = b :=
iff.mp $ eq_div_iff_mul_eq a b hc
lemma add_div_eq_mul_add_div (a b : α) {c : α} (hc : c ≠ 0) : a + b / c = (a * c + b) / c :=
have (a + b / c) * c = a * c + b, by rw [right_distrib, (div_mul_cancel _ hc)],
(iff.mpr (eq_div_iff_mul_eq _ _ hc)) this
lemma mul_mul_div (a : α) {c : α} (hc : c ≠ 0) : a = a * c * (1 / c) :=
by simp [hc]
lemma eq_of_mul_eq_mul_of_nonzero_left {a b c : α} (h : a ≠ 0) (h₂ : a * b = a * c) : b = c :=
by rw [← one_mul b, ← inv_mul_cancel h, mul_assoc, h₂, ← mul_assoc, inv_mul_cancel h, one_mul]
lemma eq_of_mul_eq_mul_of_nonzero_right {a b c : α} (h : c ≠ 0) (h2 : a * c = b * c) : a = b :=
by rw [← mul_one a, ← mul_inv_cancel h, ← mul_assoc, h2, mul_assoc, mul_inv_cancel h, mul_one]
instance division_ring.to_domain : domain α :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h,
classical.by_contradiction $ λ hn,
division_ring.mul_ne_zero (mt or.inl hn) (mt or.inr hn) h
..‹division_ring α›, ..(by apply_instance : semiring α) }
end division_ring
@[protect_proj, ancestor division_ring comm_ring]
class field (α : Type u) extends comm_ring α, has_inv α :=
(mul_inv_cancel : ∀ {a : α}, a ≠ 0 → a * a⁻¹ = 1)
(inv_zero : (0 : α)⁻¹ = 0)
(zero_ne_one : (0 : α) ≠ 1)
section field
variable [field α]
instance field.to_division_ring : division_ring α :=
{ inv_mul_cancel := λ _ h, by rw [mul_comm, field.mul_inv_cancel h]
..show field α, by apply_instance }
lemma one_div_mul_one_div (a b : α) : (1 / a) * (1 / b) = 1 / (a * b) :=
by rw [division_ring.one_div_mul_one_div, mul_comm b]
lemma div_mul_right {a : α} (b : α) (ha : a ≠ 0) : a / (a * b) = 1 / b :=
by rw [mul_comm, div_mul_left ha]
lemma mul_div_cancel_left {a : α} (b : α) (ha : a ≠ 0) : a * b / a = b :=
by rw [mul_comm a, (mul_div_cancel _ ha)]
lemma mul_div_cancel' (a : α) {b : α} (hb : b ≠ 0) : b * (a / b) = a :=
by rw [mul_comm, (div_mul_cancel _ hb)]
lemma one_div_add_one_div {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : 1 / a + 1 / b = (a + b) / (a * b) :=
by rw [add_comm, ← div_mul_left ha, ← div_mul_right _ hb,
division_def, division_def, division_def, ← right_distrib, mul_comm a]
local attribute [simp] mul_assoc mul_comm mul_left_comm
lemma div_mul_div (a b c d : α) :
(a / b) * (c / d) = (a * c) / (b * d) :=
begin simp [division_def], rw [mul_inv', mul_comm d⁻¹] end
lemma mul_div_mul_left (a b : α) {c : α} (hc : c ≠ 0) :
(c * a) / (c * b) = a / b :=
by rw [← div_mul_div, div_self hc, one_mul]
@[field_simps] lemma div_mul_eq_mul_div (a b c : α) : (b / c) * a = (b * a) / c :=
by simp [division_def]
lemma div_mul_eq_mul_div_comm (a b c : α) :
(b / c) * a = b * (a / c) :=
by rw [div_mul_eq_mul_div, ← one_mul c, ← div_mul_div,
div_one, one_mul]
lemma div_add_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) + (c / d) = ((a * d) + (b * c)) / (b * d) :=
by rw [← mul_div_mul_right _ b hd, ← mul_div_mul_left c d hb, div_add_div_same]
@[field_simps] lemma div_sub_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0) (hd : d ≠ 0) :
(a / b) - (c / d) = ((a * d) - (b * c)) / (b * d) :=
begin
simp [sub_eq_add_neg],
rw [neg_eq_neg_one_mul, ← mul_div_assoc, div_add_div _ _ hb hd,
← mul_assoc, mul_comm b, mul_assoc, ← neg_eq_neg_one_mul]
end
lemma mul_eq_mul_of_div_eq_div (a : α) {b : α} (c : α) {d : α} (hb : b ≠ 0)
(hd : d ≠ 0) (h : a / b = c / d) : a * d = c * b :=
by rw [← mul_one (a*d), mul_assoc, mul_comm d, ← mul_assoc, ← div_self hb,
← div_mul_eq_mul_div_comm, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
@[field_simps] lemma div_div_eq_div_mul (a b c : α) : (a / b) / c = a / (b * c) :=
by rw [div_eq_mul_one_div, div_mul_div, mul_one]
lemma div_div_div_div_eq (a : α) {b c d : α} :
(a / b) / (c / d) = (a * d) / (b * c) :=
by rw [div_div_eq_mul_div, div_mul_eq_mul_div,
div_div_eq_div_mul]
lemma div_mul_eq_div_mul_one_div (a b c : α) :
a / (b * c) = (a / b) * (1 / c) :=
by rw [← div_div_eq_div_mul, ← div_eq_mul_one_div]
lemma inv_add_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ + b⁻¹ = (a + b) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, one_div_add_one_div ha hb]
lemma inv_sub_inv {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) : a⁻¹ - b⁻¹ = (b - a) / (a * b) :=
by rw [inv_eq_one_div, inv_eq_one_div, div_sub_div _ _ ha hb, one_mul, mul_one]
@[field_simps] lemma add_div' (a b c : α) (hc : c ≠ 0) : b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
@[field_simps] lemma sub_div' (a b c : α) (hc : c ≠ 0) : b - a / c = (b * c - a) / c :=
by simpa using div_sub_div b a one_ne_zero hc
@[field_simps] lemma div_add' (a b c : α) (hc : c ≠ 0) : a / c + b = (a + b * c) / c :=
by rwa [add_comm, add_div', add_comm]
@[field_simps] lemma div_sub' (a b c : α) (hc : c ≠ 0) : a / c - b = (a - c * b) / c :=
by simpa using div_sub_div a b hc one_ne_zero
/-- Every field is a `comm_group_with_zero`. -/
instance field.to_comm_group_with_zero :
comm_group_with_zero α :=
{ .. (_ : group_with_zero α), .. ‹field α› }
@[priority 100] -- see Note [lower instance priority]
instance field.to_integral_domain : integral_domain α :=
{ ..‹field α›, ..division_ring.to_domain }
end field
namespace ring_hom
section
variables {β : Type*} [division_ring α] [division_ring β] (f : α →+* β) {x y : α}
lemma map_ne_zero : f x ≠ 0 ↔ x ≠ 0 :=
⟨mt $ λ h, h.symm ▸ f.map_zero,
λ x0 h, one_ne_zero $ by rw [← f.map_one, ← mul_inv_cancel x0, f.map_mul, h, zero_mul]⟩
lemma map_eq_zero : f x = 0 ↔ x = 0 :=
by haveI := classical.dec; exact not_iff_not.1 f.map_ne_zero
lemma map_inv : f x⁻¹ = (f x)⁻¹ :=
begin
classical, by_cases h : x = 0, by simp [h],
apply (domain.mul_right_inj (f.map_ne_zero.2 h)).1,
rw [mul_inv_cancel (f.map_ne_zero.2 h), ← f.map_mul, mul_inv_cancel h, f.map_one]
end
lemma map_div : f (x / y) = f x / f y :=
(f.map_mul _ _).trans $ congr_arg _ $ f.map_inv
lemma injective : function.injective f :=
f.injective_iff.2
(λ a ha, classical.by_contradiction $ λ ha0,
by simpa [ha, f.map_mul, f.map_one, zero_ne_one]
using congr_arg f (mul_inv_cancel ha0))
end
end ring_hom
|
a0d9a8b99291997c171563db2ced13e5c1200932 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /03_Propositions_and_Proofs.org.19.lean | 061bfc01f0963c5c1a9641633123646bc6f957f5 | [] | no_license | cjmazey/lean-tutorial | ba559a49f82aa6c5848b9bf17b7389bf7f4ba645 | 381f61c9fcac56d01d959ae0fa6e376f2c4e3b34 | refs/heads/master | 1,610,286,098,832 | 1,447,124,923,000 | 1,447,124,923,000 | 43,082,433 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 159 | lean | /- page 39 -/
import standard
variables p q : Prop
-- BEGIN
example (H : p ∧ q) : p := and.elim_left H
example (H : p ∧ q) : q := and.elim_right H
-- END
|
404b1dab63dd3aa9c91fdb6975e4dff5441a7237 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/algebra/pi_instances.lean | d5acb8655714706510e9eb31c7e0191dd2c35f77 | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 18,757 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
Pi instances for algebraic structures.
-/
import order.basic
import algebra.module algebra.group
import data.finset
import ring_theory.subring
import tactic.pi_instances
namespace pi
universes u v w
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equiped with instances
variables (x y : Π i, f i) (i : I)
instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩
@[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl
instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩
@[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
attribute [to_additive pi.has_zero] pi.has_one
attribute [to_additive pi.zero_apply] pi.one_apply
instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩
@[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩
@[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
attribute [to_additive pi.has_add] pi.has_mul
attribute [to_additive pi.add_apply] pi.mul_apply
instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩
@[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩
@[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl
attribute [to_additive pi.has_neg] pi.has_inv
attribute [to_additive pi.neg_apply] pi.inv_apply
instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance
instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance
instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance
instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance
instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance
instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance
instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance
instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance
instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance
instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : mul_action α (Π i : I, f i) :=
{ smul := λ c f i, c • f i,
mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _,
one_smul := λ f, funext $ λ i, one_smul α _ }
instance distrib_mul_action (α) {m : monoid α} [∀ i, add_monoid $ f i] [∀ i, distrib_mul_action α $ f i] : distrib_mul_action α (Π i : I, f i) :=
{ smul_zero := λ c, funext $ λ i, smul_zero _,
smul_add := λ c f g, funext $ λ i, smul_add _ _ _,
..pi.mul_action _ }
variables (I f)
instance semimodule (α) {r : semiring α} [∀ i, add_comm_monoid $ f i] [∀ i, semimodule α $ f i] : semimodule α (Π i : I, f i) :=
{ add_smul := λ c f g, funext $ λ i, add_smul _ _ _,
zero_smul := λ f, funext $ λ i, zero_smul α _,
..pi.distrib_mul_action _ }
variables {I f}
instance module (α) {r : ring α} [∀ i, add_comm_group $ f i] [∀ i, module α $ f i] : module α (Π i : I, f i) := {..pi.semimodule I f α}
instance vector_space (α) {r : discrete_field α} [∀ i, add_comm_group $ f i] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) := {..pi.module α}
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) :=
by pi_instance
instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) :=
{ add_lt_add_left := λ a b hab c, ⟨λ i, add_le_add_left (hab.1 i) (c i),
λ h, hab.2 $ λ i, le_of_add_le_add_left (h i)⟩,
add_le_add_left := λ x y hxy c i, add_le_add_left (hxy i) _,
..pi.add_comm_group,
..pi.partial_order }
attribute [to_additive pi.add_semigroup] pi.semigroup
attribute [to_additive pi.add_comm_semigroup] pi.comm_semigroup
attribute [to_additive pi.add_monoid] pi.monoid
attribute [to_additive pi.add_comm_monoid] pi.comm_monoid
attribute [to_additive pi.add_group] pi.group
attribute [to_additive pi.add_comm_group] pi.comm_group
attribute [to_additive pi.add_left_cancel_semigroup] pi.left_cancel_semigroup
attribute [to_additive pi.add_right_cancel_semigroup] pi.right_cancel_semigroup
@[to_additive pi.list_sum_apply]
lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) :
∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod
| [] := rfl
| (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l]
@[to_additive pi.multiset_sum_apply]
lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α)
(s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod :=
quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end
@[to_additive pi.finset_sum_apply]
lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α)
(s : finset γ) (g : γ → Πa, β a) : s.prod g a = s.prod (λc, g c a) :=
show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod,
by rw [multiset_prod_apply, multiset.map_map]
instance is_ring_hom_pi
{α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)]
{γ : Type w} [ring γ]
(f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] :
is_ring_hom (λ x b, f b x) :=
begin
split,
-- It's a pity that these can't be done using `simp` lemmas.
{ ext, rw [is_ring_hom.map_one (f x)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_mul (f z)], refl, },
{ intros x y, ext1 z, rw [is_ring_hom.map_add (f z)], refl, }
end
end pi
namespace prod
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β}
instance [has_add α] [has_add β] : has_add (α × β) :=
⟨λp q, (p.1 + q.1, p.2 + q.2)⟩
@[to_additive prod.has_add]
instance [has_mul α] [has_mul β] : has_mul (α × β) :=
⟨λp q, (p.1 * q.1, p.2 * q.2)⟩
@[simp, to_additive prod.fst_add]
lemma fst_mul [has_mul α] [has_mul β] : (p * q).1 = p.1 * q.1 := rfl
@[simp, to_additive prod.snd_add]
lemma snd_mul [has_mul α] [has_mul β] : (p * q).2 = p.2 * q.2 := rfl
@[simp, to_additive prod.mk_add_mk]
lemma mk_mul_mk [has_mul α] [has_mul β] (a₁ a₂ : α) (b₁ b₂ : β) :
(a₁, b₁) * (a₂, b₂) = (a₁ * a₂, b₁ * b₂) := rfl
instance [has_zero α] [has_zero β] : has_zero (α × β) := ⟨(0, 0)⟩
@[to_additive prod.has_zero]
instance [has_one α] [has_one β] : has_one (α × β) := ⟨(1, 1)⟩
@[simp, to_additive prod.fst_zero]
lemma fst_one [has_one α] [has_one β] : (1 : α × β).1 = 1 := rfl
@[simp, to_additive prod.snd_zero]
lemma snd_one [has_one α] [has_one β] : (1 : α × β).2 = 1 := rfl
@[to_additive prod.zero_eq_mk]
lemma one_eq_mk [has_one α] [has_one β] : (1 : α × β) = (1, 1) := rfl
instance [has_neg α] [has_neg β] : has_neg (α × β) := ⟨λp, (- p.1, - p.2)⟩
@[to_additive prod.has_neg]
instance [has_inv α] [has_inv β] : has_inv (α × β) := ⟨λp, (p.1⁻¹, p.2⁻¹)⟩
@[simp, to_additive prod.fst_neg]
lemma fst_inv [has_inv α] [has_inv β] : (p⁻¹).1 = (p.1)⁻¹ := rfl
@[simp, to_additive prod.snd_neg]
lemma snd_inv [has_inv α] [has_inv β] : (p⁻¹).2 = (p.2)⁻¹ := rfl
@[to_additive prod.neg_mk]
lemma inv_mk [has_inv α] [has_inv β] (a : α) (b : β) : (a, b)⁻¹ = (a⁻¹, b⁻¹) := rfl
instance [add_semigroup α] [add_semigroup β] : add_semigroup (α × β) :=
{ add_assoc := assume a b c, mk.inj_iff.mpr ⟨add_assoc _ _ _, add_assoc _ _ _⟩,
.. prod.has_add }
@[to_additive prod.add_semigroup]
instance [semigroup α] [semigroup β] : semigroup (α × β) :=
{ mul_assoc := assume a b c, mk.inj_iff.mpr ⟨mul_assoc _ _ _, mul_assoc _ _ _⟩,
.. prod.has_mul }
instance [add_monoid α] [add_monoid β] : add_monoid (α × β) :=
{ zero_add := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨zero_add _, zero_add _⟩,
add_zero := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨add_zero _, add_zero _⟩,
.. prod.add_semigroup, .. prod.has_zero }
@[to_additive prod.add_monoid]
instance [monoid α] [monoid β] : monoid (α × β) :=
{ one_mul := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨one_mul _, one_mul _⟩,
mul_one := assume a, prod.rec_on a $ λa b, mk.inj_iff.mpr ⟨mul_one _, mul_one _⟩,
.. prod.semigroup, .. prod.has_one }
instance [add_group α] [add_group β] : add_group (α × β) :=
{ add_left_neg := assume a, mk.inj_iff.mpr ⟨add_left_neg _, add_left_neg _⟩,
.. prod.add_monoid, .. prod.has_neg }
@[to_additive prod.add_group]
instance [group α] [group β] : group (α × β) :=
{ mul_left_inv := assume a, mk.inj_iff.mpr ⟨mul_left_inv _, mul_left_inv _⟩,
.. prod.monoid, .. prod.has_inv }
instance [add_comm_semigroup α] [add_comm_semigroup β] : add_comm_semigroup (α × β) :=
{ add_comm := assume a b, mk.inj_iff.mpr ⟨add_comm _ _, add_comm _ _⟩,
.. prod.add_semigroup }
@[to_additive prod.add_comm_semigroup]
instance [comm_semigroup α] [comm_semigroup β] : comm_semigroup (α × β) :=
{ mul_comm := assume a b, mk.inj_iff.mpr ⟨mul_comm _ _, mul_comm _ _⟩,
.. prod.semigroup }
instance [add_comm_monoid α] [add_comm_monoid β] : add_comm_monoid (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_monoid }
@[to_additive prod.add_comm_monoid]
instance [comm_monoid α] [comm_monoid β] : comm_monoid (α × β) :=
{ .. prod.comm_semigroup, .. prod.monoid }
instance [add_comm_group α] [add_comm_group β] : add_comm_group (α × β) :=
{ .. prod.add_comm_semigroup, .. prod.add_group }
@[to_additive prod.add_comm_group]
instance [comm_group α] [comm_group β] : comm_group (α × β) :=
{ .. prod.comm_semigroup, .. prod.group }
@[to_additive fst.is_add_monoid_hom]
lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive snd.is_add_monoid_hom]
lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl, map_one := rfl }
@[to_additive fst.is_add_group_hom]
lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) :=
{ map_mul := λ _ _, rfl }
@[to_additive snd.is_add_group_hom]
lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) :=
{ map_mul := λ _ _, rfl }
attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom
fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom
@[to_additive prod.fst_sum]
lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).1 = t.prod (λc, (f c).1) :=
(finset.prod_hom prod.fst).symm
@[to_additive prod.snd_sum]
lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} :
(t.prod f).2 = t.prod (λc, (f c).2) :=
(finset.prod_hom prod.snd).symm
instance [semiring α] [semiring β] : semiring (α × β) :=
{ zero_mul := λ a, mk.inj_iff.mpr ⟨zero_mul _, zero_mul _⟩,
mul_zero := λ a, mk.inj_iff.mpr ⟨mul_zero _, mul_zero _⟩,
left_distrib := λ a b c, mk.inj_iff.mpr ⟨left_distrib _ _ _, left_distrib _ _ _⟩,
right_distrib := λ a b c, mk.inj_iff.mpr ⟨right_distrib _ _ _, right_distrib _ _ _⟩,
..prod.add_comm_monoid, ..prod.monoid }
instance [ring α] [ring β] : ring (α × β) :=
{ ..prod.add_comm_group, ..prod.semiring }
instance [comm_ring α] [comm_ring β] : comm_ring (α × β) :=
{ ..prod.ring, ..prod.comm_monoid }
instance [nonzero_comm_ring α] [comm_ring β] : nonzero_comm_ring (α × β) :=
{ zero_ne_one := mt (congr_arg prod.fst) zero_ne_one,
..prod.comm_ring }
instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) :=
by refine_struct {..}; simp
instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) :=
by refine_struct {..}; simp
/-- Left injection function for the inner product
From a vector space (and also group and module) perspective the product is the same as the sum of
two vector spaces. `inl` and `inr` provide the corresponding injection functions.
-/
def inl [has_zero β] (a : α) : α × β := (a, 0)
/-- Right injection function for the inner product -/
def inr [has_zero α] (b : β) : α × β := (0, b)
lemma injective_inl [has_zero β] : function.injective (inl : α → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).1
lemma injective_inr [has_zero α] : function.injective (inr : β → α × β) :=
assume x y h, (prod.mk.inj_iff.mp h).2
@[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ :=
iff.intro (assume h, injective_inl h) (assume h, h ▸ rfl)
@[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ :=
iff.intro (assume h, injective_inr h) (assume h, h ▸ rfl)
@[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} :
inl a = inr b ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} :
inr b = inl a ↔ a = 0 ∧ b = 0 :=
by constructor; simp [inl, inr] {contextual := tt}
@[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl
@[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl
@[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl
@[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl
instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩
@[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl
@[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ]
(a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl
@[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ]
(a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl
instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ]
[semimodule α β] [semimodule α γ] : semimodule α (β × γ) :=
{ smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩,
add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩,
mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩,
one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩,
zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩,
smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩,
.. prod.has_scalar }
instance {r : ring α} [add_comm_group β] [add_comm_group γ]
[module α β] [module α γ] : module α (β × γ) := {}
instance {r : discrete_field α} [add_comm_group β] [add_comm_group γ]
[vector_space α β] [vector_space α γ] : vector_space α (β × γ) := {}
section substructures
variables (s : set α) (t : set β)
@[to_additive prod.is_add_submonoid]
instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] :
is_submonoid (s.prod t) :=
{ one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem,
mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto }
@[to_additive prod.is_add_subgroup]
instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] :
is_subgroup (s.prod t) :=
{ inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto,
.. prod.is_submonoid s t }
instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] :
is_subring (s.prod t) :=
{ .. prod.is_submonoid s t, .. prod.is_add_subgroup s t }
end substructures
end prod
namespace finset
@[to_additive finset.prod_mk_sum]
lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ)
(f : γ → α) (g : γ → β) : (s.prod f, s.prod g) = s.prod (λ x, (f x, g x)) :=
by haveI := classical.dec_eq γ; exact
finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt})
end finset
|
6260d12d3a4d275c148b5a645a07bf7bbf6f1d92 | 01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab | /categories/yoneda.lean | 52ae8ff44ae220bc0a24d8d478c21344c086d3e8 | [] | no_license | PatrickMassot/lean-category-theory | 0f56a83464396a253c28a42dece16c93baf8ad74 | ef239978e91f2e1c3b8e88b6e9c64c155dc56c99 | refs/heads/master | 1,629,739,187,316 | 1,512,422,659,000 | 1,512,422,659,000 | 113,098,786 | 0 | 0 | null | 1,512,424,022,000 | 1,512,424,022,000 | null | UTF-8 | Lean | false | false | 3,111 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import .natural_transformation
import .isomorphism
import .opposites
import .equivalence
import .products.switch
import .types
open categories
open categories.functor
open categories.natural_transformation
open categories.functor_categories
open categories.isomorphism
open categories.equivalence
open categories.types
open categories.products
namespace categories.yoneda
definition {u v} Yoneda ( C : Category.{u v} ) : Functor C (FunctorCategory (Opposite C) CategoryOfTypes.{v}) :=
{
onObjects := λ X, {
onObjects := λ Y, C.Hom Y X,
onMorphisms := λ Y Y' f, λ g, C.compose f g,
identities := ♯,
functoriality := ♯
},
onMorphisms := λ X X' f, {
components := λ Y, λ g, C.compose g f,
naturality := ♯
},
identities := ♯,
functoriality := ♯
}
@[reducible] definition {v} YonedaEvaluation ( C : Category.{v v} )
: Functor (ProductCategory (FunctorCategory (Opposite C) CategoryOfTypes.{v}) (Opposite C)) CategoryOfTypes.{v}
:= Evaluation (Opposite C) CategoryOfTypes.{v}
@[reducible] definition {v} YonedaPairing ( C : Category.{v v} )
: Functor (ProductCategory (FunctorCategory (Opposite C) CategoryOfTypes.{v}) (Opposite C)) CategoryOfTypes.{v}
:= FunctorComposition
(FunctorComposition
(ProductFunctor (IdentityFunctor _) (OppositeFunctor (Yoneda C)))
(SwitchProductCategory _ _))
(HomPairing (FunctorCategory (Opposite C) CategoryOfTypes.{v}))
@[simp] private lemma YonedaLemma_aux_1
{ C : Category }
{ X Y : C.Obj }
( f : C.Hom X Y )
{ F G : Functor (Opposite C) CategoryOfTypes }
( τ : NaturalTransformation F G )
( Z : F.onObjects Y ) :
G.onMorphisms f (τ.components Y Z) = τ.components X (F.onMorphisms f Z) := eq.symm (congr_fun (τ.naturality f) Z)
-- TODO restore this
-- theorem {v} YonedaLemma ( C : Category.{v v} ) : NaturalIsomorphism (YonedaPairing C) (YonedaEvaluation C) :=
-- begin
-- tidy {hints:=[8, 7, 8, 7, 6, 8, 6, 11, 10, 8, 11, 15, 16, 15, 16, 15, 16, 15, 16, 18, 17, 16, 15, 16, 15, 16, 15, 16, 18, 16, 17, 16, 15, 16, 18, 16, 21, 20, 18, 21]},
-- exact ((a.components _) (C.identity _)),
-- tidy {hints:=[2, 8, 9]},
-- exact ((fst.onMorphisms a_1) a),
-- tidy {hints:=[2, 9, 3, 2, 9, 3, 2, 9, 2, 9, 3]},
-- end
-- theorem {u v} YonedaEmbedding ( C : Category.{u v} ) : Embedding (Yoneda C) :=
-- begin
-- unfold Embedding,
-- fsplit,
-- {
-- -- Show it is full
-- fsplit,
-- {
-- tidy,
-- exact (f.components X) (C.identity X)
-- },
-- {
-- tidy,
-- have q := congr_fun (f.naturality x) (C.identity X),
-- tidy,
-- }
-- },
-- {
-- -- Show it is faithful
-- tidy,
-- have q := congr_arg NaturalTransformation.components p,
-- have q' := congr_fun q X,
-- have q'' := congr_fun q' (C.identity X),
-- tidy,
-- }
-- end
end categories.yoneda |
94e68c6462b52afc1d6293ddd764cadcd7ac61b6 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/probability/conditional_expectation.lean | bc789e927ee6a403a6c5f4ccaa460a0cfa64f1e3 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,471 | lean | /-
Copyright (c) 2022 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import probability.notation
import probability.independence
import measure_theory.function.conditional_expectation.basic
/-!
# Probabilistic properties of the conditional expectation
This file contains some properties about the conditional expectation which does not belong in
the main conditional expectation file.
## Main result
* `measure_theory.condexp_indep_eq`: If `m₁, m₂` are independent σ-algebras and `f` is a
`m₁`-measurable function, then `𝔼[f | m₂] = 𝔼[f]` almost everywhere.
-/
open topological_space filter
open_locale nnreal ennreal measure_theory probability_theory big_operators
namespace measure_theory
open probability_theory
variables {Ω E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E]
{m₁ m₂ m : measurable_space Ω} {μ : measure Ω} {f : Ω → E}
/-- If `m₁, m₂` are independent σ-algebras and `f` is `m₁`-measurable, then `𝔼[f | m₂] = 𝔼[f]`
almost everywhere. -/
lemma condexp_indep_eq
(hle₁ : m₁ ≤ m) (hle₂ : m₂ ≤ m) [sigma_finite (μ.trim hle₂)]
(hf : strongly_measurable[m₁] f) (hindp : indep m₁ m₂ μ) :
μ[f | m₂] =ᵐ[μ] λ x, μ[f] :=
begin
by_cases hfint : integrable f μ,
swap, { rw [condexp_undef hfint, integral_undef hfint], refl, },
have hfint₁ := hfint.trim hle₁ hf,
refine (ae_eq_condexp_of_forall_set_integral_eq hle₂ hfint
(λ s _ hs, integrable_on_const.2 (or.inr hs)) (λ s hms hs, _)
strongly_measurable_const.ae_strongly_measurable').symm,
rw set_integral_const,
rw ← mem_ℒp_one_iff_integrable at hfint,
refine hfint.induction_strongly_measurable hle₁ ennreal.one_ne_top _ _ _ _ _ _,
{ intros c t hmt ht,
rw [integral_indicator (hle₁ _ hmt), set_integral_const, smul_smul,
← ennreal.to_real_mul, mul_comm, ← hindp _ _ hmt hms, set_integral_indicator (hle₁ _ hmt),
set_integral_const, set.inter_comm] },
{ intros u v hdisj huint hvint hu hv hu_eq hv_eq,
rw mem_ℒp_one_iff_integrable at huint hvint,
rw [integral_add' huint hvint, smul_add, hu_eq, hv_eq,
integral_add' huint.integrable_on hvint.integrable_on], },
{ have heq₁ : (λ f : Lp_meas E ℝ m₁ 1 μ, ∫ x, f x ∂μ) =
(λ f : Lp E 1 μ, ∫ x, f x ∂μ) ∘ (submodule.subtypeL _),
{ refine funext (λ f, integral_congr_ae _),
simp_rw [submodule.coe_subtypeL', submodule.coe_subtype, ← coe_fn_coe_base], },
have heq₂ : (λ f : Lp_meas E ℝ m₁ 1 μ, ∫ x in s, f x ∂μ) =
(λ f : Lp E 1 μ, ∫ x in s, f x ∂μ) ∘ (submodule.subtypeL _),
{ refine funext (λ f, integral_congr_ae (ae_restrict_of_ae _)),
simp_rw [submodule.coe_subtypeL', submodule.coe_subtype, ← coe_fn_coe_base],
exact eventually_of_forall (λ _, rfl), },
refine is_closed_eq (continuous.const_smul _ _) _,
{ rw heq₁,
exact continuous_integral.comp (continuous_linear_map.continuous _), },
{ rw heq₂,
exact (continuous_set_integral _).comp (continuous_linear_map.continuous _), }, },
{ intros u v huv huint hueq,
rwa [← integral_congr_ae huv,
← (set_integral_congr_ae (hle₂ _ hms) _ : ∫ x in s, u x ∂μ = ∫ x in s, v x ∂μ)],
filter_upwards [huv] with x hx _ using hx, },
{ exact ⟨f, hf, eventually_eq.rfl⟩, },
end
end measure_theory
|
bb85317ca0cca90ab7874fc1bc87707cbc27628a | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/number_theory/liouville/basic.lean | 3ae3a256fdd7b48ca9288ab94694270ef79c0849 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,334 | lean | /-
Copyright (c) 2020 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa, Jujian Zhang
-/
import analysis.calculus.mean_value
import data.polynomial.denoms_clearable
import data.real.irrational
/-!
# Liouville's theorem
This file contains a proof of Liouville's theorem stating that all Liouville numbers are
transcendental.
To obtain this result, there is first a proof that Liouville numbers are irrational and two
technical lemmas. These lemmas exploit the fact that a polynomial with integer coefficients
takes integer values at integers. When evaluating at a rational number, we can clear denominators
and obtain precise inequalities that ultimately allow us to prove transcendence of
Liouville numbers.
-/
/--
A Liouville number is a real number `x` such that for every natural number `n`, there exist
`a, b ∈ ℤ` with `1 < b` such that `0 < |x - a/b| < 1/bⁿ`.
In the implementation, the condition `x ≠ a/b` replaces the traditional equivalent `0 < |x - a/b|`.
-/
def liouville (x : ℝ) := ∀ n : ℕ, ∃ a b : ℤ, 1 < b ∧ x ≠ a / b ∧ abs (x - a / b) < 1 / b ^ n
namespace liouville
@[protected] lemma irrational {x : ℝ} (h : liouville x) : irrational x :=
begin
-- By contradiction, `x = a / b`, with `a ∈ ℤ`, `0 < b ∈ ℕ` is a Liouville number,
rintros ⟨⟨a, b, bN0, cop⟩, rfl⟩,
-- clear up the mess of constructions of rationals
change (liouville (a / b)) at h,
-- Since `a / b` is a Liouville number, there are `p, q ∈ ℤ`, with `q1 : 1 < q`,
-- `a0 : a / b ≠ p / q` and `a1 : abs (a / b - p / q) < 1 / q ^ (b + 1)`
rcases h (b + 1) with ⟨p, q, q1, a0, a1⟩,
-- A few useful inequalities
have qR0 : (0 : ℝ) < q := int.cast_pos.mpr (zero_lt_one.trans q1),
have b0 : (b : ℝ) ≠ 0 := ne_of_gt (nat.cast_pos.mpr bN0),
have bq0 : (0 : ℝ) < b * q := mul_pos (nat.cast_pos.mpr bN0) qR0,
-- At a1, clear denominators...
replace a1 : abs (a * q - b * p) * q ^ (b + 1) < b * q, by
rwa [div_sub_div _ _ b0 (ne_of_gt qR0), abs_div, div_lt_div_iff (abs_pos.mpr (ne_of_gt bq0))
(pow_pos qR0 _), abs_of_pos bq0, one_mul,
-- ... and revert to integers
← int.cast_pow, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_mul,
← int.cast_sub, ← int.cast_abs, ← int.cast_mul, int.cast_lt] at a1,
-- At a0, clear denominators...
replace a0 : ¬a * q - ↑b * p = 0, by
rwa [ne.def, div_eq_div_iff b0 (ne_of_gt qR0), mul_comm ↑p, ← sub_eq_zero,
-- ... and revert to integers
← int.cast_coe_nat, ← int.cast_mul, ← int.cast_mul, ← int.cast_sub, int.cast_eq_zero] at a0,
-- Actually, `q` is a natural number
lift q to ℕ using (zero_lt_one.trans q1).le,
-- Looks innocuous, but we now have an integer with non-zero absolute value: this is at
-- least one away from zero. The gain here is what gets the proof going.
have ap : 0 < abs (a * ↑q - ↑b * p) := abs_pos.mpr a0,
-- Actually, the absolute value of an integer is a natural number
lift (abs (a * ↑q - ↑b * p)) to ℕ using (abs_nonneg (a * ↑q - ↑b * p)),
-- At a1, revert to natural numbers
rw [← int.coe_nat_mul, ← int.coe_nat_pow, ← int.coe_nat_mul, int.coe_nat_lt] at a1,
-- Recall this is by contradiction: we obtained the inequality `b * q ≤ x * q ^ (b + 1)`, so
-- we are done.
exact not_le.mpr a1 (nat.mul_lt_mul_pow_succ (int.coe_nat_pos.mp ap) (int.coe_nat_lt.mp q1)).le,
end
open polynomial metric set real ring_hom
/-- Let `Z, N` be types, let `R` be a metric space, let `α : R` be a point and let
`j : Z → N → R` be a function. We aim to estimate how close we can get to `α`, while staying
in the image of `j`. The points `j z a` of `R` in the image of `j` come with a "cost" equal to
`d a`. As we get closer to `α` while staying in the image of `j`, we are interested in bounding
the quantity `d a * dist α (j z a)` from below by a strictly positive amount `1 / A`: the intuition
is that approximating well `α` with the points in the image of `j` should come at a high cost. The
hypotheses on the function `f : R → R` provide us with sufficient conditions to ensure our goal.
The first hypothesis is that `f` is Lipschitz at `α`: this yields a bound on the distance.
The second hypothesis is specific to the Liouville argument and provides the missing bound
involving the cost function `d`.
This lemma collects the properties used in the proof of `exists_pos_real_of_irrational_root`.
It is stated in more general form than needed: in the intended application, `Z = ℤ`, `N = ℕ`,
`R = ℝ`, `d a = (a + 1) ^ f.nat_degree`, `j z a = z / (a + 1)`, `f ∈ ℤ[x]`, `α` is an irrational
root of `f`, `ε` is small, `M` is a bound on the Lipschitz constant of `f` near `α`, `n` is
the degree of the polynomial `f`.
-/
lemma exists_one_le_pow_mul_dist {Z N R : Type*} [metric_space R]
{d : N → ℝ} {j : Z → N → R} {f : R → R} {α : R} {ε M : ℝ}
-- denominators are positive
(d0 : ∀ (a : N), 1 ≤ d a)
(e0 : 0 < ε)
-- function is Lipschitz at α
(B : ∀ ⦃y : R⦄, y ∈ closed_ball α ε → dist (f α) (f y) ≤ (dist α y) * M)
-- clear denominators
(L : ∀ ⦃z : Z⦄, ∀ ⦃a : N⦄, j z a ∈ closed_ball α ε → 1 ≤ (d a) * dist (f α) (f (j z a))) :
∃ A : ℝ, 0 < A ∧ ∀ (z : Z), ∀ (a : N), 1 ≤ (d a) * (dist α (j z a) * A) :=
begin
-- A useful inequality to keep at hand
have me0 : 0 < max (1 / ε) M := lt_max_iff.mpr (or.inl (one_div_pos.mpr e0)),
-- The maximum between `1 / ε` and `M` works
refine ⟨max (1 / ε) M, me0, λ z a, _⟩,
-- First, let's deal with the easy case in which we are far away from `α`
by_cases dm1 : 1 ≤ (dist α (j z a) * max (1 / ε) M),
{ exact one_le_mul_of_one_le_of_one_le (d0 a) dm1 },
{ -- `j z a = z / (a + 1)`: we prove that this ratio is close to `α`
have : j z a ∈ closed_ball α ε,
{ refine mem_closed_ball'.mp (le_trans _ ((one_div_le me0 e0).mpr (le_max_left _ _))),
exact ((le_div_iff me0).mpr (not_le.mp dm1).le) },
-- use the "separation from `1`" (assumption `L`) for numerators,
refine (L this).trans _,
-- remove a common factor and use the Lipschitz assumption `B`
refine mul_le_mul_of_nonneg_left ((B this).trans _) (zero_le_one.trans (d0 a)),
exact mul_le_mul_of_nonneg_left (le_max_right _ M) dist_nonneg }
end
lemma exists_pos_real_of_irrational_root {α : ℝ} (ha : irrational α)
{f : polynomial ℤ} (f0 : f ≠ 0) (fa : eval α (map (algebra_map ℤ ℝ) f) = 0):
∃ A : ℝ, 0 < A ∧
∀ (a : ℤ), ∀ (b : ℕ), (1 : ℝ) ≤ (b + 1) ^ f.nat_degree * (abs (α - (a / (b + 1))) * A) :=
begin
-- `fR` is `f` viewed as a polynomial with `ℝ` coefficients.
set fR : polynomial ℝ := map (algebra_map ℤ ℝ) f,
-- `fR` is non-zero, since `f` is non-zero.
obtain fR0 : fR ≠ 0 := λ fR0, (map_injective (algebra_map ℤ ℝ) (λ _ _ A, int.cast_inj.mp A)).ne
f0 (fR0.trans (polynomial.map_zero _).symm),
-- reformulating assumption `fa`: `α` is a root of `fR`.
have ar : α ∈ (fR.roots.to_finset : set ℝ) :=
finset.mem_coe.mpr (multiset.mem_to_finset.mpr ((mem_roots fR0).mpr (is_root.def.mpr fa))),
-- Since the polynomial `fR` has finitely many roots, there is a closed interval centered at `α`
-- such that `α` is the only root of `fR` in the interval.
obtain ⟨ζ, z0, U⟩ : ∃ ζ > 0, closed_ball α ζ ∩ (fR.roots.to_finset) = {α} :=
@exists_closed_ball_inter_eq_singleton_of_discrete _ _ _ discrete_of_t1_of_finite _ ar,
-- Since `fR` is continuous, it is bounded on the interval above.
obtain ⟨xm, -, hM⟩ : ∃ (xm : ℝ) (H : xm ∈ Icc (α - ζ) (α + ζ)), ∀ (y : ℝ),
y ∈ Icc (α - ζ) (α + ζ) → abs (fR.derivative.eval y) ≤ abs (fR.derivative.eval xm) :=
is_compact.exists_forall_ge is_compact_Icc
⟨α, (sub_lt_self α z0).le, (lt_add_of_pos_right α z0).le⟩
(continuous_abs.comp fR.derivative.continuous_aeval).continuous_on,
-- Use the key lemma `exists_one_le_pow_mul_dist`: we are left to show that ...
refine @exists_one_le_pow_mul_dist ℤ ℕ ℝ _ _ _ (λ y, fR.eval y) α ζ
(abs (fR.derivative.eval xm)) _ z0 (λ y hy, _) (λ z a hq, _),
-- 1: the denominators are positive -- essentially by definition;
{ exact λ a, one_le_pow_of_one_le ((le_add_iff_nonneg_left 1).mpr a.cast_nonneg) _ },
-- 2: the polynomial `fR` is Lipschitz at `α` -- as its derivative continuous;
{ rw mul_comm,
rw real.closed_ball_eq at hy,
-- apply the Mean Value Theorem: the bound on the derivative comes from differentiability.
refine convex.norm_image_sub_le_of_norm_deriv_le (λ _ _, fR.differentiable_at)
(λ y h, by { rw fR.deriv, exact hM _ h }) (convex_Icc _ _) hy (mem_Icc_iff_abs_le.mp _),
exact @mem_closed_ball_self ℝ _ α ζ (le_of_lt z0) },
-- 3: the weird inequality of Liouville type with powers of the denominators.
{ show 1 ≤ (a + 1 : ℝ) ^ f.nat_degree * abs (eval α fR - eval (z / (a + 1)) fR),
rw [fa, zero_sub, abs_neg],
-- key observation: the right-hand side of the inequality is an *integer*. Therefore,
-- if its absolute value is not at least one, then it vanishes. Proceed by contradiction
refine one_le_pow_mul_abs_eval_div (int.coe_nat_succ_pos a) (λ hy, _),
-- As the evaluation of the polynomial vanishes, we found a root of `fR` that is rational.
-- We know that `α` is the only root of `fR` in our interval, and `α` is irrational:
-- follow your nose.
refine (irrational_iff_ne_rational α).mp ha z (a + 1) ((mem_singleton_iff.mp _).symm),
refine U.subset _,
refine ⟨hq, finset.mem_coe.mp (multiset.mem_to_finset.mpr _)⟩,
exact (mem_roots fR0).mpr (is_root.def.mpr hy) }
end
/-- **Liouville's Theorem** -/
theorem transcendental {x : ℝ} (lx : liouville x) :
transcendental ℤ x :=
begin
-- Proceed by contradiction: if `x` is algebraic, then `x` is the root (`ef0`) of a
-- non-zero (`f0`) polynomial `f`
rintros ⟨f : polynomial ℤ, f0, ef0⟩,
-- Change `aeval x f = 0` to `eval (map _ f) = 0`, who knew.
replace ef0 : (f.map (algebra_map ℤ ℝ)).eval x = 0, { rwa [aeval_def, ← eval_map] at ef0 },
-- There is a "large" real number `A` such that `(b + 1) ^ (deg f) * |f (x - a / (b + 1))| * A`
-- is at least one. This is obtained from lemma `exists_pos_real_of_irrational_root`.
obtain ⟨A, hA, h⟩ : ∃ (A : ℝ), 0 < A ∧
∀ (a : ℤ) (b : ℕ), (1 : ℝ) ≤ (b.succ) ^ f.nat_degree * (abs (x - a / (b.succ)) * A) :=
exists_pos_real_of_irrational_root lx.irrational f0 ef0,
-- Since the real numbers are Archimedean, a power of `2` exceeds `A`: `hn : A < 2 ^ r`.
rcases pow_unbounded_of_one_lt A (lt_add_one 1) with ⟨r, hn⟩,
-- Use the Liouville property, with exponent `r + deg f`.
obtain ⟨a, b, b1, -, a1⟩ : ∃ (a b : ℤ), 1 < b ∧ x ≠ a / b ∧
abs (x - a / b) < 1 / b ^ (r + f.nat_degree) := lx (r + f.nat_degree),
have b0 : (0 : ℝ) < b := zero_lt_one.trans (by { rw ← int.cast_one, exact int.cast_lt.mpr b1 }),
-- Prove that `b ^ f.nat_degree * abs (x - a / b)` is strictly smaller than itself
-- recall, this is a proof by contradiction!
refine lt_irrefl ((b : ℝ) ^ f.nat_degree * abs (x - ↑a / ↑b)) _,
-- clear denominators at `a1`
rw [lt_div_iff' (pow_pos b0 _), pow_add, mul_assoc] at a1,
-- split the inequality via `1 / A`.
refine ((_ : (b : ℝ) ^ f.nat_degree * abs (x - a / b) < 1 / A).trans_le _),
-- This branch of the proof uses the Liouville condition and the Archimedean property
{ refine (lt_div_iff' hA).mpr _,
refine lt_of_le_of_lt _ a1,
refine mul_le_mul_of_nonneg_right _ (mul_nonneg (pow_nonneg b0.le _) (abs_nonneg _)),
refine hn.le.trans _,
refine pow_le_pow_of_le_left zero_le_two _ _,
exact int.cast_two.symm.le.trans (int.cast_le.mpr (int.add_one_le_iff.mpr b1)) },
-- this branch of the proof exploits the "integrality" of evaluations of polynomials
-- at ratios of integers.
{ lift b to ℕ using zero_le_one.trans b1.le,
specialize h a b.pred,
rwa [nat.succ_pred_eq_of_pos (zero_lt_one.trans _), ← mul_assoc, ← (div_le_iff hA)] at h,
exact int.coe_nat_lt.mp b1 }
end
end liouville
|
2e6e70f839ea602a7af741cb497744dd3d9d2d5f | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/misc.lean | f158339bcf8f96e34db9d36ca6f256e04d65350f | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 1,285 | lean | import data.nat.basic
universe u
def string.drop_chars (c : char) (s : string) : string :=
⟨s.data.drop_while (λ x, x = c)⟩
def string.reverse (s : string) : string := ⟨s.data.reverse⟩
def update (α : Type u) (k : nat) (a : α) (f : nat → α) : nat → α :=
λ x : nat, if x = k then a else f x
lemma forall_lt_zero (p : nat → Prop) : ∀ x < 0, p x :=
λ x h, by cases h
axiom any {P : Prop} : P
lemma forall_lt_succ (p : nat → Prop) (k : nat) :
p k → (∀ x < k, p x) → (∀ x < k.succ, p x) :=
begin
intros h1 h2 m h3,
apply or.elim (nat.lt_succ_iff_lt_or_eq.elim_left h3); intro h4,
apply h2 m h4,
apply @eq.rec _ _ p h1 _ h4.symm,
end
lemma forall_lt_succ_iff (p : nat → Prop) (k : nat) :
(∀ x < k.succ, p x) ↔ (p k ∧ (∀ x < k, p x)) :=
iff.intro
(λ h, ⟨ h k (nat.lt_succ_self k),
λ x h2, h x (lt.trans h2 (nat.lt_succ_self k))⟩)
(λ h, forall_lt_succ p k h.left h.right)
instance forall_lt.decidable (p : nat → Prop) [decidable_pred p] :
∀ k : nat, decidable (∀ x < k, p x)
| 0 := decidable.is_true (forall_lt_zero p)
| (k+1) := decidable_of_iff' _ (forall_lt_succ_iff p k)
open tactic
meta def get_default (αx : expr) : tactic expr :=
to_expr ``(@inhabited.default %%αx _)
|
d7bc2a4fc05965d4b1317ef0a448439820af1b93 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/metric_space/basic.lean | c2bc8c35a982563ad94039e2b3c7618a525d821e | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 134,985 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.int.interval
import tactic.positivity
import topology.algebra.order.compact
import topology.metric_space.emetric_space
import topology.bornology.constructions
import topology.uniform_space.complete_separated
/-!
# Metric spaces
This file defines metric spaces. Many definitions and theorems expected
on metric spaces are already introduced on uniform spaces and topological spaces.
For example: open and closed sets, compactness, completeness, continuity and uniform continuity
## Main definitions
* `has_dist α`: Endows a space `α` with a function `dist a b`.
* `pseudo_metric_space α`: A space endowed with a distance function, which can
be zero even if the two elements are non-equal.
* `metric.ball x ε`: The set of all points `y` with `dist y x < ε`.
* `metric.bounded s`: Whether a subset of a `pseudo_metric_space` is bounded.
* `metric_space α`: A `pseudo_metric_space` with the guarantee `dist x y = 0 → x = y`.
Additional useful definitions:
* `nndist a b`: `dist` as a function to the non-negative reals.
* `metric.closed_ball x ε`: The set of all points `y` with `dist y x ≤ ε`.
* `metric.sphere x ε`: The set of all points `y` with `dist y x = ε`.
* `proper_space α`: A `pseudo_metric_space` where all closed balls are compact.
* `metric.diam s` : The `supr` of the distances of members of `s`.
Defined in terms of `emetric.diam`, for better handling of the case when it should be infinite.
TODO (anyone): Add "Main results" section.
## Implementation notes
Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the
theory of `pseudo_metric_space`, where we don't require `dist x y = 0 → x = y` and we specialize
to `metric_space` at the end.
## Tags
metric, pseudo_metric, dist
-/
open set filter topological_space bornology
open_locale uniformity topological_space big_operators filter nnreal ennreal
universes u v w
variables {α : Type u} {β : Type v} {X : Type*}
/-- Construct a uniform structure core from a distance function and metric space axioms.
This is a technical construction that can be immediately used to construct a uniform structure
from a distance function and metric space axioms but is also useful when discussing
metrizable topologies, see `pseudo_metric_space.of_metrizable`. -/
def uniform_space.core_of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space.core α :=
{ uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_of_mem (ε / 2) $ mem_infi_of_mem (div_pos h zero_lt_two) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core (uniform_space.core_of_dist dist dist_self dist_comm dist_triangle)
/-- This is an internal lemma used to construct a bornology from a metric in `bornology.of_dist`. -/
private lemma bounded_iff_aux {α : Type*} (dist : α → α → ℝ)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(s : set α) (a : α) :
(∃ c, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ c) ↔ (∃ r, ∀ ⦃x⦄, x ∈ s → dist x a ≤ r) :=
begin
split; rintro ⟨C, hC⟩,
{ rcases s.eq_empty_or_nonempty with rfl | ⟨x, hx⟩,
{ exact ⟨0, by simp⟩ },
{ exact ⟨C + dist x a, λ y hy,
(dist_triangle y x a).trans (add_le_add_right (hC hy hx) _)⟩ } },
{ exact ⟨C + C, λ x hx y hy,
(dist_triangle x a y).trans (add_le_add (hC hx) (by {rw dist_comm, exact hC hy}))⟩ }
end
/-- Construct a bornology from a distance function and metric space axioms. -/
def bornology.of_dist {α : Type*} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) :
bornology α :=
bornology.of_bounded
{ s : set α | ∃ C, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C }
⟨0, λ x hx y, hx.elim⟩
(λ s ⟨c, hc⟩ t h, ⟨c, λ x hx y hy, hc (h hx) (h hy)⟩)
(λ s hs t ht,
begin
rcases s.eq_empty_or_nonempty with rfl | ⟨z, hz⟩,
{ exact (empty_union t).symm ▸ ht },
{ simp only [λ u, bounded_iff_aux dist dist_comm dist_triangle u z] at hs ht ⊢,
rcases ⟨hs, ht⟩ with ⟨⟨r₁, hr₁⟩, ⟨r₂, hr₂⟩⟩,
exact ⟨max r₁ r₂, λ x hx, or.elim hx
(λ hx', (hr₁ hx').trans (le_max_left _ _))
(λ hx', (hr₂ hx').trans (le_max_right _ _))⟩ }
end)
(λ z, ⟨0, λ x hx y hy,
by { rw [eq_of_mem_singleton hx, eq_of_mem_singleton hy], exact (dist_self z).le }⟩)
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
@[ext] class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
-- the uniform structure and the emetric space structure are embedded in the metric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- This is an internal lemma used inside the default of `pseudo_metric_space.edist`. -/
private theorem pseudo_metric_space.dist_nonneg' {α} {x y : α} (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z): 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_right this zero_lt_two
/-- This tactic is used to populate `pseudo_metric_space.edist_dist` when the default `edist` is
used. -/
protected meta def pseudo_metric_space.edist_dist_tac : tactic unit :=
tactic.intros >> `[exact (ennreal.of_real_eq_coe_nnreal _).symm <|> control_laws_tac]
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
-/
class pseudo_metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ℝ≥0∞ := λ x y,
@coe (ℝ≥0) _ _ ⟨dist x y, pseudo_metric_space.dist_nonneg' _ ‹_› ‹_› ‹_›⟩)
(edist_dist : ∀ x y : α,
edist x y = ennreal.of_real (dist x y) . pseudo_metric_space.edist_dist_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
(to_bornology : bornology α := bornology.of_dist dist dist_self dist_comm dist_triangle)
(cobounded_sets : (bornology.cobounded α).sets =
{ s | ∃ C, ∀ ⦃x⦄, x ∈ sᶜ → ∀ ⦃y⦄, y ∈ sᶜ → dist x y ≤ C } . control_laws_tac)
/-- Two pseudo metric space structures with the same distance function coincide. -/
@[ext] lemma pseudo_metric_space.ext {α : Type*} {m m' : pseudo_metric_space α}
(h : m.to_has_dist = m'.to_has_dist) : m = m' :=
begin
unfreezingI { rcases m, rcases m' },
dsimp at h,
unfreezingI { subst h },
congr,
{ ext x y : 2,
dsimp at m_edist_dist m'_edist_dist,
simp [m_edist_dist, m'_edist_dist] },
{ dsimp at m_uniformity_dist m'_uniformity_dist,
rw ← m'_uniformity_dist at m_uniformity_dist,
exact uniform_space_eq m_uniformity_dist },
{ ext1,
dsimp at m_cobounded_sets m'_cobounded_sets,
rw ← m'_cobounded_sets at m_cobounded_sets,
exact filter_eq m_cobounded_sets }
end
variables [pseudo_metric_space α]
attribute [priority 100, instance] pseudo_metric_space.to_uniform_space
attribute [priority 100, instance] pseudo_metric_space.to_bornology
@[priority 200] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_edist : has_edist α := ⟨pseudo_metric_space.edist⟩
/-- Construct a pseudo-metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def pseudo_metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s) :
pseudo_metric_space α :=
{ dist := dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
to_uniform_space := { is_open_uniformity := begin
dsimp only [uniform_space.core_of_dist],
intros s,
change is_open s ↔ _,
rw H s,
refine forall₂_congr (λ x x_in, _),
erw (has_basis_binfi_principal _ nonempty_Ioi).mem_iff,
{ refine exists₂_congr (λ ε ε_pos, _),
simp only [prod.forall, set_of_subset_set_of],
split,
{ rintros h _ y H rfl,
exact h y H },
{ intros h y hxy,
exact h _ _ hxy rfl } },
{ exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ },
{ apply_instance }
end,
..uniform_space.core_of_dist dist dist_self dist_comm dist_triangle },
uniformity_dist := rfl,
to_bornology := bornology.of_dist dist dist_self dist_comm dist_triangle,
cobounded_sets := rfl }
@[simp] theorem dist_self (x : α) : dist x x = 0 := pseudo_metric_space.dist_self x
theorem dist_comm (x y : α) : dist x y = dist y x := pseudo_metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
pseudo_metric_space.edist_dist x y
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
pseudo_metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by { rw [add_left_comm, dist_comm x₁, ← add_assoc], apply dist_triangle4 }
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by { rw [add_right_comm, dist_comm y₁], apply dist_triangle4 }
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) :=
begin
revert n,
apply nat.le_induction,
{ simp only [finset.sum_empty, finset.Ico_self, dist_self] },
{ assume n hn hrec,
calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl
... = ∑ i in finset.Ico m (n+1), _ :
by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) :=
nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_dist f (nat.zero_le n)
/-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (dist_le_Ico_sum_dist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2
/-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced
with an upper estimate. -/
lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) :
dist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
nat.Ico_zero_eq_range ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd)
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : |dist x z - dist y z| ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
pseudo_metric_space.dist_nonneg' dist dist_self dist_comm dist_triangle
section
open tactic tactic.positivity
/-- Extension for the `positivity` tactic: distances are nonnegative. -/
@[positivity]
meta def _root_.tactic.positivity_dist : expr → tactic strictness
| `(dist %%a %%b) := nonnegative <$> mk_app ``dist_nonneg [a, b]
| _ := failed
end
@[simp] theorem abs_dist {a b : α} : |dist a b| = dist a b :=
abs_of_nonneg dist_nonneg
/-- A version of `has_dist` that takes value in `ℝ≥0`. -/
class has_nndist (α : Type*) := (nndist : α → α → ℝ≥0)
export has_nndist (nndist)
/-- Distance as a nonnegative real number. -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_has_nndist : has_nndist α := ⟨λ a b, ⟨dist a b, dist_nonneg⟩⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, real.to_nnreal, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by { simpa only [edist_dist, ennreal.of_real_eq_coe_nnreal dist_nonneg] }
@[simp, norm_cast] lemma coe_nnreal_ennreal_nndist (x y : α) : ↑(nndist x y) = edist x y :=
(edist_nndist x y).symm
@[simp, norm_cast] lemma edist_lt_coe {x y : α} {c : ℝ≥0} :
edist x y < c ↔ nndist x y < c :=
by rw [edist_nndist, ennreal.coe_lt_coe]
@[simp, norm_cast] lemma edist_le_coe {x y : α} {c : ℝ≥0} :
edist x y ≤ c ↔ nndist x y ≤ c :=
by rw [edist_nndist, ennreal.coe_le_coe]
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_lt_top {α : Type*} [pseudo_metric_space α] (x y : α) : edist x y < ⊤ :=
(edist_dist x y).symm ▸ ennreal.of_real_lt_top
/--In a pseudometric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := (edist_lt_top x y).ne
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
@[simp, norm_cast] lemma coe_nndist (x y : α) : ↑(nndist x y) = dist x y :=
(dist_nndist x y).symm
@[simp, norm_cast] lemma dist_lt_coe {x y : α} {c : ℝ≥0} :
dist x y < c ↔ nndist x y < c :=
iff.rfl
@[simp, norm_cast] lemma dist_le_coe {x y : α} {c : ℝ≥0} :
dist x y ≤ c ↔ nndist x y ≤ c :=
iff.rfl
@[simp] lemma edist_lt_of_real {x y : α} {r : ℝ} : edist x y < ennreal.of_real r ↔ dist x y < r :=
by rw [edist_dist, ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg]
@[simp] lemma edist_le_of_real {x y : α} {r : ℝ} (hr : 0 ≤ r) :
edist x y ≤ ennreal.of_real r ↔ dist x y ≤ r :=
by rw [edist_dist, ennreal.of_real_le_of_real_iff hr]
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = real.to_nnreal (dist x y) :=
by rw [dist_nndist, real.to_nnreal_coe]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
dist_triangle _ _ _
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
dist_triangle_left _ _ _
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
dist_triangle_right _ _ _
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate pseudometric space as a topology -/
variables {x y z : α} {δ ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw [dist_comm, mem_ball]
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
dist_nonneg.trans_lt hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
@[simp] lemma nonempty_ball : (ball x ε).nonempty ↔ 0 < ε :=
⟨λ ⟨x, hx⟩, pos_of_mem_ball hx, λ h, ⟨x, mem_ball_self h⟩⟩
@[simp] lemma ball_eq_empty : ball x ε = ∅ ↔ ε ≤ 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_ball, not_lt]
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [ball_eq_empty]
/-- If a point belongs to an open ball, then there is a strictly smaller radius whose ball also
contains it.
See also `exists_lt_subset_ball`. -/
lemma exists_lt_mem_ball_of_mem_ball (h : x ∈ ball y ε) : ∃ ε' < ε, x ∈ ball y ε' :=
begin
simp only [mem_ball] at h ⊢,
exact ⟨(ε + dist x y) / 2, by linarith, by linarith⟩,
end
lemma ball_eq_ball (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl
lemma ball_eq_ball' (ε : ℝ) (x : α) :
uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε :=
by { ext, simp [dist_comm, uniform_space.ball] }
@[simp] lemma Union_ball_nat (x : α) : (⋃ n : ℕ, ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_gt (dist y x)
@[simp] lemma Union_ball_nat_succ (x : α) : (⋃ n : ℕ, ball x (n + 1)) = univ :=
Union_eq_univ_iff.2 $ λ y, (exists_nat_gt (dist y x)).imp $ λ n hn,
hn.trans (lt_add_one _)
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ dist x y ≤ ε := by rw [dist_comm, mem_closed_ball]
/-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/
def sphere (x : α) (ε : ℝ) := {y | dist y x = ε}
@[simp] theorem mem_sphere : y ∈ sphere x ε ↔ dist y x = ε := iff.rfl
theorem mem_sphere' : y ∈ sphere x ε ↔ dist x y = ε := by rw [dist_comm, mem_sphere]
theorem ne_of_mem_sphere (h : y ∈ sphere x ε) (hε : ε ≠ 0) : y ≠ x :=
by { contrapose! hε, symmetry, simpa [hε] using h }
theorem sphere_eq_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) :
sphere x ε = ∅ :=
set.eq_empty_iff_forall_not_mem.mpr $ λ y hy, ne_of_mem_sphere hy hε (subsingleton.elim _ _)
theorem sphere_is_empty_of_subsingleton [subsingleton α] (hε : ε ≠ 0) :
is_empty (sphere x ε) :=
by simp only [sphere_eq_empty_of_subsingleton hε, set.has_emptyc.emptyc.is_empty α]
theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
@[simp] lemma nonempty_closed_ball : (closed_ball x ε).nonempty ↔ 0 ≤ ε :=
⟨λ ⟨x, hx⟩, dist_nonneg.trans hx, λ h, ⟨x, mem_closed_ball_self h⟩⟩
@[simp] lemma closed_ball_eq_empty : closed_ball x ε = ∅ ↔ ε < 0 :=
by rw [← not_nonempty_iff_eq_empty, nonempty_closed_ball, not_le]
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y (hy : _ < _), le_of_lt hy
theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε :=
λ y, le_of_eq
lemma closed_ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (closed_ball x δ) (ball y ε) :=
λ a ha, (h.trans $ dist_triangle_left _ _ _).not_lt $ add_lt_add_of_le_of_lt ha.1 ha.2
lemma ball_disjoint_closed_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (closed_ball y ε) :=
(closed_ball_disjoint_ball $ by rwa [add_comm, dist_comm]).symm
lemma ball_disjoint_ball (h : δ + ε ≤ dist x y) : disjoint (ball x δ) (ball y ε) :=
(closed_ball_disjoint_ball h).mono_left ball_subset_closed_ball
lemma closed_ball_disjoint_closed_ball (h : δ + ε < dist x y) :
disjoint (closed_ball x δ) (closed_ball y ε) :=
λ a ha, h.not_le $ (dist_triangle_left _ _ _).trans $ add_le_add ha.1 ha.2
theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) :=
λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂
@[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε :=
set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm
@[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε :=
by rw [union_comm, ball_union_sphere]
@[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm]
@[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε :=
by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm]
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by rw [mem_ball', mem_ball]
theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε :=
by rw [mem_closed_ball', mem_closed_ball]
theorem mem_sphere_comm : x ∈ sphere y ε ↔ y ∈ sphere x ε :=
by rw [mem_sphere', mem_sphere]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
lemma ball_subset_ball' (h : ε₁ + dist x y ≤ ε₂) : ball x ε₁ ⊆ ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... < ε₁ + dist x y : add_lt_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
lemma closed_ball_subset_closed_ball' (h : ε₁ + dist x y ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball y ε₂ :=
λ z hz, calc
dist z y ≤ dist z x + dist x y : dist_triangle _ _ _
... ≤ ε₁ + dist x y : add_le_add_right hz _
... ≤ ε₂ : h
theorem closed_ball_subset_ball (h : ε₁ < ε₂) :
closed_ball x ε₁ ⊆ ball x ε₂ :=
λ y (yh : dist y x ≤ ε₁), lt_of_le_of_lt yh h
lemma dist_le_add_of_nonempty_closed_ball_inter_closed_ball
(h : (closed_ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y ≤ ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... ≤ ε₁ + ε₂ : add_le_add hz.1 hz.2
lemma dist_lt_add_of_nonempty_closed_ball_inter_ball (h : (closed_ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
let ⟨z, hz⟩ := h in calc
dist x y ≤ dist z x + dist z y : dist_triangle_left _ _ _
... < ε₁ + ε₂ : add_lt_add_of_le_of_lt hz.1 hz.2
lemma dist_lt_add_of_nonempty_ball_inter_closed_ball (h : (ball x ε₁ ∩ closed_ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
begin
rw inter_comm at h,
rw [add_comm, dist_comm],
exact dist_lt_add_of_nonempty_closed_ball_inter_ball h
end
lemma dist_lt_add_of_nonempty_ball_inter_ball (h : (ball x ε₁ ∩ ball y ε₂).nonempty) :
dist x y < ε₁ + ε₂ :=
dist_lt_add_of_nonempty_closed_ball_inter_ball $
h.mono (inter_subset_inter ball_subset_closed_ball subset.rfl)
@[simp] lemma Union_closed_ball_nat (x : α) : (⋃ n : ℕ, closed_ball x n) = univ :=
Union_eq_univ_iff.2 $ λ y, exists_nat_ge (dist y x)
lemma Union_inter_closed_ball_nat (s : set α) (x : α) :
(⋃ (n : ℕ), s ∩ closed_ball x n) = s :=
by rw [← inter_Union, Union_closed_ball_nat, inter_univ]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
/-- If a property holds for all points in closed balls of arbitrarily large radii, then it holds for
all points. -/
lemma forall_of_forall_mem_closed_ball (p : α → Prop) (x : α)
(H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ closed_ball x R, p y) (y : α) :
p y :=
begin
obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x ≤ R), ∀ (z : α), z ∈ closed_ball x R → p z :=
frequently_iff.1 H (Ici_mem_at_top (dist y x)),
exact h _ hR
end
/-- If a property holds for all points in balls of arbitrarily large radii, then it holds for all
points. -/
lemma forall_of_forall_mem_ball (p : α → Prop) (x : α)
(H : ∃ᶠ (R : ℝ) in at_top, ∀ y ∈ ball x R, p y) (y : α) :
p y :=
begin
obtain ⟨R, hR, h⟩ : ∃ (R : ℝ) (H : dist y x < R), ∀ (z : α), z ∈ ball x R → p z :=
frequently_iff.1 H (Ioi_mem_at_top (dist y x)),
exact h _ hR
end
theorem is_bounded_iff {s : set α} :
is_bounded s ↔ ∃ C : ℝ, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
by rw [is_bounded_def, ← filter.mem_sets, (@pseudo_metric_space.cobounded_sets α _).out,
mem_set_of_eq, compl_compl]
theorem is_bounded_iff_eventually {s : set α} :
is_bounded s ↔ ∀ᶠ C in at_top, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
is_bounded_iff.trans ⟨λ ⟨C, h⟩, eventually_at_top.2 ⟨C, λ C' hC' x hx y hy, (h hx hy).trans hC'⟩,
eventually.exists⟩
theorem is_bounded_iff_exists_ge {s : set α} (c : ℝ) :
is_bounded s ↔ ∃ C, c ≤ C ∧ ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → dist x y ≤ C :=
⟨λ h, ((eventually_ge_at_top c).and (is_bounded_iff_eventually.1 h)).exists,
λ h, is_bounded_iff.2 $ h.imp $ λ _, and.right⟩
theorem is_bounded_iff_nndist {s : set α} :
is_bounded s ↔ ∃ C : ℝ≥0, ∀ ⦃x⦄, x ∈ s → ∀ ⦃y⦄, y ∈ s → nndist x y ≤ C :=
by simp only [is_bounded_iff_exists_ge 0, nnreal.exists, ← nnreal.coe_le_coe, ← dist_nndist,
nnreal.coe_mk, exists_prop]
theorem uniformity_basis_dist :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) :=
begin
rw ← pseudo_metric_space.uniformity_dist.symm,
refine has_basis_binfi_principal _ nonempty_Ioi,
exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp,
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p),
λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩
end
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`,
and `uniformity_basis_dist_inv_nat_pos`. -/
protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) :
(𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀,
exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
theorem uniformity_basis_dist_inv_nat_succ :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) :=
metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n)
(λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩)
theorem uniformity_basis_dist_inv_nat_pos :
(𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) :=
metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn)
(λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n,
by exact_mod_cast hn.le⟩)
theorem uniformity_basis_dist_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < r ^ n }) :=
metric.mk_uniformity_basis (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem uniformity_basis_dist_lt {R : ℝ} (hR : 0 < R) :
(𝓤 α).has_basis (λ r : ℝ, 0 < r ∧ r < R) (λ r, {p : α × α | dist p.1 p.2 < r}) :=
metric.mk_uniformity_basis (λ r, and.left) $ λ r hr,
⟨min r (R / 2), ⟨lt_min hr (half_pos hR), min_lt_iff.2 $ or.inr (half_lt_self hR)⟩,
min_le_left _ _⟩
/-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}`
form a basis of `𝓤 α`.
Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor.
More can be easily added if needed in the future. -/
protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ }
end
/-- Contant size closed neighborhoods of the diagonal form a basis
of the uniformity filter. -/
theorem uniformity_basis_dist_le :
(𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) :=
metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_dist_le_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓤 α).has_basis (λ n:ℕ, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 ≤ r ^ n }) :=
metric.mk_uniformity_basis_le (λ n hn, pow_pos h0 _)
(λ ε ε0, let ⟨n, hn⟩ := exists_pow_lt_of_lt_one ε0 h1 in ⟨n, trivial, hn.le⟩)
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
uniformity_basis_dist.mem_uniformity_iff
/-- A constant size neighborhood of the diagonal is an entourage. -/
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [pseudo_metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist
lemma uniform_continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε :=
metric.uniformity_basis_dist.uniform_continuous_on_iff metric.uniformity_basis_dist
lemma uniform_continuous_on_iff_le [pseudo_metric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y ≤ δ → dist (f x) (f y) ≤ ε :=
metric.uniformity_basis_dist_le.uniform_continuous_on_iff metric.uniformity_basis_dist_le
theorem uniform_embedding_iff [pseudo_metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- If a map between pseudometric spaces is a uniform embedding then the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_uniform_embedding [pseudo_metric_space β] {f : α → β} :
uniform_embedding f →
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩
end
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩
/-- A pseudometric space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) (_ : fintype β) (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
cases s.eq_empty_or_nonempty with hs hs,
{ rw hs, exact totally_bounded_empty },
rcases hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) :
∀ ε > 0, ∃ t ⊆ s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
begin
intros ε ε_pos,
rw totally_bounded_iff_subset at hs,
exact hs _ (dist_mem_uniformity ε_pos),
end
/-- Expressing uniform convergence using `dist` -/
lemma tendsto_uniformly_on_filter_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {p' : filter β} :
tendsto_uniformly_on_filter F f p p' ↔
∀ ε > 0, ∀ᶠ (n : ι × β) in (p ×ᶠ p'), dist (f n.snd) (F n.fst n.snd) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
refine (H ε εpos).mono (λ n hn, hε hn),
end
/-- Expressing locally uniform convergence on a set using `dist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `dist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `dist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
nhds_within_univ, mem_univ, forall_const, exists_prop]
/-- Expressing uniform convergence using `dist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
uniformity_basis_dist.cauchy_iff
theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_dist
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s :=
nhds_basis_ball.mem_iff
theorem eventually_nhds_iff {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ε>0, ∀ ⦃y⦄, dist y x < ε → p y :=
mem_nhds_iff
lemma eventually_nhds_iff_ball {p : α → Prop} :
(∀ᶠ y in 𝓝 x, p y) ↔ ∃ ε>0, ∀ y ∈ ball x ε, p y :=
mem_nhds_iff
theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_dist_le
theorem nhds_basis_ball_inv_nat_succ :
(𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ
theorem nhds_basis_ball_inv_nat_pos :
(𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) :=
nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos
theorem nhds_basis_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_pow h0 h1)
theorem nhds_basis_closed_ball_pow {r : ℝ} (h0 : 0 < r) (h1 : r < 1) :
(𝓝 x).has_basis (λ n, true) (λ n:ℕ, closed_ball x (r ^ n)) :=
nhds_basis_uniformity (uniformity_basis_dist_le_pow h0 h1)
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp only [is_open_iff_mem_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
is_open_ball.mem_nhds (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem closed_ball_mem_nhds_of_mem {x c : α} {ε : ℝ} (h : x ∈ ball c ε) :
closed_ball c ε ∈ 𝓝 x :=
mem_of_superset (is_open_ball.mem_nhds h) ball_subset_closed_ball
theorem nhds_within_basis_ball {s : set α} :
(𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_ball s
theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_ball.mem_iff
theorem tendsto_nhds_within_nhds_within [pseudo_metric_space β] {t : set β} {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε :=
(nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $
forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ,
forall_congr $ λ x, by simp; itauto
theorem tendsto_nhds_within_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within],
simp only [mem_univ, true_and] }
theorem tendsto_nhds_nhds [pseudo_metric_space β] {f : α → β} {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
nhds_basis_ball.tendsto_iff nhds_basis_ball
theorem continuous_at_iff [pseudo_metric_space β] {f : α → β} {a : α} :
continuous_at f a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_at, tendsto_nhds_nhds]
theorem continuous_within_at_iff [pseudo_metric_space β] {f : α → β} {a : α} {s : set α} :
continuous_within_at f s a ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε :=
by rw [continuous_within_at, tendsto_nhds_within_nhds]
theorem continuous_on_iff [pseudo_metric_space β] {f : α → β} {s : set α} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff]
theorem continuous_iff [pseudo_metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε :=
nhds_basis_ball.tendsto_right_iff
theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} :
continuous_at f b ↔
∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε :=
by rw [continuous_at, tendsto_nhds]
theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} :
continuous_within_at f s b ↔
∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by rw [continuous_within_at, tendsto_nhds]
theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} :
continuous_on f s ↔
∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε :=
by simp [continuous_on, continuous_within_at_iff']
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
/--
A variant of `tendsto_at_top` that
uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...`
-/
theorem tendsto_at_top' [nonempty β] [semilattice_sup β] [no_max_order β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n>N, dist (u n) a < ε :=
(at_top_basis_Ioi.tendsto_iff nhds_basis_ball).trans $
by { simp only [exists_prop, true_and], refl }
lemma is_open_singleton_iff {α : Type*} [pseudo_metric_space α] {x : α} :
is_open ({x} : set α) ↔ ∃ ε > 0, ∀ y, dist y x < ε → y = x :=
by simp [is_open_iff, subset_singleton_iff, mem_ball]
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is an open ball
centered at `x` and intersecting `s` only at `x`. -/
lemma exists_ball_inter_eq_singleton_of_mem_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.ball x ε ∩ s = {x} :=
nhds_basis_ball.exists_inter_eq_singleton_of_mem_discrete hx
/-- Given a point `x` in a discrete subset `s` of a pseudometric space, there is a closed ball
of positive radius centered at `x` and intersecting `s` only at `x`. -/
lemma exists_closed_ball_inter_eq_singleton_of_discrete [discrete_topology s] {x : α} (hx : x ∈ s) :
∃ ε > 0, metric.closed_ball x ε ∩ s = {x} :=
nhds_basis_closed_ball.exists_inter_eq_singleton_of_mem_discrete hx
lemma _root_.dense.exists_dist_lt {s : set α} (hs : dense s) (x : α) {ε : ℝ} (hε : 0 < ε) :
∃ y ∈ s, dist x y < ε :=
begin
have : (ball x ε).nonempty, by simp [hε],
simpa only [mem_ball'] using hs.exists_mem_open is_open_ball this
end
lemma _root_.dense_range.exists_dist_lt {β : Type*} {f : β → α} (hf : dense_range f)
(x : α) {ε : ℝ} (hε : 0 < ε) :
∃ y, dist x (f y) < ε :=
exists_range_iff.1 (hf.exists_dist_lt x hε)
end metric
open metric
/-Instantiate a pseudometric space as a pseudoemetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma pseudo_metric.uniformity_basis_edist :
(𝓤 α).has_basis (λ ε:ℝ≥0∞, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) :=
⟨begin
intro t,
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0],
rintros ⟨a, b⟩,
simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end⟩
theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) :=
pseudo_metric.uniformity_basis_edist.eq_binfi
/-- A pseudometric space induces a pseudoemetric space -/
@[priority 100] -- see Note [lower instance priority]
instance pseudo_metric_space.to_pseudo_emetric_space : pseudo_emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := metric.uniformity_edist,
..‹pseudo_metric_space α› }
/-- In a pseudometric space, an open ball of infinite radius is the whole space -/
lemma metric.eball_top_eq_univ (x : α) :
emetric.ball x ∞ = set.univ :=
set.eq_univ_iff_forall.mpr (λ y, edist_lt_top y x)
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
ext y,
simp only [emetric.mem_ball, mem_ball, edist_dist],
exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg
end
/-- Balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_ball_nnreal {x : α} {ε : ℝ≥0} : emetric.ball x ε = ball x ε :=
by { convert metric.emetric_ball, simp }
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
/-- Closed balls defined using the distance or the edistance coincide -/
@[simp] lemma metric.emetric_closed_ball_nnreal {x : α} {ε : ℝ≥0} :
emetric.closed_ball x ε = closed_ball x ε :=
by { convert metric.emetric_closed_ball ε.2, simp }
@[simp] lemma metric.emetric_ball_top (x : α) : emetric.ball x ⊤ = univ :=
eq_univ_of_forall $ λ y, edist_lt_top _ _
lemma metric.inseparable_iff {x y : α} : inseparable x y ↔ dist x y = 0 :=
by rw [emetric.inseparable_iff, edist_nndist, dist_nndist, ennreal.coe_eq_zero,
nnreal.coe_eq_zero]
/-- Build a new pseudometric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
pseudo_metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans pseudo_metric_space.uniformity_dist }
lemma pseudo_metric_space.replace_uniformity_eq {α} [U : uniform_space α]
(m : pseudo_metric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
m.replace_uniformity H = m :=
by { ext, refl }
/-- Build a new pseudo metric space from an old one where the bundled topological structure is
provably (but typically non-definitionaly) equal to some given topological structure.
See Note [forgetful inheritance].
-/
@[reducible] def pseudo_metric_space.replace_topology {γ} [U : topological_space γ]
(m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) :
pseudo_metric_space γ :=
@pseudo_metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl
lemma pseudo_metric_space.replace_topology_eq {γ} [U : topological_space γ]
(m : pseudo_metric_space γ) (H : U = m.to_uniform_space.to_topological_space) :
m.replace_topology H = m :=
by { ext, refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the pseudoemetric space. In this definition, the
distance is given separately, to be able to prescribe some expression which is not defeq to the
push-forward of the edistance to reals. -/
def pseudo_emetric_space.to_pseudo_metric_space_of_dist {α : Type u} [e : pseudo_emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
pseudo_metric_space α :=
let m : pseudo_metric_space α :=
{ dist := dist,
dist_self := λx, by simp [h],
dist_comm := λx y, by simp [h, pseudo_emetric_space.edist_comm],
dist_triangle := λx y z, begin
simp only [h],
rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _),
ennreal.to_real_le_to_real (edist_ne_top _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, edist_ne_top] }
end,
edist := edist,
edist_dist := λ x y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in
m.replace_uniformity $ by { rw [uniformity_pseudoedist, metric.uniformity_edist], refl }
/-- One gets a pseudometric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the pseudometric space and the emetric space. -/
def pseudo_emetric_space.to_pseudo_metric_space {α : Type u} [e : pseudo_emetric_space α]
(h : ∀x y: α, edist x y ≠ ⊤) : pseudo_metric_space α :=
pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Build a new pseudometric space from an old one where the bundled bornology structure is provably
(but typically non-definitionaly) equal to some given bornology structure.
See Note [forgetful inheritance].
-/
def pseudo_metric_space.replace_bornology {α} [B : bornology α] (m : pseudo_metric_space α)
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
pseudo_metric_space α :=
{ to_bornology := B,
cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s, (H s).trans $
by rw [is_bounded_iff, mem_set_of_eq, compl_compl],
.. m }
lemma pseudo_metric_space.replace_bornology_eq {α} [m : pseudo_metric_space α] [B : bornology α]
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
pseudo_metric_space.replace_bornology _ H = m :=
by { ext, refl }
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) →
∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
uniform_space.complete_of_convergent_controlled_sequences
(λ n, {p:α×α | dist p.1 p.2 < B n}) (λ n, dist_mem_uniformity $ hB n) H
theorem metric.complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
emetric.complete_of_cauchy_seq_tendsto
section real
/-- Instantiate the reals as a pseudometric space. -/
noncomputable instance real.pseudo_metric_space : pseudo_metric_space ℝ :=
{ dist := λx y, |x - y|,
dist_self := by simp [abs_zero],
dist_comm := assume x y, abs_sub_comm _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = |x - y| := rfl
theorem real.nndist_eq (x y : ℝ) : nndist x y = real.nnabs (x - y) := rfl
theorem real.nndist_eq' (x y : ℝ) : nndist x y = real.nnabs (y - x) := nndist_comm _ _
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = |x| :=
by simp [real.dist_eq]
theorem real.dist_left_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist x y ≤ dist x z :=
by simpa only [dist_comm x] using abs_sub_left_of_mem_interval h
theorem real.dist_right_le_of_mem_interval {x y z : ℝ} (h : y ∈ interval x z) :
dist y z ≤ dist x z :=
by simpa only [dist_comm _ z] using abs_sub_right_of_mem_interval h
theorem real.dist_le_of_mem_interval {x y x' y' : ℝ} (hx : x ∈ interval x' y')
(hy : y ∈ interval x' y') : dist x y ≤ dist x' y' :=
abs_sub_le_of_subinterval $ interval_subset_interval (by rwa interval_swap) (by rwa interval_swap)
theorem real.dist_le_of_mem_Icc {x y x' y' : ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ y' - x' :=
by simpa only [real.dist_eq, abs_of_nonpos (sub_nonpos.2 $ hx.1.trans hx.2), neg_sub]
using real.dist_le_of_mem_interval (Icc_subset_interval hx) (Icc_subset_interval hy)
theorem real.dist_le_of_mem_Icc_01 {x y : ℝ} (hx : x ∈ Icc (0:ℝ) 1) (hy : y ∈ Icc (0:ℝ) 1) :
dist x y ≤ 1 :=
by simpa only [sub_zero] using real.dist_le_of_mem_Icc hx hy
instance : order_topology ℝ :=
order_topology_of_nhds_abs $ λ x,
by simp only [nhds_basis_ball.eq_binfi, ball, real.dist_eq, abs_sub_comm]
lemma real.ball_eq_Ioo (x r : ℝ) : ball x r = Ioo (x - r) (x + r) :=
set.ext $ λ y, by rw [mem_ball, dist_comm, real.dist_eq,
abs_sub_lt_iff, mem_Ioo, ← sub_lt_iff_lt_add', sub_lt]
lemma real.closed_ball_eq_Icc {x r : ℝ} : closed_ball x r = Icc (x - r) (x + r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
theorem real.Icc_eq_closed_ball (x y : ℝ) : Icc x y = closed_ball ((x + y) / 2) ((y - x) / 2) :=
by rw [real.closed_ball_eq_Icc, ← sub_div, add_comm, ← sub_add,
add_sub_cancel', add_self_div_two, ← add_div,
add_assoc, add_sub_cancel'_right, add_self_div_two]
section metric_ordered
variables [preorder α] [compact_Icc_space α]
lemma totally_bounded_Icc (a b : α) : totally_bounded (Icc a b) :=
is_compact_Icc.totally_bounded
lemma totally_bounded_Ico (a b : α) : totally_bounded (Ico a b) :=
totally_bounded_subset Ico_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioc (a b : α) : totally_bounded (Ioc a b) :=
totally_bounded_subset Ioc_subset_Icc_self (totally_bounded_Icc a b)
lemma totally_bounded_Ioo (a b : α) : totally_bounded (Ioo a b) :=
totally_bounded_subset Ioo_subset_Icc_self (totally_bounded_Icc a b)
end metric_ordered
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the
general case. -/
lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t)
(hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft
/-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le`
and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) :=
squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) :=
by { ext s,
simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] }
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) :=
by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff,
prod.map_def]
lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} :
tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) :=
by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff]
lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₂ p (𝓝 a) :=
h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist
lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α}
(h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) :
tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) :=
uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h
/-- If `u` is a neighborhood of `x`, then for small enough `r`, the closed ball
`closed_ball x r` is contained in `u`. -/
lemma eventually_closed_ball_subset {x : α} {u : set α} (hu : u ∈ 𝓝 x) :
∀ᶠ r in 𝓝 (0 : ℝ), closed_ball x r ⊆ u :=
begin
obtain ⟨ε, εpos, hε⟩ : ∃ ε (hε : 0 < ε), closed_ball x ε ⊆ u :=
nhds_basis_closed_ball.mem_iff.1 hu,
have : Iic ε ∈ 𝓝 (0 : ℝ) := Iic_mem_nhds εpos,
filter_upwards [this] with _ hr using subset.trans (closed_ball_subset_closed_ball hr) hε,
end
end real
section cauchy_seq
variables [nonempty β] [semilattice_sup β]
/-- In a pseudometric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
uniformity_basis_dist.cauchy_seq_iff
/-- A variation around the pseudometric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
uniformity_basis_dist.cauchy_seq_iff'
/-- In a pseudometric space, unifom Cauchy sequences are characterized by the fact that, eventually,
the distance between all its elements is uniformly, arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem metric.uniform_cauchy_seq_on_iff {γ : Type*}
{F : β → γ → α} {s : set γ} :
uniform_cauchy_seq_on F at_top s ↔
∀ ε : ℝ, ε > 0 → ∃ (N : β), ∀ m : β, m ≥ N → ∀ n : β, n ≥ N → ∀ x : γ, x ∈ s →
dist (F m x) (F n x) < ε :=
begin
split,
{ intros h ε hε,
let u := { a : α × α | dist a.fst a.snd < ε },
have hu : u ∈ 𝓤 α := metric.mem_uniformity_dist.mpr ⟨ε, hε, (λ a b, by simp)⟩,
rw ←@filter.eventually_at_top_prod_self' _ _ _
(λ m, ∀ x : γ, x ∈ s → dist (F m.fst x) (F m.snd x) < ε),
specialize h u hu,
rw prod_at_top_at_top_eq at h,
exact h.mono (λ n h x hx, set.mem_set_of_eq.mp (h x hx)), },
{ intros h u hu,
rcases (metric.mem_uniformity_dist.mp hu) with ⟨ε, hε, hab⟩,
rcases h ε hε with ⟨N, hN⟩,
rw [prod_at_top_at_top_eq, eventually_at_top],
use (N, N),
intros b hb x hx,
rcases hb with ⟨hbl, hbr⟩,
exact hab (hN b.fst hbl.ge b.snd hbr.ge x hx), },
end
/-- If the distance between `s n` and `s m`, `n ≤ m` is bounded above by `b n`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0' {s : β → α} (b : β → ℝ)
(h : ∀ n m : β, n ≤ m → dist (s n) (s m) ≤ b n) (h₀ : tendsto b at_top (𝓝 0)) :
cauchy_seq s :=
metric.cauchy_seq_iff'.2 $ λ ε ε0,
(h₀.eventually (gt_mem_nhds ε0)).exists.imp $ λ N hN n hn,
calc dist (s n) (s N) = dist (s N) (s n) : dist_comm _ _
... ≤ b N : h _ _ hn
... < ε : hN
/-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N`
and `b` converges to zero, then `s` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ)
(h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (𝓝 0)) :
cauchy_seq s :=
cauchy_seq_of_le_tendsto_0' b (λ n m hnm, h _ _ _ le_rfl hnm) h₀
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
rsuffices ⟨R, R0, H⟩ : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (𝓝 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) :=
λ m n N hm hn, le_cSup (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_rfl, le_rfl⟩, dist_self _⟩,
have S0 := λ n, le_cSup (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (cSup_le ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ (le_trans hn hm') _ (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩
end cauchy_seq
/-- Pseudometric space structure pulled back by a function. -/
def pseudo_metric_space.induced {α β} (f : α → β)
(m : pseudo_metric_space β) : pseudo_metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine compl_surjective.forall.2 (λ s, compl_mem_comap.trans $ mem_uniformity_dist.trans _),
simp only [mem_compl_iff, @imp_not_comm _ (_ ∈ _), ← prod.forall', prod.mk.eta, ball_image_iff]
end,
to_bornology := bornology.induced f,
cobounded_sets := set.ext $ compl_surjective.forall.2 $ λ s,
by simp only [compl_mem_comap, filter.mem_sets, ← is_bounded_def, mem_set_of_eq, compl_compl,
is_bounded_iff, ball_image_iff] }
/-- Pull back a pseudometric space structure by an inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `topological_space`
structure. -/
def inducing.comap_pseudo_metric_space {α β} [topological_space α] [pseudo_metric_space β]
{f : α → β} (hf : inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_topology hf.induced
/-- Pull back a pseudometric space structure by a uniform inducing map. This is a version of
`pseudo_metric_space.induced` useful in case if the domain already has a `uniform_space`
structure. -/
def uniform_inducing.comap_pseudo_metric_space {α β} [uniform_space α] [pseudo_metric_space β]
(f : α → β) (h : uniform_inducing f) : pseudo_metric_space α :=
(pseudo_metric_space.induced f ‹_›).replace_uniformity h.comap_uniformity.symm
instance subtype.pseudo_metric_space {p : α → Prop} : pseudo_metric_space (subtype p) :=
pseudo_metric_space.induced coe ‹_›
theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl
theorem subtype.nndist_eq {p : α → Prop} (x y : subtype p) : nndist x y = nndist (x : α) y := rfl
namespace mul_opposite
@[to_additive]
instance : pseudo_metric_space (αᵐᵒᵖ) := pseudo_metric_space.induced mul_opposite.unop ‹_›
@[simp, to_additive] theorem dist_unop (x y : αᵐᵒᵖ) : dist (unop x) (unop y) = dist x y := rfl
@[simp, to_additive] theorem dist_op (x y : α) : dist (op x) (op y) = dist x y := rfl
@[simp, to_additive] theorem nndist_unop (x y : αᵐᵒᵖ) : nndist (unop x) (unop y) = nndist x y := rfl
@[simp, to_additive] theorem nndist_op (x y : α) : nndist (op x) (op y) = nndist x y := rfl
end mul_opposite
section nnreal
noncomputable instance : pseudo_metric_space ℝ≥0 := subtype.pseudo_metric_space
lemma nnreal.dist_eq (a b : ℝ≥0) : dist a b = |(a:ℝ) - b| := rfl
lemma nnreal.nndist_eq (a b : ℝ≥0) :
nndist a b = max (a - b) (b - a) :=
begin
/- WLOG, `b ≤ a`. `wlog h : b ≤ a` works too but it is much slower because Lean tries to prove one
case from the other and fails; `tactic.skip` tells Lean not to try. -/
wlog h : b ≤ a := le_total b a using [a b, b a] tactic.skip,
{ rw [← nnreal.coe_eq, ← dist_nndist, nnreal.dist_eq, tsub_eq_zero_iff_le.2 h,
max_eq_left (zero_le $ a - b), ← nnreal.coe_sub h, abs_of_nonneg (a - b).coe_nonneg] },
{ rwa [nndist_comm, max_comm] }
end
@[simp] lemma nnreal.nndist_zero_eq_val (z : ℝ≥0) : nndist 0 z = z :=
by simp only [nnreal.nndist_eq, max_eq_right, tsub_zero, zero_tsub, zero_le']
@[simp] lemma nnreal.nndist_zero_eq_val' (z : ℝ≥0) : nndist z 0 = z :=
by { rw nndist_comm, exact nnreal.nndist_zero_eq_val z, }
lemma nnreal.le_add_nndist (a b : ℝ≥0) : a ≤ b + nndist a b :=
begin
suffices : (a : ℝ) ≤ (b : ℝ) + (dist a b),
{ exact nnreal.coe_le_coe.mp this, },
linarith [le_of_abs_le (by refl : abs (a-b : ℝ) ≤ (dist a b))],
end
end nnreal
section ulift
variables [pseudo_metric_space β]
instance : pseudo_metric_space (ulift β) :=
pseudo_metric_space.induced ulift.down ‹_›
lemma ulift.dist_eq (x y : ulift β) : dist x y = dist x.down y.down := rfl
lemma ulift.nndist_eq (x y : ulift β) : nndist x y = nndist x.down y.down := rfl
@[simp] lemma ulift.dist_up_up (x y : β) : dist (ulift.up x) (ulift.up y) = dist x y := rfl
@[simp] lemma ulift.nndist_up_up (x y : β) : nndist (ulift.up x) (ulift.up y) = nndist x y := rfl
end ulift
section prod
variables [pseudo_metric_space β]
noncomputable instance prod.pseudo_metric_space_max :
pseudo_metric_space (α × β) :=
(pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λ x y : α × β, max (dist x.1 y.1) (dist x.2 y.2))
(λ x y, (max_lt (edist_lt_top _ _) (edist_lt_top _ _)).ne)
(λ x y, by simp only [dist_edist, ← ennreal.to_real_max (edist_ne_top _ _) (edist_ne_top _ _),
prod.edist_eq])).replace_bornology $
λ s, by { simp only [← is_bounded_image_fst_and_snd, is_bounded_iff_eventually, ball_image_iff,
← eventually_and, ← forall_and_distrib, ← max_le_iff], refl }
lemma prod.dist_eq {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
@[simp]
lemma dist_prod_same_left {x : α} {y₁ y₂ : β} : dist (x, y₁) (x, y₂) = dist y₁ y₂ :=
by simp [prod.dist_eq, dist_nonneg]
@[simp]
lemma dist_prod_same_right {x₁ x₂ : α} {y : β} : dist (x₁, y) (x₂, y) = dist x₁ x₂ :=
by simp [prod.dist_eq, dist_nonneg]
theorem ball_prod_same (x : α) (y : β) (r : ℝ) :
ball x r ×ˢ ball y r = ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
theorem closed_ball_prod_same (x : α) (y : β) (r : ℝ) :
closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r :=
ext $ λ z, by simp [prod.dist_eq]
end prod
theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous.dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
uniform_continuous_dist.comp (hf.prod_mk hg)
@[continuity]
theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist.continuous
@[continuity]
theorem continuous.dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) :=
(continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a :=
by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero,
comap_comap, (∘), dist_comm]
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma continuous_iff_continuous_dist [topological_space β] {f : β → α} :
continuous f ↔ continuous (λ x : β × β, dist (f x.1) (f x.2)) :=
⟨λ h, (h.comp continuous_fst).dist (h.comp continuous_snd), λ h, continuous_iff_continuous_at.2 $
λ x, tendsto_iff_dist_tendsto_zero.2 $
(h.comp (continuous_id.prod_mk continuous_const)).tendsto' _ _ $ dist_self _⟩
lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_dist.subtype_mk _
lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f)
(hg : uniform_continuous g) :
uniform_continuous (λ b, nndist (f b) (g b)) :=
uniform_continuous_nndist.comp (hf.prod_mk hg)
lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist.continuous
lemma continuous.nndist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) :=
continuous_nndist.comp (hf.prod_mk hg : _)
theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) :
tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) :=
(continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg)
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_id.dist continuous_const) continuous_const
lemma is_closed_sphere : is_closed (sphere x ε) :=
is_closed_eq (continuous_id.dist continuous_const) continuous_const
@[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε :=
is_closed_ball.closure_eq
theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε :=
closure_minimal ball_subset_closed_ball is_closed_ball
theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε :=
frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε :=
frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const
theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) :=
interior_maximal ball_subset_closed_ball is_open_ball
/-- ε-characterization of the closure in pseudometric spaces-/
theorem mem_closure_iff {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
(mem_closure_iff_nhds_basis nhds_basis_ball).trans $
by simp only [mem_ball, dist_comm]
lemma mem_closure_range_iff {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε :=
by simp only [mem_closure_iff, exists_range_iff]
lemma mem_closure_range_iff_nat {e : β → α} {a : α} :
a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) :=
(mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $
by simp only [mem_ball, dist_comm, exists_range_iff, forall_const]
theorem mem_of_closed' {s : set α} (hs : is_closed s) {a : α} :
a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a
lemma closed_ball_zero' (x : α) : closed_ball x 0 = closure {x} :=
subset.antisymm
(λ y hy, mem_closure_iff.2 $ λ ε ε0, ⟨x, mem_singleton x, (mem_closed_ball.1 hy).trans_lt ε0⟩)
(closure_minimal (singleton_subset_iff.2 (dist_self x).le) is_closed_ball)
lemma dense_iff {s : set α} :
dense s ↔ ∀ x, ∀ r > 0, (ball x r ∩ s).nonempty :=
forall_congr $ λ x, by simp only [mem_closure_iff, set.nonempty, exists_prop, mem_inter_eq,
mem_ball', and_comm]
lemma dense_range_iff {f : β → α} :
dense_range f ↔ ∀ x, ∀ r > 0, ∃ y, dist x (f y) < r :=
forall_congr $ λ x, by simp only [mem_closure_iff, exists_range_iff]
/-- If a set `s` is separable, then the corresponding subtype is separable in a metric space.
This is not obvious, as the countable set whose closure covers `s` does not need in general to
be contained in `s`. -/
lemma _root_.topological_space.is_separable.separable_space {s : set α} (hs : is_separable s) :
separable_space s :=
begin
classical,
rcases eq_empty_or_nonempty s with rfl|⟨⟨x₀, x₀s⟩⟩,
{ apply_instance },
rcases hs with ⟨c, hc, h'c⟩,
haveI : encodable c := hc.to_encodable,
obtain ⟨u, -, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧
tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ),
let f : c × ℕ → α := λ p, if h : (metric.ball (p.1 : α) (u p.2) ∩ s).nonempty then h.some else x₀,
have fs : ∀ p, f p ∈ s,
{ rintros ⟨y, n⟩,
by_cases h : (ball (y : α) (u n) ∩ s).nonempty,
{ simpa only [f, h, dif_pos] using h.some_spec.2 },
{ simpa only [f, h, not_false_iff, dif_neg] } },
let g : c × ℕ → s := λ p, ⟨f p, fs p⟩,
apply separable_space_of_dense_range g,
apply metric.dense_range_iff.2,
rintros ⟨x, xs⟩ r (rpos : 0 < r),
obtain ⟨n, hn⟩ : ∃ n, u n < r / 2 := ((tendsto_order.1 u_lim).2 _ (half_pos rpos)).exists,
obtain ⟨z, zc, hz⟩ : ∃ z ∈ c, dist x z < u n :=
metric.mem_closure_iff.1 (h'c xs) _ (u_pos n),
refine ⟨(⟨z, zc⟩, n), _⟩,
change dist x (f (⟨z, zc⟩, n)) < r,
have A : (metric.ball z (u n) ∩ s).nonempty := ⟨x, hz, xs⟩,
dsimp [f],
simp only [A, dif_pos],
calc dist x A.some
≤ dist x z + dist z A.some : dist_triangle _ _ _
... < r/2 + r/2 : add_lt_add (hz.trans hn) ((metric.mem_ball'.1 A.some_spec.1).trans hn)
... = r : add_halves _
end
/-- The preimage of a separable set by an inducing map is separable. -/
protected lemma _root_.inducing.is_separable_preimage {f : β → α} [topological_space β]
(hf : inducing f) {s : set α} (hs : is_separable s) :
is_separable (f ⁻¹' s) :=
begin
haveI : second_countable_topology s,
{ haveI : separable_space s := hs.separable_space,
exact uniform_space.second_countable_of_separable _ },
let g : f ⁻¹' s → s := cod_restrict (f ∘ coe) s (λ x, x.2),
have : inducing g := (hf.comp inducing_coe).cod_restrict _,
haveI : second_countable_topology (f ⁻¹' s) := this.second_countable_topology,
rw show f ⁻¹' s = coe '' (univ : set (f ⁻¹' s)),
by simpa only [image_univ, subtype.range_coe_subtype],
exact (is_separable_of_separable_space _).image continuous_subtype_coe
end
protected lemma _root_.embedding.is_separable_preimage {f : β → α} [topological_space β]
(hf : embedding f) {s : set α} (hs : is_separable s) :
is_separable (f ⁻¹' s) :=
hf.to_inducing.is_separable_preimage hs
/-- If a map is continuous on a separable set `s`, then the image of `s` is also separable. -/
lemma _root_.continuous_on.is_separable_image [topological_space β] {f : α → β} {s : set α}
(hf : continuous_on f s) (hs : is_separable s) :
is_separable (f '' s) :=
begin
rw show f '' s = s.restrict f '' univ, by ext ; simp,
exact (is_separable_univ_iff.2 hs.separable_space).image
(continuous_on_iff_continuous_restrict.1 hf),
end
end metric
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
/-- A finite product of pseudometric spaces is a pseudometric space, with the sup distance. -/
noncomputable instance pseudo_metric_space_pi : pseudo_metric_space (Πb, π b) :=
begin
/- we construct the instance from the pseudoemetric space instance to avoid checking again that
the uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
refine (pseudo_emetric_space.to_pseudo_metric_space_of_dist
(λf g : Π b, π b, ((sup univ (λb, nndist (f b) (g b)) : ℝ≥0) : ℝ))
(λ f g, _) (λ f g, _)).replace_bornology (λ s, _),
show edist f g ≠ ⊤,
from ne_of_lt ((finset.sup_lt_iff bot_lt_top).2 $ λ b hb, edist_lt_top _ _),
show ↑(sup univ (λ b, nndist (f b) (g b))) = (sup univ (λ b, edist (f b) (g b))).to_real,
by simp only [edist_nndist, ← ennreal.coe_finset_sup, ennreal.coe_to_real],
show (@is_bounded _ pi.bornology s ↔ @is_bounded _ pseudo_metric_space.to_bornology _),
{ simp only [← is_bounded_def, is_bounded_iff_eventually, ← forall_is_bounded_image_eval_iff,
ball_image_iff, ← eventually_all, function.eval_apply, @dist_nndist (π _)],
refine eventually_congr ((eventually_ge_at_top 0).mono $ λ C hC, _),
lift C to ℝ≥0 using hC,
refine ⟨λ H x hx y hy, nnreal.coe_le_coe.2 $ finset.sup_le $ λ b hb, H b x hx y hy,
λ H b x hx y hy, nnreal.coe_le_coe.2 _⟩,
simpa only using finset.sup_le_iff.1 (nnreal.coe_le_coe.1 $ H hx hy) b (finset.mem_univ b) }
end
lemma nndist_pi_def (f g : Πb, π b) : nndist f g = sup univ (λb, nndist (f b) (g b)) :=
nnreal.eq rfl
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (sup univ (λb, nndist (f b) (g b)) : ℝ≥0) := rfl
@[simp] lemma dist_pi_const [nonempty β] (a b : α) : dist (λ x : β, a) (λ _, b) = dist a b :=
by simpa only [dist_edist] using congr_arg ennreal.to_real (edist_pi_const a b)
@[simp] lemma nndist_pi_const [nonempty β] (a b : α) :
nndist (λ x : β, a) (λ _, b) = nndist a b := nnreal.eq $ dist_pi_const a b
lemma nndist_pi_le_iff {f g : Πb, π b} {r : ℝ≥0} :
nndist f g ≤ r ↔ ∀b, nndist (f b) (g b) ≤ r :=
by simp [nndist_pi_def]
lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) :
dist f g < r ↔ ∀b, dist (f b) (g b) < r :=
begin
lift r to ℝ≥0 using hr.le,
simp [dist_pi_def, finset.sup_lt_iff (show ⊥ < r, from hr)],
end
lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) :
dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r :=
begin
lift r to ℝ≥0 using hr,
exact nndist_pi_le_iff
end
lemma nndist_le_pi_nndist (f g : Πb, π b) (b : β) : nndist (f b) (g b) ≤ nndist f g :=
by { rw [nndist_pi_def], exact finset.le_sup (finset.mem_univ b) }
lemma dist_le_pi_dist (f g : Πb, π b) (b : β) : dist (f b) (g b) ≤ dist f g :=
by simp only [dist_nndist, nnreal.coe_le_coe, nndist_le_pi_nndist f g b]
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi'`
for a version assuming `nonempty β` instead of `0 < r`. -/
lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
by { ext p, simp [dist_pi_lt_iff hr] }
/-- An open ball in a product space is a product of open balls. See also `metric.ball_pi`
for a version assuming `0 < r` instead of `nonempty β`. -/
lemma ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
ball x r = set.pi univ (λ b, ball (x b) r) :=
(lt_or_le 0 r).elim (ball_pi x) $ λ hr, by simp [ball_eq_empty.2 hr]
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi'`
for a version assuming `nonempty β` instead of `0 ≤ r`. -/
lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
by { ext p, simp [dist_pi_le_iff hr] }
/-- A closed ball in a product space is a product of closed balls. See also `metric.closed_ball_pi`
for a version assuming `0 ≤ r` instead of `nonempty β`. -/
lemma closed_ball_pi' [nonempty β] (x : Π b, π b) (r : ℝ) :
closed_ball x r = set.pi univ (λ b, closed_ball (x b) r) :=
(le_or_lt 0 r).elim (closed_ball_pi x) $ λ hr, by simp [closed_ball_eq_empty.2 hr]
@[simp] lemma fin.nndist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*}
[Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) :
nndist (i.insert_nth x f) (i.insert_nth y g) = max (nndist x y) (nndist f g) :=
eq_of_forall_ge_iff $ λ c, by simp [nndist_pi_le_iff, i.forall_iff_succ_above]
@[simp] lemma fin.dist_insert_nth_insert_nth {n : ℕ} {α : fin (n + 1) → Type*}
[Π i, pseudo_metric_space (α i)] (i : fin (n + 1)) (x y : α i) (f g : Π j, α (i.succ_above j)) :
dist (i.insert_nth x f) (i.insert_nth y g) = max (dist x y) (dist f g) :=
by simp only [dist_nndist, fin.nndist_insert_nth_insert_nth, nnreal.coe_max]
lemma real.dist_le_of_mem_pi_Icc {x y x' y' : β → ℝ} (hx : x ∈ Icc x' y') (hy : y ∈ Icc x' y') :
dist x y ≤ dist x' y' :=
begin
refine (dist_pi_le_iff dist_nonneg).2 (λ b, (real.dist_le_of_mem_interval _ _).trans
(dist_le_pi_dist _ _ b)); refine Icc_subset_interval _,
exacts [⟨hx.1 _, hx.2 _⟩, ⟨hy.1 _, hy.2 _⟩]
end
end pi
section compact
/-- Any compact set in a pseudometric space can be covered by finitely many balls of a given
positive radius -/
lemma finite_cover_balls_of_compact {α : Type u} [pseudo_metric_space α] {s : set α}
(hs : is_compact s) {e : ℝ} (he : 0 < e) :
∃t ⊆ s, set.finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply hs.elim_finite_subcover_image,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls
end compact
section proper_space
open metric
/-- A pseudometric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [pseudo_metric_space α] : Prop :=
(is_compact_closed_ball : ∀x:α, ∀r, is_compact (closed_ball x r))
export proper_space (is_compact_closed_ball)
/-- In a proper pseudometric space, all spheres are compact. -/
lemma is_compact_sphere {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
is_compact (sphere x r) :=
compact_of_is_closed_subset (is_compact_closed_ball x r) is_closed_sphere sphere_subset_closed_ball
/-- In a proper pseudometric space, any sphere is a `compact_space` when considered as a subtype. -/
instance {α : Type*} [pseudo_metric_space α] [proper_space α] (x : α) (r : ℝ) :
compact_space (sphere x r) :=
is_compact_iff_compact_space.mp (is_compact_sphere _ _)
/-- A proper pseudo metric space is sigma compact, and therefore second countable. -/
@[priority 100] -- see Note [lower instance priority]
instance second_countable_of_proper [proper_space α] :
second_countable_topology α :=
begin
-- We already have `sigma_compact_space_of_locally_compact_second_countable`, so we don't
-- add an instance for `sigma_compact_space`.
suffices : sigma_compact_space α, by exactI emetric.second_countable_of_sigma_compact α,
rcases em (nonempty α) with ⟨⟨x⟩⟩|hn,
{ exact ⟨⟨λ n, closed_ball x n, λ n, is_compact_closed_ball _ _, Union_closed_ball_nat _⟩⟩ },
{ exact ⟨⟨λ n, ∅, λ n, is_compact_empty, Union_eq_univ_iff.2 $ λ x, (hn ⟨x⟩).elim⟩⟩ }
end
lemma tendsto_dist_right_cocompact_at_top [proper_space α] (x : α) :
tendsto (λ y, dist y x) (cocompact α) at_top :=
(has_basis_cocompact.tendsto_iff at_top_basis).2 $ λ r hr,
⟨closed_ball x r, is_compact_closed_ball x r, λ y hy, (not_le.1 $ mt mem_closed_ball.2 hy).le⟩
lemma tendsto_dist_left_cocompact_at_top [proper_space α] (x : α) :
tendsto (dist x) (cocompact α) at_top :=
by simpa only [dist_comm] using tendsto_dist_right_cocompact_at_top x
/-- If all closed balls of large enough radius are compact, then the space is proper. Especially
useful when the lower bound for the radius is 0. -/
lemma proper_space_of_compact_closed_ball_of_le
(R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) :
proper_space α :=
⟨begin
assume x r,
by_cases hr : R ≤ r,
{ exact h x r hr },
{ have : closed_ball x r = closed_ball x R ∩ closed_ball x r,
{ symmetry,
apply inter_eq_self_of_subset_right,
exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) },
rw this,
exact (h x R le_rfl).inter_right is_closed_ball }
end⟩
/- A compact pseudometric space is proper -/
@[priority 100] -- see Note [lower instance priority]
instance proper_of_compact [compact_space α] : proper_space α :=
⟨assume x r, is_closed_ball.is_compact⟩
/-- A proper space is locally compact -/
@[priority 100] -- see Note [lower instance priority]
instance locally_compact_of_proper [proper_space α] :
locally_compact_space α :=
locally_compact_space_of_has_basis (λ x, nhds_basis_closed_ball) $
λ x ε ε0, is_compact_closed_ball _ _
/-- A proper space is complete -/
@[priority 100] -- see Note [lower instance priority]
instance complete_of_proper [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
obtain ⟨t, t_fset, ht⟩ : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 :=
(metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩,
have : closed_ball x 1 ∈ f := mem_of_superset t_fset (λ y yt, (ht y yt x xt).le),
rcases (compact_iff_totally_bounded_complete.1 (is_compact_closed_ball x 1)).2 f hf
(le_principal_iff.2 this) with ⟨y, -, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A finite product of proper spaces is proper. -/
instance pi_proper_space {π : β → Type*} [fintype β] [∀b, pseudo_metric_space (π b)]
[h : ∀b, proper_space (π b)] : proper_space (Πb, π b) :=
begin
refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _),
rw closed_ball_pi _ hr,
apply is_compact_univ_pi (λb, _),
apply (h b).is_compact_closed_ball
end
variables [proper_space α] {x : α} {r : ℝ} {s : set α}
/-- If a nonempty ball in a proper space includes a closed set `s`, then there exists a nonempty
ball with the same center and a strictly smaller radius that includes `s`. -/
lemma exists_pos_lt_subset_ball (hr : 0 < r) (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' ∈ Ioo 0 r, s ⊆ ball x r' :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with rfl|hne },
{ exact ⟨r / 2, ⟨half_pos hr, half_lt_self hr⟩, empty_subset _⟩ },
have : is_compact s,
from compact_of_is_closed_subset (is_compact_closed_ball x r) hs
(subset.trans h ball_subset_closed_ball),
obtain ⟨y, hys, hy⟩ : ∃ y ∈ s, s ⊆ closed_ball x (dist y x),
from this.exists_forall_ge hne (continuous_id.dist continuous_const).continuous_on,
have hyr : dist y x < r, from h hys,
rcases exists_between hyr with ⟨r', hyr', hrr'⟩,
exact ⟨r', ⟨dist_nonneg.trans_lt hyr', hrr'⟩, subset.trans hy $ closed_ball_subset_ball hyr'⟩
end
/-- If a ball in a proper space includes a closed set `s`, then there exists a ball with the same
center and a strictly smaller radius that includes `s`. -/
lemma exists_lt_subset_ball (hs : is_closed s) (h : s ⊆ ball x r) :
∃ r' < r, s ⊆ ball x r' :=
begin
cases le_or_lt r 0 with hr hr,
{ rw [ball_eq_empty.2 hr, subset_empty_iff] at h, unfreezingI { subst s },
exact (exists_lt r).imp (λ r' hr', ⟨hr', empty_subset _⟩) },
{ exact (exists_pos_lt_subset_ball hr hs h).imp (λ r' hr', ⟨hr'.fst.2, hr'.snd⟩) }
end
end proper_space
lemma is_compact.is_separable {s : set α} (hs : is_compact s) :
is_separable s :=
begin
haveI : compact_space s := is_compact_iff_compact_space.mp hs,
exact is_separable_of_separable_space_subtype s,
end
namespace metric
section second_countable
open topological_space
/-- A pseudometric space is second countable if, for every `ε > 0`, there is a countable set which
is `ε`-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, s.countable ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
refine emetric.second_countable_of_almost_dense_set (λ ε ε0, _),
rcases ennreal.lt_iff_exists_nnreal_btwn.1 ε0 with ⟨ε', ε'0, ε'ε⟩,
choose s hsc y hys hyx using H ε' (by exact_mod_cast ε'0),
refine ⟨s, hsc, Union₂_eq_univ_iff.2 (λ x, ⟨y x, hys _, le_trans _ ε'ε.le⟩)⟩,
exact_mod_cast hyx x
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : is_compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : is_compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a pseudometric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
lemma bounded_iff_is_bounded (s : set α) : bounded s ↔ is_bounded s :=
begin
change bounded s ↔ sᶜ ∈ (cobounded α).sets,
simp [pseudo_metric_space.cobounded_sets, metric.bounded],
end
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H,
s.eq_empty_or_nonempty.elim
(λ hs, hs.symm ▸ bounded_empty)
(λ ⟨x, hx⟩, H x hx)⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.mono (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x hx y hy, hC x (incl hx) y (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y hy z hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.mono ball_subset_closed_ball
/-- Spheres are bounded -/
lemma bounded_sphere : bounded (sphere x r) :=
bounded_closed_ball.mono sphere_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ cases s.eq_empty_or_nonempty with h h,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y hy x hx) _⟩ } },
{ exact bounded_closed_ball.mono hC }
end
lemma bounded.subset_ball (h : bounded s) (c : α) : ∃ r, s ⊆ closed_ball c r :=
(bounded_iff_subset_ball c).1 h
lemma bounded.subset_ball_lt (h : bounded s) (a : ℝ) (c : α) : ∃ r, a < r ∧ s ⊆ closed_ball c r :=
begin
rcases h.subset_ball c with ⟨r, hr⟩,
refine ⟨max r (a+1), lt_of_lt_of_le (by linarith) (le_max_right _ _), _⟩,
exact subset.trans hr (closed_ball_subset_closed_ball (le_max_left _ _))
end
lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) :=
let ⟨C, h⟩ := h in
⟨C, λ a ha b hb, (is_closed_le' C).closure_subset $ map_mem_closure₂ continuous_dist ha hb h⟩
alias bounded_closure_of_bounded ← bounded.closure
@[simp] lemma bounded_closure_iff : bounded (closure s) ↔ bounded s :=
⟨λ h, h.mono subset_closure, λ h, h.closure⟩
/-- The union of two bounded sets is bounded. -/
lemma bounded.union (hs : bounded s) (ht : bounded t) : bounded (s ∪ t) :=
begin
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end
/-- The union of two sets is bounded iff each of the sets is bounded. -/
@[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λ h, ⟨h.mono (by simp), h.mono (by simp)⟩, λ h, h.1.union h.2⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : I.finite) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
protected lemma bounded.prod [pseudo_metric_space β] {s : set α} {t : set β}
(hs : bounded s) (ht : bounded t) : bounded (s ×ˢ t) :=
begin
refine bounded_iff_mem_bounded.mpr (λ x hx, _),
rcases hs.subset_ball x.1 with ⟨rs, hrs⟩,
rcases ht.subset_ball x.2 with ⟨rt, hrt⟩,
suffices : s ×ˢ t ⊆ closed_ball x (max rs rt),
from bounded_closed_ball.mono this,
rw [← @prod.mk.eta _ _ x, ← closed_ball_prod_same],
exact prod_mono (hrs.trans $ closed_ball_subset_closed_ball $ le_max_left _ _)
(hrt.trans $ closed_ball_subset_closed_ball $ le_max_right _ _)
end
/-- A totally bounded set is bounded -/
lemma _root_.totally_bounded.bounded {s : set α} (h : totally_bounded s) : bounded s :=
-- We cover the totally bounded set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, fint, subs⟩ := (totally_bounded_iff.mp h) 1 zero_lt_one in
bounded.mono subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
/-- A compact set is bounded -/
lemma _root_.is_compact.bounded {s : set α} (h : is_compact s) : bounded s :=
-- A compact set is totally bounded, thus bounded
h.totally_bounded.bounded
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : s.finite) : bounded s :=
h.is_compact.bounded
alias bounded_of_finite ← _root_.set.finite.bounded
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩,
by rintro H _ ⟨x, rfl⟩ _ ⟨y, rfl⟩; exact H x y⟩
lemma bounded_range_of_tendsto_cofinite_uniformity {f : β → α}
(hf : tendsto (prod.map f f) (cofinite ×ᶠ cofinite) (𝓤 α)) :
bounded (range f) :=
begin
rcases (has_basis_cofinite.prod_self.tendsto_iff uniformity_basis_dist).1 hf 1 zero_lt_one
with ⟨s, hsf, hs1⟩,
rw [← image_univ, ← union_compl_self s, image_union, bounded_union],
use [(hsf.image f).bounded, 1],
rintro _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩,
exact le_of_lt (hs1 (x, y) ⟨hx, hy⟩)
end
lemma bounded_range_of_cauchy_map_cofinite {f : β → α} (hf : cauchy (map f cofinite)) :
bounded (range f) :=
bounded_range_of_tendsto_cofinite_uniformity $ (cauchy_map_iff.1 hf).2
lemma _root_.cauchy_seq.bounded_range {f : ℕ → α} (hf : cauchy_seq f) : bounded (range f) :=
bounded_range_of_cauchy_map_cofinite $ by rwa nat.cofinite_eq_at_top
lemma bounded_range_of_tendsto_cofinite {f : β → α} {a : α} (hf : tendsto f cofinite (𝓝 a)) :
bounded (range f) :=
bounded_range_of_tendsto_cofinite_uniformity $
(hf.prod_map hf).mono_right $ nhds_prod_eq.symm.trans_le (nhds_le_uniformity a)
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
compact_univ.bounded.mono (subset_univ _)
lemma bounded_range_of_tendsto {α : Type*} [pseudo_metric_space α] (u : ℕ → α) {x : α}
(hu : tendsto u at_top (𝓝 x)) :
bounded (range u) :=
hu.cauchy_seq.bounded_range
/-- The **Heine–Borel theorem**: In a proper space, a closed bounded set is compact. -/
lemma is_compact_of_is_closed_bounded [proper_space α] (hc : is_closed s) (hb : bounded s) :
is_compact s :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with (rfl|⟨x, hx⟩) },
{ exact is_compact_empty },
{ rcases hb.subset_ball x with ⟨r, hr⟩,
exact compact_of_is_closed_subset (is_compact_closed_ball x r) hc hr }
end
/-- The **Heine–Borel theorem**: In a proper space, the closure of a bounded set is compact. -/
lemma bounded.is_compact_closure [proper_space α] (h : bounded s) :
is_compact (closure s) :=
is_compact_of_is_closed_bounded is_closed_closure h.closure
/-- The **Heine–Borel theorem**:
In a proper Hausdorff space, a set is compact if and only if it is closed and bounded. -/
lemma compact_iff_closed_bounded [t2_space α] [proper_space α] :
is_compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨h.is_closed, h.bounded⟩, λ h, is_compact_of_is_closed_bounded h.1 h.2⟩
lemma compact_space_iff_bounded_univ [proper_space α] : compact_space α ↔ bounded (univ : set α) :=
⟨@bounded_of_compact_space α _ _, λ hb, ⟨is_compact_of_is_closed_bounded is_closed_univ hb⟩⟩
section conditionally_complete_linear_order
variables [preorder α] [compact_Icc_space α]
lemma bounded_Icc (a b : α) : bounded (Icc a b) :=
(totally_bounded_Icc a b).bounded
lemma bounded_Ico (a b : α) : bounded (Ico a b) :=
(totally_bounded_Ico a b).bounded
lemma bounded_Ioc (a b : α) : bounded (Ioc a b) :=
(totally_bounded_Ioc a b).bounded
lemma bounded_Ioo (a b : α) : bounded (Ioo a b) :=
(totally_bounded_Ioo a b).bounded
/-- In a pseudo metric space with a conditionally complete linear order such that the order and the
metric structure give the same topology, any order-bounded set is metric-bounded. -/
lemma bounded_of_bdd_above_of_bdd_below {s : set α} (h₁ : bdd_above s) (h₂ : bdd_below s) :
bounded s :=
let ⟨u, hu⟩ := h₁, ⟨l, hl⟩ := h₂ in
bounded.mono (λ x hx, mem_Icc.mpr ⟨hl hx, hu hx⟩) (bounded_Icc l u)
end conditionally_complete_linear_order
end bounded
section diam
variables {s : set α} {x y z : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
noncomputable def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
-- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x})
lemma diam_pair : diam ({x, y} : set α) = dist x y :=
by simp only [diam, emetric.diam_pair, dist_edist]
-- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x}))
lemma diam_triple :
metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) :=
begin
simp only [metric.diam, emetric.diam_triple, dist_edist],
rw [ennreal.to_real_max, ennreal.to_real_max];
apply_rules [ne_of_lt, edist_lt_top, max_lt]
end
/-- If the distance between any two points in a set is bounded by some constant `C`,
then `ennreal.of_real C` bounds the emetric diameter of this set. -/
lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
emetric.diam s ≤ ennreal.of_real C :=
emetric.diam_le $
λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy)
/-- If the distance between any two points in a set is bounded by some non-negative constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) :
diam s ≤ C :=
ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h)
/-- If the distance between any two points in a nonempty set is bounded by some constant,
this constant bounds the diameter. -/
lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ}
(h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C :=
have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx),
diam_le_of_forall_dist_le h₀ h
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) :
dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) h,
exact emetric.edist_le_diam_of_mem hx hy
end
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
iff.intro
(λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top $ ediam_le_of_forall_dist_le hC)
(λ h, ⟨diam s, λ x hx y hy, dist_le_diam_of_mem' h hx hy⟩)
lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ :=
bounded_iff_ediam_ne_top.1 h
lemma ediam_univ_eq_top_iff_noncompact [proper_space α] :
emetric.diam (univ : set α) = ∞ ↔ noncompact_space α :=
by rw [← not_compact_space_iff, compact_space_iff_bounded_univ, bounded_iff_ediam_ne_top, not_not]
@[simp] lemma ediam_univ_of_noncompact [proper_space α] [noncompact_space α] :
emetric.diam (univ : set α) = ∞ :=
ediam_univ_eq_top_iff_noncompact.mpr ‹_›
@[simp] lemma diam_univ_of_noncompact [proper_space α] [noncompact_space α] :
diam (univ : set α) = 0 :=
by simp [diam]
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
dist_le_diam_of_mem' h.ediam_ne_top hx hy
lemma ediam_of_unbounded (h : ¬(bounded s)) : emetric.diam s = ∞ :=
by rwa [bounded_iff_ediam_ne_top, not_not] at h
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
by rw [diam, ediam_of_unbounded h, ennreal.top_to_real]
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded.mono h ht).ediam_ne_top ht.ediam_ne_top,
exact emetric.diam_mono h
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) :
diam (s ∪ t) ≤ diam s + dist x y + diam t :=
begin
by_cases H : bounded (s ∪ t),
{ have hs : bounded s, from H.mono (subset_union_left _ _),
have ht : bounded t, from H.mono (subset_union_right _ _),
rw [bounded_iff_ediam_ne_top] at H hs ht,
rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add,
ennreal.to_real_le_to_real];
repeat { apply ennreal.add_ne_top.2; split }; try { assumption };
try { apply edist_ne_top },
exact emetric.diam_union xs yt },
{ rw [diam_eq_zero_of_unbounded H],
apply_rules [add_nonneg, diam_nonneg, dist_nonneg] }
end
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
lemma diam_le_of_subset_closed_ball {r : ℝ} (hr : 0 ≤ r) (h : s ⊆ closed_ball x r) :
diam s ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg zero_le_two hr) $ λa ha b hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add (h ha) (h hb)
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_subset_closed_ball h subset.rfl
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r :=
diam_le_of_subset_closed_ball h ball_subset_closed_ball
/-- If a family of complete sets with diameter tending to `0` is such that each finite intersection
is nonempty, then the total intersection is also nonempty. -/
lemma _root_.is_complete.nonempty_Inter_of_nonempty_bInter {s : ℕ → set α} (h0 : is_complete (s 0))
(hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty)
(h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) :
(⋂ n, s n).nonempty :=
begin
let u := λ N, (h N).some,
have I : ∀ n N, n ≤ N → u N ∈ s n,
{ assume n N hn,
apply mem_of_subset_of_mem _ ((h N).some_spec),
assume x hx,
simp only [mem_Inter] at hx,
exact hx n hn },
have : ∀ n, u n ∈ s 0 := λ n, I 0 n (zero_le _),
have : cauchy_seq u,
{ apply cauchy_seq_of_le_tendsto_0 _ _ h',
assume m n N hm hn,
exact dist_le_diam_of_mem (h's N) (I _ _ hm) (I _ _ hn) },
obtain ⟨x, hx, xlim⟩ : ∃ (x : α) (H : x ∈ s 0), tendsto (λ (n : ℕ), u n) at_top (𝓝 x) :=
cauchy_seq_tendsto_of_is_complete h0 (λ n, I 0 n (zero_le _)) this,
refine ⟨x, mem_Inter.2 (λ n, _)⟩,
apply (hs n).mem_of_tendsto xlim,
filter_upwards [Ici_mem_at_top n] with p hp,
exact I n p hp,
end
/-- In a complete space, if a family of closed sets with diameter tending to `0` is such that each
finite intersection is nonempty, then the total intersection is also nonempty. -/
lemma nonempty_Inter_of_nonempty_bInter [complete_space α] {s : ℕ → set α}
(hs : ∀ n, is_closed (s n)) (h's : ∀ n, bounded (s n)) (h : ∀ N, (⋂ n ≤ N, s n).nonempty)
(h' : tendsto (λ n, diam (s n)) at_top (𝓝 0)) :
(⋂ n, s n).nonempty :=
(hs 0).is_complete.nonempty_Inter_of_nonempty_bInter hs h's h h'
end diam
end metric
lemma comap_dist_right_at_top_le_cocompact (x : α) : comap (λ y, dist y x) at_top ≤ cocompact α :=
begin
refine filter.has_basis_cocompact.ge_iff.2 (λ s hs, mem_comap.2 _),
rcases hs.bounded.subset_ball x with ⟨r, hr⟩,
exact ⟨Ioi r, Ioi_mem_at_top r, λ y hy hys, (mem_closed_ball.1 $ hr hys).not_lt hy⟩
end
lemma comap_dist_left_at_top_le_cocompact (x : α) : comap (dist x) at_top ≤ cocompact α :=
by simpa only [dist_comm _ x] using comap_dist_right_at_top_le_cocompact x
lemma comap_dist_right_at_top_eq_cocompact [proper_space α] (x : α) :
comap (λ y, dist y x) at_top = cocompact α :=
(comap_dist_right_at_top_le_cocompact x).antisymm $ (tendsto_dist_right_cocompact_at_top x).le_comap
lemma comap_dist_left_at_top_eq_cocompact [proper_space α] (x : α) :
comap (dist x) at_top = cocompact α :=
(comap_dist_left_at_top_le_cocompact x).antisymm $ (tendsto_dist_left_cocompact_at_top x).le_comap
lemma tendsto_cocompact_of_tendsto_dist_comp_at_top {f : β → α} {l : filter β} (x : α)
(h : tendsto (λ y, dist (f y) x) l at_top) : tendsto f l (cocompact α) :=
by { refine tendsto.mono_right _ (comap_dist_right_at_top_le_cocompact x), rwa tendsto_comap_iff }
namespace int
open metric
/-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/
lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) :=
begin
refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _,
simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball],
change ∀ r : ℝ, (coe ⁻¹' (ball (0 : ℝ) r)).finite,
simp [real.ball_eq_Ioo, set.finite_Ioo],
end
end int
/-- We now define `metric_space`, extending `pseudo_metric_space`. -/
class metric_space (α : Type u) extends pseudo_metric_space α : Type u :=
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
/-- Two metric space structures with the same distance coincide. -/
@[ext] lemma metric_space.ext {α : Type*} {m m' : metric_space α}
(h : m.to_has_dist = m'.to_has_dist) : m = m' :=
begin
have h' : m.to_pseudo_metric_space = m'.to_pseudo_metric_space := pseudo_metric_space.ext h,
unfreezingI { rcases m, rcases m' },
dsimp at h',
unfreezingI { subst h' },
end
/-- Construct a metric space structure whose underlying topological space structure
(definitionally) agrees which a pre-existing topology which is compatible with a given distance
function. -/
def metric_space.of_metrizable {α : Type*} [topological_space α] (dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(H : ∀ s : set α, is_open s ↔ ∀ x ∈ s, ∃ ε > 0, ∀ y, dist x y < ε → y ∈ s)
(eq_of_dist_eq_zero : ∀ x y : α, dist x y = 0 → x = y) : metric_space α :=
{ eq_of_dist_eq_zero := eq_of_dist_eq_zero,
..pseudo_metric_space.of_metrizable dist dist_self dist_comm dist_triangle H }
variables {γ : Type w} [metric_space γ]
theorem eq_of_dist_eq_zero {x y : γ} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
@[simp] theorem dist_eq_zero {x y : γ} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : γ} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_ne_zero {x y : γ} : dist x y ≠ 0 ↔ x ≠ y :=
by simpa only [not_iff_not] using dist_eq_zero
@[simp] theorem dist_le_zero {x y : γ} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : γ} : 0 < dist x y ↔ x ≠ y :=
by simpa only [not_le] using not_congr dist_le_zero
theorem eq_of_forall_dist_le {x y : γ} (h : ∀ ε > 0, dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : γ} : nndist x y = 0 → x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : γ} : nndist x y = 0 ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : γ} : 0 = nndist x y ↔ x = y :=
by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist]
namespace metric
variables {x : γ} {s : set γ}
@[simp] lemma closed_ball_zero : closed_ball x 0 = {x} :=
set.ext $ λ y, dist_le_zero
@[simp] lemma sphere_zero : sphere x 0 = {x} :=
set.ext $ λ y, dist_eq_zero
lemma subsingleton_closed_ball (x : γ) {r : ℝ} (hr : r ≤ 0) : (closed_ball x r).subsingleton :=
begin
rcases hr.lt_or_eq with hr|rfl,
{ rw closed_ball_eq_empty.2 hr, exact subsingleton_empty },
{ rw closed_ball_zero, exact subsingleton_singleton }
end
lemma subsingleton_sphere (x : γ) {r : ℝ} (hr : r ≤ 0) : (sphere x r).subsingleton :=
(subsingleton_closed_ball x hr).anti sphere_subset_closed_ball
/-- A map between metric spaces is a uniform embedding if and only if the distance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [metric_space β] {f : γ → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, dist a b < δ → dist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, dist (f a) (f b) < ε → dist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : dist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : dist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
@[priority 100] -- see Note [lower instance priority]
instance _root_.metric_space.to_separated : separated_space γ :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-- If a `pseudo_metric_space` is a T₀ space, then it is a `metric_space`. -/
def of_t0_pseudo_metric_space (α : Type*) [pseudo_metric_space α] [t0_space α] :
metric_space α :=
{ eq_of_dist_eq_zero := λ x y hdist, inseparable.eq $ metric.inseparable_iff.2 hdist,
..‹pseudo_metric_space α› }
/-- A metric space induces an emetric space -/
@[priority 100] -- see Note [lower instance priority]
instance metric_space.to_emetric_space : emetric_space γ :=
emetric.of_t0_pseudo_emetric_space γ
lemma is_closed_of_pairwise_le_dist {s : set γ} {ε : ℝ} (hε : 0 < ε)
(hs : s.pairwise (λ x y, ε ≤ dist x y)) : is_closed s :=
is_closed_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hs
lemma closed_embedding_of_pairwise_le_dist {α : Type*} [topological_space α] [discrete_topology α]
{ε : ℝ} (hε : 0 < ε) {f : α → γ} (hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) :
closed_embedding f :=
closed_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
/-- If `f : β → α` sends any two distinct points to points at distance at least `ε > 0`, then
`f` is a uniform embedding with respect to the discrete uniformity on `β`. -/
lemma uniform_embedding_bot_of_pairwise_le_dist {β : Type*} {ε : ℝ} (hε : 0 < ε) {f : β → α}
(hf : pairwise (λ x y, ε ≤ dist (f x) (f y))) : @uniform_embedding _ _ ⊥ (by apply_instance) f :=
uniform_embedding_of_spaced_out (dist_mem_uniformity hε) $ by simpa using hf
end metric
/-- Build a new metric space from an old one where the bundled uniform structure is provably
(but typically non-definitionaly) equal to some given uniform structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_uniformity {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
metric_space γ :=
{ eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
..pseudo_metric_space.replace_uniformity m.to_pseudo_metric_space H, }
lemma metric_space.replace_uniformity_eq {γ} [U : uniform_space γ] (m : metric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
m.replace_uniformity H = m :=
by { ext, refl }
/-- Build a new metric space from an old one where the bundled topological structure is provably
(but typically non-definitionaly) equal to some given topological structure.
See Note [forgetful inheritance].
-/
@[reducible] def metric_space.replace_topology {γ} [U : topological_space γ] (m : metric_space γ)
(H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) :
metric_space γ :=
@metric_space.replace_uniformity γ (m.to_uniform_space.replace_topology H) m rfl
lemma metric_space.replace_topology_eq {γ} [U : topological_space γ] (m : metric_space γ)
(H : U = m.to_pseudo_metric_space.to_uniform_space.to_topological_space) :
m.replace_topology H = m :=
by { ext, refl }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. In this definition, the distance
is given separately, to be able to prescribe some expression which is not defeq to the push-forward
of the edistance to reals. -/
def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α]
(dist : α → α → ℝ)
(edist_ne_top : ∀x y: α, edist x y ≠ ⊤)
(h : ∀x y, dist x y = ennreal.to_real (edist x y)) :
metric_space α :=
{ dist := dist,
eq_of_dist_eq_zero := λx y hxy,
by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy,
..pseudo_emetric_space.to_pseudo_metric_space_of_dist dist edist_ne_top h, }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the
uniformity are defeq in the metric space and the emetric space. -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl)
/-- Build a new metric space from an old one where the bundled bornology structure is provably
(but typically non-definitionaly) equal to some given bornology structure.
See Note [forgetful inheritance].
-/
def metric_space.replace_bornology {α} [B : bornology α] (m : metric_space α)
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
metric_space α :=
{ to_bornology := B,
.. pseudo_metric_space.replace_bornology _ H,
.. m }
lemma metric_space.replace_bornology_eq {α} [m : metric_space α] [B : bornology α]
(H : ∀ s, @is_bounded _ B s ↔ @is_bounded _ pseudo_metric_space.to_bornology s) :
metric_space.replace_bornology _ H = m :=
by { ext, refl }
/-- Metric space structure pulled back by an injective function. Injectivity is necessary to
ensure that `dist x y = 0` only if `x = y`. -/
def metric_space.induced {γ β} (f : γ → β) (hf : function.injective f)
(m : metric_space β) : metric_space γ :=
{ eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
..pseudo_metric_space.induced f m.to_pseudo_metric_space }
/-- Pull back a metric space structure by a uniform embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `uniform_space` structure. -/
@[reducible] def uniform_embedding.comap_metric_space
{α β} [uniform_space α] [metric_space β] (f : α → β) (h : uniform_embedding f) :
metric_space α :=
(metric_space.induced f h.inj ‹_›).replace_uniformity h.comap_uniformity.symm
/-- Pull back a metric space structure by an embedding. This is a version of
`metric_space.induced` useful in case if the domain already has a `topological_space` structure. -/
@[reducible] def embedding.comap_metric_space
{α β} [topological_space α] [metric_space β] (f : α → β) (h : embedding f) :
metric_space α :=
begin
letI : uniform_space α := embedding.comap_uniform_space f h,
exact uniform_embedding.comap_metric_space f (h.to_uniform_embedding f),
end
instance subtype.metric_space {α : Type*} {p : α → Prop} [metric_space α] :
metric_space (subtype p) :=
metric_space.induced coe subtype.coe_injective ‹_›
@[to_additive] instance {α : Type*} [metric_space α] : metric_space (αᵐᵒᵖ) :=
metric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_›
instance : metric_space empty :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero,
to_uniform_space := empty.uniform_space,
uniformity_dist := subsingleton.elim _ _ }
instance : metric_space punit.{u + 1} :=
{ dist := λ _ _, 0,
dist_self := λ _, rfl,
dist_comm := λ _ _, rfl,
eq_of_dist_eq_zero := λ _ _ _, subsingleton.elim _ _,
dist_triangle := λ _ _ _, show (0:ℝ) ≤ 0 + 0, by rw add_zero,
to_uniform_space := punit.uniform_space,
uniformity_dist :=
begin
simp only,
haveI : ne_bot (⨅ ε > (0 : ℝ), 𝓟 {p : punit.{u + 1} × punit.{u + 1} | 0 < ε}),
{ exact @uniformity.ne_bot _ (uniform_space_of_dist (λ _ _, 0) (λ _, rfl) (λ _ _, rfl)
(λ _ _ _, by rw zero_add)) _ },
refine (eq_top_of_ne_bot _).trans (eq_top_of_ne_bot _).symm,
end}
section real
/-- Instantiate the reals as a metric space. -/
noncomputable instance real.metric_space : metric_space ℝ :=
{ eq_of_dist_eq_zero := λ x y h, by simpa [dist, sub_eq_zero] using h,
..real.pseudo_metric_space }
end real
section nnreal
noncomputable instance : metric_space ℝ≥0 := subtype.metric_space
end nnreal
instance [metric_space β] : metric_space (ulift β) :=
metric_space.induced ulift.down ulift.down_injective ‹_›
section prod
noncomputable instance prod.metric_space_max [metric_space β] : metric_space (γ × β) :=
{ eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
..prod.pseudo_metric_space_max, }
end prod
section pi
open finset
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
/-- A finite product of metric spaces is a metric space, with the sup distance. -/
noncomputable instance metric_space_pi : metric_space (Πb, π b) :=
/- we construct the instance from the emetric space instance to avoid checking again that the
uniformity is the same as the product uniformity, but we register nevertheless a nice formula
for the distance -/
{ eq_of_dist_eq_zero := assume f g eq0,
begin
have eq1 : edist f g = 0 := by simp only [edist_dist, eq0, ennreal.of_real_zero],
have eq2 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq1,
simp only [finset.sup_le_iff] at eq2,
exact (funext $ assume b, edist_le_zero.1 $ eq2 b $ mem_univ b)
end,
..pseudo_metric_space_pi }
end pi
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if one can reconstruct up to any `ε>0` any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type*) (_ : encodable β) (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
cases (univ : set α).eq_empty_or_nonempty with hs hs,
{ haveI : compact_space α := ⟨by rw hs; exact is_compact_empty⟩, by apply_instance },
rcases hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
resetI,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
section eq_rel
/-- The canonical equivalence relation on a pseudometric space. -/
def pseudo_metric.dist_setoid (α : Type u) [pseudo_metric_space α] : setoid α :=
setoid.mk (λx y, dist x y = 0)
begin
unfold equivalence,
repeat { split },
{ exact pseudo_metric_space.dist_self },
{ assume x y h, rwa pseudo_metric_space.dist_comm },
{ assume x y z hxy hyz,
refine le_antisymm _ dist_nonneg,
calc dist x z ≤ dist x y + dist y z : pseudo_metric_space.dist_triangle _ _ _
... = 0 + 0 : by rw [hxy, hyz]
... = 0 : by simp }
end
local attribute [instance] pseudo_metric.dist_setoid
/-- The canonical quotient of a pseudometric space, identifying points at distance `0`. -/
@[reducible] definition pseudo_metric_quot (α : Type u) [pseudo_metric_space α] : Type* :=
quotient (pseudo_metric.dist_setoid α)
instance has_dist_metric_quot {α : Type u} [pseudo_metric_space α] :
has_dist (pseudo_metric_quot α) :=
{ dist := quotient.lift₂ (λp q : α, dist p q)
begin
assume x y x' y' hxx' hyy',
have Hxx' : dist x x' = 0 := hxx',
have Hyy' : dist y y' = 0 := hyy',
have A : dist x y ≤ dist x' y' := calc
dist x y ≤ dist x x' + dist x' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y : by simp [Hxx']
... ≤ dist x' y' + dist y' y : pseudo_metric_space.dist_triangle _ _ _
... = dist x' y' : by simp [pseudo_metric_space.dist_comm, Hyy'],
have B : dist x' y' ≤ dist x y := calc
dist x' y' ≤ dist x' x + dist x y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y' : by simp [pseudo_metric_space.dist_comm, Hxx']
... ≤ dist x y + dist y y' : pseudo_metric_space.dist_triangle _ _ _
... = dist x y : by simp [Hyy'],
exact le_antisymm A B
end }
lemma pseudo_metric_quot_dist_eq {α : Type u} [pseudo_metric_space α] (p q : α) :
dist ⟦p⟧ ⟦q⟧ = dist p q := rfl
instance metric_space_quot {α : Type u} [pseudo_metric_space α] :
metric_space (pseudo_metric_quot α) :=
{ dist_self := begin
refine quotient.ind (λy, _),
exact pseudo_metric_space.dist_self _
end,
eq_of_dist_eq_zero := λxc yc, by exact quotient.induction_on₂ xc yc (λx y H, quotient.sound H),
dist_comm :=
λxc yc, quotient.induction_on₂ xc yc (λx y, pseudo_metric_space.dist_comm _ _),
dist_triangle :=
λxc yc zc, quotient.induction_on₃ xc yc zc (λx y z, pseudo_metric_space.dist_triangle _ _ _) }
end eq_rel
/-!
### `additive`, `multiplicative`
The distance on those type synonyms is inherited without change.
-/
open additive multiplicative
section
variables [has_dist X]
instance : has_dist (additive X) := ‹has_dist X›
instance : has_dist (multiplicative X) := ‹has_dist X›
@[simp] lemma dist_of_mul (a b : X) : dist (of_mul a) (of_mul b) = dist a b := rfl
@[simp] lemma dist_of_add (a b : X) : dist (of_add a) (of_add b) = dist a b := rfl
@[simp] lemma dist_to_mul (a b : additive X) : dist (to_mul a) (to_mul b) = dist a b := rfl
@[simp] lemma dist_to_add (a b : multiplicative X) : dist (to_add a) (to_add b) = dist a b := rfl
end
section
variables [pseudo_metric_space X]
instance : pseudo_metric_space (additive X) := ‹pseudo_metric_space X›
instance : pseudo_metric_space (multiplicative X) := ‹pseudo_metric_space X›
@[simp] lemma nndist_of_mul (a b : X) : nndist (of_mul a) (of_mul b) = nndist a b := rfl
@[simp] lemma nndist_of_add (a b : X) : nndist (of_add a) (of_add b) = nndist a b := rfl
@[simp] lemma nndist_to_mul (a b : additive X) : nndist (to_mul a) (to_mul b) = nndist a b := rfl
@[simp] lemma nndist_to_add (a b : multiplicative X) : nndist (to_add a) (to_add b) = nndist a b :=
rfl
end
instance [metric_space X] : metric_space (additive X) := ‹metric_space X›
instance [metric_space X] : metric_space (multiplicative X) := ‹metric_space X›
instance [pseudo_metric_space X] [proper_space X] : proper_space (additive X) := ‹proper_space X›
instance [pseudo_metric_space X] [proper_space X] : proper_space (multiplicative X) :=
‹proper_space X›
/-!
### Order dual
The distance on this type synonym is inherited without change.
-/
open order_dual
section
variables [has_dist X]
instance : has_dist Xᵒᵈ := ‹has_dist X›
@[simp] lemma dist_to_dual (a b : X) : dist (to_dual a) (to_dual b) = dist a b := rfl
@[simp] lemma dist_of_dual (a b : Xᵒᵈ) : dist (of_dual a) (of_dual b) = dist a b := rfl
end
section
variables [pseudo_metric_space X]
instance : pseudo_metric_space Xᵒᵈ := ‹pseudo_metric_space X›
@[simp] lemma nndist_to_dual (a b : X) : nndist (to_dual a) (to_dual b) = nndist a b := rfl
@[simp] lemma nndist_of_dual (a b : Xᵒᵈ) : nndist (of_dual a) (of_dual b) = nndist a b := rfl
end
instance [metric_space X] : metric_space Xᵒᵈ := ‹metric_space X›
instance [pseudo_metric_space X] [proper_space X] : proper_space Xᵒᵈ := ‹proper_space X›
|
b9bc9bc0b988985ed75eaa3156393b9dbee425a3 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/int/cast.lean | 0a27981734db4cf329889d9af5fb8bcfd2b89278 | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,659 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.int.basic
import data.nat.cast
/-!
# Cast of integers
This file defines the *canonical* homomorphism from the integers into a type `α` with `0`,
`1`, `+` and `-` (typically a `ring`).
## Main declarations
* `cast`: Canonical homomorphism `ℤ → α` where `α` has a `0`, `1`, `+` and `-`.
* `cast_add_hom`: `cast` bundled as an `add_monoid_hom`.
* `cast_ring_hom`: `cast` bundled as a `ring_hom`.
## Implementation note
Setting up the coercions priorities is tricky. See Note [coercion into rings].
-/
open nat
namespace int
@[simp, push_cast] theorem nat_cast_eq_coe_nat : ∀ n,
@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n =
@coe ℕ ℤ (@coe_to_lift _ _ (@coe_base _ _ int.has_coe)) n
| 0 := rfl
| (n+1) := congr_arg (+(1:ℤ)) (nat_cast_eq_coe_nat n)
/-- Coercion `ℕ → ℤ` as a `ring_hom`. -/
def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩
section cast
variables {α : Type*}
section
variables [has_zero α] [has_one α] [has_add α] [has_neg α]
/-- Canonical homomorphism from the integers to any ring(-like) structure `α` -/
protected def cast : ℤ → α
| (n : ℕ) := n
| -[1+ n] := -(n+1)
-- see Note [coercion into rings]
@[priority 900] instance cast_coe : has_coe_t ℤ α := ⟨int.cast⟩
@[simp, norm_cast] theorem cast_zero : ((0 : ℤ) : α) = 0 := rfl
theorem cast_of_nat (n : ℕ) : (of_nat n : α) = n := rfl
@[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℤ) : α) = n := rfl
theorem cast_coe_nat' (n : ℕ) :
(@coe ℕ ℤ (@coe_to_lift _ _ nat.cast_coe) n : α) = n :=
by simp
@[simp, norm_cast] theorem cast_neg_succ_of_nat (n : ℕ) : (-[1+ n] : α) = -(n + 1) := rfl
end
@[simp, norm_cast] theorem cast_one [add_monoid α] [has_one α] [has_neg α] :
((1 : ℤ) : α) = 1 := nat.cast_one
@[simp] theorem cast_sub_nat_nat [add_group α] [has_one α] (m n) :
((int.sub_nat_nat m n : ℤ) : α) = m - n :=
begin
unfold sub_nat_nat, cases e : n - m,
{ simp [sub_nat_nat, e, tsub_eq_zero_iff_le.mp e] },
{ rw [sub_nat_nat, cast_neg_succ_of_nat, ← nat.cast_succ, ← e,
nat.cast_sub $ _root_.le_of_lt $ nat.lt_of_sub_eq_succ e, neg_sub] },
end
@[simp, norm_cast] theorem cast_neg_of_nat [add_group α] [has_one α] :
∀ n, ((neg_of_nat n : ℤ) : α) = -n
| 0 := neg_zero.symm
| (n+1) := rfl
@[simp, norm_cast] theorem cast_add [add_group α] [has_one α] : ∀ m n, ((m + n : ℤ) : α) = m + n
| (m : ℕ) (n : ℕ) := nat.cast_add _ _
| (m : ℕ) -[1+ n] := by simpa only [sub_eq_add_neg] using cast_sub_nat_nat _ _
| -[1+ m] (n : ℕ) := (cast_sub_nat_nat _ _).trans $ sub_eq_of_eq_add $
show (n:α) = -(m+1) + n + (m+1),
by rw [add_assoc, ← cast_succ, ← nat.cast_add, add_comm,
nat.cast_add, cast_succ, neg_add_cancel_left]
| -[1+ m] -[1+ n] := show -((m + n + 1 + 1 : ℕ) : α) = -(m + 1) + -(n + 1),
begin
rw [← neg_add_rev, ← nat.cast_add_one, ← nat.cast_add_one, ← nat.cast_add],
apply congr_arg (λ x:ℕ, -(x:α)),
ac_refl
end
@[simp, norm_cast] theorem cast_neg [add_group α] [has_one α] : ∀ n, ((-n : ℤ) : α) = -n
| (n : ℕ) := cast_neg_of_nat _
| -[1+ n] := (neg_neg _).symm
@[simp, norm_cast] theorem cast_sub [add_group α] [has_one α] (m n) : ((m - n : ℤ) : α) = m - n :=
by simp [sub_eq_add_neg]
@[simp, norm_cast] theorem cast_mul [ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n
| (m : ℕ) (n : ℕ) := nat.cast_mul _ _
| (m : ℕ) -[1+ n] := (cast_neg_of_nat _).trans $
show (-(m * (n + 1) : ℕ) : α) = m * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_mul_neg]
| -[1+ m] (n : ℕ) := (cast_neg_of_nat _).trans $
show (-((m + 1) * n : ℕ) : α) = -(m + 1) * n,
by rw [nat.cast_mul, nat.cast_add_one, neg_mul_eq_neg_mul]
| -[1+ m] -[1+ n] := show (((m + 1) * (n + 1) : ℕ) : α) = -(m + 1) * -(n + 1),
by rw [nat.cast_mul, nat.cast_add_one, nat.cast_add_one, neg_mul_neg]
/-- `coe : ℤ → α` as an `add_monoid_hom`. -/
def cast_add_hom (α : Type*) [add_group α] [has_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩
@[simp] lemma coe_cast_add_hom [add_group α] [has_one α] : ⇑(cast_add_hom α) = coe := rfl
/-- `coe : ℤ → α` as a `ring_hom`. -/
def cast_ring_hom (α : Type*) [ring α] : ℤ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩
@[simp] lemma coe_cast_ring_hom [ring α] : ⇑(cast_ring_hom α) = coe := rfl
lemma cast_commute [ring α] (m : ℤ) (x : α) : commute ↑m x :=
int.cases_on m (λ n, n.cast_commute x) (λ n, ((n+1).cast_commute x).neg_left)
lemma cast_comm [ring α] (m : ℤ) (x : α) : (m : α) * x = x * m :=
(cast_commute m x).eq
lemma commute_cast [ring α] (x : α) (m : ℤ) : commute x m :=
(m.cast_commute x).symm
@[simp, norm_cast]
theorem coe_nat_bit0 (n : ℕ) : (↑(bit0 n) : ℤ) = bit0 ↑n := by {unfold bit0, simp}
@[simp, norm_cast]
theorem coe_nat_bit1 (n : ℕ) : (↑(bit1 n) : ℤ) = bit1 ↑n := by {unfold bit1, unfold bit0, simp}
@[simp, norm_cast] theorem cast_bit0 [ring α] (n : ℤ) : ((bit0 n : ℤ) : α) = bit0 n := cast_add _ _
@[simp, norm_cast] theorem cast_bit1 [ring α] (n : ℤ) : ((bit1 n : ℤ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
lemma cast_two [ring α] : ((2 : ℤ) : α) = 2 := by simp
theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) :=
begin
intros m n h,
rw ← sub_nonneg at h,
lift n - m to ℕ using h with k,
rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat],
exact k.cast_nonneg
end
@[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one,
by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le
@[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) :=
strict_mono_of_le_iff_le $ λ m n, cast_le.symm
@[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) < n ↔ m < n :=
cast_strict_mono.lt_iff_lt
@[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp, norm_cast] theorem cast_min [linear_ordered_ring α] {a b : ℤ} :
(↑(min a b) : α) = min a b :=
monotone.map_min cast_mono
@[simp, norm_cast] theorem cast_max [linear_ordered_ring α] {a b : ℤ} :
(↑(max a b) : α) = max a b :=
monotone.map_max cast_mono
@[simp, norm_cast] theorem cast_abs [linear_ordered_ring α] {q : ℤ} :
((|q| : ℤ) : α) = |q| :=
by simp [abs_eq_max_neg]
lemma cast_nat_abs {R : Type*} [linear_ordered_ring R] : ∀ (n : ℤ), (n.nat_abs : R) = |n|
| (n : ℕ) := by simp only [int.nat_abs_of_nat, int.cast_coe_nat, nat.abs_cast]
| -[1+n] := by simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg,
← nat.cast_succ, nat.abs_cast]
lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) :
(m : α) ∣ (n : α) :=
ring_hom.map_dvd (int.cast_ring_hom α) h
end cast
end int
namespace prod
variables {α : Type*} {β : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α]
[has_zero β] [has_one β] [has_add β] [has_neg β]
@[simp] lemma fst_int_cast (n : ℤ) : (n : α × β).fst = n :=
by induction n; simp *
@[simp] lemma snd_int_cast (n : ℤ) : (n : α × β).snd = n :=
by induction n; simp *
end prod
open int
namespace add_monoid_hom
variables {A : Type*}
/-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal
if `f 1 = g 1`. -/
@[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g :=
have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat h1,
have ∀ n : ℕ, f n = g n := ext_iff.1 this,
ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1)
variables [add_group A] [has_one A]
theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A :=
ext_int $ by simp [h1]
theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n :=
ext_iff.1 (f.eq_int_cast_hom h1)
end add_monoid_hom
namespace monoid_hom
variables {M : Type*} [monoid M]
open multiplicative
@[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g :=
monoid_hom.ext $ add_monoid_hom.ext_iff.mp $
@add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1
/-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] theorem ext_int {f g : ℤ →* M}
(h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) :
f = g :=
begin
ext (x | x),
{ exact (monoid_hom.congr_fun h_nat x : _), },
{ rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul],
congr' 1,
exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), }
end
end monoid_hom
namespace monoid_with_zero_hom
variables {M : Type*} [monoid_with_zero M]
/-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] theorem ext_int {f g : monoid_with_zero_hom ℤ M}
(h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom =
g.comp int.of_nat_hom.to_monoid_with_zero_hom) :
f = g :=
to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _)
/-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/
theorem ext_int' {φ₁ φ₂ : monoid_with_zero_hom ℤ M}
(h_neg_one : φ₁ (-1) = φ₂ (-1)) (h_pos : ∀ n : ℕ, 0 < n → φ₁ n = φ₂ n) : φ₁ = φ₂ :=
ext_int h_neg_one $ ext_nat h_pos
end monoid_with_zero_hom
namespace ring_hom
variables {α : Type*} {β : Type*} [ring α] [ring β]
@[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n :=
f.to_add_monoid_hom.eq_int_cast f.map_one n
lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α :=
ring_hom.ext f.eq_int_cast
@[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n :=
(f.comp (int.cast_ring_hom α)).eq_int_cast n
lemma ext_int {R : Type*} [semiring R] (f g : ℤ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm
instance int.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℤ →+* R) :=
⟨ring_hom.ext_int⟩
end ring_hom
@[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n :=
((ring_hom.id ℤ).eq_int_cast n).symm
namespace pi
variables {α β : Type*}
lemma int_apply [has_zero β] [has_one β] [has_add β] [has_neg β] :
∀ (n : ℤ) (a : α), (n : α → β) a = n
| (n:ℕ) a := pi.nat_apply n a
| -[1+n] a :=
by rw [cast_neg_succ_of_nat, cast_neg_succ_of_nat, neg_apply, add_apply, one_apply, nat_apply]
@[simp] lemma coe_int [has_zero β] [has_one β] [has_add β] [has_neg β] (n : ℤ) :
(n : α → β) = λ _, n :=
by { ext, rw pi.int_apply }
end pi
|
f8e07d592d66f68b58a8f24bc462ff1acfbc7319 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/tactic/norm_num.lean | ddf8e2bed98092b2ce4f1b789282f8d2ead09d44 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 61,648 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
-/
import data.rat.cast
import data.rat.meta_defs
/-!
# `norm_num`
Evaluating arithmetic expressions including *, +, -, ^, ≤
-/
universes u v w
namespace tactic
/-- Reflexivity conversion: given `e` returns `(e, ⊢ e = e)` -/
meta def refl_conv (e : expr) : tactic (expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
/-- Transitivity conversion: given two conversions (which take an
expression `e` and returns `(e', ⊢ e = e')`), produces another
conversion that combines them with transitivity, treating failures
as reflexivity conversions. -/
meta def trans_conv (t₁ t₂ : expr → tactic (expr × expr)) (e : expr) :
tactic (expr × expr) :=
(do (e₁, p₁) ← t₁ e,
(do (e₂, p₂) ← t₂ e₁,
p ← mk_eq_trans p₁ p₂, return (e₂, p)) <|>
return (e₁, p₁)) <|> t₂ e
namespace instance_cache
/-- Faster version of `mk_app ``bit0 [e]`. -/
meta def mk_bit0 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) :=
do (c, ai) ← c.get ``has_add,
return (c, (expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])
/-- Faster version of `mk_app ``bit1 [e]`. -/
meta def mk_bit1 (c : instance_cache) (e : expr) : tactic (instance_cache × expr) :=
do (c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
return (c, (expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
end instance_cache
end tactic
open tactic
namespace norm_num
variable {α : Type u}
lemma subst_into_add {α} [has_add α] (l r tl tr t)
(prl : (l : α) = tl) (prr : r = tr) (prt : tl + tr = t) : l + r = t :=
by rw [prl, prr, prt]
lemma subst_into_mul {α} [has_mul α] (l r tl tr t)
(prl : (l : α) = tl) (prr : r = tr) (prt : tl * tr = t) : l * r = t :=
by rw [prl, prr, prt]
lemma subst_into_neg {α} [has_neg α] (a ta t : α) (pra : a = ta) (prt : -ta = t) : -a = t :=
by simp [pra, prt]
/-- The result type of `match_numeral`, either `0`, `1`, or a top level
decomposition of `bit0 e` or `bit1 e`. The `other` case means it is not a numeral. -/
meta inductive match_numeral_result
| zero | one | bit0 (e : expr) | bit1 (e : expr) | other
/-- Unfold the top level constructor of the numeral expression. -/
meta def match_numeral : expr → match_numeral_result
| `(bit0 %%e) := match_numeral_result.bit0 e
| `(bit1 %%e) := match_numeral_result.bit1 e
| `(@has_zero.zero _ _) := match_numeral_result.zero
| `(@has_one.one _ _) := match_numeral_result.one
| _ := match_numeral_result.other
theorem zero_succ {α} [semiring α] : (0 + 1 : α) = 1 := zero_add _
theorem one_succ {α} [semiring α] : (1 + 1 : α) = 2 := rfl
theorem bit0_succ {α} [semiring α] (a : α) : bit0 a + 1 = bit1 a := rfl
theorem bit1_succ {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 = bit0 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`, `b` natural numerals, proves `⊢ a + 1 = b`, assuming that this is provable.
(It may prove garbage instead of failing if `a + 1 = b` is false.) -/
meta def prove_succ : instance_cache → expr → expr → tactic (instance_cache × expr)
| c e r := match match_numeral e with
| zero := c.mk_app ``zero_succ []
| one := c.mk_app ``one_succ []
| bit0 e := c.mk_app ``bit0_succ [e]
| bit1 e := do
let r := r.app_arg,
(c, p) ← prove_succ c e r,
c.mk_app ``bit1_succ [e, r, p]
| _ := failed
end
end
theorem zero_adc {α} [semiring α] (a b : α) (h : a + 1 = b) : 0 + a + 1 = b := by rwa zero_add
theorem adc_zero {α} [semiring α] (a b : α) (h : a + 1 = b) : a + 0 + 1 = b := by rwa add_zero
theorem one_add {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + a = b := by rwa add_comm
theorem add_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b = bit0 c :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem add_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit1 b = bit1 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_assoc]
theorem add_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit1 a + bit0 b = bit1 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_comm]
theorem add_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b = bit0 c :=
h ▸ by simp [bit0, bit1, add_left_comm, add_comm]
theorem adc_one_one {α} [semiring α] : (1 + 1 + 1 : α) = 3 := rfl
theorem adc_bit0_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit0 a + 1 + 1 = bit0 b :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem adc_one_bit0 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit0 a + 1 = bit0 b :=
h ▸ by simp [bit0, add_left_comm, add_assoc]
theorem adc_bit1_one {α} [semiring α] (a b : α) (h : a + 1 = b) : bit1 a + 1 + 1 = bit1 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_one_bit1 {α} [semiring α] (a b : α) (h : a + 1 = b) : 1 + bit1 a + 1 = bit1 b :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit0 {α} [semiring α] (a b c : α) (h : a + b = c) : bit0 a + bit0 b + 1 = bit1 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit0 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit0 b + 1 = bit0 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit0_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit0 a + bit1 b + 1 = bit0 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
theorem adc_bit1_bit1 {α} [semiring α] (a b c : α) (h : a + b + 1 = c) : bit1 a + bit1 b + 1 = bit1 c :=
h ▸ by simp [bit1, bit0, add_left_comm, add_assoc]
section
open match_numeral_result
meta mutual def prove_add_nat, prove_adc_nat
with prove_add_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := c.mk_app ``zero_add [b]
| _, zero := c.mk_app ``add_zero [a]
| _, one := prove_succ c a r
| one, _ := do (c, p) ← prove_succ c b r, c.mk_app ``one_add [b, r, p]
| bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``add_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``add_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
with prove_adc_nat : instance_cache → expr → expr → expr → tactic (instance_cache × expr)
| c a b r := do
match match_numeral a, match_numeral b with
| zero, _ := do (c, p) ← prove_succ c b r, c.mk_app ``zero_adc [b, r, p]
| _, zero := do (c, p) ← prove_succ c b r, c.mk_app ``adc_zero [b, r, p]
| one, one := c.mk_app ``adc_one_one []
| bit0 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit0_one [a, r, p]
| one, bit0 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit0 [b, r, p]
| bit1 a, one := do let r := r.app_arg, (c, p) ← prove_succ c a r, c.mk_app ``adc_bit1_one [a, r, p]
| one, bit1 b := do let r := r.app_arg, (c, p) ← prove_succ c b r, c.mk_app ``adc_one_bit1 [b, r, p]
| bit0 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_add_nat c a b r, c.mk_app ``adc_bit0_bit0 [a, b, r, p]
| bit0 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit0_bit1 [a, b, r, p]
| bit1 a, bit0 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit0 [a, b, r, p]
| bit1 a, bit1 b := do let r := r.app_arg, (c, p) ← prove_adc_nat c a b r, c.mk_app ``adc_bit1_bit1 [a, b, r, p]
| _, _ := failed
end
/-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b = r`. -/
add_decl_doc prove_add_nat
/-- Given `a`,`b`,`r` natural numerals, proves `⊢ a + b + 1 = r`. -/
add_decl_doc prove_adc_nat
/-- Given `a`,`b` natural numerals, returns `(r, ⊢ a + b = r)`. -/
meta def prove_add_nat' (c : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do
na ← a.to_nat,
nb ← b.to_nat,
(c, r) ← c.of_nat (na + nb),
(c, p) ← prove_add_nat c a b r,
return (c, r, p)
end
theorem bit0_mul {α} [semiring α] (a b c : α) (h : a * b = c) :
bit0 a * b = bit0 c := h ▸ by simp [bit0, add_mul]
theorem mul_bit0' {α} [semiring α] (a b c : α) (h : a * b = c) :
a * bit0 b = bit0 c := h ▸ by simp [bit0, mul_add]
theorem mul_bit0_bit0 {α} [semiring α] (a b c : α) (h : a * b = c) :
bit0 a * bit0 b = bit0 (bit0 c) := bit0_mul _ _ _ (mul_bit0' _ _ _ h)
theorem mul_bit1_bit1 {α} [semiring α] (a b c d e : α)
(hc : a * b = c) (hd : a + b = d) (he : bit0 c + d = e) :
bit1 a * bit1 b = bit1 e :=
by rw [← he, ← hd, ← hc]; simp [bit1, bit0, mul_add, add_mul, add_left_comm, add_assoc]
section
open match_numeral_result
/-- Given `a`,`b` natural numerals, returns `(r, ⊢ a * b = r)`. -/
meta def prove_mul_nat : instance_cache → expr → expr → tactic (instance_cache × expr × expr)
| ic a b :=
match match_numeral a, match_numeral b with
| zero, _ := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, zero := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``mul_zero [a],
return (ic, z, p)
| one, _ := do (ic, p) ← ic.mk_app ``one_mul [b], return (ic, b, p)
| _, one := do (ic, p) ← ic.mk_app ``mul_one [a], return (ic, a, p)
| bit0 a, bit0 b := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``mul_bit0_bit0 [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
(ic, c') ← ic.mk_bit0 c',
return (ic, c', p)
| bit0 a, _ := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``bit0_mul [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
return (ic, c', p)
| _, bit0 b := do
(ic, c, p) ← prove_mul_nat ic a b,
(ic, p) ← ic.mk_app ``mul_bit0' [a, b, c, p],
(ic, c') ← ic.mk_bit0 c,
return (ic, c', p)
| bit1 a, bit1 b := do
(ic, c, pc) ← prove_mul_nat ic a b,
(ic, d, pd) ← prove_add_nat' ic a b,
(ic, c') ← ic.mk_bit0 c,
(ic, e, pe) ← prove_add_nat' ic c' d,
(ic, p) ← ic.mk_app ``mul_bit1_bit1 [a, b, c, d, e, pc, pd, pe],
(ic, e') ← ic.mk_bit1 e,
return (ic, e', p)
| _, _ := failed
end
end
section
open match_numeral_result
/-- Given `a` a positive natural numeral, returns `⊢ 0 < a`. -/
meta def prove_pos_nat (c : instance_cache) : expr → tactic (instance_cache × expr)
| e :=
match match_numeral e with
| one := c.mk_app ``zero_lt_one []
| bit0 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit0_pos [e, p]
| bit1 e := do (c, p) ← prove_pos_nat e, c.mk_app ``bit1_pos' [e, p]
| _ := failed
end
end
/-- Given `a` a rational numeral, returns `⊢ 0 < a`. -/
meta def prove_pos (c : instance_cache) : expr → tactic (instance_cache × expr)
| `(%%e₁ / %%e₂) := do
(c, p₁) ← prove_pos_nat c e₁, (c, p₂) ← prove_pos_nat c e₂,
c.mk_app ``div_pos [e₁, e₂, p₁, p₂]
| e := prove_pos_nat c e
/-- `match_neg (- e) = some e`, otherwise `none` -/
meta def match_neg : expr → option expr
| `(- %%e) := some e
| _ := none
/-- `match_sign (- e) = inl e`, `match_sign 0 = inr ff`, otherwise `inr tt` -/
meta def match_sign : expr → expr ⊕ bool
| `(- %%e) := sum.inl e
| `(has_zero.zero) := sum.inr ff
| _ := sum.inr tt
theorem ne_zero_of_pos {α} [ordered_add_comm_group α] (a : α) : 0 < a → a ≠ 0 := ne_of_gt
theorem ne_zero_neg {α} [add_group α] (a : α) : a ≠ 0 → -a ≠ 0 := mt neg_eq_zero.1
/-- Given `a` a rational numeral, returns `⊢ a ≠ 0`. -/
meta def prove_ne_zero (c : instance_cache) : expr → tactic (instance_cache × expr)
| a :=
match match_neg a with
| some a := do (c, p) ← prove_ne_zero a, c.mk_app ``ne_zero_neg [a, p]
| none := do (c, p) ← prove_pos c a, c.mk_app ``ne_zero_of_pos [a, p]
end
theorem clear_denom_div {α} [division_ring α] (a b b' c d : α)
(h₀ : b ≠ 0) (h₁ : b * b' = d) (h₂ : a * b' = c) : (a / b) * d = c :=
by rwa [← h₁, ← mul_assoc, div_mul_cancel _ h₀]
/-- Given `a` nonnegative rational and `d` a natural number, returns `(b, ⊢ a * d = b)`.
(`d` should be a multiple of the denominator of `a`, so that `b` is a natural number.) -/
meta def prove_clear_denom (c : instance_cache) (a d : expr) (na : ℚ) (nd : ℕ) : tactic (instance_cache × expr × expr) :=
if na.denom = 1 then
prove_mul_nat c a d
else do
[_, _, a, b] ← return a.get_app_args,
(c, b') ← c.of_nat (nd / na.denom),
(c, p₀) ← prove_ne_zero c b,
(c, _, p₁) ← prove_mul_nat c b b',
(c, r, p₂) ← prove_mul_nat c a b',
(c, p) ← c.mk_app ``clear_denom_div [a, b, b', r, d, p₀, p₁, p₂],
return (c, r, p)
theorem clear_denom_add {α} [division_ring α] (a a' b b' c c' d : α)
(h₀ : d ≠ 0) (ha : a * d = a') (hb : b * d = b') (hc : c * d = c')
(h : a' + b' = c') : a + b = c :=
mul_right_cancel' h₀ $ by rwa [add_mul, ha, hb, hc]
/-- Given `a`,`b`,`c` nonnegative rational numerals, returns `⊢ a + b = c`. -/
meta def prove_add_nonneg_rat (ic : instance_cache) (a b c : expr) (na nb nc : ℚ) : tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_add_nat ic a b c
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_ne_zero ic d,
(ic, a', pa) ← prove_clear_denom ic a d na nd,
(ic, b', pb) ← prove_clear_denom ic b d nb nd,
(ic, c', pc) ← prove_clear_denom ic c d nc nd,
(ic, p) ← prove_add_nat ic a' b' c',
ic.mk_app ``clear_denom_add [a, a', b, b', c, c', d, p₀, pa, pb, pc, p]
theorem add_pos_neg_pos {α} [add_group α] (a b c : α) (h : c + b = a) : a + -b = c :=
h ▸ by simp
theorem add_pos_neg_neg {α} [add_group α] (a b c : α) (h : c + a = b) : a + -b = -c :=
h ▸ by simp
theorem add_neg_pos_pos {α} [add_group α] (a b c : α) (h : a + c = b) : -a + b = c :=
h ▸ by simp
theorem add_neg_pos_neg {α} [add_group α] (a b c : α) (h : b + c = a) : -a + b = -c :=
h ▸ by simp
theorem add_neg_neg {α} [add_group α] (a b c : α) (h : b + a = c) : -a + -b = -c :=
h ▸ by simp
/-- Given `a`,`b`,`c` rational numerals, returns `⊢ a + b = c`. -/
meta def prove_add_rat (ic : instance_cache) (ea eb ec : expr) (a b c : ℚ) : tactic (instance_cache × expr) :=
match match_neg ea, match_neg eb, match_neg ec with
| some ea, some eb, some ec := do
(ic, p) ← prove_add_nonneg_rat ic eb ea ec (-b) (-a) (-c),
ic.mk_app ``add_neg_neg [ea, eb, ec, p]
| some ea, none, some ec := do
(ic, p) ← prove_add_nonneg_rat ic eb ec ea b (-c) (-a),
ic.mk_app ``add_neg_pos_neg [ea, eb, ec, p]
| some ea, none, none := do
(ic, p) ← prove_add_nonneg_rat ic ea ec eb (-a) c b,
ic.mk_app ``add_neg_pos_pos [ea, eb, ec, p]
| none, some eb, some ec := do
(ic, p) ← prove_add_nonneg_rat ic ec ea eb (-c) a (-b),
ic.mk_app ``add_pos_neg_neg [ea, eb, ec, p]
| none, some eb, none := do
(ic, p) ← prove_add_nonneg_rat ic ec eb ea c (-b) a,
ic.mk_app ``add_pos_neg_pos [ea, eb, ec, p]
| _, _, _ := prove_add_nonneg_rat ic ea eb ec a b c
end
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a + b = c)`. -/
meta def prove_add_rat' (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) := do
na ← a.to_rat,
nb ← b.to_rat,
let nc := na + nb,
(ic, c) ← ic.of_rat nc,
(ic, p) ← prove_add_rat ic a b c na nb nc,
return (ic, c, p)
theorem clear_denom_simple_nat {α} [division_ring α] (a : α) :
(1:α) ≠ 0 ∧ a * 1 = a := ⟨one_ne_zero, mul_one _⟩
theorem clear_denom_simple_div {α} [division_ring α] (a b : α) (h : b ≠ 0) :
b ≠ 0 ∧ a / b * b = a := ⟨h, div_mul_cancel _ h⟩
/-- Given `a` a nonnegative rational numeral, returns `(b, c, ⊢ a * b = c)`
where `b` and `c` are natural numerals. (`b` will be the denominator of `a`.) -/
meta def prove_clear_denom_simple (c : instance_cache) (a : expr) (na : ℚ) : tactic (instance_cache × expr × expr × expr) :=
if na.denom = 1 then do
(c, d) ← c.mk_app ``has_one.one [],
(c, p) ← c.mk_app ``clear_denom_simple_nat [a],
return (c, d, a, p)
else do
[α, _, a, b] ← return a.get_app_args,
(c, p₀) ← prove_ne_zero c b,
(c, p) ← c.mk_app ``clear_denom_simple_div [a, b, p₀],
return (c, b, a, p)
theorem clear_denom_mul {α} [field α] (a a' b b' c c' d₁ d₂ d : α)
(ha : d₁ ≠ 0 ∧ a * d₁ = a') (hb : d₂ ≠ 0 ∧ b * d₂ = b')
(hc : c * d = c') (hd : d₁ * d₂ = d)
(h : a' * b' = c') : a * b = c :=
mul_right_cancel' ha.1 $ mul_right_cancel' hb.1 $
by rw [mul_assoc c, hd, hc, ← h, ← ha.2, ← hb.2, ← mul_assoc, mul_right_comm a]
/-- Given `a`,`b` nonnegative rational numerals, returns `(c, ⊢ a * b = c)`. -/
meta def prove_mul_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_mul_nat ic a b
else do
let nc := na * nb, (ic, c) ← ic.of_rat nc,
(ic, d₁, a', pa) ← prove_clear_denom_simple ic a na,
(ic, d₂, b', pb) ← prove_clear_denom_simple ic b nb,
(ic, d, pd) ← prove_mul_nat ic d₁ d₂, nd ← d.to_nat,
(ic, c', pc) ← prove_clear_denom ic c d nc nd,
(ic, _, p) ← prove_mul_nat ic a' b',
(ic, p) ← ic.mk_app ``clear_denom_mul [a, a', b, b', c, c', d₁, d₂, d, pa, pb, pc, pd, p],
return (ic, c, p)
theorem mul_neg_pos {α} [ring α] (a b c : α) (h : a * b = c) : -a * b = -c := h ▸ by simp
theorem mul_pos_neg {α} [ring α] (a b c : α) (h : a * b = c) : a * -b = -c := h ▸ by simp
theorem mul_neg_neg {α} [ring α] (a b c : α) (h : a * b = c) : -a * -b = c := h ▸ by simp
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a * b = c)`. -/
meta def prove_mul_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) (-nb),
(ic, p) ← ic.mk_app ``mul_neg_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff, _ := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``zero_mul [b],
return (ic, z, p)
| _, sum.inr ff := do
(ic, z) ← ic.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``mul_zero [a],
return (ic, z, p)
| sum.inl a, sum.inr tt := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b (-na) nb,
(ic, p) ← ic.mk_app ``mul_neg_pos [a, b, c, p],
(ic, c') ← ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inl b := do
(ic, c, p) ← prove_mul_nonneg_rat ic a b na (-nb),
(ic, p) ← ic.mk_app ``mul_pos_neg [a, b, c, p],
(ic, c') ← ic.mk_app ``has_neg.neg [c],
return (ic, c', p)
| sum.inr tt, sum.inr tt := prove_mul_nonneg_rat ic a b na nb
end
theorem inv_neg {α} [division_ring α] (a b : α) (h : a⁻¹ = b) : (-a)⁻¹ = -b :=
h ▸ by simp only [inv_eq_one_div, one_div_neg_eq_neg_one_div]
theorem inv_one {α} [division_ring α] : (1 : α)⁻¹ = 1 := inv_one
theorem inv_one_div {α} [division_ring α] (a : α) : (1 / a)⁻¹ = a :=
by rw [one_div, inv_inv']
theorem inv_div_one {α} [division_ring α] (a : α) : a⁻¹ = 1 / a :=
inv_eq_one_div _
theorem inv_div {α} [division_ring α] (a b : α) : (a / b)⁻¹ = b / a :=
by simp only [inv_eq_one_div, one_div_div]
/-- Given `a` a rational numeral, returns `(b, ⊢ a⁻¹ = b)`. -/
meta def prove_inv : instance_cache → expr → ℚ → tactic (instance_cache × expr × expr)
| ic e n :=
match match_sign e with
| sum.inl e := do
(ic, e', p) ← prove_inv ic e (-n),
(ic, r) ← ic.mk_app ``has_neg.neg [e'],
(ic, p) ← ic.mk_app ``inv_neg [e, e', p],
return (ic, r, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``inv_zero [],
return (ic, e, p)
| sum.inr tt :=
if n.num = 1 then
if n.denom = 1 then do
(ic, p) ← ic.mk_app ``inv_one [],
return (ic, e, p)
else do
let e := e.app_arg,
(ic, p) ← ic.mk_app ``inv_one_div [e],
return (ic, e, p)
else if n.denom = 1 then do
(ic, p) ← ic.mk_app ``inv_div_one [e],
e ← infer_type p,
return (ic, e.app_arg, p)
else do
[_, _, a, b] ← return e.get_app_args,
(ic, e') ← ic.mk_app ``has_div.div [b, a],
(ic, p) ← ic.mk_app ``inv_div [a, b],
return (ic, e', p)
end
theorem div_eq {α} [division_ring α] (a b b' c : α)
(hb : b⁻¹ = b') (h : a * b' = c) : a / b = c := by rwa ← hb at h
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a / b = c)`. -/
meta def prove_div (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr × expr) :=
do (ic, b', pb) ← prove_inv ic b nb,
(ic, c, p) ← prove_mul_rat ic a b' na nb⁻¹,
(ic, p) ← ic.mk_app ``div_eq [a, b, b', c, pb, p],
return (ic, c, p)
/-- Given `a` a rational numeral, returns `(b, ⊢ -a = b)`. -/
meta def prove_neg (ic : instance_cache) (a : expr) : tactic (instance_cache × expr × expr) :=
match match_sign a with
| sum.inl a := do
(ic, p) ← ic.mk_app ``neg_neg [a],
return (ic, a, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``neg_zero [],
return (ic, a, p)
| sum.inr tt := do
(ic, a') ← ic.mk_app ``has_neg.neg [a],
p ← mk_eq_refl a',
return (ic, a', p)
end
theorem sub_pos {α} [add_group α] (a b b' c : α) (hb : -b = b') (h : a + b' = c) : a - b = c :=
by rwa ← hb at h
theorem sub_neg {α} [add_group α] (a b c : α) (h : a + b = c) : a - -b = c :=
by rwa sub_neg_eq_add
/-- Given `a`,`b` rational numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub (ic : instance_cache) (a b : expr) : tactic (instance_cache × expr × expr) :=
match match_sign b with
| sum.inl b := do
(ic, c, p) ← prove_add_rat' ic a b,
(ic, p) ← ic.mk_app ``sub_neg [a, b, c, p],
return (ic, c, p)
| sum.inr ff := do
(ic, p) ← ic.mk_app ``sub_zero [a],
return (ic, a, p)
| sum.inr tt := do
(ic, b', pb) ← prove_neg ic b,
(ic, c, p) ← prove_add_rat' ic a b',
(ic, p) ← ic.mk_app ``sub_pos [a, b, b', c, pb, p],
return (ic, c, p)
end
theorem sub_nat_pos (a b c : ℕ) (h : b + c = a) : a - b = c :=
h ▸ nat.add_sub_cancel_left _ _
theorem sub_nat_neg (a b c : ℕ) (h : a + c = b) : a - b = 0 :=
nat.sub_eq_zero_of_le $ h ▸ nat.le_add_right _ _
/-- Given `a : nat`,`b : nat` natural numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub_nat (ic : instance_cache) (a b : expr) : tactic (expr × expr) :=
do na ← a.to_nat, nb ← b.to_nat,
if nb ≤ na then do
(ic, c) ← ic.of_nat (na - nb),
(ic, p) ← prove_add_nat ic b c a,
return (c, `(sub_nat_pos).mk_app [a, b, c, p])
else do
(ic, c) ← ic.of_nat (nb - na),
(ic, p) ← prove_add_nat ic a c b,
return (`(0 : ℕ), `(sub_nat_neg).mk_app [a, b, c, p])
/-- This is needed because when `a` and `b` are numerals lean is more likely to unfold them
than unfold the instances in order to prove that `add_group_has_sub = int.has_sub`. -/
theorem int_sub_hack (a b c : ℤ) (h : @has_sub.sub ℤ add_group_has_sub a b = c) : a - b = c := h
/-- Given `a : ℤ`, `b : ℤ` integral numerals, returns `(c, ⊢ a - b = c)`. -/
meta def prove_sub_int (ic : instance_cache) (a b : expr) : tactic (expr × expr) :=
do (_, c, p) ← prove_sub ic a b,
return (c, `(int_sub_hack).mk_app [a, b, c, p])
/-- Evaluates the basic field operations `+`,`neg`,`-`,`*`,`inv`,`/` on numerals.
Also handles nat subtraction. Does not do recursive simplification; that is,
`1 + 1 + 1` will not simplify but `2 + 1` will. This is handled by the top level
`simp` call in `norm_num.derive`. -/
meta def eval_field : expr → tactic (expr × expr)
| `(%%e₁ + %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
let n₃ := n₁ + n₂,
(c, e₃) ← c.of_rat n₃,
(_, p) ← prove_add_rat c e₁ e₂ e₃ n₁ n₂ n₃,
return (e₃, p)
| `(%%e₁ * %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_mul_rat c e₁ e₂ n₁ n₂
| `(- %%e) := do
c ← infer_type e >>= mk_instance_cache,
prod.snd <$> prove_neg c e
| `(@has_sub.sub %%α %%inst %%a %%b) := do
c ← mk_instance_cache α,
if α = `(nat) then prove_sub_nat c a b
else if inst = `(int.has_sub) then prove_sub_int c a b
else prod.snd <$> prove_sub c a b
| `(has_inv.inv %%e) := do
n ← e.to_rat,
c ← infer_type e >>= mk_instance_cache,
prod.snd <$> prove_inv c e n
| `(%%e₁ / %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_div c e₁ e₂ n₁ n₂
| _ := failed
lemma pow_bit0 [monoid α] (a c' c : α) (b : ℕ)
(h : a ^ b = c') (h₂ : c' * c' = c) : a ^ bit0 b = c :=
h₂ ▸ by simp [pow_bit0, h]
lemma pow_bit1 [monoid α] (a c₁ c₂ c : α) (b : ℕ)
(h : a ^ b = c₁) (h₂ : c₁ * c₁ = c₂) (h₃ : c₂ * a = c) : a ^ bit1 b = c :=
by rw [← h₃, ← h₂]; simp [pow_bit1, h]
section
open match_numeral_result
/-- Given `a` a rational numeral and `b : nat`, returns `(c, ⊢ a ^ b = c)`. -/
meta def prove_pow (a : expr) (na : ℚ) : instance_cache → expr → tactic (instance_cache × expr × expr)
| ic b :=
match match_numeral b with
| zero := do
(ic, p) ← ic.mk_app ``pow_zero [a],
(ic, o) ← ic.mk_app ``has_one.one [],
return (ic, o, p)
| one := do
(ic, p) ← ic.mk_app ``pow_one [a],
return (ic, a, p)
| bit0 b := do
(ic, c', p) ← prove_pow ic b,
nc' ← expr.to_rat c',
(ic, c, p₂) ← prove_mul_rat ic c' c' nc' nc',
(ic, p) ← ic.mk_app ``pow_bit0 [a, c', c, b, p, p₂],
return (ic, c, p)
| bit1 b := do
(ic, c₁, p) ← prove_pow ic b,
nc₁ ← expr.to_rat c₁,
(ic, c₂, p₂) ← prove_mul_rat ic c₁ c₁ nc₁ nc₁,
(ic, c, p₃) ← prove_mul_rat ic c₂ a (nc₁ * nc₁) na,
(ic, p) ← ic.mk_app ``pow_bit1 [a, c₁, c₂, c, b, p, p₂, p₃],
return (ic, c, p)
| _ := failed
end
end
/-- Evaluates expressions of the form `a ^ b`, `monoid.pow a b` or `nat.pow a b`. -/
meta def eval_pow : expr → tactic (expr × expr)
| `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
match m with
| `(@monoid.has_pow %%_ %%_) := prod.snd <$> prove_pow e₁ n₁ c e₂
| _ := failed
end
| `(monoid.pow %%e₁ %%e₂) := do
n₁ ← e₁.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
prod.snd <$> prove_pow e₁ n₁ c e₂
| _ := failed
theorem nonneg_pos {α} [ordered_cancel_add_comm_monoid α] (a : α) : 0 < a → 0 ≤ a := le_of_lt
theorem lt_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 < bit0 a :=
lt_of_lt_of_le one_lt_two (bit0_le_bit0.2 h)
theorem lt_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 < bit1 a :=
one_lt_bit1.2 h
theorem lt_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit0 a < bit0 b := bit0_lt_bit0.2
theorem lt_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a < bit1 b :=
lt_of_le_of_lt (bit0_le_bit0.2 h) (lt_add_one _)
theorem lt_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a < bit0 b :=
lt_of_lt_of_le (by simp [bit0, bit1, zero_lt_one, add_assoc]) (bit0_le_bit0.2 h)
theorem lt_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a < b → bit1 a < bit1 b := bit1_lt_bit1.2
theorem le_one_bit0 {α} [linear_ordered_semiring α] (a : α) (h : 1 ≤ a) : 1 ≤ bit0 a :=
le_of_lt (lt_one_bit0 _ h)
-- deliberately strong hypothesis because bit1 0 is not a numeral
theorem le_one_bit1 {α} [linear_ordered_semiring α] (a : α) (h : 0 < a) : 1 ≤ bit1 a :=
le_of_lt (lt_one_bit1 _ h)
theorem le_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit0 a ≤ bit0 b := bit0_le_bit0.2
theorem le_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a ≤ bit1 b :=
le_of_lt (lt_bit0_bit1 _ _ h)
theorem le_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a ≤ bit0 b :=
le_of_lt (lt_bit1_bit0 _ _ h)
theorem le_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) : a ≤ b → bit1 a ≤ bit1 b := bit1_le_bit1.2
theorem sle_one_bit0 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit0 a := bit0_le_bit0.2
theorem sle_one_bit1 {α} [linear_ordered_semiring α] (a : α) : 1 ≤ a → 1 + 1 ≤ bit1 a := le_bit0_bit1 _ _
theorem sle_bit0_bit0 {α} [linear_ordered_semiring α] (a b : α) : a + 1 ≤ b → bit0 a + 1 ≤ bit0 b := le_bit1_bit0 _ _
theorem sle_bit0_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a ≤ b) : bit0 a + 1 ≤ bit1 b := bit1_le_bit1.2 h
theorem sle_bit1_bit0 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit0 b :=
(bit1_succ a _ rfl).symm ▸ bit0_le_bit0.2 h
theorem sle_bit1_bit1 {α} [linear_ordered_semiring α] (a b : α) (h : a + 1 ≤ b) : bit1 a + 1 ≤ bit1 b :=
(bit1_succ a _ rfl).symm ▸ le_bit0_bit1 _ _ h
/-- Given `a` a rational numeral, returns `⊢ 0 ≤ a`. -/
meta def prove_nonneg (ic : instance_cache) : expr → tactic (instance_cache × expr)
| e@`(has_zero.zero) := ic.mk_app ``le_refl [e]
| e :=
if ic.α = `(ℕ) then
return (ic, `(nat.zero_le).mk_app [e])
else do
(ic, p) ← prove_pos ic e,
ic.mk_app ``nonneg_pos [e, p]
section
open match_numeral_result
/-- Given `a` a rational numeral, returns `⊢ 1 ≤ a`. -/
meta def prove_one_le_nat (ic : instance_cache) : expr → tactic (instance_cache × expr)
| a :=
match match_numeral a with
| one := ic.mk_app ``le_refl [a]
| bit0 a := do (ic, p) ← prove_one_le_nat a, ic.mk_app ``le_one_bit0 [a, p]
| bit1 a := do (ic, p) ← prove_pos_nat ic a, ic.mk_app ``le_one_bit1 [a, p]
| _ := failed
end
meta mutual def prove_le_nat, prove_sle_nat (ic : instance_cache)
with prove_le_nat : expr → expr → tactic (instance_cache × expr)
| a b :=
if a = b then ic.mk_app ``le_refl [a] else
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``le_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``le_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``le_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``le_bit1_bit1 [a, b, p]
| _, _ := failed
end
with prove_sle_nat : expr → expr → tactic (instance_cache × expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_nonneg ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``sle_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat a b, ic.mk_app ``sle_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_sle_nat a b, ic.mk_app ``sle_bit1_bit1 [a, b, p]
| _, _ := failed
end
/-- Given `a`,`b` natural numerals, proves `⊢ a ≤ b`. -/
add_decl_doc prove_le_nat
/-- Given `a`,`b` natural numerals, proves `⊢ a + 1 ≤ b`. -/
add_decl_doc prove_sle_nat
/-- Given `a`,`b` natural numerals, proves `⊢ a < b`. -/
meta def prove_lt_nat (ic : instance_cache) : expr → expr → tactic (instance_cache × expr)
| a b :=
match match_numeral a, match_numeral b with
| zero, _ := prove_pos ic b
| one, bit0 b := do (ic, p) ← prove_one_le_nat ic b, ic.mk_app ``lt_one_bit0 [b, p]
| one, bit1 b := do (ic, p) ← prove_pos_nat ic b, ic.mk_app ``lt_one_bit1 [b, p]
| bit0 a, bit0 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit0_bit0 [a, b, p]
| bit0 a, bit1 b := do (ic, p) ← prove_le_nat ic a b, ic.mk_app ``lt_bit0_bit1 [a, b, p]
| bit1 a, bit0 b := do (ic, p) ← prove_sle_nat ic a b, ic.mk_app ``lt_bit1_bit0 [a, b, p]
| bit1 a, bit1 b := do (ic, p) ← prove_lt_nat a b, ic.mk_app ``lt_bit1_bit1 [a, b, p]
| _, _ := failed
end
end
theorem clear_denom_lt {α} [linear_ordered_semiring α] (a a' b b' d : α)
(h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' < b') : a < b :=
lt_of_mul_lt_mul_right (by rwa [ha, hb]) (le_of_lt h₀)
/-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a < b`. -/
meta def prove_lt_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_lt_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_pos ic d,
(ic, a', pa) ← prove_clear_denom ic a d na nd,
(ic, b', pb) ← prove_clear_denom ic b d nb nd,
(ic, p) ← prove_lt_nat ic a' b',
ic.mk_app ``clear_denom_lt [a, a', b, b', d, p₀, pa, pb, p]
lemma lt_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 < a) (hb : 0 < b) : -a < b :=
lt_trans (neg_neg_of_pos ha) hb
/-- Given `a`,`b` rational numerals, proves `⊢ a < b`. -/
meta def prove_lt_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, p) ← prove_lt_nonneg_rat ic a b (-na) (-nb),
ic.mk_app ``neg_lt_neg [a, b, p]
| sum.inl a, sum.inr ff := do
(ic, p) ← prove_pos ic a,
ic.mk_app ``neg_neg_of_pos [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) ← prove_pos ic a,
(ic, pb) ← prove_pos ic b,
ic.mk_app ``lt_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_pos ic b
| sum.inr tt, _ := prove_lt_nonneg_rat ic a b na nb
end
theorem clear_denom_le {α} [linear_ordered_semiring α] (a a' b b' d : α)
(h₀ : 0 < d) (ha : a * d = a') (hb : b * d = b') (h : a' ≤ b') : a ≤ b :=
le_of_mul_le_mul_right (by rwa [ha, hb]) h₀
/-- Given `a`,`b` nonnegative rational numerals, proves `⊢ a ≤ b`. -/
meta def prove_le_nonneg_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) :=
if na.denom = 1 ∧ nb.denom = 1 then
prove_le_nat ic a b
else do
let nd := na.denom.lcm nb.denom,
(ic, d) ← ic.of_nat nd,
(ic, p₀) ← prove_pos ic d,
(ic, a', pa) ← prove_clear_denom ic a d na nd,
(ic, b', pb) ← prove_clear_denom ic b d nb nd,
(ic, p) ← prove_le_nat ic a' b',
ic.mk_app ``clear_denom_le [a, a', b, b', d, p₀, pa, pb, p]
lemma le_neg_pos {α} [ordered_add_comm_group α] (a b : α) (ha : 0 ≤ a) (hb : 0 ≤ b) : -a ≤ b :=
le_trans (neg_nonpos_of_nonneg ha) hb
/-- Given `a`,`b` rational numerals, proves `⊢ a ≤ b`. -/
meta def prove_le_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) :=
match match_sign a, match_sign b with
| sum.inl a, sum.inl b := do
(ic, p) ← prove_le_nonneg_rat ic a b (-na) (-nb),
ic.mk_app ``neg_le_neg [a, b, p]
| sum.inl a, sum.inr ff := do
(ic, p) ← prove_nonneg ic a,
ic.mk_app ``neg_nonpos_of_nonneg [a, p]
| sum.inl a, sum.inr tt := do
(ic, pa) ← prove_nonneg ic a,
(ic, pb) ← prove_nonneg ic b,
ic.mk_app ``le_neg_pos [a, b, pa, pb]
| sum.inr ff, _ := prove_nonneg ic b
| sum.inr tt, _ := prove_le_nonneg_rat ic a b na nb
end
/-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. This version
tries to prove `⊢ a < b` or `⊢ b < a`, and so is not appropriate for types without an order relation. -/
meta def prove_ne_rat (ic : instance_cache) (a b : expr) (na nb : ℚ) : tactic (instance_cache × expr) :=
if na < nb then do
(ic, p) ← prove_lt_rat ic a b na nb,
ic.mk_app ``ne_of_lt [a, b, p]
else do
(ic, p) ← prove_lt_rat ic b a nb na,
ic.mk_app ``ne_of_gt [a, b, p]
theorem nat_cast_zero {α} [semiring α] : ↑(0 : ℕ) = (0 : α) := nat.cast_zero
theorem nat_cast_one {α} [semiring α] : ↑(1 : ℕ) = (1 : α) := nat.cast_one
theorem nat_cast_bit0 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ nat.cast_bit0 _
theorem nat_cast_bit1 {α} [semiring α] (a : ℕ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ nat.cast_bit1 _
theorem int_cast_zero {α} [ring α] : ↑(0 : ℤ) = (0 : α) := int.cast_zero
theorem int_cast_one {α} [ring α] : ↑(1 : ℤ) = (1 : α) := int.cast_one
theorem int_cast_bit0 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ int.cast_bit0 _
theorem int_cast_bit1 {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ int.cast_bit1 _
theorem rat_cast_bit0 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit0 a) = bit0 a' :=
h ▸ rat.cast_bit0 _
theorem rat_cast_bit1 {α} [division_ring α] [char_zero α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑(bit1 a) = bit1 a' :=
h ▸ rat.cast_bit1 _
/-- Given `a' : α` a natural numeral, returns `(a : ℕ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_nat_uncast (ic nc : instance_cache) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(nc, e) ← nc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``nat_cast_zero [],
return (ic, nc, e, p)
| match_numeral_result.one := do
(nc, e) ← nc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``nat_cast_one [],
return (ic, nc, e, p)
| match_numeral_result.bit0 a' := do
(ic, nc, a, p) ← prove_nat_uncast a',
(nc, a0) ← nc.mk_bit0 a,
(ic, p) ← ic.mk_app ``nat_cast_bit0 [a, a', p],
return (ic, nc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, nc, a, p) ← prove_nat_uncast a',
(nc, a1) ← nc.mk_bit1 a,
(ic, p) ← ic.mk_app ``nat_cast_bit1 [a, a', p],
return (ic, nc, a1, p)
| _ := failed
end
/-- Given `a' : α` a natural numeral, returns `(a : ℤ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast_nat (ic zc : instance_cache) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(zc, e) ← zc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``int_cast_zero [],
return (ic, zc, e, p)
| match_numeral_result.one := do
(zc, e) ← zc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``int_cast_one [],
return (ic, zc, e, p)
| match_numeral_result.bit0 a' := do
(ic, zc, a, p) ← prove_int_uncast_nat a',
(zc, a0) ← zc.mk_bit0 a,
(ic, p) ← ic.mk_app ``int_cast_bit0 [a, a', p],
return (ic, zc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, zc, a, p) ← prove_int_uncast_nat a',
(zc, a1) ← zc.mk_bit1 a,
(ic, p) ← ic.mk_app ``int_cast_bit1 [a, a', p],
return (ic, zc, a1, p)
| _ := failed
end
/-- Given `a' : α` a natural numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nat (ic qc : instance_cache) (cz_inst : expr) : ∀ (a' : expr),
tactic (instance_cache × instance_cache × expr × expr)
| a' :=
match match_numeral a' with
| match_numeral_result.zero := do
(qc, e) ← qc.mk_app ``has_zero.zero [],
(ic, p) ← ic.mk_app ``rat.cast_zero [cz_inst],
return (ic, qc, e, p)
| match_numeral_result.one := do
(qc, e) ← qc.mk_app ``has_one.one [],
(ic, p) ← ic.mk_app ``rat.cast_one [],
return (ic, qc, e, p)
| match_numeral_result.bit0 a' := do
(ic, qc, a, p) ← prove_rat_uncast_nat a',
(qc, a0) ← qc.mk_bit0 a,
(ic, p) ← ic.mk_app ``rat_cast_bit0 [cz_inst, a, a', p],
return (ic, qc, a0, p)
| match_numeral_result.bit1 a' := do
(ic, qc, a, p) ← prove_rat_uncast_nat a',
(qc, a1) ← qc.mk_bit1 a,
(ic, p) ← ic.mk_app ``rat_cast_bit1 [cz_inst, a, a', p],
return (ic, qc, a1, p)
| _ := failed
end
theorem rat_cast_div {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') : ↑(a / b) = a' / b' :=
ha ▸ hb ▸ rat.cast_div _ _
/-- Given `a' : α` a nonnegative rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast_nonneg (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) :
tactic (instance_cache × instance_cache × expr × expr) :=
if na'.denom = 1 then
prove_rat_uncast_nat ic qc cz_inst a'
else do
[_, _, a', b'] ← return a'.get_app_args,
(ic, qc, a, pa) ← prove_rat_uncast_nat ic qc cz_inst a',
(ic, qc, b, pb) ← prove_rat_uncast_nat ic qc cz_inst b',
(qc, e) ← qc.mk_app ``has_div.div [a, b],
(ic, p) ← ic.mk_app ``rat_cast_div [cz_inst, a, b, a', b', pa, pb],
return (ic, qc, e, p)
theorem int_cast_neg {α} [ring α] (a : ℤ) (a' : α) (h : ↑a = a') : ↑-a = -a' :=
h ▸ int.cast_neg _
theorem rat_cast_neg {α} [division_ring α] (a : ℚ) (a' : α) (h : ↑a = a') : ↑-a = -a' :=
h ▸ rat.cast_neg _
/-- Given `a' : α` an integer numeral, returns `(a : ℤ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_int_uncast (ic zc : instance_cache) (a' : expr) :
tactic (instance_cache × instance_cache × expr × expr) :=
match match_neg a' with
| some a' := do
(ic, zc, a, p) ← prove_int_uncast_nat ic zc a',
(zc, e) ← zc.mk_app ``has_neg.neg [a],
(ic, p) ← ic.mk_app ``int_cast_neg [a, a', p],
return (ic, zc, e, p)
| none := prove_int_uncast_nat ic zc a'
end
/-- Given `a' : α` a rational numeral, returns `(a : ℚ, ⊢ ↑a = a')`.
(Note that the returned value is on the left of the equality.) -/
meta def prove_rat_uncast (ic qc : instance_cache) (cz_inst a' : expr) (na' : ℚ) :
tactic (instance_cache × instance_cache × expr × expr) :=
match match_neg a' with
| some a' := do
(ic, qc, a, p) ← prove_rat_uncast_nonneg ic qc cz_inst a' (-na'),
(qc, e) ← qc.mk_app ``has_neg.neg [a],
(ic, p) ← ic.mk_app ``rat_cast_neg [a, a', p],
return (ic, qc, e, p)
| none := prove_rat_uncast_nonneg ic qc cz_inst a' na'
end
theorem nat_cast_ne {α} [semiring α] [char_zero α] (a b : ℕ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt nat.cast_inj.1 h
theorem int_cast_ne {α} [ring α] [char_zero α] (a b : ℤ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt int.cast_inj.1 h
theorem rat_cast_ne {α} [division_ring α] [char_zero α] (a b : ℚ) (a' b' : α)
(ha : ↑a = a') (hb : ↑b = b') (h : a ≠ b) : a' ≠ b' :=
ha ▸ hb ▸ mt rat.cast_inj.1 h
/-- Given `a`,`b` rational numerals, proves `⊢ a ≠ b`. Currently it tries two methods:
* Prove `⊢ a < b` or `⊢ b < a`, if the base type has an order
* Embed `↑(a':ℚ) = a` and `↑(b':ℚ) = b`, and then prove `a' ≠ b'`.
This requires that the base type be `char_zero`, and also that it be a `division_ring`
so that the coercion from `ℚ` is well defined.
We may also add coercions to `ℤ` and `ℕ` as well in order to support `char_zero`
rings and semirings. -/
meta def prove_ne : instance_cache → expr → expr → ℚ → ℚ → tactic (instance_cache × expr)
| ic a b na nb := prove_ne_rat ic a b na nb <|> do
cz_inst ← mk_mapp ``char_zero [ic.α, none, none] >>= mk_instance,
if na.denom = 1 ∧ nb.denom = 1 then
if na ≥ 0 ∧ nb ≥ 0 then do
guard (ic.α ≠ `(ℕ)),
nc ← mk_instance_cache `(ℕ),
(ic, nc, a', pa) ← prove_nat_uncast ic nc a,
(ic, nc, b', pb) ← prove_nat_uncast ic nc b,
(nc, p) ← prove_ne_rat nc a' b' na nb,
ic.mk_app ``nat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.α ≠ `(ℤ)),
zc ← mk_instance_cache `(ℤ),
(ic, zc, a', pa) ← prove_int_uncast ic zc a,
(ic, zc, b', pb) ← prove_int_uncast ic zc b,
(zc, p) ← prove_ne_rat zc a' b' na nb,
ic.mk_app ``int_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
else do
guard (ic.α ≠ `(ℚ)),
qc ← mk_instance_cache `(ℚ),
(ic, qc, a', pa) ← prove_rat_uncast ic qc cz_inst a na,
(ic, qc, b', pb) ← prove_rat_uncast ic qc cz_inst b nb,
(qc, p) ← prove_ne_rat qc a' b' na nb,
ic.mk_app ``rat_cast_ne [cz_inst, a', b', a, b, pa, pb, p]
/-- Given `∣- p`, returns `(true, ⊢ p = true)`. -/
meta def true_intro (p : expr) : tactic (expr × expr) :=
prod.mk `(true) <$> mk_app ``eq_true_intro [p]
/-- Given `∣- ¬ p`, returns `(false, ⊢ p = false)`. -/
meta def false_intro (p : expr) : tactic (expr × expr) :=
prod.mk `(false) <$> mk_app ``eq_false_intro [p]
theorem not_refl_false_intro {α} (a : α) : (a ≠ a) = false :=
eq_false_intro $ not_not_intro rfl
/-- Evaluates the inequality operations `=`,`<`,`>`,`≤`,`≥`,`≠` on numerals. -/
meta def eval_ineq : expr → tactic (expr × expr)
| `(%%e₁ < %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then
do (_, p) ← prove_lt_rat c e₁ e₂ n₁ n₂, true_intro p
else if n₁ = n₂ then do
(_, p) ← c.mk_app ``lt_irrefl [e₁],
false_intro p
else do
(c, p') ← prove_lt_rat c e₂ e₁ n₂ n₁,
(_, p) ← c.mk_app ``not_lt_of_gt [e₁, e₂, p'],
false_intro p
| `(%%e₁ ≤ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ ≤ n₂ then do
(_, p) ←
if n₁ = n₂ then c.mk_app ``le_refl [e₁]
else prove_le_rat c e₁ e₂ n₁ n₂,
true_intro p
else do
(c, p) ← prove_lt_rat c e₂ e₁ n₂ n₁,
(_, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p],
false_intro p
| `(%%e₁ = %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ = n₂ then mk_eq_refl e₁ >>= true_intro
else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, false_intro p
| `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= eval_ineq
| `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= eval_ineq
| `(%%e₁ ≠ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ = n₂ then
prod.mk `(false) <$> mk_app ``not_refl_false_intro [e₁]
else do (_, p) ← prove_ne c e₁ e₂ n₁ n₂, true_intro p
| _ := failed
theorem nat_succ_eq (a b c : ℕ) (h₁ : a = b) (h₂ : b + 1 = c) : nat.succ a = c := by rwa h₁
/-- Evaluates the expression `nat.succ ... (nat.succ n)` where `n` is a natural numeral.
(We could also just handle `nat.succ n` here and rely on `simp` to work bottom up, but we figure
that towers of successors coming from e.g. `induction` are a common case.) -/
meta def prove_nat_succ (ic : instance_cache) : expr → tactic (instance_cache × ℕ × expr × expr)
| `(nat.succ %%a) := do
(ic, n, b, p₁) ← prove_nat_succ a,
let n' := n + 1,
(ic, c) ← ic.of_nat n',
(ic, p₂) ← prove_add_nat ic b `(1) c,
return (ic, n', c, `(nat_succ_eq).mk_app [a, b, c, p₁, p₂])
| e := do
n ← e.to_nat,
p ← mk_eq_refl e,
return (ic, n, e, p)
lemma nat_div (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a / b = q :=
by rw [← h, ← hm, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂),
nat.div_eq_of_lt h₂, zero_add]
lemma int_div (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q :=
by rw [← h, ← hm, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)),
int.div_eq_zero_of_lt h₁ h₂, zero_add]
lemma nat_mod (a b q r m : ℕ) (hm : q * b = m) (h : r + m = a) (h₂ : r < b) : a % b = r :=
by rw [← h, ← hm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂]
lemma int_mod (a b q r m : ℤ) (hm : q * b = m) (h : r + m = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r :=
by rw [← h, ← hm, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂]
lemma int_div_neg (a b c' c : ℤ) (h : a / b = c') (h₂ : -c' = c) : a / -b = c :=
h₂ ▸ h ▸ int.div_neg _ _
lemma int_mod_neg (a b c : ℤ) (h : a % b = c) : a % -b = c :=
(int.mod_neg _ _).trans h
/-- Given `a`,`b` numerals in `nat` or `int`,
* `prove_div_mod ic a b ff` returns `(c, ⊢ a / b = c)`
* `prove_div_mod ic a b tt` returns `(c, ⊢ a % b = c)`
-/
meta def prove_div_mod (ic : instance_cache) : expr → expr → bool → tactic (instance_cache × expr × expr)
| a b mod :=
match match_neg b with
| some b := do
(ic, c', p) ← prove_div_mod a b mod,
if mod then
return (ic, c', `(int_mod_neg).mk_app [a, b, c', p])
else do
(ic, c, p₂) ← prove_neg ic c',
return (ic, c, `(int_div_neg).mk_app [a, b, c', c, p, p₂])
| none := do
nb ← b.to_nat,
na ← a.to_int,
let nq := na / nb,
let nr := na % nb,
let nm := nq * nr,
(ic, q) ← ic.of_int nq,
(ic, r) ← ic.of_int nr,
(ic, m, pm) ← prove_mul_rat ic q b (rat.of_int nq) (rat.of_int nb),
(ic, p) ← prove_add_rat ic r m a (rat.of_int nr) (rat.of_int nm) (rat.of_int na),
(ic, p') ← prove_lt_nat ic r b,
if ic.α = `(nat) then
if mod then return (ic, r, `(nat_mod).mk_app [a, b, q, r, m, pm, p, p'])
else return (ic, q, `(nat_div).mk_app [a, b, q, r, m, pm, p, p'])
else if ic.α = `(int) then do
(ic, p₀) ← prove_nonneg ic r,
if mod then return (ic, r, `(int_mod).mk_app [a, b, q, r, m, pm, p, p₀, p'])
else return (ic, q, `(int_div).mk_app [a, b, q, r, m, pm, p, p₀, p'])
else failed
end
theorem dvd_eq_nat (a b c : ℕ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p :=
(propext $ by rw [← h₁, nat.dvd_iff_mod_eq_zero]).trans h₂
theorem dvd_eq_int (a b c : ℤ) (p) (h₁ : b % a = c) (h₂ : (c = 0) = p) : (a ∣ b) = p :=
(propext $ by rw [← h₁, int.dvd_iff_mod_eq_zero]).trans h₂
/-- Evaluates some extra numeric operations on `nat` and `int`, specifically
`nat.succ`, `/` and `%`, and `∣` (divisibility). -/
meta def eval_nat_int_ext : expr → tactic (expr × expr)
| e@`(nat.succ _) := do
ic ← mk_instance_cache `(ℕ),
(_, _, ep) ← prove_nat_succ ic e,
return ep
| `(%%a / %%b) := do
c ← infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b ff
| `(%%a % %%b) := do
c ← infer_type a >>= mk_instance_cache,
prod.snd <$> prove_div_mod c a b tt
| `(%%a ∣ %%b) := do
α ← infer_type a,
ic ← mk_instance_cache α,
th ← if α = `(nat) then return (`(dvd_eq_nat):expr) else
if α = `(int) then return `(dvd_eq_int) else failed,
(ic, c, p₁) ← prove_div_mod ic b a tt,
(ic, z) ← ic.mk_app ``has_zero.zero [],
(e', p₂) ← mk_app ``eq [c, z] >>= eval_ineq,
return (e', th.mk_app [a, b, c, e', p₁, p₂])
| _ := failed
lemma not_prime_helper (a b n : ℕ)
(h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬ nat.prime n :=
by rw ← h; exact nat.not_prime_mul h₁ h₂
lemma is_prime_helper (n : ℕ)
(h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n :=
nat.prime_def_min_fac.2 ⟨h₁, h₂⟩
lemma min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = 2 :=
by simp [nat.min_fac_eq, show 2 ∣ bit0 n, by simp [bit0_eq_two_mul n]]
/-- A predicate representing partial progress in a proof of `min_fac`. -/
def min_fac_helper (n k : ℕ) : Prop :=
0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n)
theorem min_fac_helper.n_pos {n k : ℕ} (h : min_fac_helper n k) : 0 < n :=
nat.pos_iff_ne_zero.2 $ λ e,
by rw e at h; exact not_le_of_lt (nat.bit1_lt h.1) h.2
lemma min_fac_ne_bit0 {n k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k :=
by rw bit0_eq_two_mul; exact λ e, absurd
((nat.dvd_add_iff_right (by simp [bit0_eq_two_mul n])).2
(dvd_trans ⟨_, e⟩ (nat.min_fac_dvd _)))
dec_trivial
lemma min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 :=
begin
refine ⟨zero_lt_one, lt_of_le_of_ne _ min_fac_ne_bit0.symm⟩,
refine @lt_of_le_of_ne ℕ _ _ _ (nat.min_fac_pos _) _,
intro e,
have := nat.min_fac_prime _,
{ rw ← e at this, exact nat.not_prime_one this },
{ exact ne_of_gt (nat.bit1_lt h) }
end
lemma min_fac_helper_1 {n k k' : ℕ} (e : k + 1 = k')
(np : nat.min_fac (bit1 n) ≠ bit1 k)
(h : min_fac_helper n k) : min_fac_helper n k' :=
begin
rw ← e,
refine ⟨nat.succ_pos _,
(lt_of_le_of_ne (lt_of_le_of_ne _ _ : k+1+k < _)
min_fac_ne_bit0.symm : bit0 (k+1) < _)⟩,
{ rw add_right_comm, exact h.2 },
{ rw add_right_comm, exact np.symm }
end
lemma min_fac_helper_2 (n k k' : ℕ) (e : k + 1 = k')
(np : ¬ nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' :=
begin
refine min_fac_helper_1 e _ h,
intro e₁, rw ← e₁ at np,
exact np (nat.min_fac_prime $ ne_of_gt $ nat.bit1_lt h.n_pos)
end
lemma min_fac_helper_3 (n k k' c : ℕ) (e : k + 1 = k')
(nc : bit1 n % bit1 k = c) (c0 : 0 < c)
(h : min_fac_helper n k) : min_fac_helper n k' :=
begin
refine min_fac_helper_1 e _ h,
refine mt _ (ne_of_gt c0), intro e₁,
rw [← nc, ← nat.dvd_iff_mod_eq_zero, ← e₁],
apply nat.min_fac_dvd
end
lemma min_fac_helper_4 (n k : ℕ) (hd : bit1 n % bit1 k = 0)
(h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k :=
by rw ← nat.dvd_iff_mod_eq_zero at hd; exact
le_antisymm (nat.min_fac_le_of_dvd (nat.bit1_lt h.1) hd) h.2
lemma min_fac_helper_5 (n k k' : ℕ) (e : bit1 k * bit1 k = k')
(hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n :=
begin
refine (nat.prime_def_min_fac.1 (nat.prime_def_le_sqrt.2
⟨nat.bit1_lt h.n_pos, _⟩)).2,
rw ← e at hd,
intros m m2 hm md,
have := le_trans h.2 (le_trans (nat.min_fac_le_of_dvd m2 md) hm),
rw nat.le_sqrt at this,
exact not_le_of_lt hd this
end
/-- Given `e` a natural numeral and `d : nat` a factor of it, return `⊢ ¬ prime e`. -/
meta def prove_non_prime (e : expr) (n d₁ : ℕ) : tactic expr :=
do let e₁ := reflect d₁,
c ← mk_instance_cache `(nat),
(c, p₁) ← prove_lt_nat c `(1) e₁,
let d₂ := n / d₁, let e₂ := reflect d₂,
(c, e', p) ← prove_mul_nat c e₁ e₂,
guard (e' =ₐ e),
(c, p₂) ← prove_lt_nat c `(1) e₂,
return $ `(not_prime_helper).mk_app [e₁, e₂, e, p, p₁, p₂]
/-- Given `a`,`a1 := bit1 a`, `n1` the value of `a1`, `b` and `p : min_fac_helper a b`,
returns `(c, ⊢ min_fac a1 = c)`. -/
meta def prove_min_fac_aux (a a1 : expr) (n1 : ℕ) :
instance_cache → expr → expr → tactic (instance_cache × expr × expr)
| ic b p := do
k ← b.to_nat,
let k1 := bit1 k,
let b1 := `(bit1:ℕ→ℕ).mk_app [b],
if n1 < k1*k1 then do
(ic, e', p₁) ← prove_mul_nat ic b1 b1,
(ic, p₂) ← prove_lt_nat ic a1 e',
return (ic, a1, `(min_fac_helper_5).mk_app [a, b, e', p₁, p₂, p])
else let d := k1.min_fac in
if to_bool (d < k1) then do
let k' := k+1, let e' := reflect k',
(ic, p₁) ← prove_succ ic b e',
p₂ ← prove_non_prime b1 k1 d,
prove_min_fac_aux ic e' $ `(min_fac_helper_2).mk_app [a, b, e', p₁, p₂, p]
else do
let nc := n1 % k1,
(ic, c, pc) ← prove_div_mod ic a1 b1 tt,
if nc = 0 then
return (ic, b1, `(min_fac_helper_4).mk_app [a, b, pc, p])
else do
(ic, p₀) ← prove_pos ic c,
let k' := k+1, let e' := reflect k',
(ic, p₁) ← prove_succ ic b e',
prove_min_fac_aux ic e' $ `(min_fac_helper_3).mk_app [a, b, e', c, p₁, pc, p₀, p]
/-- Given `a` a natural numeral, returns `(b, ⊢ min_fac a = b)`. -/
meta def prove_min_fac (ic : instance_cache) (e : expr) : tactic (instance_cache × expr × expr) :=
match match_numeral e with
| match_numeral_result.zero := return (ic, `(2:ℕ), `(nat.min_fac_zero))
| match_numeral_result.one := return (ic, `(1:ℕ), `(nat.min_fac_one))
| match_numeral_result.bit0 e := return (ic, `(2), `(min_fac_bit0).mk_app [e])
| match_numeral_result.bit1 e := do
n ← e.to_nat,
c ← mk_instance_cache `(nat),
(c, p) ← prove_pos c e,
let a1 := `(bit1:ℕ→ℕ).mk_app [e],
prove_min_fac_aux e a1 (bit1 n) c `(1) (`(min_fac_helper_0).mk_app [e, p])
| _ := failed
end
/-- Evaluates the `prime` and `min_fac` functions. -/
meta def eval_prime : expr → tactic (expr × expr)
| `(nat.prime %%e) := do
n ← e.to_nat,
match n with
| 0 := false_intro `(nat.not_prime_zero)
| 1 := false_intro `(nat.not_prime_one)
| _ := let d₁ := n.min_fac in
if d₁ < n then prove_non_prime e n d₁ >>= false_intro
else do
let e₁ := reflect d₁,
c ← mk_instance_cache `(nat),
(c, p₁) ← prove_lt_nat c `(1) e₁,
(c, e₁, p) ← prove_min_fac c e,
true_intro $ `(is_prime_helper).mk_app [e, p₁, p]
end
| `(nat.min_fac %%e) := do
ic ← mk_instance_cache `(ℕ),
prod.snd <$> prove_min_fac ic e
| _ := failed
/-- This version of `derive` does not fail when the input is already a numeral -/
meta def derive' (e : expr) : tactic (expr × expr) :=
eval_field e <|> eval_nat_int_ext e <|>
eval_pow e <|> eval_ineq e <|> eval_prime e
meta def derive : expr → tactic (expr × expr) | e :=
do e ← instantiate_mvars e,
(_, e', pr) ←
ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed)
(λ _ _ _ _ e,
do (new_e, pr) ← derive' e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, tt))
`eq e,
return (e', pr)
end norm_num
namespace tactic.interactive
open norm_num interactive interactive.types
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 (loc : parse location) : tactic unit :=
do ns ← loc.get_locals,
tt ← tactic.replace_at derive ns loc.include_goal
| fail "norm_num failed to simplify",
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) (l : parse location) : tactic unit :=
repeat1 $ orelse' (norm_num1 l) $
simp_core {} (norm_num1 (loc.ns [none])) ff hs [] l
add_hint_tactic "norm_num"
/-- Normalizes a numerical expression and tries to close the goal with the result. -/
meta def apply_normed (x : parse texpr) : tactic unit :=
do x₁ ← to_expr x,
(x₂,_) ← derive x₁,
tactic.exact x₂
/--
Normalises numerical expressions. It supports the operations `+` `-` `*` `/` `^` and `%` over
numerical types such as `ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ`, and can prove goals of the form `A = B`, `A ≠ B`,
`A < B` and `A ≤ B`, where `A` and `B` are
numerical expressions. It also has a relatively simple primality prover.
```lean
import data.real.basic
example : (2 : ℝ) + 2 = 4 := by norm_num
example : (12345.2 : ℝ) ≠ 12345.3 := by norm_num
example : (73 : ℝ) < 789/2 := by norm_num
example : 123456789 + 987654321 = 1111111110 := by norm_num
example (R : Type*) [ring R] : (2 : R) + 2 = 4 := by norm_num
example (F : Type*) [linear_ordered_field F] : (2 : F) + 2 < 5 := by norm_num
example : nat.prime (2^13 - 1) := by norm_num
example : ¬ nat.prime (2^11 - 1) := by norm_num
example (x : ℝ) (h : x = 123 + 456) : x = 579 := by norm_num at h; assumption
```
The variant `norm_num1` does not call `simp`.
Both `norm_num` and `norm_num1` can be called inside the `conv` tactic.
The tactic `apply_normed` normalises a numerical expression and tries to close the goal with
the result. Compare:
```lean
def a : ℕ := 2^100
#print a -- 2 ^ 100
def normed_a : ℕ := by apply_normed 2^100
#print normed_a -- 1267650600228229401496703205376
```
-/
add_tactic_doc
{ name := "norm_num",
category := doc_category.tactic,
decl_names := [`tactic.interactive.norm_num1, `tactic.interactive.norm_num,
`tactic.interactive.apply_normed],
tags := ["arithmetic", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive tactic.interactive
open norm_num (derive)
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 : conv unit := replace_lhs derive
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` and `%` over numerical types such as
`ℕ`, `ℤ`, `ℚ`, `ℝ`, `ℂ` and some general algebraic types,
and can prove goals of the form `A = B`, `A ≠ B`, `A < B` and `A ≤ B`,
where `A` and `B` are numerical expressions.
It also has a relatively simple primality prover. -/
meta def norm_num (hs : parse simp_arg_list) : conv unit :=
repeat1 $ orelse' norm_num1 $
conv.interactive.simp ff hs [] { discharger := tactic.interactive.norm_num1 (loc.ns [none]) }
end conv.interactive
|
0aa3bed5e228c97325d06ac7a3364c1ba2dbc4fa | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/LoadDynlib.lean | f076d7c59611b2fa935d64d762b62bae01d543ea | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 491 | lean | /-
Copyright (c) 2021 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
namespace Lean
/--
Dynamically loads a shared library so that its symbols can be used by
the Lean interpreter (e.g., for interpreting `@[extern]` declarations).
Equivalent to passing `--load-dynlib=lib` to `lean`.
Note that Lean never unloads libraries.
-/
@[extern "lean_load_dynlib"]
opaque loadDynlib (path : @& System.FilePath) : IO Unit
|
0541502fa8f1ed2e1646911d2492843b013e586d | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/data/multiset.lean | d7f50b84664f2253761e0f9194efe9a80df83b36 | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 134,655 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Multisets.
-/
import logic.function order.boolean_algebra
data.equiv.basic data.list.basic data.list.perm data.list.sort data.quot data.string.basic
algebra.order_functions algebra.group_power algebra.ordered_group
category.traversable.lemmas tactic.interactive
category.traversable.instances category.basic
open list subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale add_monoid
/-- `multiset α` is the quotient of `list α` by list permutation. The result
is a type of finite sets with duplicates allowed. -/
def {u} multiset (α : Type u) : Type u :=
quotient (list.is_setoid α)
namespace multiset
instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩
@[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl
@[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl
@[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl
@[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq
instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α)
| s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂,
decidable_of_iff' _ quotient.eq
/- empty multiset -/
/-- `0 : multiset α` is the empty set -/
protected def zero : multiset α := @nil α
instance : has_zero (multiset α) := ⟨multiset.zero⟩
instance : has_emptyc (multiset α) := ⟨0⟩
instance : inhabited (multiset α) := ⟨0⟩
@[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl
@[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl
theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] :=
iff.trans coe_eq_coe perm_nil
/- cons -/
/-- `cons a s` is the multiset which contains `s` plus one more
instance of `a`. -/
def cons (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (a :: l : multiset α))
(λ l₁ l₂ p, quot.sound ((perm_cons a).2 p))
notation a :: b := cons a b
instance : has_insert α (multiset α) := ⟨cons⟩
@[simp] theorem insert_eq_cons (a : α) (s : multiset α) :
insert a s = a::s := rfl
@[simp] theorem cons_coe (a : α) (l : list α) :
(a::l : multiset α) = (a::l : list α) := rfl
theorem singleton_coe (a : α) : (a::0 : multiset α) = ([a] : list α) := rfl
@[simp] theorem cons_inj_left {a b : α} (s : multiset α) :
a::s = b::s ↔ a = b :=
⟨quot.induction_on s $ λ l e,
have [a] ++ l ~ [b] ++ l, from quotient.exact e,
eq_singleton_of_perm $ (perm_app_right_iff _).1 this, congr_arg _⟩
@[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a::s = a::t ↔ s = t :=
by rintros ⟨l₁⟩ ⟨l₂⟩; simp [perm_cons]
@[recursor 5] protected theorem induction {p : multiset α → Prop}
(h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : ∀s, p s :=
by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih]
@[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop}
(s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a :: s)) : p s :=
multiset.induction h₁ h₂ s
theorem cons_swap (a b : α) (s : multiset α) : a :: b :: s = b :: a :: s :=
quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _
section rec
variables {C : multiset α → Sort*}
/-- Dependent recursor on multisets.
TODO: should be @[recursor 6], but then the definition of `multiset.pi` failes with a stack
overflow in `whnf`.
-/
protected def rec
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b))
(m : multiset α) : C m :=
quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $
assume l l' h,
list.rec_heq_of_perm h
(assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc)
(assume a a' l, C_cons_heq a a' ⟦l⟧)
@[elab_as_eliminator]
protected def rec_on (m : multiset α)
(C_0 : C 0)
(C_cons : Πa m, C m → C (a::m))
(C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)) :
C m :=
multiset.rec C_0 C_cons C_cons_heq m
variables {C_0 : C 0} {C_cons : Πa m, C m → C (a::m)}
{C_cons_heq : ∀a a' m b, C_cons a (a'::m) (C_cons a' m b) == C_cons a' (a::m) (C_cons a m b)}
@[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 :=
rfl
@[simp] lemma rec_on_cons (a : α) (m : multiset α) :
(a :: m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) :=
quotient.induction_on m $ assume l, rfl
end rec
section mem
/-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/
def mem (a : α) (s : multiset α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ mem_of_perm e)
instance : has_mem α (multiset α) := ⟨mem⟩
@[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl
instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) :=
quot.rec_on_subsingleton s $ list.decidable_mem a
@[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b :: s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, iff.rfl
lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b :: s :=
mem_cons.2 $ or.inr h
@[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a :: s :=
mem_cons.2 (or.inl rfl)
theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a :: t :=
quot.induction_on s $ λ l (h : a ∈ l),
let ⟨l₁, l₂, e⟩ := mem_split h in
e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩
@[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id
theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 :=
quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl
theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s :=
⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩
theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s :=
quot.induction_on s $ assume l hl,
match l, hl with
| [] := assume h, false.elim $ h rfl
| (a :: l) := assume _, ⟨a, by simp⟩
end
@[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a :: m :=
assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this
@[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a :: m ≠ 0 := zero_ne_cons.symm
lemma cons_eq_cons {a b : α} {as bs : multiset α} :
a :: as = b :: bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b :: cs ∧ bs = a :: cs)) :=
begin
haveI : decidable_eq α := classical.dec_eq α,
split,
{ assume eq,
by_cases a = b,
{ subst h, simp * at * },
{ have : a ∈ b :: bs, from eq ▸ mem_cons_self _ _,
have : a ∈ bs, by simpa [h],
rcases exists_cons_of_mem this with ⟨cs, hcs⟩,
simp [h, hcs],
have : a :: as = b :: a :: cs, by simp [eq, hcs],
have : a :: as = a :: b :: cs, by rwa [cons_swap],
simpa using this } },
{ assume h,
rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ simp * },
{ simp [*, cons_swap a b] } }
end
end mem
/- subset -/
section subset
/-- `s ⊆ t` is the lift of the list subset relation. It means that any
element with nonzero multiplicity in `s` has nonzero multiplicity in `t`,
but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`;
see `s ≤ t` for this relation. -/
protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t
instance : has_subset (multiset α) := ⟨multiset.subset⟩
@[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl
@[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h
theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u :=
λ h₁ h₂ a m, h₂ (h₁ m)
theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl
theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _
@[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s :=
λ a, (not_mem_nil a).elim
@[simp] theorem cons_subset {a : α} {s t : multiset α} : (a :: s) ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp [subset_iff, or_imp_distrib, forall_and_distrib]
theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 :=
eq_zero_of_forall_not_mem h
theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 :=
⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩
end subset
/- multiset order -/
/-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation).
Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/
protected def le (s t : multiset α) : Prop :=
quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
propext (p₂.subperm_left.trans p₁.subperm_right)
instance : partial_order (multiset α) :=
{ le := multiset.le,
le_refl := by rintros ⟨l⟩; exact subperm.refl _,
le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _,
le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) }
theorem subset_of_le {s t : multiset α} : s ≤ t → s ⊆ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subset_of_subperm
theorem mem_of_le {s t : multiset α} {a : α} (h : s ≤ t) : a ∈ s → a ∈ t :=
mem_of_subset (subset_of_le h)
@[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl
@[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop}
{s t : multiset α} (h : s ≤ t)
(H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t :=
quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩,
(show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h
theorem zero_le (s : multiset α) : 0 ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ nil_sublist l
theorem le_zero {s : multiset α} : s ≤ 0 ↔ s = 0 :=
⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩
theorem lt_cons_self (s : multiset α) (a : α) : s < a :: s :=
quot.induction_on s $ λ l,
suffices l <+~ a :: l ∧ (¬l ~ a :: l),
by simpa [lt_iff_le_and_ne],
⟨subperm_of_sublist (sublist_cons _ _),
λ p, ne_of_lt (lt_succ_self (length l)) (perm_length p)⟩
theorem le_cons_self (s : multiset α) (a : α) : s ≤ a :: s :=
le_of_lt $ lt_cons_self _ _
theorem cons_le_cons_iff (a : α) {s t : multiset α} : a :: s ≤ a :: t ↔ s ≤ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a
theorem cons_le_cons (a : α) {s t : multiset α} : s ≤ t → a :: s ≤ a :: t :=
(cons_le_cons_iff a).2
theorem le_cons_of_not_mem {a : α} {s t : multiset α} (m : a ∉ s) : s ≤ a :: t ↔ s ≤ t :=
begin
refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩,
suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a :: s ≤ t',
{ exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) },
introv h, revert m, refine le_induction_on h _,
introv s m₁ m₂,
rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩,
exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ subperm_of_sublist $
(sublist_or_mem_of_sublist s).resolve_right m₁)
end
/- cardinality -/
/-- The cardinality of a multiset is the sum of the multiplicities
of all its elements, or simply the length of the underlying list. -/
def card (s : multiset α) : ℕ :=
quot.lift_on s length $ λ l₁ l₂, perm_length
@[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl
@[simp] theorem card_zero : @card α 0 = 0 := rfl
@[simp] theorem card_cons (a : α) (s : multiset α) : card (a :: s) = card s + 1 :=
quot.induction_on s $ λ l, rfl
@[simp] theorem card_singleton (a : α) : card (a::0) = 1 := by simp
theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t :=
le_induction_on h $ λ l₁ l₂, length_le_of_sublist
theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t :=
le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂
theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t :=
lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂
theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a :: s ≤ t :=
⟨quotient.induction_on₂ s t $ λ l₁ l₂ h,
subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h),
λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩
@[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 :=
⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩
theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s :=
quot.induction_on s $ λ l, length_pos_iff_exists_mem
@[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} :
∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s
| s := λ ih, ih s $ λ t h,
have card t < card s, from card_lt_of_lt h,
strong_induction_on t ih
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]}
theorem strong_induction_eq {p : multiset α → Sort*}
(s : multiset α) (H) : @strong_induction_on _ p s H =
H s (λ t h, @strong_induction_on _ p t H) :=
by rw [strong_induction_on]
@[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop}
(s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a :: s)) : p s :=
multiset.strong_induction_on s $ assume s,
multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $
λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _
/- singleton -/
@[simp] theorem singleton_eq_singleton (a : α) : singleton a = a::0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ a::0 ↔ b = a := by simp
theorem mem_singleton_self (a : α) : a ∈ (a::0 : multiset α) := mem_cons_self _ _
theorem singleton_inj {a b : α} : a::0 = b::0 ↔ a = b := cons_inj_left _
@[simp] theorem singleton_ne_zero (a : α) : a::0 ≠ 0 :=
ne_of_gt (lt_cons_self _ _)
@[simp] theorem singleton_le {a : α} {s : multiset α} : a::0 ≤ s ↔ a ∈ s :=
⟨λ h, mem_of_le h (mem_singleton_self _),
λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩
theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = a::0 :=
⟨quot.induction_on s $ λ l h,
(list.length_eq_one.1 h).imp $ λ a, congr_arg coe,
λ ⟨a, e⟩, e.symm ▸ rfl⟩
/- add -/
/-- The sum of two multisets is the lift of the list append operation.
This adds the multiplicities of each element,
i.e. `count a (s + t) = count a s + count a t`. -/
protected def add (s₁ s₂ : multiset α) : multiset α :=
quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $
λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ perm_app p₁ p₂
instance : has_add (multiset α) := ⟨multiset.add⟩
@[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl
protected theorem add_comm (s t : multiset α) : s + t = t + s :=
quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_app_comm
protected theorem zero_add (s : multiset α) : 0 + s = s :=
quot.induction_on s $ λ l, rfl
theorem singleton_add (a : α) (s : multiset α) : ↑[a] + s = a::s := rfl
protected theorem add_le_add_left (s) {t u : multiset α} : s + t ≤ s + u ↔ t ≤ u :=
quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_app_left _
protected theorem add_left_cancel (s) {t u : multiset α} (h : s + t = s + u) : t = u :=
le_antisymm ((multiset.add_le_add_left _).1 (le_of_eq h))
((multiset.add_le_add_left _).1 (le_of_eq h.symm))
instance : ordered_cancel_comm_monoid (multiset α) :=
{ zero := 0,
add := (+),
add_comm := multiset.add_comm,
add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃,
congr_arg coe $ append_assoc l₁ l₂ l₃,
zero_add := multiset.zero_add,
add_zero := λ s, by rw [multiset.add_comm, multiset.zero_add],
add_left_cancel := multiset.add_left_cancel,
add_right_cancel := λ s₁ s₂ s₃ h, multiset.add_left_cancel s₂ $
by simpa [multiset.add_comm] using h,
add_le_add_left := λ s₁ s₂ h s₃, (multiset.add_le_add_left _).2 h,
le_of_add_le_add_left := λ s₁ s₂ s₃, (multiset.add_le_add_left _).1,
..@multiset.partial_order α }
@[simp] theorem cons_add (a : α) (s t : multiset α) : a :: s + t = a :: (s + t) :=
by rw [← singleton_add, ← singleton_add, add_assoc]
@[simp] theorem add_cons (a : α) (s t : multiset α) : s + a :: t = a :: (s + t) :=
by rw [add_comm, cons_add, add_comm]
theorem le_add_right (s t : multiset α) : s ≤ s + t :=
by simpa using add_le_add_left (zero_le t) s
theorem le_add_left (s t : multiset α) : s ≤ t + s :=
by simpa using add_le_add_right (zero_le t) s
@[simp] theorem card_add (s t : multiset α) : card (s + t) = card s + card t :=
quotient.induction_on₂ s t length_append
lemma card_smul (s : multiset α) (n : ℕ) :
(n • s).card = n * s.card :=
by induction n; simp [succ_smul, *, nat.succ_mul]
@[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, mem_append
theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u :=
⟨λ h, le_induction_on h $ λ l₁ l₂ s,
let ⟨l, p⟩ := exists_perm_append_of_sublist s in ⟨l, quot.sound p⟩,
λ⟨u, e⟩, e.symm ▸ le_add_right s u⟩
instance : canonically_ordered_monoid (multiset α) :=
{ lt_of_add_lt_add_left := @lt_of_add_lt_add_left _ _,
le_iff_exists_add := @le_iff_exists_add _,
bot := 0,
bot_le := multiset.zero_le,
..multiset.ordered_cancel_comm_monoid }
/- repeat -/
/-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/
def repeat (a : α) (n : ℕ) : multiset α := repeat a n
@[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl
@[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a :: repeat a n := by simp [repeat]
@[simp] lemma repeat_one (a : α) : repeat a 1 = a :: 0 := by simp
@[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat
theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat
theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
(perm_repeat.1 $ (quotient.exact h).symm).symm, congr_arg coe⟩ eq_repeat'
theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card :=
eq_repeat'.2
theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a :=
⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩,
λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩
theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ a::0 := repeat_subset_singleton
theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l :=
⟨λ ⟨l', p, s⟩, (perm_repeat.1 p.symm).symm ▸ s, subperm_of_sublist⟩
/- range -/
/-- `range n` is the multiset lifted from the list `range n`,
that is, the set `{0, 1, ..., n-1}`. -/
def range (n : ℕ) : multiset ℕ := range n
@[simp] theorem range_zero : range 0 = 0 := rfl
@[simp] theorem range_succ (n : ℕ) : range (succ n) = n :: range n :=
by rw [range, range_concat, ← coe_add, add_comm]; refl
@[simp] theorem card_range (n : ℕ) : card (range n) = n := length_range _
theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := range_subset
@[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := mem_range
@[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := not_mem_range_self
/- erase -/
section erase
variables [decidable_eq α] {s t : multiset α} {a b : α}
/-- `erase s a` is the multiset that subtracts 1 from the
multiplicity of `a`. -/
def erase (s : multiset α) (a : α) : multiset α :=
quot.lift_on s (λ l, (l.erase a : multiset α))
(λ l₁ l₂ p, quot.sound (erase_perm_erase a p))
@[simp] theorem coe_erase (l : list α) (a : α) :
erase (l : multiset α) a = l.erase a := rfl
@[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl
@[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a :: s).erase a = s :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l
@[simp] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b::s).erase a = b :: s.erase a :=
quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h
@[simp] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s :=
quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h
@[simp] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a :: s.erase a = s :=
quot.induction_on s $ λ l h, quot.sound (perm_erase h).symm
theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a :: s.erase a :=
if h : a ∈ s then le_of_eq (cons_erase h).symm
else by rw erase_of_not_mem h; apply le_cons_self
theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h
theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a :=
by rw [add_comm, erase_add_left_pos s h, add_comm]
theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h
theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t :=
by rw [add_comm, erase_add_right_neg s h, add_comm]
theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist (erase_sublist a l)
@[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s :=
⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h),
λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩
theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s :=
subset_of_le (erase_le a s)
theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s :=
quot.induction_on s $ λ l, list.mem_erase_of_ne ab
theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s :=
mem_of_subset (erase_subset _ _)
theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a :=
quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b
theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist (erase_sublist_erase _ h)
theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a :: t :=
⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h),
λ h, if m : a ∈ s
then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h
else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩
@[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) :=
quot.induction_on s $ λ l, length_erase_of_mem
theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s :=
λ h, card_lt_of_lt (erase_lt.mpr h)
theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s :=
card_le_of_le (erase_le a s)
end erase
@[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l :=
quot.sound $ reverse_perm _
/- map -/
/-- `map f s` is the lift of the list `map` operation. The multiplicity
of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity)
such that `f a = b`. -/
def map (f : α → β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l : list α, (l.map f : multiset β))
(λ l₁ l₂ p, quot.sound (perm_map f p))
@[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl
@[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl
@[simp] theorem map_cons (f : α → β) (a s) : map f (a::s) = f a :: map f s :=
quot.induction_on s $ λ l, rfl
@[simp] lemma map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl
@[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _
instance (f : α → β) : is_add_monoid_hom (map f) :=
{ map_add := map_add _, map_zero := map_zero _ }
@[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} :
b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b :=
quot.induction_on s $ λ l, mem_map
@[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s :=
quot.induction_on s $ λ l, length_map _ _
@[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 :=
by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero]
theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s :=
mem_map.2 ⟨_, h, rfl⟩
@[simp] theorem mem_map_of_inj {f : α → β} (H : function.injective f) {a : α} {s : multiset α} :
f a ∈ map f s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_map_of_inj H
@[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _
@[simp] theorem map_id (s : multiset α) : map id s = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_id _
@[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s
@[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card :=
quot.induction_on s $ λ l, congr_arg coe $ map_const _ _
@[congr] theorem map_congr {f g : α → β} {s : multiset α} : (∀ x ∈ s, f x = g x) → map f s = map g s :=
quot.induction_on s $ λ l H, congr_arg coe $ map_congr H
lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m :=
begin subst h, simp at hf, simp [map_congr hf] end
theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ :=
eq_of_mem_repeat $ by rwa map_const at h
@[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ map_sublist_map f h
@[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t :=
λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩
/- fold -/
/-- `foldl f H b s` is the lift of the list operation `foldl f b l`,
which folds `f` over the multiset. It is well defined when `f` is right-commutative,
that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/
def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldl f b l)
(λ l₁ l₂ p, foldl_eq_of_perm H p b)
@[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl
@[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a :: s) = foldl f H (f b a) s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _
/-- `foldr f H b s` is the lift of the list operation `foldr f b l`,
which folds `f` over the multiset. It is well defined when `f` is left-commutative,
that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/
def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β :=
quot.lift_on s (λ l, foldr f b l)
(λ l₁ l₂ p, foldr_eq_of_perm H p b)
@[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl
@[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a :: s) = f a (foldr f H b s) :=
quot.induction_on s $ λ l, rfl
@[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s :=
quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _
@[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldr f b := rfl
@[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) :
foldl f H b l = l.foldl f b := rfl
theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) :
foldr f H b l = l.foldl (λ x y, f y x) b :=
(congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _
theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) :
foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _
theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) :
foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s :=
(foldr_swap _ _ _ _).symm
/-- Product of a multiset given a commutative monoid structure on `α`.
`prod {a, b, c} = a * b * c` -/
@[to_additive]
def prod [comm_monoid α] : multiset α → α :=
foldr (*) (λ x y z, by simp [mul_left_comm]) 1
@[to_additive]
theorem prod_eq_foldr [comm_monoid α] (s : multiset α) :
prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl
@[to_additive]
theorem prod_eq_foldl [comm_monoid α] (s : multiset α) :
prod s = foldl (*) (λ x y z, by simp [mul_right_comm]) 1 s :=
(foldr_swap _ _ _ _).trans (by simp [mul_comm])
@[simp, to_additive]
theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod :=
prod_eq_foldl _
@[simp, to_additive]
theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl
@[simp, to_additive]
theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s :=
foldr_cons _ _ _ _ _
@[to_additive]
theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp
@[simp, to_additive]
theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t :=
quotient.induction_on₂ s t $ λ l₁ l₂, by simp
instance sum.is_add_monoid_hom [add_comm_monoid α] : is_add_monoid_hom (sum : multiset α → α) :=
{ map_add := sum_add, map_zero := sum_zero }
lemma prod_smul {α : Type*} [comm_monoid α] (m : multiset α) :
∀n, (add_monoid.smul n m).prod = m.prod ^ n
| 0 := rfl
| (n + 1) :=
by rw [add_monoid.add_smul, add_monoid.one_smul, _root_.pow_add, _root_.pow_one, prod_add, prod_smul n]
@[simp] theorem prod_repeat [comm_monoid α] (a : α) (n : ℕ) : prod (multiset.repeat a n) = a ^ n :=
by simp [repeat, list.prod_repeat]
@[simp] theorem sum_repeat [add_comm_monoid α] : ∀ (a : α) (n : ℕ), sum (multiset.repeat a n) = n • a :=
@prod_repeat (multiplicative α) _
attribute [to_additive] prod_repeat
@[simp] lemma prod_map_one [comm_monoid γ] {m : multiset α} :
prod (m.map (λa, (1 : γ))) = (1 : γ) :=
multiset.induction_on m (by simp) (by simp)
@[simp] lemma sum_map_zero [add_comm_monoid γ] {m : multiset α} :
sum (m.map (λa, (0 : γ))) = (0 : γ) :=
multiset.induction_on m (by simp) (by simp)
attribute [to_additive] prod_map_one
@[simp, to_additive]
lemma prod_map_mul [comm_monoid γ] {m : multiset α} {f g : α → γ} :
prod (m.map $ λa, f a * g a) = prod (m.map f) * prod (m.map g) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih]; cc)
lemma prod_map_prod_map [comm_monoid γ] (m : multiset α) (n : multiset β) {f : α → β → γ} :
prod (m.map $ λa, prod $ n.map $ λb, f a b) = prod (n.map $ λb, prod $ m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (assume a m ih, by simp [ih])
lemma sum_map_sum_map [add_comm_monoid γ] : ∀ (m : multiset α) (n : multiset β) {f : α → β → γ},
sum (m.map $ λa, sum $ n.map $ λb, f a b) = sum (n.map $ λb, sum $ m.map $ λa, f a b) :=
@prod_map_prod_map _ _ (multiplicative γ) _
attribute [to_additive] prod_map_prod_map
lemma sum_map_mul_left [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, b * f a)) = b * sum (s.map f) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, mul_add])
lemma sum_map_mul_right [semiring β] {b : β} {s : multiset α} {f : α → β} :
sum (s.map (λa, f a * b)) = sum (s.map f) * b :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, add_mul])
lemma prod_hom [comm_monoid α] [comm_monoid β] (f : α → β) [is_monoid_hom f] (s : multiset α) :
(s.map f).prod = f s.prod :=
multiset.induction_on s (by simp [is_monoid_hom.map_one f])
(by simp [is_monoid_hom.map_mul f] {contextual := tt})
lemma dvd_prod [comm_semiring α] {a : α} {s : multiset α} : a ∈ s → a ∣ s.prod :=
quotient.induction_on s (λ l a h, by simpa using list.dvd_prod h) a
lemma sum_hom [add_comm_monoid α] [add_comm_monoid β] (f : α → β) [is_add_monoid_hom f] (s : multiset α) :
(s.map f).sum = f s.sum :=
multiset.induction_on s (by simp [is_add_monoid_hom.map_zero f])
(by simp [is_add_monoid_hom.map_add f] {contextual := tt})
attribute [to_additive] multiset.prod_hom
lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β]
(f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : multiset α) :
f s.sum ≤ (s.map f).sum :=
multiset.induction_on s (le_of_eq h_zero) $
assume a s ih, by rw [sum_cons, map_cons, sum_cons];
from le_trans (h_add a s.sum) (add_le_add_left' ih)
lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {s : multiset α} :
abs s.sum ≤ (s.map abs).sum :=
le_sum_of_subadditive _ abs_zero abs_add s
/- join -/
/-- `join S`, where `S` is a multiset of multisets, is the lift of the list join
operation, that is, the union of all the sets.
join {{1, 2}, {1, 2}, {0, 1}} = {0, 1, 1, 1, 2, 2} -/
def join : multiset (multiset α) → multiset α := sum
theorem coe_join : ∀ L : list (list α),
join (L.map (@coe _ (multiset α) _) : multiset (multiset α)) = L.join
| [] := rfl
| (l :: L) := congr_arg (λ s : multiset α, ↑l + s) (coe_join L)
@[simp] theorem join_zero : @join α 0 = 0 := rfl
@[simp] theorem join_cons (s S) : @join α (s :: S) = s + join S :=
sum_cons _ _
@[simp] theorem join_add (S T) : @join α (S + T) = join S + join T :=
sum_add _ _
@[simp] theorem mem_join {a S} : a ∈ @join α S ↔ ∃ s ∈ S, a ∈ s :=
multiset.induction_on S (by simp) $
by simp [or_and_distrib_right, exists_or_distrib] {contextual := tt}
@[simp] theorem card_join (S) : card (@join α S) = sum (map card S) :=
multiset.induction_on S (by simp) (by simp)
/- bind -/
/-- `bind s f` is the monad bind operation, defined as `join (map f s)`.
It is the union of `f a` as `a` ranges over `s`. -/
def bind (s : multiset α) (f : α → multiset β) : multiset β :=
join (map f s)
@[simp] theorem coe_bind (l : list α) (f : α → list β) :
@bind α β l (λ a, f a) = l.bind f :=
by rw [list.bind, ← coe_join, list.map_map]; refl
@[simp] theorem zero_bind (f : α → multiset β) : bind 0 f = 0 := rfl
@[simp] theorem cons_bind (a s) (f : α → multiset β) : bind (a::s) f = f a + bind s f :=
by simp [bind]
@[simp] theorem add_bind (s t) (f : α → multiset β) : bind (s + t) f = bind s f + bind t f :=
by simp [bind]
@[simp] theorem bind_zero (s : multiset α) : bind s (λa, 0 : α → multiset β) = 0 :=
by simp [bind, -map_const, join]
@[simp] theorem bind_add (s : multiset α) (f g : α → multiset β) :
bind s (λa, f a + g a) = bind s f + bind s g :=
by simp [bind, join]
@[simp] theorem bind_cons (s : multiset α) (f : α → β) (g : α → multiset β) :
bind s (λa, f a :: g a) = map f s + bind s g :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
@[simp] theorem mem_bind {b s} {f : α → multiset β} : b ∈ bind s f ↔ ∃ a ∈ s, b ∈ f a :=
by simp [bind]; simp [-exists_and_distrib_right, exists_and_distrib_right.symm];
rw exists_swap; simp [and_assoc]
@[simp] theorem card_bind (s) (f : α → multiset β) : card (bind s f) = sum (map (card ∘ f) s) :=
by simp [bind]
lemma bind_congr {f g : α → multiset β} {m : multiset α} : (∀a∈m, f a = g a) → bind m f = bind m g :=
by simp [bind] {contextual := tt}
lemma bind_hcongr {β' : Type*} {m : multiset α} {f : α → multiset β} {f' : α → multiset β'}
(h : β = β') (hf : ∀a∈m, f a == f' a) : bind m f == bind m f' :=
begin subst h, simp at hf, simp [bind_congr hf] end
lemma map_bind (m : multiset α) (n : α → multiset β) (f : β → γ) :
map f (bind m n) = bind m (λa, map f (n a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map (m : multiset α) (n : β → multiset γ) (f : α → β) :
bind (map f m) n = bind m (λa, n (f a)) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_assoc {s : multiset α} {f : α → multiset β} {g : β → multiset γ} :
(s.bind f).bind g = s.bind (λa, (f a).bind g) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma bind_bind (m : multiset α) (n : multiset β) {f : α → β → multiset γ} :
(bind m $ λa, bind n $ λb, f a b) = (bind n $ λb, bind m $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
lemma bind_map_comm (m : multiset α) (n : multiset β) {f : α → β → γ} :
(bind m $ λa, n.map $ λb, f a b) = (bind n $ λb, m.map $ λa, f a b) :=
multiset.induction_on m (by simp) (by simp {contextual := tt})
@[simp, to_additive]
lemma prod_bind [comm_monoid β] (s : multiset α) (t : α → multiset β) :
prod (bind s t) = prod (s.map $ λa, prod (t a)) :=
multiset.induction_on s (by simp) (assume a s ih, by simp [ih, cons_bind])
/- product -/
/-- The multiplicity of `(a, b)` in `product s t` is
the product of the multiplicity of `a` in `s` and `b` in `t`. -/
def product (s : multiset α) (t : multiset β) : multiset (α × β) :=
s.bind $ λ a, t.map $ prod.mk a
@[simp] theorem coe_product (l₁ : list α) (l₂ : list β) :
@product α β l₁ l₂ = l₁.product l₂ :=
by rw [product, list.product, ← coe_bind]; simp
@[simp] theorem zero_product (t) : @product α β 0 t = 0 := rfl
@[simp] theorem cons_product (a : α) (s : multiset α) (t : multiset β) :
product (a :: s) t = map (prod.mk a) t + product s t :=
by simp [product]
@[simp] theorem product_singleton (a : α) (b : β) : product (a::0) (b::0) = (a,b)::0 := rfl
@[simp] theorem add_product (s t : multiset α) (u : multiset β) :
product (s + t) u = product s u + product t u :=
by simp [product]
@[simp] theorem product_add (s : multiset α) : ∀ t u : multiset β,
product s (t + u) = product s t + product s u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_product, IH]; simp
@[simp] theorem mem_product {s t} : ∀ {p : α × β}, p ∈ @product α β s t ↔ p.1 ∈ s ∧ p.2 ∈ t
| (a, b) := by simp [product, and.left_comm]
@[simp] theorem card_product (s : multiset α) (t : multiset β) : card (product s t) = card s * card t :=
by simp [product, repeat, (∘), mul_comm]
/- sigma -/
section
variable {σ : α → Type*}
/-- `sigma s t` is the dependent version of `product`. It is the sum of
`(a, b)` as `a` ranges over `s` and `b` ranges over `t a`. -/
protected def sigma (s : multiset α) (t : Π a, multiset (σ a)) : multiset (Σ a, σ a) :=
s.bind $ λ a, (t a).map $ sigma.mk a
@[simp] theorem coe_sigma (l₁ : list α) (l₂ : Π a, list (σ a)) :
@multiset.sigma α σ l₁ (λ a, l₂ a) = l₁.sigma l₂ :=
by rw [multiset.sigma, list.sigma, ← coe_bind]; simp
@[simp] theorem zero_sigma (t) : @multiset.sigma α σ 0 t = 0 := rfl
@[simp] theorem cons_sigma (a : α) (s : multiset α) (t : Π a, multiset (σ a)) :
(a :: s).sigma t = map (sigma.mk a) (t a) + s.sigma t :=
by simp [multiset.sigma]
@[simp] theorem sigma_singleton (a : α) (b : α → β) :
(a::0).sigma (λ a, b a::0) = ⟨a, b a⟩::0 := rfl
@[simp] theorem add_sigma (s t : multiset α) (u : Π a, multiset (σ a)) :
(s + t).sigma u = s.sigma u + t.sigma u :=
by simp [multiset.sigma]
@[simp] theorem sigma_add (s : multiset α) : ∀ t u : Π a, multiset (σ a),
s.sigma (λ a, t a + u a) = s.sigma t + s.sigma u :=
multiset.induction_on s (λ t u, rfl) $ λ a s IH t u,
by rw [cons_sigma, IH]; simp
@[simp] theorem mem_sigma {s t} : ∀ {p : Σ a, σ a},
p ∈ @multiset.sigma α σ s t ↔ p.1 ∈ s ∧ p.2 ∈ t p.1
| ⟨a, b⟩ := by simp [multiset.sigma, and_assoc, and.left_comm]
@[simp] theorem card_sigma (s : multiset α) (t : Π a, multiset (σ a)) :
card (s.sigma t) = sum (map (λ a, card (t a)) s) :=
by simp [multiset.sigma, (∘)]
end
/- map for partial functions -/
/-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset
`s` whose elements are all in the domain of `f`. -/
def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β :=
quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂),
funext $ λ (H₂ : ∀ a ∈ l₂, p a),
have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a ((mem_of_perm pp).1 h),
have ∀ {s₂ e H}, @eq.rec (multiset α) l₁
(λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁))
s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e,
this.trans $ quot.sound $ perm_pmap f pp
@[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β)
(l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl
@[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) :
pmap f 0 h = 0 := rfl
@[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) :
∀(h : ∀b∈a::m, p b), pmap f (a :: m) h =
f a (h a (mem_cons_self a m)) :: pmap f m (λa ha, h a $ mem_cons_of_mem ha) :=
quotient.induction_on m $ assume l h, rfl
/-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce
a multiset on `{x // x ∈ s}`. -/
def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id)
@[simp] theorem coe_attach (l : list α) :
@eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl
theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) :
∀ H, @pmap _ _ p (λ a _, f a) s H = map f s :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H
theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β}
(s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) :
pmap f s H₁ = pmap g s H₂ :=
quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂
theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β)
(s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H :=
quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H
theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β)
(s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) :=
quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H
theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s :=
quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l
@[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach :=
quot.induction_on s $ λ l, mem_attach _
@[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β}
{s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b :=
quot.induction_on s (λ l H, mem_pmap) H
@[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β)
(s H) : card (pmap f s H) = card s :=
quot.induction_on s (λ l H, length_pmap) H
@[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _
@[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl
lemma attach_cons (a : α) (m : multiset α) :
(a :: m).attach = ⟨a, mem_cons_self a m⟩ :: (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) :=
quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $
by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl)
section decidable_pi_exists
variables {m : multiset α}
protected def decidable_forall_multiset {p : α → Prop} [hp : ∀a, decidable (p a)] :
decidable (∀a∈m, p a) :=
quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a∈l, p a) $ by simp)
instance decidable_dforall_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∀a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _))
/-- decidable equality for functions whose domain is bounded by multisets -/
instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈m, β a) :=
assume f g, decidable_of_iff (∀a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff])
def decidable_exists_multiset {p : α → Prop} [decidable_pred p] :
decidable (∃ x ∈ m, p x) :=
quotient.rec_on_subsingleton m list.decidable_exists_mem
instance decidable_dexists_multiset {p : Πa∈m, Prop} [hp : ∀a (h : a ∈ m), decidable (p a h)] :
decidable (∃a (h : a ∈ m), p a h) :=
decidable_of_decidable_of_iff
(@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _)
(iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩)
(λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩))
end decidable_pi_exists
/- subtraction -/
section
variables [decidable_eq α] {s t u : multiset α} {a b : α}
/-- `s - t` is the multiset such that
`count a (s - t) = count a s - count a t` for all `a`. -/
protected def sub (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_diff_right w₁ p₂ ▸ perm_diff_left _ p₁
instance : has_sub (multiset α) := ⟨multiset.sub⟩
@[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl
theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂,
by rw diff_eq_foldl l₁ l₂; exact foldl_hom _ _ _ _ (λ x y, rfl) _
@[simp] theorem sub_zero (s : multiset α) : s - 0 = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a::t = s.erase a - t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _
theorem add_sub_of_le (h : s ≤ t) : s + (t - s) = t :=
begin
revert t,
refine multiset.induction_on s (by simp) (λ a s IH t h, _),
have := cons_erase (mem_of_le h (mem_cons_self _ _)),
rw [cons_add, sub_cons, IH, this],
exact (cons_le_cons_iff a).1 (this.symm ▸ h)
end
theorem sub_add' : s - (t + u) = s - t - u :=
quotient.induction_on₃ s t u $
λ l₁ l₂ l₃, congr_arg coe $ diff_append _ _ _
theorem sub_add_cancel (h : t ≤ s) : s - t + t = s :=
by rw [add_comm, add_sub_of_le h]
@[simp] theorem add_sub_cancel_left (s : multiset α) : ∀ t, s + t - s = t :=
multiset.induction_on s (by simp)
(λ a s IH t, by rw [cons_add, sub_cons, erase_cons_head, IH])
@[simp] theorem add_sub_cancel (s t : multiset α) : s + t - t = s :=
by rw [add_comm, add_sub_cancel_left]
theorem sub_le_sub_right (h : s ≤ t) (u) : s - u ≤ t - u :=
by revert s t h; exact
multiset.induction_on u (by simp {contextual := tt})
(λ a u IH s t h, by simp [IH, erase_le_erase a h])
theorem sub_le_sub_left (h : s ≤ t) : ∀ u, u - t ≤ u - s :=
le_induction_on h $ λ l₁ l₂ h, begin
induction h with l₁ l₂ a s IH l₁ l₂ a s IH; intro u,
{ refl },
{ rw [← cons_coe, sub_cons],
exact le_trans (sub_le_sub_right (erase_le _ _) _) (IH u) },
{ rw [← cons_coe, sub_cons, ← cons_coe, sub_cons],
exact IH _ }
end
theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t :=
by revert s; exact
multiset.induction_on t (by simp)
(λ a t IH s, by simp [IH, erase_le_iff_le_cons])
theorem le_sub_add (s t : multiset α) : s ≤ s - t + t :=
sub_le_iff_le_add.1 (le_refl _)
theorem sub_le_self (s t : multiset α) : s - t ≤ s :=
sub_le_iff_le_add.2 (le_add_right _ _)
@[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t :=
(nat.sub_eq_of_eq_add $ by rw [add_comm, ← card_add, sub_add_cancel h]).symm
/- union -/
/-- `s ∪ t` is the lattice join operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum
of the multiplicities in `s` and `t`. -/
def union (s t : multiset α) : multiset α := s - t + t
instance : has_union (multiset α) := ⟨union⟩
theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl
theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_sub_add _ _
theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _
theorem eq_union_left : t ≤ s → s ∪ t = s := sub_add_cancel
theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u :=
add_le_add_right (sub_le_sub_right h _) u
theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u :=
by rw ← eq_union_left h₂; exact union_le_union_right h₁ t
@[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t :=
⟨λ h, (mem_add.1 h).imp_left (mem_of_le $ sub_le_self _ _),
or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩
@[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} :
map f (s ∪ t) = map f s ∪ map f t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
congr_arg coe (by rw [list.map_append f, list.map_diff finj])
/- inter -/
/-- `s ∩ t` is the lattice meet operation with respect to the
multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum
of the multiplicities in `s` and `t`. -/
def inter (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_bag_inter_right w₁ p₂ ▸ perm_bag_inter_left _ p₁
instance : has_inter (multiset α) := ⟨inter⟩
@[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil
@[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 :=
quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter
@[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} :
a ∈ t → (a :: s) ∩ t = a :: s ∩ t.erase a :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_pos _ h
@[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} :
a ∉ t → (a :: s) ∩ t = s ∩ t :=
quotient.induction_on₂ s t $ λ l₁ l₂ h,
congr_arg coe $ cons_bag_inter_of_neg _ h
theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ bag_inter_sublist_left _ _
theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t :=
multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $
λ a s IH t, if h : a ∈ t
then by simpa [h] using cons_le_cons a (IH (t.erase a))
else by simp [h, IH]
theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u :=
begin
revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros,
{ simp [h₁] },
by_cases a ∈ u,
{ rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons],
exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) },
{ rw cons_inter_of_neg _ h,
exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ }
end
@[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t :=
⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩,
λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩
instance : lattice (multiset α) :=
{ sup := (∪),
sup_le := @union_le _ _,
le_sup_left := le_union_left,
le_sup_right := le_union_right,
inf := (∩),
le_inf := @le_inter _ _,
inf_le_left := inter_le_left,
inf_le_right := inter_le_right,
..@multiset.partial_order α }
@[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl
@[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff
@[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff
instance : semilattice_inf_bot (multiset α) :=
{ bot := 0, bot_le := zero_le, ..multiset.lattice.lattice }
theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm
theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm
theorem eq_union_right (h : s ≤ t) : s ∪ t = t :=
by rw [union_comm, eq_union_left h]
theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t :=
sup_le_sup_left h _
theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t :=
union_le (le_add_right _ _) (le_add_left _ _)
theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) :=
by simpa [(∪), union, eq_comm] using show s + u - (t + u) = s - t,
by rw [add_comm t, sub_add', add_sub_cancel]
theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) :=
by rw [add_comm, union_add_distrib, add_comm s, add_comm s]
theorem cons_union_distrib (a : α) (s t : multiset α) : a :: (s ∪ t) = (a :: s) ∪ (a :: t) :=
by simpa using add_union_distrib (a::0) s t
theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) :=
begin
by_contra h,
cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter
(add_le_add_right (inter_le_left s t) u)
(add_le_add_right (inter_le_right s t) u)) h) with a hl,
rw ← cons_add at hl,
exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter
(le_of_add_le_add_right (le_trans hl (inter_le_left _ _)))
(le_of_add_le_add_right (le_trans hl (inter_le_right _ _))))
end
theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) :=
by rw [add_comm, inter_add_distrib, add_comm s, add_comm s]
theorem cons_inter_distrib (a : α) (s t : multiset α) : a :: (s ∩ t) = (a :: s) ∩ (a :: t) :=
by simp
theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t :=
begin
apply le_antisymm,
{ rw union_add_distrib,
refine union_le (add_le_add_left (inter_le_right _ _) _) _,
rw add_comm, exact add_le_add_right (inter_le_left _ _) _ },
{ rw [add_comm, add_inter_distrib],
refine le_inter (add_le_add_right (le_union_right _ _) _) _,
rw add_comm, exact add_le_add_right (le_union_left _ _) _ }
end
theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s :=
begin
rw [inter_comm],
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
by_cases a ∈ s,
{ rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] },
{ rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] }
end
theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t :=
add_right_cancel $
by rw [sub_add_inter s t, sub_add_cancel (inter_le_left _ _)]
end
/- filter -/
section
variables {p : α → Prop} [decidable_pred p]
/-- `filter p s` returns the elements in `s` (with the same multiplicities)
which satisfy `p`, and removes the rest. -/
def filter (p : α → Prop) [h : decidable_pred p] (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (filter p l : multiset α))
(λ l₁ l₂ h, quot.sound $ perm_filter p h)
@[simp] theorem coe_filter (p : α → Prop) [h : decidable_pred p]
(l : list α) : filter p (↑l) = l.filter p := rfl
@[simp] theorem filter_zero (p : α → Prop) [h : decidable_pred p] : filter p 0 = 0 := rfl
@[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a::s) = a :: filter p s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h
@[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a::s) = filter p s :=
quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h
lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q]
{s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s :=
quot.induction_on s $ λ l h, congr_arg coe $ filter_congr h
@[simp] theorem filter_add (s t : multiset α) :
filter p (s + t) = filter p s + filter p t :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _
@[simp] theorem filter_le (s : multiset α) : filter p s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ filter_sublist _
@[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s :=
subset_of_le $ filter_le _
@[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a :=
quot.induction_on s $ λ l, mem_filter
theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a :=
(mem_filter.1 h).2
theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s :=
(mem_filter.1 h).1
theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l :=
mem_filter.2 ⟨m, h⟩
theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_self
theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a :=
quot.induction_on s $ λ l, iff.trans ⟨λ h,
eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h),
congr_arg coe⟩ filter_eq_nil
theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t :=
le_induction_on h $ λ l₁ l₂ h, subperm_of_sublist $ filter_sublist_filter h
theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a :=
⟨λ h, ⟨le_trans h (filter_le _), λ a m, of_mem_filter (mem_of_le h m)⟩,
λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter h⟩
@[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) :
filter p (s - t) = filter p s - filter p t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _),
rw [sub_cons, IH],
by_cases p a,
{ rw [filter_cons_of_pos _ h, sub_cons], congr,
by_cases m : a ∈ s,
{ rw [← cons_inj_right a, ← filter_cons_of_pos _ h,
cons_erase (mem_filter_of_mem m h), cons_erase m] },
{ rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } },
{ rw [filter_cons_of_neg _ h],
by_cases m : a ∈ s,
{ rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a :: erase s a)),
cons_erase m] },
{ rw [erase_of_not_mem m] } }
end
@[simp] theorem filter_union [decidable_eq α] (s t : multiset α) :
filter p (s ∪ t) = filter p s ∪ filter p t :=
by simp [(∪), union]
@[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) :
filter p (s ∩ t) = filter p s ∩ filter p t :=
le_antisymm (le_inter
(filter_le_filter $ inter_le_left _ _)
(filter_le_filter $ inter_le_right _ _)) $ le_filter.2
⟨inf_le_inf (filter_le _) (filter_le _),
λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩
@[simp] theorem filter_filter {q} [decidable_pred q] (s : multiset α) :
filter p (filter q s) = filter (λ a, p a ∧ q a) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter l
theorem filter_add_filter {q} [decidable_pred q] (s : multiset α) :
filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s :=
multiset.induction_on s rfl $ λ a s IH,
by by_cases p a; by_cases q a; simp *
theorem filter_add_not (s : multiset α) :
filter p s + filter (λ a, ¬ p a) s = s :=
by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em]
/- filter_map -/
/-- `filter_map f s` is a combination filter/map operation on `s`.
The function `f : α → option β` is applied to each element of `s`;
if `f a` is `some b` then `b` is added to the result, otherwise
`a` is removed from the resulting multiset. -/
def filter_map (f : α → option β) (s : multiset α) : multiset β :=
quot.lift_on s (λ l, (filter_map f l : multiset β))
(λ l₁ l₂ h, quot.sound $perm_filter_map f h)
@[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl
@[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl
@[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) :
filter_map f (a :: s) = filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h
@[simp] theorem filter_map_cons_some (f : α → option β)
(a : α) (s : multiset α) {b : β} (h : f a = some b) :
filter_map f (a :: s) = b :: filter_map f s :=
quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h
theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l
theorem filter_map_eq_filter (p : α → Prop) [decidable_pred p] :
filter_map (option.guard p) = filter p :=
funext $ λ s, quot.induction_on s $ λ l,
@congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l
theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) :
filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l
theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) :
map g (filter_map f s) = filter_map (λ x, (f x).map g) s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l
theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) :
filter_map g (map f s) = filter_map (g ∘ f) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l
theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) :
filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l
theorem filter_map_filter (p : α → Prop) [decidable_pred p] (f : α → option β) (s : multiset α) :
filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l
@[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s :=
quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l
@[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} :
b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b :=
quot.induction_on s $ λ l, mem_filter_map f l
theorem map_filter_map_of_inv (f : α → option β) (g : β → α)
(H : ∀ x : α, (f x).map g = some x) (s : multiset α) :
map g (filter_map f s) = s :=
quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l
theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α}
(h : s ≤ t) : filter_map f s ≤ filter_map f t :=
le_induction_on h $ λ l₁ l₂ h,
subperm_of_sublist $ filter_map_sublist_filter_map _ h
/- powerset -/
def powerset_aux (l : list α) : list (multiset α) :=
0 :: sublists_aux l (λ x y, x :: y)
theorem powerset_aux_eq_map_coe {l : list α} :
powerset_aux l = (sublists l).map coe :=
by simp [powerset_aux, sublists];
rw [← show @sublists_aux₁ α (multiset α) l (λ x, [↑x]) =
sublists_aux l (λ x, list.cons ↑x),
from sublists_aux₁_eq_sublists_aux _ _,
sublists_aux_cons_eq_sublists_aux₁,
← bind_ret_eq_map, sublists_aux₁_bind]; refl
@[simp] theorem mem_powerset_aux {l : list α} {s} :
s ∈ powerset_aux l ↔ s ≤ ↑l :=
quotient.induction_on s $
by simp [powerset_aux_eq_map_coe, subperm, and.comm]
def powerset_aux' (l : list α) : list (multiset α) := (sublists' l).map coe
theorem powerset_aux_perm_powerset_aux' {l : list α} :
powerset_aux l ~ powerset_aux' l :=
by rw powerset_aux_eq_map_coe; exact
perm_map _ (sublists_perm_sublists' _)
@[simp] theorem powerset_aux'_nil : powerset_aux' (@nil α) = [0] := rfl
@[simp] theorem powerset_aux'_cons (a : α) (l : list α) :
powerset_aux' (a::l) = powerset_aux' l ++ list.map (cons a) (powerset_aux' l) :=
by simp [powerset_aux']; refl
theorem powerset_aux'_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux' l₁ ~ powerset_aux' l₂ :=
begin
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {simp},
{ simp, exact perm_app IH (perm_map _ IH) },
{ simp, apply perm_app_right,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
theorem powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_aux l₁ ~ powerset_aux l₂ :=
powerset_aux_perm_powerset_aux'.trans $
(powerset_aux'_perm p).trans powerset_aux_perm_powerset_aux'.symm
def powerset (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_aux l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_aux_perm h))
theorem powerset_coe (l : list α) :
@powerset α l = ((sublists l).map coe : list (multiset α)) :=
congr_arg coe powerset_aux_eq_map_coe
@[simp] theorem powerset_coe' (l : list α) :
@powerset α l = ((sublists' l).map coe : list (multiset α)) :=
quot.sound powerset_aux_perm_powerset_aux'
@[simp] theorem powerset_zero : @powerset α 0 = 0::0 := rfl
@[simp] theorem powerset_cons (a : α) (s) :
powerset (a::s) = powerset s + map (cons a) (powerset s) :=
quotient.induction_on s $ λ l, by simp; refl
@[simp] theorem mem_powerset {s t : multiset α} :
s ∈ powerset t ↔ s ≤ t :=
quotient.induction_on₂ s t $ by simp [subperm, and.comm]
theorem map_single_le_powerset (s : multiset α) :
s.map (λ a, a::0) ≤ powerset s :=
quotient.induction_on s $ λ l, begin
simp [powerset_coe],
show l.map (coe ∘ list.ret) <+~ (sublists l).map coe,
rw ← list.map_map,
exact subperm_of_sublist
(map_sublist_map _ (map_ret_sublist_sublists _))
end
@[simp] theorem card_powerset (s : multiset α) :
card (powerset s) = 2 ^ card s :=
quotient.induction_on s $ by simp
/- antidiagonal -/
theorem revzip_powerset_aux {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux_eq_map_coe, ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists _ _ _ h)
end
theorem revzip_powerset_aux' {l : list α} ⦃x⦄
(h : x ∈ revzip (powerset_aux' l)) : x.1 + x.2 = ↑l :=
begin
rw [revzip, powerset_aux', ← map_reverse, zip_map, ← revzip] at h,
simp at h, rcases h with ⟨l₁, l₂, h, rfl, rfl⟩,
exact quot.sound (revzip_sublists' _ _ _ h)
end
theorem revzip_powerset_aux_lemma [decidable_eq α] (l : list α)
{l' : list (multiset α)} (H : ∀ ⦃x : _ × _⦄, x ∈ revzip l' → x.1 + x.2 = ↑l) :
revzip l' = l'.map (λ x, (x, ↑l - x)) :=
begin
have : forall₂ (λ (p : multiset α × multiset α) (s : multiset α), p = (s, ↑l - s))
(revzip l') ((revzip l').map prod.fst),
{ rw forall₂_map_right_iff,
apply forall₂_same, rintro ⟨s, t⟩ h,
dsimp, rw [← H h, add_sub_cancel_left] },
rw [← forall₂_eq_eq_eq, forall₂_map_right_iff], simpa
end
theorem revzip_powerset_aux_perm_aux' {l : list α} :
revzip (powerset_aux l) ~ revzip (powerset_aux' l) :=
begin
haveI := classical.dec_eq α,
rw [revzip_powerset_aux_lemma l revzip_powerset_aux,
revzip_powerset_aux_lemma l revzip_powerset_aux'],
exact perm_map _ powerset_aux_perm_powerset_aux',
end
theorem revzip_powerset_aux_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) :
revzip (powerset_aux l₁) ~ revzip (powerset_aux l₂) :=
begin
haveI := classical.dec_eq α,
simp [λ l:list α, revzip_powerset_aux_lemma l revzip_powerset_aux, coe_eq_coe.2 p],
exact perm_map _ (powerset_aux_perm p)
end
/-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/
def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) :=
quot.lift_on s
(λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α)))
(λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h))
theorem antidiagonal_coe (l : list α) :
@antidiagonal α l = revzip (powerset_aux l) := rfl
@[simp] theorem antidiagonal_coe' (l : list α) :
@antidiagonal α l = revzip (powerset_aux' l) :=
quot.sound revzip_powerset_aux_perm_aux'
/-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s`
if and only if `t₁ + t₂ = s`. -/
@[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} :
x ∈ antidiagonal s ↔ x.1 + x.2 = s :=
quotient.induction_on s $ λ l, begin
simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩,
haveI := classical.dec_eq α,
simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm],
cases x with x₁ x₂,
exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩
end
@[simp] theorem antidiagonal_map_fst (s : multiset α) :
(antidiagonal s).map prod.fst = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_map_snd (s : multiset α) :
(antidiagonal s).map prod.snd = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl
@[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) =
map (prod.map id (cons a)) (antidiagonal s) +
map (prod.map (cons a) id) (antidiagonal s) :=
quotient.induction_on s $ λ l, begin
simp [revzip, reverse_append],
rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)],
{congr; simp}, {simp}
end
@[simp] theorem card_antidiagonal (s : multiset α) :
card (antidiagonal s) = 2 ^ card s :=
by have := card_powerset s;
rwa [← antidiagonal_map_fst, card_map] at this
lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} :
prod (s.map (λa, f a + g a)) =
sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) :=
begin
refine s.induction_on _ _,
{ simp },
{ assume a s ih, simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm] },
end
/- powerset_len -/
def powerset_len_aux (n : ℕ) (l : list α) : list (multiset α) :=
sublists_len_aux n l coe []
theorem powerset_len_aux_eq_map_coe {n} {l : list α} :
powerset_len_aux n l = (sublists_len n l).map coe :=
by rw [powerset_len_aux, sublists_len_aux_eq, append_nil]
@[simp] theorem mem_powerset_len_aux {n} {l : list α} {s} :
s ∈ powerset_len_aux n l ↔ s ≤ ↑l ∧ card s = n :=
quotient.induction_on s $
by simp [powerset_len_aux_eq_map_coe, subperm]; exact
λ l₁, ⟨λ ⟨l₂, ⟨s, e⟩, p⟩, ⟨⟨_, p, s⟩, (perm_length p.symm).trans e⟩,
λ ⟨⟨l₂, p, s⟩, e⟩, ⟨_, ⟨s, (perm_length p).trans e⟩, p⟩⟩
@[simp] theorem powerset_len_aux_zero (l : list α) :
powerset_len_aux 0 l = [0] :=
by simp [powerset_len_aux_eq_map_coe]
@[simp] theorem powerset_len_aux_nil (n : ℕ) :
powerset_len_aux (n+1) (@nil α) = [] := rfl
@[simp] theorem powerset_len_aux_cons (n : ℕ) (a : α) (l : list α) :
powerset_len_aux (n+1) (a::l) =
powerset_len_aux (n+1) l ++ list.map (cons a) (powerset_len_aux n l) :=
by simp [powerset_len_aux_eq_map_coe]; refl
theorem powerset_len_aux_perm {n} {l₁ l₂ : list α} (p : l₁ ~ l₂) :
powerset_len_aux n l₁ ~ powerset_len_aux n l₂ :=
begin
induction n with n IHn generalizing l₁ l₂, {simp},
induction p with a l₁ l₂ p IH a b l l₁ l₂ l₃ p₁ p₂ IH₁ IH₂, {refl},
{ simp, exact perm_app IH (perm_map _ (IHn p)) },
{ simp, apply perm_app_right,
cases n, {simp, apply perm.swap},
simp,
rw [← append_assoc, ← append_assoc,
(by funext s; simp [cons_swap] : cons b ∘ cons a = cons a ∘ cons b)],
exact perm_app_left _ perm_app_comm },
{ exact IH₁.trans IH₂ }
end
def powerset_len (n : ℕ) (s : multiset α) : multiset (multiset α) :=
quot.lift_on s
(λ l, (powerset_len_aux n l : multiset (multiset α)))
(λ l₁ l₂ h, quot.sound (powerset_len_aux_perm h))
theorem powerset_len_coe' (n) (l : list α) :
@powerset_len α n l = powerset_len_aux n l := rfl
theorem powerset_len_coe (n) (l : list α) :
@powerset_len α n l = ((sublists_len n l).map coe : list (multiset α)) :=
congr_arg coe powerset_len_aux_eq_map_coe
@[simp] theorem powerset_len_zero_left (s : multiset α) :
powerset_len 0 s = 0::0 :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem powerset_len_zero_right (n : ℕ) :
@powerset_len α (n + 1) 0 = 0 := rfl
@[simp] theorem powerset_len_cons (n : ℕ) (a : α) (s) :
powerset_len (n + 1) (a::s) =
powerset_len (n + 1) s + map (cons a) (powerset_len n s) :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe']; refl
@[simp] theorem mem_powerset_len {n : ℕ} {s t : multiset α} :
s ∈ powerset_len n t ↔ s ≤ t ∧ card s = n :=
quotient.induction_on t $ λ l, by simp [powerset_len_coe']
@[simp] theorem card_powerset_len (n : ℕ) (s : multiset α) :
card (powerset_len n s) = nat.choose (card s) n :=
quotient.induction_on s $ by simp [powerset_len_coe]
theorem powerset_len_le_powerset (n : ℕ) (s : multiset α) :
powerset_len n s ≤ powerset s :=
quotient.induction_on s $ λ l, by simp [powerset_len_coe]; exact
subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_sublists' _ _))
theorem powerset_len_mono (n : ℕ) {s t : multiset α} (h : s ≤ t) :
powerset_len n s ≤ powerset_len n t :=
le_induction_on h $ λ l₁ l₂ h, by simp [powerset_len_coe]; exact
subperm_of_sublist (map_sublist_map _ (sublists_len_sublist_of_sublist _ h))
/- countp -/
/-- `countp p s` counts the number of elements of `s` (with multiplicity) that
satisfy `p`. -/
def countp (p : α → Prop) [decidable_pred p] (s : multiset α) : ℕ :=
quot.lift_on s (countp p) (λ l₁ l₂, perm_countp p)
@[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl
@[simp] theorem countp_zero (p : α → Prop) [decidable_pred p] : countp p 0 = 0 := rfl
@[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a::s) = countp p s + 1 :=
quot.induction_on s countp_cons_of_pos
@[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a::s) = countp p s :=
quot.induction_on s countp_cons_of_neg
theorem countp_eq_card_filter (s) : countp p s = card (filter p s) :=
quot.induction_on s $ λ l, countp_eq_length_filter _
@[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t :=
by simp [countp_eq_card_filter]
instance countp.is_add_monoid_hom : is_add_monoid_hom (countp p : multiset α → ℕ) :=
{ map_add := countp_add, map_zero := countp_zero _ }
theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a :=
by simp [countp_eq_card_filter, card_pos_iff_exists_mem]
@[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) :
countp p (s - t) = countp p s - countp p t :=
by simp [countp_eq_card_filter, h, filter_le_filter]
theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s :=
countp_pos.2 ⟨_, h, pa⟩
theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t :=
by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter h)
@[simp] theorem countp_filter {q} [decidable_pred q] (s : multiset α) :
countp p (filter q s) = countp (λ a, p a ∧ q a) s :=
by simp [countp_eq_card_filter]
end
/- count -/
section
variable [decidable_eq α]
/-- `count a s` is the multiplicity of `a` in `s`. -/
def count (a : α) : multiset α → ℕ := countp (eq a)
@[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _
@[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl
@[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a::s) = succ (count a s) :=
countp_cons_of_pos _ rfl
@[simp] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b::s) = count a s :=
countp_cons_of_neg _ h
theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t :=
countp_le_of_le
theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b :: s) :=
count_le_of_le _ (le_cons_self _ _)
theorem count_singleton (a : α) : count a (a::0) = 1 :=
by simp
@[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t :=
countp_add
instance count.is_add_monoid_hom (a : α) : is_add_monoid_hom (count a : multiset α → ℕ) :=
countp.is_add_monoid_hom
@[simp] theorem count_smul (a : α) (n s) : count a (n • s) = n * count a s :=
by induction n; simp [*, succ_smul', succ_mul]
theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s :=
by simp [count, countp_pos]
@[simp] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 :=
by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h')
theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s :=
iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero
@[simp] theorem count_repeat (a : α) (n : ℕ) : count a (repeat a n) = n :=
by simp [repeat]
@[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) :=
begin
by_cases a ∈ s,
{ rw [(by rw cons_erase h : count a s = count a (a::erase s a)),
count_cons_self]; refl },
{ rw [erase_of_not_mem h, count_eq_zero.2 h]; refl }
end
@[simp] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s :=
begin
by_cases b ∈ s,
{ rw [← count_cons_of_ne ab, cons_erase h] },
{ rw [erase_of_not_mem h] }
end
@[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t :=
begin
revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _),
rw [sub_cons, IH],
by_cases ab : a = b,
{ subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] },
{ rw [count_erase_of_ne ab, count_cons_of_ne ab] }
end
@[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) :=
by simp [(∪), union, sub_add_eq_max, -add_comm]
@[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) :=
begin
apply @nat.add_left_cancel (count a (s - t)),
rw [← count_add, sub_add_inter, count_sub, sub_add_min],
end
lemma count_bind {m : multiset β} {f : β → multiset α} {a : α} :
count a (bind m f) = sum (m.map $ λb, count a $ f b) :=
multiset.induction_on m (by simp) (by simp)
theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s :=
quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm
@[simp] theorem count_filter {p} [decidable_pred p]
{a} {s : multiset α} (h : p a) : count a (filter p s) = count a s :=
quot.induction_on s $ λ l, count_filter h
theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t :=
quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count
@[ext]
theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t :=
ext.2
@[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) :=
by ext; simp
theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t :=
⟨λ h a, count_le_of_le a h, λ al,
by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t);
apply le_union_left⟩
instance : distrib_lattice (multiset α) :=
{ le_sup_inf := λ s t u, le_of_eq $ eq.symm $
ext.2 $ λ a, by simp only [max_min_distrib_left,
multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter],
..multiset.lattice.lattice }
instance : semilattice_sup_bot (multiset α) :=
{ bot := 0,
bot_le := zero_le,
..multiset.lattice.lattice }
end
/- relator -/
section rel
/-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`,
s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/
inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop
| zero {} : rel 0 0
| cons {a b as bs} : r a b → rel as bs → rel (a :: as) (b :: bs)
run_cmd tactic.mk_iff_of_inductive_prop `multiset.rel `multiset.rel_iff
variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop}
private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s :=
rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih)
lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s :=
⟨rel_flip_aux, rel_flip_aux⟩
lemma rel_eq_refl {s : multiset α} : rel (=) s s :=
multiset.induction_on s rel.zero (assume a s, rel.cons rfl)
lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t :=
begin
split,
{ assume h, induction h; simp * },
{ assume h, subst h, exact rel_eq_refl }
end
lemma rel.mono {p : α → β → Prop} {s t} (h : ∀a b, r a b → p a b) (hst : rel r s t) : rel p s t :=
begin
induction hst,
case rel.zero { exact rel.zero },
case rel.cons : a b s t hab hst ih { exact ih.cons (h a b hab) }
end
lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) :=
begin
induction hst,
case rel.zero { simpa using huv },
case rel.cons : a b s t hab hst ih { simpa using ih.cons hab }
end
lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t :=
show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm]
@[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 :=
by rw [rel_iff]; simp
@[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 :=
by rw [rel_iff]; simp
lemma rel_cons_left {a as bs} :
rel r (a :: as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b :: bs') :=
begin
split,
{ generalize hm : a :: as = m,
assume h,
induction h generalizing as,
case rel.zero { simp at hm, contradiction },
case rel.cons : a' b as' bs ha'b h ih {
rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩,
{ subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ },
{ rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩,
exact ⟨b', b::bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ }
} },
{ exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h }
end
lemma rel_cons_right {as b bs} :
rel r as (b :: bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a :: as') :=
begin
rw [← rel_flip, rel_cons_left],
apply exists_congr, assume a,
apply exists_congr, assume as',
rw [rel_flip, flip]
end
lemma rel_add_left {as₀ as₁} :
∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) :=
multiset.induction_on as₀ (by simp)
begin
assume a s ih bs,
simp only [ih, cons_add, rel_cons_left],
split,
{ assume h,
rcases h with ⟨b, bs', hab, h, rfl⟩,
rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩,
exact ⟨b :: bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ },
{ assume h,
rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩,
rcases h with ⟨b, bs, hab, h₀, rfl⟩,
exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ }
end
lemma rel_add_right {as bs₀ bs₁} :
rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) :=
by rw [← rel_flip, rel_add_left]; simp [rel_flip]
lemma rel_map_left {s : multiset γ} {f : γ → α} :
∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t :=
multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt})
lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} :
rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t :=
by rw [← rel_flip, rel_map_left, ← rel_flip]; refl
lemma rel_join {s t} (h : rel (rel r) s t) : rel r s.join t.join :=
begin
induction h,
case rel.zero { simp },
case rel.cons : a b s t hab hst ih { simpa using hab.add ih }
end
lemma rel_map {p : γ → δ → Prop} {s t} {f : α → γ} {g : β → δ} (h : (r ⇒ p) f g) (hst : rel r s t) :
rel p (s.map f) (t.map g) :=
by rw [rel_map_left, rel_map_right]; exact hst.mono h
lemma rel_bind {p : γ → δ → Prop} {s t} {f : α → multiset γ} {g : β → multiset δ}
(h : (r ⇒ rel p) f g) (hst : rel r s t) :
rel p (s.bind f) (t.bind g) :=
by apply rel_join; apply rel_map; assumption
lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
card s = card t :=
by induction h; simp [*]
lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) :
∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b :=
begin
induction h with x y s t hxy hst ih,
{ simp },
{ assume a ha,
cases mem_cons.1 ha with ha ha,
{ exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ },
{ rcases ih ha with ⟨b, hbt, hab⟩,
exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } }
end
end rel
section map
theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} :
s.map f = t.map f ↔ s = t :=
by rw [← rel_eq, ← rel_eq, rel_map_left, rel_map_right]; simp [hf.eq_iff]
theorem injective_map {f : α → β} (hf : function.injective f) :
function.injective (multiset.map f) :=
assume x y, (map_eq_map hf).1
end map
section quot
theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) :
s.map (quot.mk r) = t.map (quot.mk r) :=
rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab]
theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) :
∃t:multiset α, s = t.map (quot.mk r) :=
multiset.induction_on s ⟨0, rfl⟩ $
assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a::t, (map_cons _ _ _).symm⟩
theorem induction_on_multiset_quot
{r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) :
(∀s:multiset α, p (s.map (quot.mk r))) → p s :=
match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end
end quot
/- disjoint -/
/-- `disjoint s t` means that `s` and `t` have no elements in common. -/
def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false
@[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl
theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s
| a i₂ i₁ := d i₁ i₂
@[simp] theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s :=
⟨disjoint.symm, disjoint.symm⟩
theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl
theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
disjoint_comm
theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t
| x m₁ := d (h m₁)
theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t
| x m m₁ := d m (h m₁)
theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t :=
disjoint_of_subset_left (subset_of_le h)
theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t :=
disjoint_of_subset_right (subset_of_le h)
@[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l
| a := (not_mem_nil a).elim
@[simp] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint (a::0) l ↔ a ∉ l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l (a::0) ↔ a ∉ l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_add_left {s t u : multiset α} :
disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_add_right {s t u : multiset α} :
disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u :=
disjoint_comm.trans $ by simp [disjoint_append_left]
@[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} :
disjoint (a::s) t ↔ a ∉ t ∧ disjoint s t :=
(@disjoint_add_left _ (a::0) s t).trans $ by simp
@[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} :
disjoint s (a::t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp [disjoint_cons_left]
theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} :
disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) :=
begin
simp [disjoint],
split,
from assume h a ha b hb eq, h _ ha rfl _ hb eq.symm,
from assume h c a ha eq₁ b hb eq₂, h _ ha _ hb (eq₂.symm ▸ eq₁)
end
/-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/
def pairwise (r : α → α → Prop) (m : multiset α) : Prop :=
∃l:list α, m = l ∧ l.pairwise r
lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} :
multiset.pairwise r l ↔ l.pairwise r :=
iff.intro
(assume ⟨l', eq, h⟩, (list.perm_pairwise hr (quotient.exact eq)).2 h)
(assume h, ⟨l, rfl, h⟩)
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext $ perm_nodup p)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem forall_mem_ne {a : α} {l : list α} : (∀ (a' : α), a' ∈ l → ¬a = a') ↔ a ∉ l :=
⟨λ h m, h _ m rfl, λ h a' m e, h (e.symm ▸ m)⟩
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a::s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
theorem nodup_cons_of_nodup {a : α} {s : multiset α} (m : a ∉ s) (n : nodup s) : nodup (a::s) :=
nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup (a::0) := nodup_singleton
theorem nodup_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : nodup s :=
(nodup_cons.1 h).2
theorem not_mem_of_nodup_cons {a : α} {s : multiset α} (h : nodup (a::s)) : a ∉ s :=
(nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup_of_sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a::a::0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a::a::0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma pairwise_of_nodup {r : α → α → Prop} {s : multiset α} :
(∀a∈s, ∀b∈s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
lemma forall_of_pairwise {r : α → α → Prop} (H : symmetric r) {s : multiset α}
(hs : pairwise r s) : (∀a∈s, ∀b∈s, a ≠ b → r a b) :=
let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ list.forall_of_pairwise H hl₂
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
theorem nodup_add_of_nodup {s t : multiset α} (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
theorem nodup_of_nodup_map (f : α → β) {s : multiset α} : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup_of_nodup_map f
theorem nodup_map_on {f : α → β} {s : multiset α} : (∀x∈s, ∀y∈s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup_map_on
theorem nodup_map {f : α → β} {s : multiset α} (hf : function.injective f) : nodup s → nodup (map f s) :=
nodup_map_on (λ x _ y _ h, hf h)
theorem nodup_filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup_filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup_pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ nodup_erase_eq_filter a d
theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
theorem mem_erase_iff_of_nodup [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw nodup_erase_eq_filter b d; simp [and_comm]
theorem mem_erase_of_nodup [decidable_eq α] {a : α} {l} (h : nodup l) : a ∉ l.erase a :=
by rw mem_erase_iff_of_nodup h; simp
theorem nodup_product {s : multiset α} {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [nodup_product d₁ d₂]
theorem nodup_sigma {σ : α → Type*} {s : multiset α} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ assume l₁,
begin
choose f hf using assume a, quotient.exists_rep (t a),
rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a),
simpa using nodup_sigma
end
theorem nodup_filter_map (f : α → option β) {s : multiset α}
(H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup_filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
theorem nodup_inter_left [decidable_eq α] {s : multiset α} (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
theorem nodup_inter_right [decidable_eq α] (s) {t : multiset α} : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} : nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, nodup_of_nodup_map _ (nodup_of_le (map_single_le_powerset _) h),
quotient.induction_on s $ λ l h,
by simp; refine list.nodup_map_on _ (nodup_sublists'.2 h); exact
λ x sx y sy e,
(perm_ext_sublist_nodup h (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
theorem nodup_powerset_len {n : ℕ} {s : multiset α}
(h : nodup s) : nodup (powerset_len n s) :=
nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h)
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
theorem nodup_ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, subperm_of_subset_nodup d⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le (sub_le_self _ _) h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, nat.sub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le (le_sub_add _ _) h₁) h₂⟩
lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β}
(hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β)
(hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂)
(i_surj : ∀b∈t, ∃a ha, b = i a ha) :
s.map f = t.map g :=
have t = s.attach.map (λ x, i x.1 x.2),
from (nodup_ext ht (nodup_map
(show function.injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy,
subtype.eq (i_inj x.1 y.1 x.2 y.2 hxy))
(nodup_attach.2 hs))).2
(λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach];
exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩),
calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map]
... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach]
... = t.map g : by rw [this, multiset.map_map]; exact map_congr (λ x _, h _ _)
section
variable [decidable_eq α]
/- erase_dup -/
/-- `erase_dup s` removes duplicates from `s`, yielding a `nodup` multiset. -/
def erase_dup (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.erase_dup : multiset α))
(λ s t p, quot.sound (perm_erase_dup_of_perm p))
@[simp] theorem coe_erase_dup (l : list α) : @erase_dup α _ l = l.erase_dup := rfl
@[simp] theorem erase_dup_zero : @erase_dup α _ 0 = 0 := rfl
@[simp] theorem mem_erase_dup {a : α} {s : multiset α} : a ∈ erase_dup s ↔ a ∈ s :=
quot.induction_on s $ λ l, mem_erase_dup
@[simp] theorem erase_dup_cons_of_mem {a : α} {s : multiset α} : a ∈ s →
erase_dup (a::s) = erase_dup s :=
quot.induction_on s $ λ l m, @congr_arg _ _ _ _ coe $ erase_dup_cons_of_mem m
@[simp] theorem erase_dup_cons_of_not_mem {a : α} {s : multiset α} : a ∉ s →
erase_dup (a::s) = a :: erase_dup s :=
quot.induction_on s $ λ l m, congr_arg coe $ erase_dup_cons_of_not_mem m
theorem erase_dup_le (s : multiset α) : erase_dup s ≤ s :=
quot.induction_on s $ λ l, subperm_of_sublist $ erase_dup_sublist _
theorem erase_dup_subset (s : multiset α) : erase_dup s ⊆ s :=
subset_of_le $ erase_dup_le _
theorem subset_erase_dup (s : multiset α) : s ⊆ erase_dup s :=
λ a, mem_erase_dup.2
@[simp] theorem erase_dup_subset' {s t : multiset α} : erase_dup s ⊆ t ↔ s ⊆ t :=
⟨subset.trans (subset_erase_dup _), subset.trans (erase_dup_subset _)⟩
@[simp] theorem subset_erase_dup' {s t : multiset α} : s ⊆ erase_dup t ↔ s ⊆ t :=
⟨λ h, subset.trans h (erase_dup_subset _), λ h, subset.trans h (subset_erase_dup _)⟩
@[simp] theorem nodup_erase_dup (s : multiset α) : nodup (erase_dup s) :=
quot.induction_on s nodup_erase_dup
theorem erase_dup_eq_self {s : multiset α} : erase_dup s = s ↔ nodup s :=
⟨λ e, e ▸ nodup_erase_dup s,
quot.induction_on s $ λ l h, congr_arg coe $ erase_dup_eq_self.2 h⟩
theorem erase_dup_eq_zero {s : multiset α} : erase_dup s = 0 ↔ s = 0 :=
⟨λ h, eq_zero_of_subset_zero $ h ▸ subset_erase_dup _,
λ h, h.symm ▸ erase_dup_zero⟩
@[simp] theorem erase_dup_singleton {a : α} : erase_dup (a :: 0) = a :: 0 :=
erase_dup_eq_self.2 $ nodup_singleton _
theorem le_erase_dup {s t : multiset α} : s ≤ erase_dup t ↔ s ≤ t ∧ nodup s :=
⟨λ h, ⟨le_trans h (erase_dup_le _), nodup_of_le h (nodup_erase_dup _)⟩,
λ ⟨l, d⟩, (le_iff_subset d).2 $ subset.trans (subset_of_le l) (subset_erase_dup _)⟩
theorem erase_dup_ext {s t : multiset α} : erase_dup s = erase_dup t ↔ ∀ a, a ∈ s ↔ a ∈ t :=
by simp [nodup_ext]
theorem erase_dup_map_erase_dup_eq [decidable_eq β] (f : α → β) (s : multiset α) :
erase_dup (map f (erase_dup s)) = erase_dup (map f s) := by simp [erase_dup_ext]
/- finset insert -/
/-- `ndinsert a s` is the lift of the list `insert` operation. This operation
does not respect multiplicities, unlike `cons`, but it is suitable as
an insert operation on `finset`. -/
def ndinsert (a : α) (s : multiset α) : multiset α :=
quot.lift_on s (λ l, (l.insert a : multiset α))
(λ s t p, quot.sound (perm_insert a p))
@[simp] theorem coe_ndinsert (a : α) (l : list α) : ndinsert a l = (insert a l : list α) := rfl
@[simp] theorem ndinsert_zero (a : α) : ndinsert a 0 = a::0 := rfl
@[simp] theorem ndinsert_of_mem {a : α} {s : multiset α} : a ∈ s → ndinsert a s = s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_mem h
@[simp] theorem ndinsert_of_not_mem {a : α} {s : multiset α} : a ∉ s → ndinsert a s = a :: s :=
quot.induction_on s $ λ l h, congr_arg coe $ insert_of_not_mem h
@[simp] theorem mem_ndinsert {a b : α} {s : multiset α} : a ∈ ndinsert b s ↔ a = b ∨ a ∈ s :=
quot.induction_on s $ λ l, mem_insert_iff
@[simp] theorem le_ndinsert_self (a : α) (s : multiset α) : s ≤ ndinsert a s :=
quot.induction_on s $ λ l, subperm_of_sublist $ sublist_of_suffix $ suffix_insert _ _
@[simp] theorem mem_ndinsert_self (a : α) (s : multiset α) : a ∈ ndinsert a s :=
mem_ndinsert.2 (or.inl rfl)
@[simp] theorem mem_ndinsert_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ ndinsert b s :=
mem_ndinsert.2 (or.inr h)
@[simp] theorem length_ndinsert_of_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∈ s) :
card (ndinsert a s) = card s :=
by simp [h]
@[simp] theorem length_ndinsert_of_not_mem {a : α} [decidable_eq α] {s : multiset α} (h : a ∉ s) :
card (ndinsert a s) = card s + 1 :=
by simp [h]
theorem erase_dup_cons {a : α} {s : multiset α} :
erase_dup (a::s) = ndinsert a (erase_dup s) :=
by by_cases a ∈ s; simp [h]
theorem nodup_ndinsert (a : α) {s : multiset α} : nodup s → nodup (ndinsert a s) :=
quot.induction_on s $ λ l, nodup_insert
theorem ndinsert_le {a : α} {s t : multiset α} : ndinsert a s ≤ t ↔ s ≤ t ∧ a ∈ t :=
⟨λ h, ⟨le_trans (le_ndinsert_self _ _) h, mem_of_le h (mem_ndinsert_self _ _)⟩,
λ ⟨l, m⟩, if h : a ∈ s then by simp [h, l] else
by rw [ndinsert_of_not_mem h, ← cons_erase m, cons_le_cons_iff,
← le_cons_of_not_mem h, cons_erase m]; exact l⟩
lemma attach_ndinsert (a : α) (s : multiset α) :
(s.ndinsert a).attach =
ndinsert ⟨a, mem_ndinsert_self a s⟩ (s.attach.map $ λp, ⟨p.1, mem_ndinsert_of_mem p.2⟩) :=
have eq : ∀h : ∀(p : {x // x ∈ s}), p.1 ∈ s,
(λ (p : {x // x ∈ s}), ⟨p.val, h p⟩ : {x // x ∈ s} → {x // x ∈ s}) = id, from
assume h, funext $ assume p, subtype.eq rfl,
have ∀t (eq : s.ndinsert a = t), t.attach = ndinsert ⟨a, eq ▸ mem_ndinsert_self a s⟩
(s.attach.map $ λp, ⟨p.1, eq ▸ mem_ndinsert_of_mem p.2⟩),
begin
intros t ht,
by_cases a ∈ s,
{ rw [ndinsert_of_mem h] at ht,
subst ht,
rw [eq, map_id, ndinsert_of_mem (mem_attach _ _)] },
{ rw [ndinsert_of_not_mem h] at ht,
subst ht,
simp [attach_cons, h] }
end,
this _ rfl
@[simp] theorem disjoint_ndinsert_left {a : α} {s t : multiset α} :
disjoint (ndinsert a s) t ↔ a ∉ t ∧ disjoint s t :=
iff.trans (by simp [disjoint]) disjoint_cons_left
@[simp] theorem disjoint_ndinsert_right {a : α} {s t : multiset α} :
disjoint s (ndinsert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint_comm.trans $ by simp
/- finset union -/
/-- `ndunion s t` is the lift of the list `union` operation. This operation
does not respect multiplicities, unlike `s ∪ t`, but it is suitable as
a union operation on `finset`. (`s ∪ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndunion (s t : multiset α) : multiset α :=
quotient.lift_on₂ s t (λ l₁ l₂, (l₁.union l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂,
quot.sound $ perm_union p₁ p₂
@[simp] theorem coe_ndunion (l₁ l₂ : list α) : @ndunion α _ l₁ l₂ = (l₁ ∪ l₂ : list α) := rfl
@[simp] theorem zero_ndunion (s : multiset α) : ndunion 0 s = s :=
quot.induction_on s $ λ l, rfl
@[simp] theorem cons_ndunion (s t : multiset α) (a : α) : ndunion (a :: s) t = ndinsert a (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, rfl
@[simp] theorem mem_ndunion {s t : multiset α} {a : α} : a ∈ ndunion s t ↔ a ∈ s ∨ a ∈ t :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.mem_union
theorem le_ndunion_right (s t : multiset α) : t ≤ ndunion s t :=
quotient.induction_on₂ s t $ λ l₁ l₂,
subperm_of_sublist $ sublist_of_suffix $ suffix_union_right _ _
theorem ndunion_le_add (s t : multiset α) : ndunion s t ≤ s + t :=
quotient.induction_on₂ s t $ λ l₁ l₂, subperm_of_sublist $ union_sublist_append _ _
theorem ndunion_le {s t u : multiset α} : ndunion s t ≤ u ↔ s ⊆ u ∧ t ≤ u :=
multiset.induction_on s (by simp) (by simp [ndinsert_le, and_comm, and.left_comm] {contextual := tt})
theorem subset_ndunion_left (s t : multiset α) : s ⊆ ndunion s t :=
λ a h, mem_ndunion.2 $ or.inl h
theorem le_ndunion_left {s} (t : multiset α) (d : nodup s) : s ≤ ndunion s t :=
(le_iff_subset d).2 $ subset_ndunion_left _ _
theorem ndunion_le_union (s t : multiset α) : ndunion s t ≤ s ∪ t :=
ndunion_le.2 ⟨subset_of_le (le_union_left _ _), le_union_right _ _⟩
theorem nodup_ndunion (s : multiset α) {t : multiset α} : nodup t → nodup (ndunion s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, list.nodup_union _
@[simp] theorem ndunion_eq_union {s t : multiset α} (d : nodup s) : ndunion s t = s ∪ t :=
le_antisymm (ndunion_le_union _ _) $ union_le (le_ndunion_left _ d) (le_ndunion_right _ _)
theorem erase_dup_add (s t : multiset α) : erase_dup (s + t) = ndunion s (erase_dup t) :=
quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ erase_dup_append _ _
/- finset inter -/
/-- `ndinter s t` is the lift of the list `∩` operation. This operation
does not respect multiplicities, unlike `s ∩ t`, but it is suitable as
an intersection operation on `finset`. (`s ∩ t` would also work as a union operation
on finset, but this is more efficient.) -/
def ndinter (s t : multiset α) : multiset α := filter (∈ t) s
@[simp] theorem coe_ndinter (l₁ l₂ : list α) : @ndinter α _ l₁ l₂ = (l₁ ∩ l₂ : list α) := rfl
@[simp] theorem zero_ndinter (s : multiset α) : ndinter 0 s = 0 := rfl
@[simp] theorem cons_ndinter_of_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∈ t) :
ndinter (a::s) t = a :: (ndinter s t) := by simp [ndinter, h]
@[simp] theorem ndinter_cons_of_not_mem {a : α} (s : multiset α) {t : multiset α} (h : a ∉ t) :
ndinter (a::s) t = ndinter s t := by simp [ndinter, h]
@[simp] theorem mem_ndinter {s t : multiset α} {a : α} : a ∈ ndinter s t ↔ a ∈ s ∧ a ∈ t :=
mem_filter
theorem nodup_ndinter {s : multiset α} (t : multiset α) : nodup s → nodup (ndinter s t) :=
nodup_filter _
theorem le_ndinter {s t u : multiset α} : s ≤ ndinter t u ↔ s ≤ t ∧ s ⊆ u :=
by simp [ndinter, le_filter, subset_iff]
theorem ndinter_le_left (s t : multiset α) : ndinter s t ≤ s :=
(le_ndinter.1 (le_refl _)).1
theorem ndinter_subset_right (s t : multiset α) : ndinter s t ⊆ t :=
(le_ndinter.1 (le_refl _)).2
theorem ndinter_le_right {s} (t : multiset α) (d : nodup s) : ndinter s t ≤ t :=
(le_iff_subset $ nodup_ndinter _ d).2 (ndinter_subset_right _ _)
theorem inter_le_ndinter (s t : multiset α) : s ∩ t ≤ ndinter s t :=
le_ndinter.2 ⟨inter_le_left _ _, subset_of_le $ inter_le_right _ _⟩
@[simp] theorem ndinter_eq_inter {s t : multiset α} (d : nodup s) : ndinter s t = s ∩ t :=
le_antisymm (le_inter (ndinter_le_left _ _) (ndinter_le_right _ d)) (inter_le_ndinter _ _)
theorem ndinter_eq_zero_iff_disjoint {s t : multiset α} : ndinter s t = 0 ↔ disjoint s t :=
by rw ← subset_zero; simp [subset_iff, disjoint]
end
/- fold -/
section fold
variables (op : α → α → α) [hc : is_commutative α op] [ha : is_associative α op]
local notation a * b := op a b
include hc ha
/-- `fold op b s` folds a commutative associative operation `op` over
the multiset `s`. -/
def fold : α → multiset α → α := foldr op (left_comm _ hc.comm ha.assoc)
theorem fold_eq_foldr (b : α) (s : multiset α) : fold op b s = foldr op (left_comm _ hc.comm ha.assoc) b s := rfl
@[simp] theorem coe_fold_r (b : α) (l : list α) : fold op b l = l.foldr op b := rfl
theorem coe_fold_l (b : α) (l : list α) : fold op b l = l.foldl op b :=
(coe_foldr_swap op _ b l).trans $ by simp [hc.comm]
theorem fold_eq_foldl (b : α) (s : multiset α) : fold op b s = foldl op (right_comm _ hc.comm ha.assoc) b s :=
quot.induction_on s $ λ l, coe_fold_l _ _ _
@[simp] theorem fold_zero (b : α) : (0 : multiset α).fold op b = b := rfl
@[simp] theorem fold_cons_left : ∀ (b a : α) (s : multiset α),
(a :: s).fold op b = a * s.fold op b := foldr_cons _ _
theorem fold_cons_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op b * a :=
by simp [hc.comm]
theorem fold_cons'_right (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (b * a) :=
by rw [fold_eq_foldl, foldl_cons, ← fold_eq_foldl]
theorem fold_cons'_left (b a : α) (s : multiset α) : (a :: s).fold op b = s.fold op (a * b) :=
by rw [fold_cons'_right, hc.comm]
theorem fold_add (b₁ b₂ : α) (s₁ s₂ : multiset α) : (s₁ + s₂).fold op (b₁ * b₂) = s₁.fold op b₁ * s₂.fold op b₂ :=
multiset.induction_on s₂
(by rw [add_zero, fold_zero, ← fold_cons'_right, ← fold_cons_right op])
(by simp {contextual := tt}; cc)
theorem fold_singleton (b a : α) : (a::0 : multiset α).fold op b = a * b := by simp
theorem fold_distrib {f g : β → α} (u₁ u₂ : α) (s : multiset β) :
(s.map (λx, f x * g x)).fold op (u₁ * u₂) = (s.map f).fold op u₁ * (s.map g).fold op u₂ :=
multiset.induction_on s (by simp) (by simp {contextual := tt}; cc)
theorem fold_hom {op' : β → β → β} [is_commutative β op'] [is_associative β op']
{m : α → β} (hm : ∀x y, m (op x y) = op' (m x) (m y)) (b : α) (s : multiset α) :
(s.map m).fold op' (m b) = m (s.fold op b) :=
multiset.induction_on s (by simp) (by simp [hm] {contextual := tt})
theorem fold_union_inter [decidable_eq α] (s₁ s₂ : multiset α) (b₁ b₂ : α) :
(s₁ ∪ s₂).fold op b₁ * (s₁ ∩ s₂).fold op b₂ = s₁.fold op b₁ * s₂.fold op b₂ :=
by rw [← fold_add op, union_add_inter, fold_add op]
@[simp] theorem fold_erase_dup_idem [decidable_eq α] [hi : is_idempotent α op] (s : multiset α) (b : α) :
(erase_dup s).fold op b = s.fold op b :=
multiset.induction_on s (by simp) $ λ a s IH, begin
by_cases a ∈ s; simp [IH, h],
show fold op b s = op a (fold op b s),
rw [← cons_erase h, fold_cons_left, ← ha.assoc, hi.idempotent],
end
end fold
theorem le_smul_erase_dup [decidable_eq α] (s : multiset α) :
∃ n : ℕ, s ≤ n • erase_dup s :=
⟨(s.map (λ a, count a s)).fold max 0, le_iff_count.2 $ λ a, begin
rw count_smul, by_cases a ∈ s,
{ refine le_trans _ (mul_le_mul_left _ $ count_pos.2 $ mem_erase_dup.2 h),
have : count a s ≤ fold max 0 (map (λ a, count a s) (a :: erase s a));
[simp [le_max_left], simpa [cons_erase h]] },
{ simp [count_eq_zero.2 h, nat.zero_le] }
end⟩
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a multiset: `sup {a, b, c} = a ⊔ b ⊔ c` -/
def sup (s : multiset α) : α := s.fold (⊔) ⊥
@[simp] lemma sup_zero : (0 : multiset α).sup = ⊥ :=
fold_zero _ _
@[simp] lemma sup_cons (a : α) (s : multiset α) :
(a :: s).sup = a ⊔ s.sup :=
fold_cons_left _ _ _ _
@[simp] lemma sup_singleton {a : α} : (a::0).sup = a := by simp
@[simp] lemma sup_add (s₁ s₂ : multiset α) : (s₁ + s₂).sup = s₁.sup ⊔ s₂.sup :=
eq.trans (by simp [sup]) (fold_add _ _ _ _ _)
variables [decidable_eq α]
@[simp] lemma sup_erase_dup (s : multiset α) : (erase_dup s).sup = s.sup :=
fold_erase_dup_idem _ _ _
@[simp] lemma sup_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).sup = s₁.sup ⊔ s₂.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_add]; simp
@[simp] lemma sup_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).sup = a ⊔ s.sup :=
by rw [← sup_erase_dup, erase_dup_ext.2, sup_erase_dup, sup_cons]; simp
lemma sup_le {s : multiset α} {a : α} : s.sup ≤ a ↔ (∀b ∈ s, b ≤ a) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma le_sup {s : multiset α} {a : α} (h : a ∈ s) : a ≤ s.sup :=
sup_le.1 (le_refl _) _ h
lemma sup_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₁.sup ≤ s₂.sup :=
sup_le.2 $ assume b hb, le_sup (h hb)
end sup
section inf
variables [semilattice_inf_top α]
/-- Infimum of a multiset: `inf {a, b, c} = a ⊓ b ⊓ c` -/
def inf (s : multiset α) : α := s.fold (⊓) ⊤
@[simp] lemma inf_zero : (0 : multiset α).inf = ⊤ :=
fold_zero _ _
@[simp] lemma inf_cons (a : α) (s : multiset α) :
(a :: s).inf = a ⊓ s.inf :=
fold_cons_left _ _ _ _
@[simp] lemma inf_singleton {a : α} : (a::0).inf = a := by simp
@[simp] lemma inf_add (s₁ s₂ : multiset α) : (s₁ + s₂).inf = s₁.inf ⊓ s₂.inf :=
eq.trans (by simp [inf]) (fold_add _ _ _ _ _)
variables [decidable_eq α]
@[simp] lemma inf_erase_dup (s : multiset α) : (erase_dup s).inf = s.inf :=
fold_erase_dup_idem _ _ _
@[simp] lemma inf_ndunion (s₁ s₂ : multiset α) :
(ndunion s₁ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_union (s₁ s₂ : multiset α) :
(s₁ ∪ s₂).inf = s₁.inf ⊓ s₂.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_add]; simp
@[simp] lemma inf_ndinsert (a : α) (s : multiset α) :
(ndinsert a s).inf = a ⊓ s.inf :=
by rw [← inf_erase_dup, erase_dup_ext.2, inf_erase_dup, inf_cons]; simp
lemma le_inf {s : multiset α} {a : α} : a ≤ s.inf ↔ (∀b ∈ s, a ≤ b) :=
multiset.induction_on s (by simp)
(by simp [or_imp_distrib, forall_and_distrib] {contextual := tt})
lemma inf_le {s : multiset α} {a : α} (h : a ∈ s) : s.inf ≤ a :=
le_inf.1 (le_refl _) _ h
lemma inf_mono {s₁ s₂ : multiset α} (h : s₁ ⊆ s₂) : s₂.inf ≤ s₁.inf :=
le_inf.2 $ assume b hb, inf_le (h hb)
end inf
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the multiset `s`.
(Uses merge sort algorithm.) -/
def sort (s : multiset α) : list α :=
quot.lift_on s (merge_sort r) $ λ a b h,
eq_of_sorted_of_perm
((perm_merge_sort _ _).trans $ h.trans (perm_merge_sort _ _).symm)
(sorted_merge_sort r _)
(sorted_merge_sort r _)
@[simp] theorem coe_sort (l : list α) : sort r l = merge_sort r l := rfl
@[simp] theorem sort_sorted (s : multiset α) : sorted r (sort r s) :=
quot.induction_on s $ λ l, sorted_merge_sort r _
@[simp] theorem sort_eq (s : multiset α) : ↑(sort r s) = s :=
quot.induction_on s $ λ l, quot.sound $ perm_merge_sort _ _
@[simp] theorem mem_sort {s : multiset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
by rw [← mem_coe, sort_eq]
@[simp] theorem length_sort {s : multiset α} : (sort r s).length = s.card :=
quot.induction_on s $ length_merge_sort _
end sort
instance [has_repr α] : has_repr (multiset α) :=
⟨λ s, "{" ++ string.intercalate ", " ((s.map repr).sort (≤)) ++ "}"⟩
section sections
def sections (s : multiset (multiset α)) : multiset (multiset α) :=
multiset.rec_on s {0} (λs _ c, s.bind $ λa, c.map ((::) a))
(assume a₀ a₁ s pi, by simp [map_bind, bind_bind a₀ a₁, cons_swap])
@[simp] lemma sections_zero : sections (0 : multiset (multiset α)) = 0::0 :=
rfl
@[simp] lemma sections_cons (s : multiset (multiset α)) (m : multiset α) :
sections (m :: s) = m.bind (λa, (sections s).map ((::) a)) :=
rec_on_cons m s
lemma coe_sections : ∀(l : list (list α)),
sections ((l.map (λl:list α, (l : multiset α))) : multiset (multiset α)) =
((l.sections.map (λl:list α, (l : multiset α))) : multiset (multiset α))
| [] := rfl
| (a :: l) :=
begin
simp,
rw [← cons_coe, sections_cons, bind_map_comm, coe_sections l],
simp [list.sections, (∘), list.bind]
end
@[simp] lemma sections_add (s t : multiset (multiset α)) :
sections (s + t) = (sections s).bind (λm, (sections t).map ((+) m)) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, bind_assoc, map_bind, bind_map, -add_comm])
lemma mem_sections {s : multiset (multiset α)} :
∀{a}, a ∈ sections s ↔ s.rel (λs a, a ∈ s) a :=
multiset.induction_on s (by simp)
(assume a s ih a',
by simp [ih, rel_cons_left, -exists_and_distrib_left, exists_and_distrib_left.symm, eq_comm])
lemma card_sections {s : multiset (multiset α)} : card (sections s) = prod (s.map card) :=
multiset.induction_on s (by simp) (by simp {contextual := tt})
lemma prod_map_sum [comm_semiring α] {s : multiset (multiset α)} :
prod (s.map sum) = sum ((sections s).map prod) :=
multiset.induction_on s (by simp)
(assume a s ih, by simp [ih, map_bind, sum_map_mul_left, sum_map_mul_right])
end sections
section pi
variables [decidable_eq α] {δ : α → Type*}
open function
def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a::m, δ a' :=
λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h
def pi.empty (δ : α → Type*) : (Πa∈(0:multiset α), δ a) .
lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a :: m) :
pi.cons m a b f a h = b :=
dif_pos rfl
lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a :: m) (h : a' ≠ a) :
pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) :=
dif_neg h
lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') :
pi.cons (a' :: m) a b (pi.cons m a' b' f) == pi.cons (a :: m) a' b' (pi.cons m a b f) :=
begin
apply hfunext, { refl }, intros a'' _ h, subst h,
apply hfunext, { rw [cons_swap] }, intros ha₁ ha₂ h,
by_cases h₁ : a'' = a; by_cases h₂ : a'' = a';
simp [*, pi.cons_same, pi.cons_ne] at *,
{ subst h₁, rw [pi.cons_same, pi.cons_same] },
{ subst h₂, rw [pi.cons_same, pi.cons_same] }
end
/-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/
def pi (m : multiset α) (t : Πa, multiset (δ a)) : multiset (Πa∈m, δ a) :=
m.rec_on {pi.empty δ} (λa m (p : multiset (Πa∈m, δ a)), (t a).bind $ λb, p.map $ pi.cons m a b)
begin
intros a a' m n,
by_cases eq : a = a',
{ subst eq },
{ simp [map_bind, bind_bind (t a') (t a)],
apply bind_hcongr, { rw [cons_swap a a'] },
intros b hb,
apply bind_hcongr, { rw [cons_swap a a'] },
intros b' hb',
apply map_hcongr, { rw [cons_swap a a'] },
intros f hf,
exact pi.cons_swap eq }
end
@[simp] lemma pi_zero (t : Πa, multiset (δ a)) : pi 0 t = pi.empty δ :: 0 := rfl
@[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (δ a)) (a : α) :
pi (a :: m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) :=
rec_on_cons a m
lemma injective_pi_cons {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume f₁ f₂ eq, funext $ assume a', funext $ assume h',
have ne : a ≠ a', from assume h, hs $ h.symm ▸ h',
have a' ∈ a :: s, from mem_cons_of_mem h',
calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm]
... = pi.cons s a b f₂ a' this : by rw [eq]
... = f₂ a' h' : by rw [pi.cons_ne this ne.symm]
lemma card_pi (m : multiset α) (t : Πa, multiset (δ a)) :
card (pi m t) = prod (m.map $ λa, card (t a)) :=
multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt})
lemma nodup_pi {s : multiset α} {t : Πa, multiset (δ a)} :
nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) :=
multiset.induction_on s (assume _ _, nodup_singleton _)
begin
assume a s ih hs ht,
have has : a ∉ s, by simp at hs; exact hs.1,
have hs : nodup s, by simp at hs; exact hs.2,
simp,
split,
{ assume b hb,
from nodup_map (injective_pi_cons has) (ih hs $ assume a' h', ht a' $ mem_cons_of_mem h') },
{ apply pairwise_of_nodup _ (ht a $ mem_cons_self _ _),
from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq,
have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _),
by rw [eq],
neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) }
end
lemma mem_pi (m : multiset α) (t : Πa, multiset (δ a)) :
∀f:Πa∈m, δ a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) :=
begin
refine multiset.induction_on m (λ f, _) (λ a m ih f, _),
{ simpa using show f = pi.empty δ, by funext a ha; exact ha.elim },
simp, split,
{ rintro ⟨b, hb, f', hf', rfl⟩ a' ha',
rw [ih] at hf',
by_cases a' = a,
{ subst h, rwa [pi.cons_same] },
{ rw [pi.cons_ne _ h], apply hf' } },
{ intro hf,
refine ⟨_, hf a (mem_cons_self a _), λa ha, f a (mem_cons_of_mem ha),
(ih _).2 (λ a' h', hf _ _), _⟩,
funext a' h',
by_cases a' = a,
{ subst h, rw [pi.cons_same] },
{ rw [pi.cons_ne _ h] } }
end
end pi
end multiset
namespace multiset
instance : functor multiset :=
{ map := @map }
instance : is_lawful_functor multiset :=
by refine { .. }; intros; simp
open is_lawful_traversable is_comm_applicative
variables {F : Type u_1 → Type u_1} [applicative F] [is_comm_applicative F]
variables {α' β' : Type u_1} (f : α' → F β')
def traverse : multiset α' → F (multiset β') :=
quotient.lift (functor.map coe ∘ traversable.traverse f)
begin
introv p, unfold function.comp,
induction p,
case perm.nil { refl },
case perm.skip {
have : multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₁) =
multiset.cons <$> f p_x <*> (coe <$> traverse f p_l₂),
{ rw [p_ih] },
simpa with functor_norm },
case perm.swap {
have : (λa b (l:list β'), (↑(a :: b :: l) : multiset β')) <$> f p_y <*> f p_x =
(λa b l, ↑(a :: b :: l)) <$> f p_x <*> f p_y,
{ rw [is_comm_applicative.commutative_map],
congr, funext a b l, simpa [flip] using perm.swap b a l },
simp [(∘), this] with functor_norm },
case perm.trans { simp [*] }
end
instance : monad multiset :=
{ pure := λ α x, x::0,
bind := @bind,
.. multiset.functor }
instance : is_lawful_monad multiset :=
{ bind_pure_comp_eq_map := λ α β f s, multiset.induction_on s rfl $ λ a s ih,
by rw [bind_cons, map_cons, bind_zero, add_zero],
pure_bind := λ α β x f, by simp only [cons_bind, zero_bind, add_zero],
bind_assoc := @bind_assoc }
open functor
open traversable is_lawful_traversable
@[simp]
lemma lift_beta {α β : Type*} (x : list α) (f : list α → β)
(h : ∀ a b : list α, a ≈ b → f a = f b) :
quotient.lift f h (x : multiset α) = f x :=
quotient.lift_beta _ _ _
@[simp]
lemma map_comp_coe {α β} (h : α → β) :
functor.map h ∘ coe = (coe ∘ functor.map h : list α → multiset β) :=
by funext; simp [functor.map]
lemma id_traverse {α : Type*} (x : multiset α) :
traverse id.mk x = x :=
quotient.induction_on x
(by { intro, rw [traverse,quotient.lift_beta,function.comp],
simp, congr })
lemma comp_traverse {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
{α β γ : Type*}
(g : α → G β) (h : β → H γ) (x : multiset α) :
traverse (comp.mk ∘ functor.map h ∘ g) x =
comp.mk (functor.map (traverse h) (traverse g x)) :=
quotient.induction_on x
(by intro;
simp [traverse,comp_traverse] with functor_norm;
simp [(<$>),(∘)] with functor_norm)
lemma map_traverse {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → G β) (h : β → γ)
(x : multiset α) :
functor.map (functor.map h) (traverse g x) =
traverse (functor.map h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse] with functor_norm;
rw [comp_map,map_traverse])
lemma traverse_map {G : Type* → Type*}
[applicative G] [is_comm_applicative G]
{α β γ : Type*}
(g : α → β) (h : β → G γ)
(x : multiset α) :
traverse h (map g x) =
traverse (h ∘ g) x :=
quotient.induction_on x
(by intro; simp [traverse];
rw [← traversable.traverse_map h g];
[ refl, apply_instance ])
lemma naturality {G H : Type* → Type*}
[applicative G] [applicative H]
[is_comm_applicative G] [is_comm_applicative H]
(eta : applicative_transformation G H)
{α β : Type*} (f : α → G β) (x : multiset α) :
eta (traverse f x) = traverse (@eta _ ∘ f) x :=
quotient.induction_on x
(by intro; simp [traverse,is_lawful_traversable.naturality] with functor_norm)
section choose
variables (p : α → Prop) [decidable_pred p] (l : multiset α)
def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } :=
quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin
intros,
funext hp,
suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y,
{ apply all_equal },
{ rintros ⟨x, px⟩ ⟨y, py⟩,
rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩,
congr,
calc x = z : z_unique x px
... = y : (z_unique y py).symm }
end
def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp
lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) :=
(choose_x p l hp).property
lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1
lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2
end choose
/- Ico -/
/-- `Ico n m` is the multiset lifted from the list `Ico n m`, e.g. the set `{n, n+1, ..., m-1}`. -/
def Ico (n m : ℕ) : multiset ℕ := Ico n m
namespace Ico
theorem map_add (n m k : ℕ) : (Ico n m).map ((+) k) = Ico (n + k) (m + k) :=
congr_arg coe $ list.Ico.map_add _ _ _
theorem map_sub (n m k : ℕ) (h : k ≤ n) : (Ico n m).map (λ x, x - k) = Ico (n - k) (m - k) :=
congr_arg coe $ list.Ico.map_sub _ _ _ h
theorem zero_bot (n : ℕ) : Ico 0 n = range n :=
congr_arg coe $ list.Ico.zero_bot _
@[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n :=
list.Ico.length _ _
theorem nodup (n m : ℕ) : nodup (Ico n m) := Ico.nodup _ _
@[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m :=
list.Ico.mem
theorem eq_zero_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = 0 :=
congr_arg coe $ list.Ico.eq_nil_of_le h
@[simp] theorem self_eq_zero {n : ℕ} : Ico n n = 0 :=
eq_zero_of_le $ le_refl n
@[simp] theorem eq_zero_iff {n m : ℕ} : Ico n m = 0 ↔ m ≤ n :=
iff.trans (coe_eq_zero _) list.Ico.eq_empty_iff
lemma add_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) :
Ico n m + Ico m l = Ico n l :=
congr_arg coe $ list.Ico.append_consecutive hnm hml
@[simp] lemma inter_consecutive (n m l : ℕ) : Ico n m ∩ Ico m l = 0 :=
congr_arg coe $ list.Ico.bag_inter_consecutive n m l
@[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} :=
congr_arg coe $ list.Ico.succ_singleton
theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = m :: Ico n m :=
by rw [Ico, list.Ico.succ_top h, ← coe_add, add_comm]; refl
theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = n :: Ico (n + 1) m :=
congr_arg coe $ list.Ico.eq_cons h
@[simp] theorem pred_singleton {m : ℕ} (h : 0 < m) : Ico (m - 1) m = {m - 1} :=
congr_arg coe $ list.Ico.pred_singleton h
@[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m :=
list.Ico.not_mem_top
lemma filter_lt_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x < l) = Ico n m :=
congr_arg coe $ list.Ico.filter_lt_of_top_le hml
lemma filter_lt_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x < l) = ∅ :=
congr_arg coe $ list.Ico.filter_lt_of_le_bot hln
lemma filter_lt_of_ge {n m l : ℕ} (hlm : l ≤ m) : (Ico n m).filter (λ x, x < l) = Ico n l :=
congr_arg coe $ list.Ico.filter_lt_of_ge hlm
@[simp] lemma filter_lt (n m l : ℕ) : (Ico n m).filter (λ x, x < l) = Ico n (min m l) :=
congr_arg coe $ list.Ico.filter_lt n m l
lemma filter_le_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, l ≤ x) = Ico n m :=
congr_arg coe $ list.Ico.filter_le_of_le_bot hln
lemma filter_le_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, l ≤ x) = ∅ :=
congr_arg coe $ list.Ico.filter_le_of_top_le hml
lemma filter_le_of_le {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, l ≤ x) = Ico l m :=
congr_arg coe $ list.Ico.filter_le_of_le hnl
@[simp] lemma filter_le (n m l : ℕ) : (Ico n m).filter (λ x, l ≤ x) = Ico (max n l) m :=
congr_arg coe $ list.Ico.filter_le n m l
end Ico
variable (α)
def subsingleton_equiv [subsingleton α] : list α ≃ multiset α :=
{ to_fun := coe,
inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b),
list.ext_le (perm_length h) $ λ n h₁ h₂, subsingleton.elim _ _,
left_inv := λ l, rfl,
right_inv := λ m, quot.induction_on m $ λ l, rfl }
namespace nat
/-- The antidiagonal of a natural number `n` is
the multiset of pairs `(i,j)` such that `i+j = n`. -/
def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) :=
list.nat.antidiagonal n
/-- A pair (i,j) is contained in the antidiagonal of `n` if and only if `i+j=n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal]
/-- The cardinality of the antidiagonal of `n` is `n+1`. -/
@[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 :=
by rw [antidiagonal, coe_card, list.nat.length_antidiagonal]
/-- The antidiagonal of `0` is the list `[(0,0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} :=
by { rw [antidiagonal, list.nat.antidiagonal_zero], refl }
/-- The antidiagonal of `n` does not contain duplicate entries. -/
lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) :=
coe_nodup.2 $ list.nat.nodup_antidiagonal n
end nat
end multiset
|
c3d54988c3b374cc3a10173d5d9b6b9fc97f7fa7 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/monoidal/internal/types.lean | 0830caa7188277c3078aafb7666582d4f8426e1e | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,643 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Mon.basic
import category_theory.monoidal.CommMon_
import category_theory.monoidal.types
/-!
# `Mon_ (Type u) ≌ Mon.{u}`
The category of internal monoid objects in `Type`
is equivalent to the category of "native" bundled monoids.
Moreover, this equivalence is compatible with the forgetful functors to `Type`.
-/
universes v u
open category_theory
namespace Mon_Type_equivalence_Mon
instance Mon_monoid (A : Mon_ (Type u)) : monoid (A.X) :=
{ one := A.one punit.star,
mul := λ x y, A.mul (x, y),
one_mul := λ x, by convert congr_fun A.one_mul (punit.star, x),
mul_one := λ x, by convert congr_fun A.mul_one (x, punit.star),
mul_assoc := λ x y z, by convert congr_fun A.mul_assoc ((x, y), z), }
/--
Converting a monoid object in `Type` to a bundled monoid.
-/
def functor : Mon_ (Type u) ⥤ Mon.{u} :=
{ obj := λ A, ⟨A.X⟩,
map := λ A B f,
{ to_fun := f.hom,
map_one' := congr_fun f.one_hom punit.star,
map_mul' := λ x y, congr_fun f.mul_hom (x, y), }, }
/--
Converting a bundled monoid to a monoid object in `Type`.
-/
def inverse : Mon.{u} ⥤ Mon_ (Type u) :=
{ obj := λ A,
{ X := A,
one := λ _, 1,
mul := λ p, p.1 * p.2,
one_mul' := by { ext ⟨_, _⟩, dsimp, simp, },
mul_one' := by { ext ⟨_, _⟩, dsimp, simp, },
mul_assoc' := by { ext ⟨⟨x, y⟩, z⟩, simp [mul_assoc], }, },
map := λ A B f,
{ hom := f, }, }
end Mon_Type_equivalence_Mon
open Mon_Type_equivalence_Mon
/--
The category of internal monoid objects in `Type`
is equivalent to the category of "native" bundled monoids.
-/
def Mon_Type_equivalence_Mon : Mon_ (Type u) ≌ Mon.{u} :=
{ functor := functor,
inverse := inverse,
unit_iso := nat_iso.of_components
(λ A, { hom := { hom := 𝟙 _, }, inv := { hom := 𝟙 _, }, })
(by tidy),
counit_iso := nat_iso.of_components (λ A,
{ hom := { to_fun := id, map_one' := rfl, map_mul' := λ x y, rfl, },
inv := { to_fun := id, map_one' := rfl, map_mul' := λ x y, rfl, }, }) (by tidy), }
/--
The equivalence `Mon_ (Type u) ≌ Mon.{u}`
is naturally compatible with the forgetful functors to `Type u`.
-/
def Mon_Type_equivalence_Mon_forget :
Mon_Type_equivalence_Mon.functor ⋙ forget Mon ≅ Mon_.forget (Type u) :=
nat_iso.of_components (λ A, iso.refl _) (by tidy)
instance Mon_Type_inhabited : inhabited (Mon_ (Type u)) :=
⟨Mon_Type_equivalence_Mon.inverse.obj (Mon.of punit)⟩
namespace CommMon_Type_equivalence_CommMon
instance CommMon_comm_monoid (A : CommMon_ (Type u)) : comm_monoid (A.X) :=
{ mul_comm := λ x y, by convert congr_fun A.mul_comm (y, x),
..Mon_Type_equivalence_Mon.Mon_monoid A.to_Mon_ }
/--
Converting a commutative monoid object in `Type` to a bundled commutative monoid.
-/
def functor : CommMon_ (Type u) ⥤ CommMon.{u} :=
{ obj := λ A, ⟨A.X⟩,
map := λ A B f, Mon_Type_equivalence_Mon.functor.map f, }
/--
Converting a bundled commutative monoid to a commutative monoid object in `Type`.
-/
def inverse : CommMon.{u} ⥤ CommMon_ (Type u) :=
{ obj := λ A,
{ mul_comm' := by { ext ⟨x, y⟩, exact comm_monoid.mul_comm y x, },
..Mon_Type_equivalence_Mon.inverse.obj ((forget₂ CommMon Mon).obj A), },
map := λ A B f, Mon_Type_equivalence_Mon.inverse.map f, }
end CommMon_Type_equivalence_CommMon
open CommMon_Type_equivalence_CommMon
/--
The category of internal commutative monoid objects in `Type`
is equivalent to the category of "native" bundled commutative monoids.
-/
def CommMon_Type_equivalence_CommMon : CommMon_ (Type u) ≌ CommMon.{u} :=
{ functor := functor,
inverse := inverse,
unit_iso := nat_iso.of_components
(λ A, { hom := { hom := 𝟙 _, }, inv := { hom := 𝟙 _, }, })
(by tidy),
counit_iso := nat_iso.of_components (λ A,
{ hom := { to_fun := id, map_one' := rfl, map_mul' := λ x y, rfl, },
inv := { to_fun := id, map_one' := rfl, map_mul' := λ x y, rfl, }, }) (by tidy), }
/--
The equivalences `Mon_ (Type u) ≌ Mon.{u}` and `CommMon_ (Type u) ≌ CommMon.{u}`
are naturally compatible with the forgetful functors to `Mon` and `Mon_ (Type u)`.
-/
def CommMon_Type_equivalence_CommMon_forget :
CommMon_Type_equivalence_CommMon.functor ⋙ forget₂ CommMon Mon ≅
CommMon_.forget₂_Mon_ (Type u) ⋙ Mon_Type_equivalence_Mon.functor :=
nat_iso.of_components (λ A, iso.refl _) (by tidy)
instance CommMon_Type_inhabited : inhabited (CommMon_ (Type u)) :=
⟨CommMon_Type_equivalence_CommMon.inverse.obj (CommMon.of punit)⟩
|
cc2bee7fda1504497bad92135e80ca54aefe5c9e | 9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e | /src/commutative_algebra/ring_of_subsets.lean | 1d8941790949fd9baf5ca8ab0b2ac3391a709d1e | [] | no_license | agusakov/lean_lib | c0e9cc29fc7d2518004e224376adeb5e69b5cc1a | f88d162da2f990b87c4d34f5f46bbca2bbc5948e | refs/heads/master | 1,642,141,461,087 | 1,557,395,798,000 | 1,557,395,798,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,604 | lean | import algebra.ring data.equiv.basic
import commutative_algebra.bool_field
import tactic.pi_instances tactic.squeeze
universes u v
variables (U : Type u) (V : Type v)
def ring_of_bool_subsets := (U → bool)
instance : comm_ring (ring_of_bool_subsets U) :=
by { unfold ring_of_bool_subsets, pi_instance, }
lemma val_zero (x : U) : (0 : ring_of_bool_subsets U) x = ff := rfl
lemma val_one (x : U) : (1 : ring_of_bool_subsets U) x = tt := rfl
lemma val_neg (f : ring_of_bool_subsets U) (x : U) : (- f) x = f x := rfl
lemma val_add (f g : ring_of_bool_subsets U) (x : U) : (f + g) x = bxor (f x) (g x) := rfl
lemma val_mul (f g : ring_of_bool_subsets U) (x : U) : (f * g) x = band (f x) (g x) := rfl
open classical
def ring_of_subsets := set V
namespace ring_of_subsets
local attribute [instance] classical.dec
instance : has_zero (ring_of_subsets V) := ⟨(∅ : set V)⟩
instance : has_one (ring_of_subsets V) := ⟨(set.univ : set V)⟩
instance : has_neg (ring_of_subsets V) := ⟨(λ s, s)⟩
instance : has_add (ring_of_subsets V) :=
⟨(λ s t : set V, (s \ t ∪ t \ s : set V))⟩
instance : has_mul (ring_of_subsets V) :=
⟨(λ s t : set V, (s ∩ t : set V))⟩
instance : has_mem V (ring_of_subsets V) :=
⟨λ (x : V) (s : set V), x ∈ s⟩
variable (x : V)
lemma mem_zero_iff : x ∈ (0 : ring_of_subsets V) ↔ false :=
(iff_false _).mpr (set.not_mem_empty x)
lemma mem_one_iff : x ∈ (1 : ring_of_subsets V) ↔ true :=
(iff_true _).mpr (set.mem_univ x)
lemma mem_neg_iff (s : ring_of_subsets V) : x ∈ (- s) ↔ x ∈ s :=
by { change x ∈ s ↔ x ∈ s, refl }
lemma mem_add_iff (s t : ring_of_subsets V) :
x ∈ s + t ↔ ((x ∈ s ∧ x ∉ t) ∨ (x∈ t ∧ x ∉ s)) :=
by { unfold has_add.add, rw[set.mem_union,set.mem_diff,set.mem_diff],}
lemma mem_mul_iff (s t : ring_of_subsets V) :
x ∈ s * t ↔ (x ∈ s ∧ x ∈ t) :=
by { unfold has_mul.mul, rw[set.mem_inter_iff], }
instance : comm_ring (ring_of_subsets V) := begin
refine_struct {
zero := (0 : ring_of_subsets V), one := 1,
neg := has_neg.neg, add := (+), mul := (*)
}; intros;ext x;
repeat{rw[mem_add_iff]};repeat{rw[mem_mul_iff]};repeat{rw[mem_neg_iff]};
repeat{rw[mem_add_iff]};repeat{rw[mem_mul_iff]};repeat{rw[mem_neg_iff]};
repeat{rw[mem_zero_iff]};repeat{rw[mem_one_iff]};
try {by_cases ha : x ∈ a};
try {by_cases hb : x ∈ b};
try {by_cases hc : x ∈ c};
try{simp[ha,hb,hc]};
try{simp[ha,hb]};
try{simp[ha]},
end
variable {V}
noncomputable def indicator : ring_of_subsets V → ring_of_bool_subsets V :=
λ s x, (if x ∈ s then tt else ff)
lemma indicator_val (s : ring_of_subsets V) (x : V) :
indicator s x = (if x ∈ s then tt else ff) := rfl
instance : is_ring_hom (@indicator V) := {
map_one := by { ext x, dsimp[indicator], rw[mem_one_iff V x,if_true], refl,},
map_mul := λ s t, by {
ext x,
change indicator (s * t) x = band (indicator s x) (indicator t x),
dsimp[indicator],rw[mem_mul_iff],
by_cases hs : x ∈ s; by_cases ht : x ∈ t; simp[hs,ht],
},
map_add := λ s t, by {
ext x,
change indicator (s + t) x = bxor (indicator s x) (indicator t x),
dsimp[indicator],rw[mem_add_iff],
by_cases hs : x ∈ s; by_cases ht : x ∈ t; simp[hs,ht],
},
}
end ring_of_subsets
namespace ring_of_bool_subsets
variable {U}
def support : (ring_of_bool_subsets U) → (ring_of_subsets U) :=
λ (f : U → bool), (λ x, f x = tt)
lemma mem_support {f : ring_of_bool_subsets U} {x : U} :
x ∈ (support f) ↔ f x = tt := by {dsimp[support], refl}
instance : is_ring_hom (@support U) := {
map_one := begin
ext x, rw[mem_support,val_one,ring_of_subsets.mem_one_iff,eq_self_iff_true],
end,
map_mul := λ s t, begin
ext x, rw[ring_of_subsets.mem_mul_iff],
repeat{rw[mem_support]},rw[val_mul],
cases (s x); cases (t x); rw[band]; exact dec_trivial,
end,
map_add := λ s t, begin
ext x, rw[ring_of_subsets.mem_add_iff],
repeat{rw[mem_support]},rw[val_add],
cases (s x); cases (t x); rw[bxor]; exact dec_trivial,
end,
}
end ring_of_bool_subsets
namespace ring_of_subsets
noncomputable def bool_equiv : (ring_of_subsets U) ≃ (ring_of_bool_subsets U) := {
to_fun := @indicator U,
inv_fun := @ring_of_bool_subsets.support U,
left_inv := λ s, begin
haveI := classical.dec,
rw[ring_of_bool_subsets.support,indicator],
ext x,dsimp[has_mem.mem,set.mem],
split_ifs;simp only [h,iff_self,eq_self_iff_true],
end,
right_inv := λ f, begin
ext x,
dsimp[indicator,ring_of_bool_subsets.support,has_mem.mem,set.mem],
cases f x; simp,
end
}
end ring_of_subsets
|
d4f9f4e41ce01fc05d0b2308b1435d3975a7926a | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/polynomial/ring_division.lean | e93c0e3807fefa49a5cf51a9bc6e88253c3bc860 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 26,917 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin
-/
import data.polynomial.basic
import data.polynomial.div
import data.polynomial.algebra_map
import data.set.finite
/-!
# Theory of univariate polynomials
This file starts looking like the ring theory of $ R[X] $
-/
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open finset
namespace polynomial
universes u v w z
variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ}
section comm_ring
variables [comm_ring R] {p q : polynomial R}
variables [comm_ring S]
lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0)
{z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
0 < p.nat_degree :=
nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj
lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0)
{z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
0 < p.degree :=
nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj)
lemma aeval_mod_by_monic_eq_self_of_root [algebra R S]
{p q : polynomial R} (hq : q.monic) {x : S} (hx : aeval x q = 0) :
aeval x (p %ₘ q) = aeval x p :=
eval₂_mod_by_monic_eq_self_of_root hq hx
end comm_ring
section integral_domain
variables [integral_domain R] {p q : polynomial R}
instance : integral_domain (polynomial R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin
have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b,
rw [leading_coeff_zero, eq_comm] at this,
erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero],
exact eq_zero_or_eq_zero_of_mul_eq_zero this
end,
..polynomial.nontrivial,
..polynomial.comm_ring }
lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) =
nat_degree p + nat_degree q :=
by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq),
with_bot.coe_add, ← degree_eq_nat_degree hp,
← degree_eq_nat_degree hq, degree_mul]
lemma nat_trailing_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) :
(p * q).nat_trailing_degree = p.nat_trailing_degree + q.nat_trailing_degree :=
begin
simp only [←nat.sub_eq_of_eq_add (nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree _)],
rw [reverse_mul_of_domain, nat_degree_mul hp hq, nat_degree_mul (mt reverse_eq_zero.mp hp)
(mt reverse_eq_zero.mp hq), reverse_nat_degree, reverse_nat_degree, ←nat.sub_sub, nat.add_comm,
nat.add_sub_assoc (nat.sub_le _ _), add_comm, nat.add_sub_assoc (nat.sub_le _ _)],
end
@[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0
then if hn0 : n = 0 then by simp [hp0, hn0]
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else nat_degree_pow'
(by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0)
lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a :=
by simp_rw [is_root, eval_mul, mul_eq_zero]
lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a :=
root_mul.1 h
lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) :=
if hp : p = 0 then by simp only [hp, zero_mul, le_refl]
else by rw [degree_mul, degree_eq_nat_degree hp,
degree_eq_nat_degree hq];
exact with_bot.coe_le_coe.2 (nat.le_add_right _ _)
theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) :
p.nat_degree ≤ q.nat_degree :=
begin
rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2,
rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _
end
section roots
open multiset
local attribute [reducible] with_zero
lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 :=
let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in
have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq,
have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq,
have nat_degree (1 : polynomial R) = nat_degree (p * q),
from congr_arg _ hq,
by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm,
_root_.add_eq_zero_iff, ← with_bot.coe_eq_coe,
← degree_eq_nat_degree hp0] at this;
exact this.1
@[simp] lemma degree_coe_units (u : units (polynomial R)) :
degree (u : polynomial R) = 0 :=
degree_eq_zero_of_is_unit ⟨u, rfl⟩
theorem prime_X_sub_C {r : R} : prime (X - C r) :=
⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C,
λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩
theorem prime_X : prime (X : polynomial R) :=
by { convert (prime_X_sub_C : prime (X - C 0 : polynomial R)), simp }
lemma prime_of_degree_eq_one_of_monic (hp1 : degree p = 1)
(hm : monic p) : prime p :=
have p = X - C (- p.coeff 0),
by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1,
this.symm ▸ prime_X_sub_C
theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) :=
irreducible_of_prime prime_X_sub_C
theorem irreducible_X : irreducible (X : polynomial R) :=
irreducible_of_prime prime_X
lemma irreducible_of_degree_eq_one_of_monic (hp1 : degree p = 1)
(hm : monic p) : irreducible p :=
irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm)
theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q :=
begin
obtain ⟨u, hu⟩ := hpq,
unfold monic at hp hq,
rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu,
rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq,
rwa [hq, C_1, mul_one] at hu
end
@[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl
lemma root_multiplicity_eq_zero {p : polynomial R} {x : R} (h : ¬ is_root p x) :
root_multiplicity x p = 0 :=
begin
rw root_multiplicity_eq_multiplicity,
split_ifs, { refl },
rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, enat.coe_zero],
intro hdvd,
exact h (dvd_iff_is_root.mp hdvd)
end
lemma root_multiplicity_pos {p : polynomial R} (hp : p ≠ 0) {x : R} :
0 < root_multiplicity x p ↔ is_root p x :=
begin
rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp,
← enat.coe_lt_coe, enat.coe_get],
exact multiplicity.dvd_iff_multiplicity_pos
end
lemma root_multiplicity_mul {p q : polynomial R} {x : R} (hpq : p * q ≠ 0) :
root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q :=
begin
have hp : p ≠ 0 := left_ne_zero_of_mul hpq,
have hq : q ≠ 0 := right_ne_zero_of_mul hpq,
rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq,
root_multiplicity_eq_multiplicity p, dif_neg hp,
root_multiplicity_eq_multiplicity q, dif_neg hq,
@multiplicity.mul' _ _ _ (X - C x) _ _ prime_X_sub_C],
end
lemma root_multiplicity_X_sub_C_self {x : R} :
root_multiplicity x (X - C x) = 1 :=
by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x),
multiplicity.get_multiplicity_self]
lemma root_multiplicity_X_sub_C {x y : R} :
root_multiplicity x (X - C y) = if x = y then 1 else 0 :=
begin
split_ifs with hxy,
{ rw hxy,
exact root_multiplicity_X_sub_C_self },
exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy))
end
/-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/
lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n :=
begin
induction n with n hn,
{ refine root_multiplicity_eq_zero _,
simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] },
have hzero := (ne_zero_of_monic (monic_pow (monic_X_sub_C a) n.succ)),
rw pow_succ (X - C a) n at hzero ⊢,
simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add]
end
/-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at
least `n`. -/
lemma root_multiplicity_of_dvd {p : polynomial R} {a : R} {n : ℕ}
(hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p :=
begin
obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h,
rw hq at hzero,
simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow,
ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right],
end
/-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/
lemma root_multiplicity_add {p q : polynomial R} (a : R) (hzero : p + q ≠ 0) :
min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) :=
begin
refine root_multiplicity_of_dvd hzero _,
have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a,
have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a,
exact min_pow_dvd_add hdivp hdivq
end
lemma exists_multiset_roots : ∀ {p : polynomial R} (hp : p ≠ 0),
∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p
| p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact
if h : ∃ x, is_root p x
then
let ⟨x, hx⟩ := h in
have hpd : 0 < degree p := degree_pos_of_root hp hx,
have hd0 : p /ₘ (X - C x) ≠ 0 :=
λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl,
have wf : degree (p /ₘ _) < degree p :=
degree_div_by_monic_lt _ (monic_X_sub_C x) hp
((degree_X_sub_C x).symm ▸ dec_trivial),
let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in
have hdeg : degree (X - C x) ≤ degree p := begin
rw [degree_X_sub_C, degree_eq_nat_degree hp],
rw degree_eq_nat_degree hp at hpd,
exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd)
end,
have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)
(ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg,
⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 :
by exact_mod_cast card_cons _ _
... ≤ degree p :
by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg,
degree_X_sub_C, add_comm];
exact add_le_add (le_refl (1 : with_bot ℕ)) htd,
begin
assume a,
conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx },
rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero _) hdiv0),
root_multiplicity_X_sub_C, ← htr a],
split_ifs with ha,
{ rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] },
{ rw [count_cons_of_ne ha, zero_add] },
end⟩
else
⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _),
by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `roots p` noncomputably gives a multiset containing all the roots of `p`,
including their multiplicities. -/
noncomputable def roots (p : polynomial R) : multiset R :=
if h : p = 0 then ∅ else classical.some (exists_multiset_roots h)
@[simp] lemma roots_zero : (0 : polynomial R).roots = 0 :=
dif_pos rfl
lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p :=
begin
unfold roots,
rw dif_neg hp0,
exact (classical.some_spec (exists_multiset_roots hp0)).1
end
lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p :=
with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0))
lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) :
((p - C a).roots.card : with_bot ℕ) ≤ degree p :=
calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) :
card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le
... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0
lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) :
(p - C a).roots.card ≤ nat_degree p :=
with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree
(λ h, by simp [*, lt_irrefl] at *)))
@[simp] lemma count_roots (hp : p ≠ 0) : p.roots.count a = root_multiplicity a p :=
by { rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a }
@[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a :=
by rw [← count_pos, count_roots hp, root_multiplicity_pos hp]
lemma eq_zero_of_infinite_is_root
(p : polynomial R) (h : set.infinite {x | is_root p x}) : p = 0 :=
begin
by_contradiction hp,
apply h,
convert p.roots.to_finset.finite_to_set using 1,
ext1 r,
simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe]
end
lemma eq_of_infinite_eval_eq {R : Type*} [integral_domain R]
(p q : polynomial R) (h : set.infinite {x | eval x p = eval x q}) : p = q :=
begin
rw [← sub_eq_zero],
apply eq_zero_of_infinite_is_root,
simpa only [is_root, eval_sub, sub_eq_zero]
end
lemma roots_mul {p q : polynomial R} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots :=
multiset.ext.mpr $ λ r,
by rw [count_add, count_roots hpq, count_roots (left_ne_zero_of_mul hpq),
count_roots (right_ne_zero_of_mul hpq), root_multiplicity_mul hpq]
@[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) :
x ∈ (p - C a).roots ↔ p.eval x = a :=
(mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h,
not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans
(by rw [is_root.def, eval_sub, eval_C, sub_eq_zero])
@[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = r ::ₘ 0 :=
begin
ext s,
rw [count_roots (X_sub_C_ne_zero r), root_multiplicity_X_sub_C],
split_ifs with h,
{ rw [h, count_singleton] },
{ rw [count_cons_of_ne h, count_zero] }
end
@[simp] lemma roots_C (x : R) : (C x).roots = 0 :=
if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r,
have h : C x ≠ 0, from λ h, H $ C_inj.1 $ h.symm ▸ C_0.symm,
have not_root : ¬ is_root (C x) r := mt (λ (h : eval r (C x) = 0), trans eval_C.symm h) H,
by rw [count_roots h, count_zero, root_multiplicity_eq_zero not_root]
@[simp] lemma roots_one : (1 : polynomial R).roots = ∅ :=
roots_C 1
lemma roots_list_prod (L : list (polynomial R)) :
((0 : polynomial R) ∉ L) → L.prod.roots = (L : multiset (polynomial R)).bind roots :=
list.rec_on L (λ _, roots_one) $ λ hd tl ih H,
begin
rw [list.mem_cons_iff, not_or_distrib] at H,
rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2),
← multiset.cons_coe, multiset.cons_bind, ih H.2]
end
lemma roots_multiset_prod (m : multiset (polynomial R)) :
(0 : polynomial R) ∉ m → m.prod.roots = m.bind roots :=
by { rcases m with ⟨L⟩, simpa only [coe_prod, quot_mk_to_coe''] using roots_list_prod L }
lemma roots_prod {ι : Type*} (f : ι → polynomial R) (s : finset ι) :
s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) :=
begin
rcases s with ⟨m, hm⟩,
simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f)
end
lemma roots_prod_X_sub_C (s : finset R) :
(s.prod (λ a, X - C a)).roots = s.val :=
(roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans
(by simp_rw [roots_X_sub_C, bind_cons, bind_zero, add_zero, multiset.map_id'])
lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) :
(roots ((X : polynomial R) ^ n - C a)).card ≤ n :=
with_bot.coe_le_coe.1 $
calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ)
≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a)
... = n : degree_X_pow_sub_C hn a
section nth_roots
/-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/
def nth_roots (n : ℕ) (a : R) : multiset R :=
roots ((X : polynomial R) ^ n - C a)
@[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} :
x ∈ nth_roots n a ↔ x ^ n = a :=
by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a),
is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq]
@[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 :=
by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C]
lemma card_nth_roots (n : ℕ) (a : R) :
(nth_roots n a).card ≤ n :=
if hn : n = 0
then if h : (X : polynomial R) ^ n - C a = 0
then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero]
else with_bot.coe_le_coe.1 (le_trans (card_roots h)
(by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)];
exact degree_C_le))
else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a];
exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a)
/-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/
def nth_roots_finset (n : ℕ) (R : Type*) [integral_domain R] : finset R :=
multiset.to_finset (nth_roots n (1 : R))
@[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} :
x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 :=
by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h]
end nth_roots
lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) :
coeff (p.comp q) (nat_degree p * nat_degree q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
if hp0 : p = 0 then by simp [hp0] else
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) :
by rw [comp, eval₂, coeff_sum]
... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) :
finset.sum_eq_single _
begin
assume b hbs hbp,
have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]),
have : coeff p b ≠ 0, by rwa finsupp.mem_support_iff at hbs,
refine coeff_eq_zero_of_degree_lt _,
erw [degree_mul, degree_C this, degree_pow, zero_add, degree_eq_nat_degree hq0,
← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id,
mul_lt_mul_right (pos_iff_ne_zero.mpr hqd0)],
exact lt_of_le_of_ne (le_nat_degree_of_ne_zero this) hbp,
end
begin
intro h, contrapose! hp0,
rw finsupp.mem_support_iff at h, push_neg at h,
rwa ← leading_coeff_eq_zero,
end
... = _ :
have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p),
by rw [leading_coeff, nat_degree_pow],
by rw [coeff_C_mul, this, leading_coeff_pow]
lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q :=
le_antisymm nat_degree_comp_le
(if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul]
else if hqd0 : nat_degree q = 0
then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree,
by rw [eq_C_of_degree_le_zero this]; simp
else le_nat_degree_of_ne_zero $
have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero],
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= leading_coeff p * leading_coeff q ^ nat_degree p :
coeff_comp_degree_mul_degree hqd0
... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0)))
lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl
lemma units_coeff_zero_smul (c : units (polynomial R)) (p : polynomial R) :
(c : polynomial R).coeff 0 • p = c * p :=
by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)]
@[simp] lemma nat_degree_coe_units (u : units (polynomial R)) :
nat_degree (u : polynomial R) = 0 :=
nat_degree_eq_of_degree_eq_some (degree_coe_units u)
lemma comp_eq_zero_iff :
p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) :=
begin
split,
{ intro h,
have key : p.nat_degree = 0 ∨ q.nat_degree = 0,
{ rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] },
replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key,
cases key,
{ rw [key, C_comp] at h,
exact or.inl (key.trans h) },
{ rw [key, comp_C, C_eq_zero] at h,
exact or.inr ⟨h, key⟩ }, },
{ exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h },
end
lemma zero_of_eval_zero [infinite R] (p : polynomial R) (h : ∀ x, p.eval x = 0) : p = 0 :=
by classical; by_contradiction hp; exact
infinite.not_fintype ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩
lemma funext [infinite R] {p q : polynomial R} (ext : ∀ r : R, p.eval r = q.eval r) : p = q :=
begin
rw ← sub_eq_zero,
apply zero_of_eval_zero,
intro x,
rw [eval_sub, sub_eq_zero, ext],
end
/-- The set of distinct roots of `p` in `E`.
If you have a non-separable polynomial, use `polynomial.roots` for the multiset
where multiple roots have the appropriate multiplicity. -/
def root_set (p : polynomial R) (S) [integral_domain S] [algebra R S] : set S :=
(p.map (algebra_map R S)).roots.to_finset
lemma root_set_def (p : polynomial R) (S) [integral_domain S] [algebra R S] :
p.root_set S = (p.map (algebra_map R S)).roots.to_finset :=
rfl
@[simp] lemma root_set_zero (S) [integral_domain S] [algebra R S] :
(0 : polynomial R).root_set S = ∅ :=
by rw [root_set_def, polynomial.map_zero, roots_zero, to_finset_zero, finset.coe_empty]
end roots
theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f :=
⟨λ hf, ⟨f.coeff 0,
is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf,
(eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩,
λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩
lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) :
coeff (u : polynomial R) 0 ≠ 0 :=
begin
conv in (0) {rw [← nat_degree_coe_units u]},
rw [← leading_coeff, ne.def, leading_coeff_eq_zero],
exact units.ne_zero _
end
lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q :=
let ⟨u, hu⟩ := h in by simp [hu.symm]
lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) :
degree p = 1 :=
let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in
have is_unit (X - C x) ∨ is_unit g, from hi.is_unit_or_is_unit hg,
this.elim
(λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x,
have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h,
by rw h₁ at h₂; exact absurd h₂ dec_trivial)
(λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero])
/-- Division by a monic polynomial doesn't change the leading coefficient. -/
lemma leading_coeff_div_by_monic_of_monic {R : Type u} [integral_domain R] {p q : polynomial R}
(hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff :=
begin
have hp := mod_by_monic_add_div p hmonic,
have hzero : (p /ₘ q) ≠ 0,
{ intro h,
exact not_lt_of_le hdegree ((div_by_monic_eq_zero_iff hmonic (monic.ne_zero hmonic)).1 h) },
have deglt : (p %ₘ q).degree < (q * (p /ₘ q)).degree,
{ rw degree_mul,
refine lt_of_lt_of_le (degree_mod_by_monic_lt p hmonic (monic.ne_zero hmonic)) _,
rw [degree_eq_nat_degree (monic.ne_zero hmonic), degree_eq_nat_degree hzero],
norm_cast,
simp only [zero_le, le_add_iff_nonneg_right] },
have hrew := (leading_coeff_add_of_degree_lt deglt),
rw leading_coeff_mul q (p /ₘ q) at hrew,
simp only [hmonic, one_mul, monic.leading_coeff] at hrew,
nth_rewrite 1 ← hp,
exact hrew.symm
end
lemma eq_of_monic_of_dvd_of_nat_degree_le (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q)
(hdeg : q.nat_degree ≤ p.nat_degree) : q = p :=
begin
obtain ⟨r, hr⟩ := hdiv,
have rzero : r ≠ 0,
{ intro h,
simpa [h, monic.ne_zero hq] using hr },
rw [hr, nat_degree_mul (monic.ne_zero hp) rzero] at hdeg,
have hdegeq : p.nat_degree + r.nat_degree = p.nat_degree,
{ suffices hdegle : p.nat_degree ≤ p.nat_degree + r.nat_degree,
{ exact le_antisymm hdeg hdegle },
exact nat.le.intro rfl },
replace hdegeq := eq_C_of_nat_degree_eq_zero (((@add_right_inj _ _ p.nat_degree) _ 0).1 hdegeq),
suffices hlead : 1 = r.leading_coeff,
{ have hcoeff := leading_coeff_C (r.coeff 0),
rw [← hdegeq, ← hlead] at hcoeff,
rw [← hcoeff, C_1] at hdegeq,
rwa [hdegeq, mul_one] at hr },
have hprod : q.leading_coeff = p.leading_coeff * r.leading_coeff,
{ simp only [hr, leading_coeff_mul] },
rwa [monic.leading_coeff hp, monic.leading_coeff hq, one_mul] at hprod
end
end integral_domain
section
variables [semiring R] [integral_domain S] (φ : R →+* S)
lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map
(f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) :
is_unit f :=
begin
have dz := degree_eq_zero_of_is_unit H,
rw degree_map_eq_of_leading_coeff_ne_zero at dz,
{ rw eq_C_of_degree_eq_zero dz,
apply is_unit.map',
convert hf,
rw (degree_eq_iff_nat_degree_eq _).1 dz,
rintro rfl,
simpa using H, },
{ intro h,
have u : is_unit (φ f.leading_coeff) := is_unit.map' _ hf,
rw h at u,
simpa using u, }
end
end
section
variables [integral_domain R] [integral_domain S] (φ : R →+* S)
/--
A polynomial over an integral domain `R` is irreducible if it is monic and
irreducible after mapping into an integral domain `S`.
A special case of this lemma is that a polynomial over `ℤ` is irreducible if
it is monic and irreducible over `ℤ/pℤ` for some prime `p`.
-/
lemma monic.irreducible_of_irreducible_map (f : polynomial R)
(h_mon : monic f) (h_irr : irreducible (map φ f)) :
irreducible f :=
begin
fsplit,
{ intro h,
exact h_irr.not_unit (is_unit.map (monoid_hom.of (map φ)) h), },
{ intros a b h,
have q := (leading_coeff_mul a b).symm,
rw ←h at q,
dsimp [monic] at h_mon,
rw h_mon at q,
have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q,
rw mul_comm at q,
have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q,
clear q h_mon,
have h' := congr_arg (map φ) h,
simp only [map_mul] at h',
cases h_irr.is_unit_or_is_unit h' with w w,
{ left,
exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, },
{ right,
exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, }
end
end
end polynomial
namespace is_integral_domain
variables {R : Type*} [comm_ring R]
/-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/
lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) :=
@integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _))
end is_integral_domain
|
7490da3059eb19f6f02983ae5f37bfcfa02c5510 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/dynamics/periodic_pts.lean | 73a4c14faceb4925c09009755458095f3fa15e3c | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 13,349 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import dynamics.fixed_points.basic
import data.set.lattice
import data.pnat.basic
import data.int.gcd
/-!
# Periodic points
A point `x : α` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`.
## Main definitions
* `is_periodic_pt f n x` : `x` is a periodic point of `f` of period `n`, i.e. `f^[n] x = x`.
We do not require `n > 0` in the definition.
* `pts_of_period f n` : the set `{x | is_periodic_pt f n x}`. Note that `n` is not required to
be the minimal period of `x`.
* `periodic_pts f` : the set of all periodic points of `f`.
* `minimal_period f x` : the minimal period of a point `x` under an endomorphism `f` or zero
if `x` is not a periodic point of `f`.
## Main statements
We provide “dot syntax”-style operations on terms of the form `h : is_periodic_pt f n x` including
arithmetic operations on `n` and `h.map (hg : semiconj_by g f f')`. We also prove that `f`
is bijective on each set `pts_of_period f n` and on `periodic_pts f`. Finally, we prove that `x`
is a periodic point of `f` of period `n` if and only if `minimal_period f x | n`.
## References
* https://en.wikipedia.org/wiki/Periodic_point
-/
open set
namespace function
variables {α : Type*} {β : Type*} {f fa : α → α} {fb : β → β} {x y : α} {m n : ℕ}
/-- A point `x` is a periodic point of `f : α → α` of period `n` if `f^[n] x = x`.
Note that we do not require `0 < n` in this definition. Many theorems about periodic points
need this assumption. -/
def is_periodic_pt (f : α → α) (n : ℕ) (x : α) := is_fixed_pt (f^[n]) x
/-- A fixed point of `f` is a periodic point of `f` of any prescribed period. -/
lemma is_fixed_pt.is_periodic_pt (hf : is_fixed_pt f x) (n : ℕ) : is_periodic_pt f n x :=
hf.iterate n
/-- For the identity map, all points are periodic. -/
lemma is_periodic_id (n : ℕ) (x : α) : is_periodic_pt id n x := (is_fixed_pt_id x).is_periodic_pt n
/-- Any point is a periodic point of period `0`. -/
lemma is_periodic_pt_zero (f : α → α) (x : α) : is_periodic_pt f 0 x := is_fixed_pt_id x
namespace is_periodic_pt
instance [decidable_eq α] {f : α → α} {n : ℕ} {x : α} : decidable (is_periodic_pt f n x) :=
is_fixed_pt.decidable
protected lemma is_fixed_pt (hf : is_periodic_pt f n x) : is_fixed_pt (f^[n]) x := hf
protected lemma map (hx : is_periodic_pt fa n x) {g : α → β} (hg : semiconj g fa fb) :
is_periodic_pt fb n (g x) :=
hx.map (hg.iterate_right n)
lemma apply_iterate (hx : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt f n (f^[m] x) :=
hx.map $ commute.iterate_self f m
protected lemma apply (hx : is_periodic_pt f n x) : is_periodic_pt f n (f x) :=
hx.apply_iterate 1
protected lemma add (hn : is_periodic_pt f n x) (hm : is_periodic_pt f m x) :
is_periodic_pt f (n + m) x :=
by { rw [is_periodic_pt, iterate_add], exact hn.comp hm }
lemma left_of_add (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f m x) :
is_periodic_pt f n x :=
by { rw [is_periodic_pt, iterate_add] at hn, exact hn.left_of_comp hm }
lemma right_of_add (hn : is_periodic_pt f (n + m) x) (hm : is_periodic_pt f n x) :
is_periodic_pt f m x :=
by { rw add_comm at hn, exact hn.left_of_add hm }
protected lemma sub (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) :
is_periodic_pt f (m - n) x :=
begin
cases le_total n m with h h,
{ refine left_of_add _ hn,
rwa [nat.sub_add_cancel h] },
{ rw [nat.sub_eq_zero_of_le h],
apply is_periodic_pt_zero }
end
protected lemma mul_const (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (m * n) x :=
by simp only [is_periodic_pt, iterate_mul, hm.is_fixed_pt.iterate n]
protected lemma const_mul (hm : is_periodic_pt f m x) (n : ℕ) : is_periodic_pt f (n * m) x :=
by simp only [mul_comm n, hm.mul_const n]
lemma trans_dvd (hm : is_periodic_pt f m x) {n : ℕ} (hn : m ∣ n) : is_periodic_pt f n x :=
let ⟨k, hk⟩ := hn in hk.symm ▸ hm.mul_const k
protected lemma iterate (hf : is_periodic_pt f n x) (m : ℕ) : is_periodic_pt (f^[m]) n x :=
begin
rw [is_periodic_pt, ← iterate_mul, mul_comm, iterate_mul],
exact hf.is_fixed_pt.iterate m
end
protected lemma mod (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) :
is_periodic_pt f (m % n) x :=
begin
rw [← nat.mod_add_div m n] at hm,
exact hm.left_of_add (hn.mul_const _)
end
protected lemma gcd (hm : is_periodic_pt f m x) (hn : is_periodic_pt f n x) :
is_periodic_pt f (m.gcd n) x :=
begin
revert hm hn,
refine nat.gcd.induction m n (λ n h0 hn, _) (λ m n hm ih hm hn, _),
{ rwa [nat.gcd_zero_left], },
{ rw [nat.gcd_rec],
exact ih (hn.mod hm) hm }
end
/-- If `f` sends two periodic points `x` and `y` of the same positive period to the same point,
then `x = y`. For a similar statement about points of different periods see `eq_of_apply_eq`. -/
lemma eq_of_apply_eq_same (hx : is_periodic_pt f n x) (hy : is_periodic_pt f n y) (hn : 0 < n)
(h : f x = f y) :
x = y :=
by rw [← hx.eq, ← hy.eq, ← iterate_pred_comp_of_pos f hn, comp_app, h]
/-- If `f` sends two periodic points `x` and `y` of positive periods to the same point,
then `x = y`. -/
lemma eq_of_apply_eq (hx : is_periodic_pt f m x) (hy : is_periodic_pt f n y) (hm : 0 < m)
(hn : 0 < n) (h : f x = f y) :
x = y :=
(hx.mul_const n).eq_of_apply_eq_same (hy.const_mul m) (mul_pos hm hn) h
end is_periodic_pt
/-- The set of periodic points of a given (possibly non-minimal) period. -/
def pts_of_period (f : α → α) (n : ℕ) : set α := {x : α | is_periodic_pt f n x}
@[simp] lemma mem_pts_of_period : x ∈ pts_of_period f n ↔ is_periodic_pt f n x :=
iff.rfl
lemma semiconj.maps_to_pts_of_period {g : α → β} (h : semiconj g fa fb) (n : ℕ) :
maps_to g (pts_of_period fa n) (pts_of_period fb n) :=
(h.iterate_right n).maps_to_fixed_pts
lemma bij_on_pts_of_period (f : α → α) {n : ℕ} (hn : 0 < n) :
bij_on f (pts_of_period f n) (pts_of_period f n) :=
⟨(commute.refl f).maps_to_pts_of_period n,
λ x hx y hy hxy, hx.eq_of_apply_eq_same hy hn hxy,
λ x hx, ⟨f^[n.pred] x, hx.apply_iterate _,
by rw [← comp_app f, comp_iterate_pred_of_pos f hn, hx.eq]⟩⟩
lemma directed_pts_of_period_pnat (f : α → α) : directed (⊆) (λ n : ℕ+, pts_of_period f n) :=
λ m n, ⟨m * n, λ x hx, hx.mul_const n, λ x hx, hx.const_mul m⟩
/-- The set of periodic points of a map `f : α → α`. -/
def periodic_pts (f : α → α) : set α := {x : α | ∃ n > 0, is_periodic_pt f n x}
lemma mk_mem_periodic_pts (hn : 0 < n) (hx : is_periodic_pt f n x) :
x ∈ periodic_pts f :=
⟨n, hn, hx⟩
lemma mem_periodic_pts : x ∈ periodic_pts f ↔ ∃ n > 0, is_periodic_pt f n x := iff.rfl
variable (f)
lemma bUnion_pts_of_period : (⋃ n > 0, pts_of_period f n) = periodic_pts f :=
set.ext $ λ x, by simp [mem_periodic_pts]
lemma Union_pnat_pts_of_period : (⋃ n : ℕ+, pts_of_period f n) = periodic_pts f :=
supr_subtype.trans $ bUnion_pts_of_period f
lemma bij_on_periodic_pts : bij_on f (periodic_pts f) (periodic_pts f) :=
Union_pnat_pts_of_period f ▸
bij_on_Union_of_directed (directed_pts_of_period_pnat f) (λ i, bij_on_pts_of_period f i.pos)
variable {f}
lemma semiconj.maps_to_periodic_pts {g : α → β} (h : semiconj g fa fb) :
maps_to g (periodic_pts fa) (periodic_pts fb) :=
λ x ⟨n, hn, hx⟩, ⟨n, hn, hx.map h⟩
open_locale classical
noncomputable theory
/-- Minimal period of a point `x` under an endomorphism `f`. If `x` is not a periodic point of `f`,
then `minimal_period f x = 0`. -/
def minimal_period (f : α → α) (x : α) :=
if h : x ∈ periodic_pts f then nat.find h else 0
lemma is_periodic_pt_minimal_period (f : α → α) (x : α) :
is_periodic_pt f (minimal_period f x) x :=
begin
delta minimal_period,
split_ifs with hx,
{ exact (nat.find_spec hx).snd },
{ exact is_periodic_pt_zero f x }
end
lemma iterate_eq_mod_minimal_period : f^[n] x = (f^[n % minimal_period f x] x) :=
begin
conv_lhs { rw ← nat.mod_add_div n (minimal_period f x) },
rw [iterate_add, mul_comm, iterate_mul, comp_app],
congr,
exact is_periodic_pt.iterate (is_periodic_pt_minimal_period _ _) _,
end
lemma minimal_period_pos_of_mem_periodic_pts (hx : x ∈ periodic_pts f) :
0 < minimal_period f x :=
by simp only [minimal_period, dif_pos hx, gt_iff_lt.1 (nat.find_spec hx).fst]
lemma is_periodic_pt.minimal_period_pos (hn : 0 < n) (hx : is_periodic_pt f n x) :
0 < minimal_period f x :=
minimal_period_pos_of_mem_periodic_pts $ mk_mem_periodic_pts hn hx
lemma minimal_period_pos_iff_mem_periodic_pts :
0 < minimal_period f x ↔ x ∈ periodic_pts f :=
⟨not_imp_not.1 $ λ h,
by simp only [minimal_period, dif_neg h, lt_irrefl 0, not_false_iff],
minimal_period_pos_of_mem_periodic_pts⟩
lemma is_periodic_pt.minimal_period_le (hn : 0 < n) (hx : is_periodic_pt f n x) :
minimal_period f x ≤ n :=
begin
rw [minimal_period, dif_pos (mk_mem_periodic_pts hn hx)],
exact nat.find_min' (mk_mem_periodic_pts hn hx) ⟨hn, hx⟩
end
lemma minimal_period_id : minimal_period id x = 1 :=
((is_periodic_id _ _ ).minimal_period_le nat.one_pos).antisymm
(nat.succ_le_of_lt ((is_periodic_id _ _ ).minimal_period_pos nat.one_pos))
lemma is_fixed_point_iff_minimal_period_eq_one : minimal_period f x = 1 ↔ is_fixed_pt f x :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ rw ← iterate_one f,
refine function.is_periodic_pt.is_fixed_pt _,
rw ← h,
exact is_periodic_pt_minimal_period f x },
{ exact ((h.is_periodic_pt 1).minimal_period_le nat.one_pos).antisymm
(nat.succ_le_of_lt ((h.is_periodic_pt 1).minimal_period_pos nat.one_pos)) }
end
lemma is_periodic_pt.eq_zero_of_lt_minimal_period (hx : is_periodic_pt f n x)
(hn : n < minimal_period f x) :
n = 0 :=
eq.symm $ (eq_or_lt_of_le $ n.zero_le).resolve_right $ λ hn0,
not_lt.2 (hx.minimal_period_le hn0) hn
lemma not_is_periodic_pt_of_pos_of_lt_minimal_period :
∀ {n: ℕ} (n0 : n ≠ 0) (hn : n < minimal_period f x), ¬ is_periodic_pt f n x
| 0 n0 _ := (n0 rfl).elim
| (n + 1) _ hn := λ hp, nat.succ_ne_zero _ (hp.eq_zero_of_lt_minimal_period hn)
lemma is_periodic_pt.minimal_period_dvd (hx : is_periodic_pt f n x) :
minimal_period f x ∣ n :=
(eq_or_lt_of_le $ n.zero_le).elim (λ hn0, hn0 ▸ dvd_zero _) $ λ hn0,
(nat.dvd_iff_mod_eq_zero _ _).2 $
(hx.mod $ is_periodic_pt_minimal_period f x).eq_zero_of_lt_minimal_period $
nat.mod_lt _ $ hx.minimal_period_pos hn0
lemma is_periodic_pt_iff_minimal_period_dvd :
is_periodic_pt f n x ↔ minimal_period f x ∣ n :=
⟨is_periodic_pt.minimal_period_dvd, λ h, (is_periodic_pt_minimal_period f x).trans_dvd h⟩
open nat
lemma minimal_period_eq_minimal_period_iff {g : β → β} {y : β} :
minimal_period f x = minimal_period g y ↔ ∀ n, is_periodic_pt f n x ↔ is_periodic_pt g n y :=
by simp_rw [is_periodic_pt_iff_minimal_period_dvd, dvd_right_iff_eq]
lemma minimal_period_eq_prime {p : ℕ} [hp : fact p.prime] (hper : is_periodic_pt f p x)
(hfix : ¬ is_fixed_pt f x) : minimal_period f x = p :=
(hp.out.2 _ (hper.minimal_period_dvd)).resolve_left
(mt is_fixed_point_iff_minimal_period_eq_one.1 hfix)
lemma minimal_period_eq_prime_pow {p k : ℕ} [hp : fact p.prime] (hk : ¬ is_periodic_pt f (p ^ k) x)
(hk1 : is_periodic_pt f (p ^ (k + 1)) x) : minimal_period f x = p ^ (k + 1) :=
begin
apply nat.eq_prime_pow_of_dvd_least_prime_pow hp.out;
rwa ← is_periodic_pt_iff_minimal_period_dvd
end
lemma commute.minimal_period_of_comp_dvd_lcm {g : α → α} (h : function.commute f g) :
minimal_period (f ∘ g) x ∣ nat.lcm (minimal_period f x) (minimal_period g x) :=
begin
rw [← is_periodic_pt_iff_minimal_period_dvd, is_periodic_pt, h.comp_iterate],
refine is_fixed_pt.comp _ _;
rw [← is_periodic_pt, is_periodic_pt_iff_minimal_period_dvd];
exact nat.dvd_lcm_left _ _ <|> exact dvd_lcm_right _ _
end
private lemma minimal_period_iterate_eq_div_gcd_aux (h : 0 < gcd (minimal_period f x) n) :
minimal_period (f ^[n]) x = minimal_period f x / nat.gcd (minimal_period f x) n :=
begin
apply nat.dvd_antisymm,
{ apply is_periodic_pt.minimal_period_dvd,
rw [is_periodic_pt, is_fixed_pt, ← iterate_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _),
mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), mul_comm, iterate_mul],
exact (is_periodic_pt_minimal_period f x).iterate _ },
{ apply coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd h),
apply dvd_of_mul_dvd_mul_right h,
rw [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _),
mul_comm],
apply is_periodic_pt.minimal_period_dvd,
rw [is_periodic_pt, is_fixed_pt, iterate_mul],
exact is_periodic_pt_minimal_period _ _ }
end
lemma minimal_period_iterate_eq_div_gcd (h : n ≠ 0) :
minimal_period (f ^[n]) x = minimal_period f x / nat.gcd (minimal_period f x) n :=
minimal_period_iterate_eq_div_gcd_aux $ gcd_pos_of_pos_right _ (nat.pos_of_ne_zero h)
lemma minimal_period_iterate_eq_div_gcd' (h : x ∈ periodic_pts f) :
minimal_period (f ^[n]) x = minimal_period f x / nat.gcd (minimal_period f x) n :=
minimal_period_iterate_eq_div_gcd_aux $
gcd_pos_of_pos_left n (minimal_period_pos_iff_mem_periodic_pts.mpr h)
end function
|
7f688687b42015dc232e3490f130b1e319cf98b2 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/analysis/normed_space/banach.lean | 7874fd69baf7492b5a3a7a80d215688b8bf930e9 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 10,515 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
Banach spaces, i.e., complete vector spaces.
This file contains the Banach open mapping theorem, i.e., the fact that a bijective
bounded linear map between Banach spaces has a bounded inverse.
-/
import topology.metric_space.baire analysis.normed_space.bounded_linear_maps
local attribute [instance] classical.prop_decidable
open function metric set filter finset
class banach_space (α : Type*) (β : Type*) [normed_field α]
extends normed_space α β, complete_space β
variables {k : Type*} [nondiscrete_normed_field k]
variables {E : Type*} [banach_space k E]
variables {F : Type*} [banach_space k F] {f : E → F}
include k
set_option class.instance_max_depth 70
/-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then
any point has a preimage with controlled norm. -/
theorem exists_preimage_norm_le (hf : is_bounded_linear_map k f) (surj : surjective f) :
∃C, 0 < C ∧ ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ :=
begin
have lin := hf.to_is_linear_map,
haveI : nonempty F := ⟨0⟩,
/- First step of the proof (using completeness of `F`): by Baire's theorem, there exists a
ball in E whose image closure has nonempty interior. Rescaling everything, it follows that
any `y ∈ F` is arbitrarily well approached by images of elements of norm at
most `C * ∥y∥`. For further use, we will only need such an element whose image
is within distance ∥y∥/2 of y, to apply an iterative process. -/
have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ,
{ refine subset.antisymm (subset_univ _) (λy hy, _),
rcases surj y with ⟨x, hx⟩,
rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩,
refine mem_Union.2 ⟨n, subset_closure _⟩,
refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩,
rwa [mem_ball, dist_eq_norm, sub_zero] },
have : ∃(n:ℕ) y ε, 0 < ε ∧ ball y ε ⊆ closure (f '' (ball 0 n)) :=
nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A,
have : ∃C, 0 ≤ C ∧ ∀y, ∃x, dist (f x) y ≤ (1/2) * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥,
{ rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩,
rcases exists_one_lt_norm k with ⟨c, hc⟩,
refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩,
{ refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _,
refine inv_nonneg.2 (div_nonneg' (le_of_lt εpos) (by norm_num)),
exact nat.cast_nonneg n },
{ by_cases hy : y = 0,
{ use 0, simp [hy, lin.map_zero] },
{ rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydle, leyd, dinv⟩,
let δ := ∥d∥ * ∥y∥/4,
have δpos : 0 < δ :=
div_pos (mul_pos ((norm_pos_iff _).2 hd) ((norm_pos_iff _).2 hy)) (by norm_num),
have : a + d • y ∈ ball a ε,
by simp [dist_eq_norm, lt_of_le_of_lt ydle (half_lt_self εpos)],
rcases mem_closure_iff'.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩,
rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩,
rw ← xz₁ at h₁,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₁,
have : a ∈ ball a ε, by { simp, exact εpos },
rcases mem_closure_iff'.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩,
rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩,
rw ← xz₂ at h₂,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₂,
let x := x₁ - x₂,
have I : ∥f x - d • y∥ ≤ 2 * δ := calc
∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ :
by { congr' 1, simp only [x, lin.map_sub], abel }
... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ :
norm_triangle_sub
... ≤ δ + δ : begin
apply add_le_add,
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ },
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ }
end
... = 2 * δ : (two_mul _).symm,
have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc
∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ :
by rwa [lin.smul, inv_mul_cancel, one_smul]
... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub]
... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, norm_inv]
... ≤ ∥d∥⁻¹ * (2 * δ) : begin
apply mul_le_mul_of_nonneg_left I,
rw inv_nonneg,
exact norm_nonneg _
end
... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring }
... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] }
... = (1/2) * ∥y∥ : by ring,
rw ← dist_eq_norm at J,
have K : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc
∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, norm_inv]
... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin
refine mul_le_mul dinv _ (norm_nonneg _) _,
{ exact le_trans (norm_triangle_sub) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) },
{ apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _),
exact inv_nonneg.2 (le_of_lt (half_pos εpos)) }
end
... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring,
exact ⟨d⁻¹ • x, J, K⟩ } } },
rcases this with ⟨C, C0, hC⟩,
/- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be
the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that
has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`,
leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage
of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a
preimage of `y`. This uses completeness of `E`. -/
choose g hg using hC,
let h := λy, y - f (g y),
have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥,
{ assume y,
rw [← dist_eq_norm, dist_comm],
exact (hg y).1 },
refine ⟨2 * C + 1, by linarith, λy, _⟩,
have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥,
{ assume n,
induction n with n IH,
{ simp only [one_div_eq_inv, nat.nat_zero_eq_zero, one_mul, nat.iterate_zero, pow_zero] },
{ rw [nat.iterate_succ'],
apply le_trans (hle _) _,
rw [pow_succ, mul_assoc],
apply mul_le_mul_of_nonneg_left IH,
norm_num } },
let u := λn, g((h^[n]) y),
have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥),
{ assume n,
apply le_trans (hg _).2 _,
calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0
... = (1 / 2) ^ n * (C * ∥y∥) : by ring },
have sNu : summable (λn, ∥u n∥),
{ refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _,
exact summable_mul_right _ (summable_geometric (by norm_num) (by norm_num)) },
have su : summable u := summable_of_summable_norm sNu,
let x := tsum u,
have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc
∥x∥ ≤ (∑n, ∥u n∥) : norm_tsum_le_tsum_norm sNu
... ≤ (∑n, (1/2)^n * (C * ∥y∥)) :
tsum_le_tsum ule sNu (summable_mul_right _ summable_geometric_two)
... = (∑n, (1/2)^n) * (C * ∥y∥) : by { rw tsum_mul_right, exact summable_geometric_two }
... = 2 * (C * ∥y∥) : by rw tsum_geometric_two
... = 2 * C * ∥y∥ + 0 : by rw [add_zero, mul_assoc]
... ≤ 2 * C * ∥y∥ + ∥y∥ : add_le_add (le_refl _) (norm_nonneg _)
... = (2 * C + 1) * ∥y∥ : by ring,
have fsumeq : ∀n:ℕ, f((range n).sum u) = y - (h^[n]) y,
{ assume n,
induction n with n IH,
{ simp [lin.map_zero] },
{ rw [sum_range_succ, lin.add, IH, nat.iterate_succ'],
simp [u, h] } },
have : tendsto (λn, (range n).sum u) at_top (nhds x) :=
tendsto_sum_nat_of_has_sum (has_sum_tsum su),
have L₁ : tendsto (λn, f((range n).sum u)) at_top (nhds (f x)) :=
tendsto.comp this (hf.continuous.tendsto _),
simp only [fsumeq] at L₁,
have L₂ : tendsto (λn, y - (h^[n]) y) at_top (nhds (y - 0)),
{ refine tendsto_sub tendsto_const_nhds _,
rw tendsto_iff_norm_tendsto_zero,
simp only [sub_zero],
refine squeeze_zero (λ_, norm_nonneg _) hnle _,
have : 0 = 0 * ∥y∥, by rw zero_mul,
rw this,
refine tendsto_mul _ tendsto_const_nhds,
exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) },
have feq : f x = y - 0,
{ apply tendsto_nhds_unique _ L₁ L₂,
simp },
rw sub_zero at feq,
exact ⟨x, feq, x_ineq⟩
end
/-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/
theorem open_mapping (hf : is_bounded_linear_map k f) (surj : surjective f) : is_open_map f :=
begin
assume s hs,
have lin := hf.to_is_linear_map,
rcases exists_preimage_norm_le hf surj with ⟨C, Cpos, hC⟩,
refine is_open_iff.2 (λy yfs, _),
rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩,
rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩,
refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩,
rcases hC (z-y) with ⟨w, wim, wnorm⟩,
have : f (x + w) = z, by { rw [lin.add, wim, fxy], abel },
rw ← this,
have : x + w ∈ ball x ε := calc
dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp }
... ≤ C * ∥z - y∥ : wnorm
... < C * (ε/C) : begin
apply mul_lt_mul_of_pos_left _ Cpos,
rwa [mem_ball, dist_eq_norm] at hz,
end
... = ε : mul_div_cancel' _ (ne_of_gt Cpos),
exact set.mem_image_of_mem _ (hε this)
end
/-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/
theorem linear_equiv.is_bounded_inv (e : linear_equiv k E F) (h : is_bounded_linear_map k e.to_fun) :
is_bounded_linear_map k e.inv_fun :=
{ bound := begin
have : surjective e.to_fun := (equiv.bijective e.to_equiv).2,
rcases exists_preimage_norm_le h this with ⟨M, Mpos, hM⟩,
refine ⟨M, Mpos, λy, _⟩,
rcases hM y with ⟨x, hx, xnorm⟩,
have : x = e.inv_fun y, by { rw ← hx, exact (e.symm_apply_apply _).symm },
rwa ← this
end,
..e.symm }
|
b9957975dc677c0229508663c009dd435b437378 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/matrix/char_p.lean | 49e8e4e21776e7563a71f695827617c33270e34f | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 586 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.matrix.basic
import algebra.char_p.basic
/-!
# Matrices in prime characteristic
-/
open matrix
variables {n : Type*} [fintype n] {R : Type*} [ring R]
instance matrix.char_p [decidable_eq n] [nonempty n] (p : ℕ) [char_p R p] :
char_p (matrix n n R) p :=
⟨begin
intro k,
rw [← char_p.cast_eq_zero_iff R p k, ← nat.cast_zero, ← map_nat_cast $ scalar n],
convert scalar_inj, {simp}, {assumption}
end⟩
|
ccd32f9641e9d7880201acc207c471370ce3c502 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/linear_algebra/basic.lean | 95f2bc09c9ef8eef01f7ee7ea8c6302e2e255a24 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 111,001 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov, Frédéric Dupuis,
Heather Macbeth
-/
import algebra.big_operators.pi
import algebra.module.hom
import algebra.module.prod
import algebra.module.submodule_lattice
import data.dfinsupp.basic
import data.finsupp.basic
import order.compactly_generated
import order.omega_complete_partial_order
/-!
# Linear algebra
This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of
modules over a ring, submodules, and linear maps.
Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in
`src/algebra/module`.
## Main definitions
* Many constructors for (semi)linear maps
* `submodule.span s` is defined to be the smallest submodule containing the set `s`.
* The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain
respectively.
* The general linear group is defined to be the group of invertible linear maps from `M` to itself.
See `linear_algebra.quotient` for quotients by submodules.
## Main theorems
See `linear_algebra.isomorphisms` for Noether's three isomorphism theorems for modules.
## Notations
* We continue to use the notations `M →ₛₗ[σ] M₂` and `M →ₗ[R] M₂` for the type of semilinear
(resp. linear) maps from `M` to `M₂` over the ring homomorphism `σ` (resp. over the ring `R`).
* We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is
`\.`, not the same as the scalar multiplication `•`/`\bub`.
## Implementation notes
We note that, when constructing linear maps, it is convenient to use operations defined on bundled
maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a
function and proving it is linear.
## TODO
* Parts of this file have not yet been generalized to semilinear maps
## Tags
linear algebra, vector space, module
-/
open function
open_locale big_operators pointwise
variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} {R₄ : Type*}
variables {S : Type*}
variables {K : Type*} {K₂ : Type*}
variables {M : Type*} {M' : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} {M₄ : Type*}
variables {N : Type*} {N₂ : Type*}
variables {ι : Type*}
variables {V : Type*} {V₂ : Type*}
namespace finsupp
lemma smul_sum {α : Type*} {β : Type*} {R : Type*} {M : Type*}
[has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M]
{v : α →₀ β} {c : R} {h : α → β → M} :
c • (v.sum h) = v.sum (λa b, c • h a b) :=
finset.smul_sum
@[simp]
lemma sum_smul_index_linear_map' {α : Type*} {R : Type*} {M : Type*} {M₂ : Type*}
[semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂]
{v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} :
(c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) :=
begin
rw [finsupp.sum_smul_index', finsupp.smul_sum],
{ simp only [linear_map.map_smul], },
{ intro i, exact (h i).map_zero },
end
variables (α : Type*) [fintype α]
variables (R M) [add_comm_monoid M] [semiring R] [module R M]
/-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between
`α →₀ β` and `α → β`. -/
@[simps apply] noncomputable def linear_equiv_fun_on_fintype :
(α →₀ M) ≃ₗ[R] (α → M) :=
{ to_fun := coe_fn,
map_add' := λ f g, by { ext, refl },
map_smul' := λ c f, by { ext, refl },
.. equiv_fun_on_fintype }
@[simp] lemma linear_equiv_fun_on_fintype_single [decidable_eq α] (x : α) (m : M) :
(linear_equiv_fun_on_fintype R M α) (single x m) = pi.single x m :=
begin
ext a,
change (equiv_fun_on_fintype (single x m)) a = _,
convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a,
end
@[simp] lemma linear_equiv_fun_on_fintype_symm_single [decidable_eq α]
(x : α) (m : M) : (linear_equiv_fun_on_fintype R M α).symm (pi.single x m) = single x m :=
begin
ext a,
change (equiv_fun_on_fintype.symm (pi.single x m)) a = _,
convert congr_fun (equiv_fun_on_fintype_symm_single x m) a,
end
@[simp] lemma linear_equiv_fun_on_fintype_symm_coe (f : α →₀ M) :
(linear_equiv_fun_on_fintype R M α).symm f = f :=
by { ext, simp [linear_equiv_fun_on_fintype], }
end finsupp
section
open_locale classical
/-- decomposing `x : ι → R` as a sum along the canonical basis -/
lemma pi_eq_sum_univ {ι : Type*} [fintype ι] {R : Type*} [semiring R] (x : ι → R) :
x = ∑ i, x i • (λj, if i = j then 1 else 0) :=
by { ext, simp }
end
/-! ### Properties of linear maps -/
namespace linear_map
section add_comm_monoid
variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂]
variables [add_comm_monoid M₃] [add_comm_monoid M₄]
variables [module R M] [module R M₁] [module R₂ M₂] [module R₃ M₃] [module R₄ M₄]
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₃₄ : R₃ →+* R₄}
variables {σ₁₃ : R →+* R₃} {σ₂₄ : R₂ →+* R₄} {σ₁₄ : R →+* R₄}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄]
variables [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄]
variables (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃)
include R R₂
theorem comp_assoc (h : M₃ →ₛₗ[σ₃₄] M₄) :
((h.comp g : M₂ →ₛₗ[σ₂₄] M₄).comp f : M →ₛₗ[σ₁₄] M₄)
= h.comp (g.comp f : M →ₛₗ[σ₁₃] M₃) := rfl
omit R R₂
/-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map
`p → M₂`. -/
def dom_restrict (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : p →ₛₗ[σ₁₂] M₂ := f.comp p.subtype
@[simp] lemma dom_restrict_apply (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) (x : p) :
f.dom_restrict p x = f x := rfl
/-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a
linear map M₂ → p. -/
def cod_restrict (p : submodule R₂ M₂) (f : M →ₛₗ[σ₁₂] M₂) (h : ∀c, f c ∈ p) : M →ₛₗ[σ₁₂] p :=
by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp
@[simp] theorem cod_restrict_apply (p : submodule R₂ M₂) (f : M →ₛₗ[σ₁₂] M₂) {h} (x : M) :
(cod_restrict p f h x : M₂) = f x := rfl
@[simp] lemma comp_cod_restrict (p : submodule R₃ M₃) (h : ∀b, g b ∈ p) :
((cod_restrict p g h).comp f : M →ₛₗ[σ₁₃] p) = cod_restrict p (g.comp f) (assume b, h _) :=
ext $ assume b, rfl
@[simp] lemma subtype_comp_cod_restrict (p : submodule R₂ M₂) (h : ∀b, f b ∈ p) :
p.subtype.comp (cod_restrict p f h) = f :=
ext $ assume b, rfl
/-- Restrict domain and codomain of an endomorphism. -/
def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p :=
(f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf
lemma restrict_apply
{f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) :
f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl
lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) :
p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl
lemma restrict_eq_cod_restrict_dom_restrict
{f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) :
f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl
lemma restrict_eq_dom_restrict_cod_restrict
{f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) :
f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl
instance unique_of_left [subsingleton M] : unique (M →ₛₗ[σ₁₂] M₂) :=
{ uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero],
.. linear_map.inhabited }
instance unique_of_right [subsingleton M₂] : unique (M →ₛₗ[σ₁₂] M₂) :=
coe_injective.unique
/-- Evaluation of a `σ₁₂`-linear map at a fixed `a`, as an `add_monoid_hom`. -/
def eval_add_monoid_hom (a : M) : (M →ₛₗ[σ₁₂] M₂) →+ M₂ :=
{ to_fun := λ f, f a,
map_add' := λ f g, linear_map.add_apply f g a,
map_zero' := rfl }
/-- `linear_map.to_add_monoid_hom` promoted to an `add_monoid_hom` -/
def to_add_monoid_hom' : (M →ₛₗ[σ₁₂] M₂) →+ (M →+ M₂) :=
{ to_fun := to_add_monoid_hom,
map_zero' := by ext; refl,
map_add' := by intros; ext; refl }
lemma sum_apply (t : finset ι) (f : ι → M →ₛₗ[σ₁₂] M₂) (b : M) :
(∑ d in t, f d) b = ∑ d in t, f d b :=
add_monoid_hom.map_sum ((add_monoid_hom.eval b).comp to_add_monoid_hom') f _
section smul_right
variables [semiring S] [module R S] [module S M] [is_scalar_tower R S M]
/-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/
def smul_right (f : M₁ →ₗ[R] S) (x : M) : M₁ →ₗ[R] M :=
{ to_fun := λb, f b • x,
map_add' := λ x y, by rw [f.map_add, add_smul],
map_smul' := λ b y, by dsimp; rw [f.map_smul, smul_assoc] }
@[simp] theorem coe_smul_right (f : M₁ →ₗ[R] S) (x : M) :
(smul_right f x : M₁ → M) = λ c, f c • x := rfl
theorem smul_right_apply (f : M₁ →ₗ[R] S) (x : M) (c : M₁) :
smul_right f x c = f c • x := rfl
end smul_right
instance [nontrivial M] : nontrivial (module.End R M) :=
begin
obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance,
exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)),
end
@[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₛₗ[σ₁₂] M₂) :
⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) :=
add_monoid_hom.map_sum ⟨@to_fun R R₂ _ _ σ₁₂ M M₂ _ _ _ _, rfl, λ x y, rfl⟩ _ _
@[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) :
(f^n) m = (f^[n] m) :=
begin
induction n with n ih,
{ refl, },
{ simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih],
exact (function.commute.iterate_self _ _ m).symm, },
end
lemma pow_map_zero_of_le
{f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 :=
by rw [← tsub_add_cancel_of_le hk, pow_add, mul_apply, hm, map_zero]
lemma commute_pow_left_of_commute
{f : M →ₛₗ[σ₁₂] M₂} {g : module.End R M} {g₂ : module.End R₂ M₂}
(h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) :=
begin
induction k with k ih,
{ simpa only [pow_zero], },
{ rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih,
← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], },
end
lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M}
{g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g)
{k : ℕ} (hG : G^k = 0) : g^k = 0 :=
begin
ext m,
have hg : N.subtype.comp (g^k) m = 0,
{ rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], },
simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg,
rw [hg, linear_map.zero_apply],
end
lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) :=
by { ext m, apply pow_apply, }
@[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n
section
variables {f' : M →ₗ[R] M}
lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' :=
by rw [pow_succ', mul_eq_comp]
lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n)
| 0 := surjective_id
| (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, }
lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n)
| 0 := injective_id
| (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, }
lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n)
| 0 := bijective_id
| (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, }
lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) :
injective f' :=
begin
rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h,
exact injective.of_comp h,
end
lemma surjective_of_iterate_surjective {n : ℕ} (hn : n ≠ 0) (h : surjective ⇑(f' ^ n)) :
surjective f' :=
begin
rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn),
nat.succ_eq_add_one, add_comm, pow_add] at h,
exact surjective.of_comp h,
end
end
section
open_locale classical
/-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements
of the canonical basis. -/
lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) :
f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) :=
begin
conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] },
apply finset.sum_congr rfl (λl hl, _),
rw f.map_smul
end
end
end add_comm_monoid
section module
variables [semiring R] [semiring S]
[add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
[module R M] [module R M₂] [module R M₃]
[module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃]
(f : M →ₗ[R] M₂)
variable (S)
/-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`.
See `linear_map.applyₗ` for a version where `S = R`. -/
@[simps]
def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ :=
{ to_fun := λ v,
{ to_fun := λ f, f v,
map_add' := λ f g, f.add_apply g v,
map_smul' := λ x f, f.smul_apply x v },
map_zero' := linear_map.ext $ λ f, f.map_zero,
map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ }
section
variables (R M)
/--
The equivalence between R-linear maps from `R` to `M`, and points of `M` itself.
This says that the forgetful functor from `R`-modules to types is representable, by `R`.
This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`.
When `R` is commutative, we can take this to be the usual action with `S = R`.
Otherwise, `S = ℕ` shows that the equivalence is additive.
See note [bundled maps over different rings].
-/
@[simps]
def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M :=
{ to_fun := λ f, f 1,
inv_fun := smul_right (1 : R →ₗ[R] R),
left_inv := λ f, by { ext, simp },
right_inv := λ x, by simp,
.. applyₗ' S (1 : R) }
end
end module
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f g : M →ₗ[R] M₂)
include R
/-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂`
to the space of linear maps `M₂ → M₃`. -/
def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) :=
{ to_fun := f.comp,
map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _,
map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ }
/-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`.
See also `linear_map.applyₗ'` for a version that works with two different semirings.
This is the `linear_map` version of `add_monoid_hom.eval`. -/
@[simps]
def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ :=
{ to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v },
map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _,
..applyₗ' R }
/-- Alternative version of `dom_restrict` as a linear map. -/
def dom_restrict'
(p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) :=
{ to_fun := λ φ, φ.dom_restrict p,
map_add' := by simp [linear_map.ext_iff],
map_smul' := by simp [linear_map.ext_iff] }
@[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) :
dom_restrict' p f x = f x := rfl
end comm_semiring
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
/--
The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`.
-/
def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M :=
{ to_fun := λ f,
{ to_fun := linear_map.smul_right f,
map_add' := λ m m', by { ext, apply smul_add, },
map_smul' := λ c m, by { ext, apply smul_comm, } },
map_add' := λ f f', by { ext, apply add_smul, },
map_smul' := λ c f, by { ext, apply mul_smul, } }
@[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) :
(smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M) f x c = (f c) • x := rfl
end comm_ring
end linear_map
/--
The `R`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`.
-/
@[simps]
def add_monoid_hom_lequiv_nat {A B : Type*} (R : Type*)
[semiring R] [add_comm_monoid A] [add_comm_monoid B] [module R B] :
(A →+ B) ≃ₗ[R] (A →ₗ[ℕ] B) :=
{ to_fun := add_monoid_hom.to_nat_linear_map,
inv_fun := linear_map.to_add_monoid_hom,
map_add' := by { intros, ext, refl },
map_smul' := by { intros, ext, refl },
left_inv := by { intros f, ext, refl },
right_inv := by { intros f, ext, refl } }
/--
The `R`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`.
-/
@[simps]
def add_monoid_hom_lequiv_int {A B : Type*} (R : Type*)
[semiring R] [add_comm_group A] [add_comm_group B] [module R B] :
(A →+ B) ≃ₗ[R] (A →ₗ[ℤ] B) :=
{ to_fun := add_monoid_hom.to_int_linear_map,
inv_fun := linear_map.to_add_monoid_hom,
map_add' := by { intros, ext, refl },
map_smul' := by { intros, ext, refl },
left_inv := by { intros f, ext, refl },
right_inv := by { intros f, ext, refl } }
/-! ### Properties of submodules -/
namespace submodule
section add_comm_monoid
variables [semiring R] [semiring R₂] [semiring R₃]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M']
variables [module R M] [module R M'] [module R₂ M₂] [module R₃ M₃]
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃}
variables {σ₂₁ : R₂ →+* R}
variables [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃]
variables (p p' : submodule R M) (q q' : submodule R₂ M₂)
variables (q₁ q₁' : submodule R M')
variables {r : R} {x y : M}
open set
variables {p p'}
/-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of
this inclusion. -/
def of_le (h : p ≤ p') : p →ₗ[R] p' :=
p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx
@[simp] theorem coe_of_le (h : p ≤ p') (x : p) :
(of_le h x : M) = x := rfl
theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl
theorem of_le_injective (h : p ≤ p') : function.injective (of_le h) :=
λ x y h, subtype.val_injective (subtype.mk.inj h)
variables (p p')
lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) :
q.subtype.comp (of_le h) = p.subtype :=
by { ext ⟨b, hb⟩, refl }
variables (R)
@[simp] lemma subsingleton_iff : subsingleton (submodule R M) ↔ subsingleton M :=
have h : subsingleton (submodule R M) ↔ subsingleton (add_submonoid M),
{ rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top],
convert to_add_submonoid_eq.symm; refl, },
h.trans add_submonoid.subsingleton_iff
@[simp] lemma nontrivial_iff : nontrivial (submodule R M) ↔ nontrivial M :=
not_iff_not.mp (
(not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans
not_nontrivial_iff_subsingleton.symm)
variables {R}
instance [subsingleton M] : unique (submodule R M) :=
⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mpr ‹_›) a _⟩
instance unique' [subsingleton R] : unique (submodule R M) :=
by haveI := module.subsingleton R M; apply_instance
instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mpr ‹_›
theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} :
(x:M) ∈ p' ↔ x = 0 :=
⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩
theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} :
(x:M) ∈ p ↔ x = 0 :=
⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩
section
variables [ring_hom_surjective σ₁₂]
/-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/
def map (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : submodule R₂ M₂ :=
{ carrier := f '' p,
smul_mem' :=
begin
rintro c x ⟨y, hy, rfl⟩,
obtain ⟨a, rfl⟩ := σ₁₂.is_surjective c,
exact ⟨_, p.smul_mem a hy, f.map_smulₛₗ _ _⟩,
end,
.. p.to_add_submonoid.map f.to_add_monoid_hom }
@[simp] lemma map_coe (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) :
(map f p : set M₂) = f '' p := rfl
lemma map_to_add_submonoid (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) :
(p.map f).to_add_submonoid = p.to_add_submonoid.map f :=
set_like.coe_injective rfl
@[simp] lemma mem_map {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {x : M₂} :
x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl
theorem mem_map_of_mem {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {r} (h : r ∈ p) :
f r ∈ map f p := set.mem_image_of_mem _ h
lemma apply_coe_mem_map (f : M →ₛₗ[σ₁₂] M₂) {p : submodule R M} (r : p) :
f r ∈ map f p := mem_map_of_mem r.prop
@[simp] lemma map_id : map (linear_map.id : M →ₗ[R] M) p = p :=
submodule.ext $ λ a, by simp
lemma map_comp [ring_hom_surjective σ₂₃] [ring_hom_surjective σ₁₃]
(f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃)
(p : submodule R M) : map (g.comp f : M →ₛₗ[σ₁₃] M₃) p = map g (map f p) :=
set_like.coe_injective $ by simp [map_coe]; rw ← image_comp
lemma map_mono {f : M →ₛₗ[σ₁₂] M₂} {p p' : submodule R M} :
p ≤ p' → map f p ≤ map f p' := image_subset _
@[simp] lemma map_zero : map (0 : M →ₛₗ[σ₁₂] M₂) p = ⊥ :=
have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩,
ext $ by simp [this, eq_comm]
lemma map_add_le (f g : M →ₛₗ[σ₁₂] M₂) : map (f + g) p ≤ map f p ⊔ map g p :=
begin
rintros x ⟨m, hm, rfl⟩,
exact add_mem_sup (mem_map_of_mem hm) (mem_map_of_mem hm),
end
lemma range_map_nonempty (N : submodule R M) :
(set.range (λ ϕ, submodule.map ϕ N : (M →ₛₗ[σ₁₂] M₂) → submodule R₂ M₂)).nonempty :=
⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩
end
include σ₂₁
/-- The pushforward of a submodule by an injective linear map is
linearly equivalent to the original submodule. See also `linear_equiv.submodule_map` for a
computable version when `f` has an explicit inverse. -/
noncomputable def equiv_map_of_injective (f : M →ₛₗ[σ₁₂] M₂) (i : injective f)
(p : submodule R M) : p ≃ₛₗ[σ₁₂] p.map f :=
{ map_add' := by { intros, simp, refl, },
map_smul' := by { intros, simp, refl, },
..(equiv.set.image f p i) }
@[simp] lemma coe_equiv_map_of_injective_apply (f : M →ₛₗ[σ₁₂] M₂) (i : injective f)
(p : submodule R M) (x : p) :
(equiv_map_of_injective f i p x : M₂) = f x := rfl
omit σ₂₁
/-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/
def comap (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R₂ M₂) : submodule R M :=
{ carrier := f ⁻¹' p,
smul_mem' := λ a x h, by simp [p.smul_mem _ h],
.. p.to_add_submonoid.comap f.to_add_monoid_hom }
@[simp] lemma comap_coe (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R₂ M₂) :
(comap f p : set M) = f ⁻¹' p := rfl
@[simp] lemma mem_comap {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R₂ M₂} :
x ∈ comap f p ↔ f x ∈ p := iff.rfl
lemma comap_id : comap linear_map.id p = p :=
set_like.coe_injective rfl
lemma comap_comp (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃)
(p : submodule R₃ M₃) : comap (g.comp f : M →ₛₗ[σ₁₃] M₃) p = comap f (comap g p) :=
rfl
lemma comap_mono {f : M →ₛₗ[σ₁₂] M₂} {q q' : submodule R₂ M₂} :
q ≤ q' → comap f q ≤ comap f q' := preimage_mono
section
variables [ring_hom_surjective σ₁₂]
lemma map_le_iff_le_comap {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {q : submodule R₂ M₂} :
map f p ≤ q ↔ p ≤ comap f q := image_subset_iff
lemma gc_map_comap (f : M →ₛₗ[σ₁₂] M₂) : galois_connection (map f) (comap f)
| p q := map_le_iff_le_comap
@[simp] lemma map_bot (f : M →ₛₗ[σ₁₂] M₂) : map f ⊥ = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma map_sup (f : M →ₛₗ[σ₁₂] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' :=
(gc_map_comap f).l_sup
@[simp] lemma map_supr {ι : Sort*} (f : M →ₛₗ[σ₁₂] M₂) (p : ι → submodule R M) :
map f (⨆i, p i) = (⨆i, map f (p i)) :=
(gc_map_comap f).l_supr
end
@[simp] lemma comap_top (f : M →ₛₗ[σ₁₂] M₂) : comap f ⊤ = ⊤ := rfl
@[simp] lemma comap_inf (f : M →ₛₗ[σ₁₂] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl
@[simp] lemma comap_infi [ring_hom_surjective σ₁₂] {ι : Sort*} (f : M →ₛₗ[σ₁₂] M₂)
(p : ι → submodule R₂ M₂) :
comap f (⨅i, p i) = (⨅i, comap f (p i)) :=
(gc_map_comap f).u_infi
@[simp] lemma comap_zero : comap (0 : M →ₛₗ[σ₁₂] M₂) q = ⊤ :=
ext $ by simp
lemma map_comap_le [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (q : submodule R₂ M₂) :
map f (comap f q) ≤ q :=
(gc_map_comap f).l_u_le _
lemma le_comap_map [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) :
p ≤ comap f (map f p) :=
(gc_map_comap f).le_u_l _
section galois_insertion
variables {f : M →ₛₗ[σ₁₂] M₂} (hf : surjective f)
variables [ring_hom_surjective σ₁₂]
include hf
/-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/
def gi_map_comap : galois_insertion (map f) (comap f) :=
(gc_map_comap f).to_galois_insertion
(λ S x hx, begin
rcases hf x with ⟨y, rfl⟩,
simp only [mem_map, mem_comap],
exact ⟨y, hx, rfl⟩
end)
lemma map_comap_eq_of_surjective (p : submodule R₂ M₂) : (p.comap f).map f = p :=
(gi_map_comap hf).l_u_eq _
lemma map_surjective_of_surjective : function.surjective (map f) :=
(gi_map_comap hf).l_surjective
lemma comap_injective_of_surjective : function.injective (comap f) :=
(gi_map_comap hf).u_injective
lemma map_sup_comap_of_surjective (p q : submodule R₂ M₂) :
(p.comap f ⊔ q.comap f).map f = p ⊔ q :=
(gi_map_comap hf).l_sup_u _ _
lemma map_supr_comap_of_sujective {ι : Sort*} (S : ι → submodule R₂ M₂) :
(⨆ i, (S i).comap f).map f = supr S :=
(gi_map_comap hf).l_supr_u _
lemma map_inf_comap_of_surjective (p q : submodule R₂ M₂) :
(p.comap f ⊓ q.comap f).map f = p ⊓ q :=
(gi_map_comap hf).l_inf_u _ _
lemma map_infi_comap_of_surjective {ι : Sort*} (S : ι → submodule R₂ M₂) :
(⨅ i, (S i).comap f).map f = infi S :=
(gi_map_comap hf).l_infi_u _
lemma comap_le_comap_iff_of_surjective (p q : submodule R₂ M₂) :
p.comap f ≤ q.comap f ↔ p ≤ q :=
(gi_map_comap hf).u_le_u_iff
lemma comap_strict_mono_of_surjective : strict_mono (comap f) :=
(gi_map_comap hf).strict_mono_u
end galois_insertion
section galois_coinsertion
variables [ring_hom_surjective σ₁₂] {f : M →ₛₗ[σ₁₂] M₂} (hf : injective f)
include hf
/-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/
def gci_map_comap : galois_coinsertion (map f) (comap f) :=
(gc_map_comap f).to_galois_coinsertion
(λ S x, by simp [mem_comap, mem_map, hf.eq_iff])
lemma comap_map_eq_of_injective (p : submodule R M) : (p.map f).comap f = p :=
(gci_map_comap hf).u_l_eq _
lemma comap_surjective_of_injective : function.surjective (comap f) :=
(gci_map_comap hf).u_surjective
lemma map_injective_of_injective : function.injective (map f) :=
(gci_map_comap hf).l_injective
lemma comap_inf_map_of_injective (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q :=
(gci_map_comap hf).u_inf_l _ _
lemma comap_infi_map_of_injective {ι : Sort*} (S : ι → submodule R M) :
(⨅ i, (S i).map f).comap f = infi S :=
(gci_map_comap hf).u_infi_l _
lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q :=
(gci_map_comap hf).u_sup_l _ _
lemma comap_supr_map_of_injective {ι : Sort*} (S : ι → submodule R M) :
(⨆ i, (S i).map f).comap f = supr S :=
(gci_map_comap hf).u_supr_l _
lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q :=
(gci_map_comap hf).l_le_l_iff
lemma map_strict_mono_of_injective : strict_mono (map f) :=
(gci_map_comap hf).strict_mono_l
end galois_coinsertion
--TODO(Mario): is there a way to prove this from order properties?
lemma map_inf_eq_map_inf_comap [ring_hom_surjective σ₁₂] {f : M →ₛₗ[σ₁₂] M₂}
{p : submodule R M} {p' : submodule R₂ M₂} :
map f p ⊓ p' = map f (p ⊓ comap f p') :=
le_antisymm
(by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩)
(le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right))
lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' :=
ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩
lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0
| ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb
/-- The infimum of a family of invariant submodule of an endomorphism is also an invariant
submodule. -/
lemma _root_.linear_map.infi_invariant {σ : R →+* R} [ring_hom_surjective σ] {ι : Sort*}
(f : M →ₛₗ[σ] M) {p : ι → submodule R M} (hf : ∀ i, ∀ v ∈ (p i), f v ∈ p i) :
∀ v ∈ infi p, f v ∈ infi p :=
begin
have : ∀ i, (p i).map f ≤ p i,
{ rintros i - ⟨v, hv, rfl⟩,
exact hf i v hv },
suffices : (infi p).map f ≤ infi p,
{ exact λ v hv, this ⟨v, hv, rfl⟩, },
exact le_infi (λ i, (submodule.map_mono (infi_le p i)).trans (this i)),
end
section
variables (R)
/-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/
def span (s : set M) : submodule R M := Inf {p | s ⊆ p}
end
variables {s t : set M}
lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_Inter₂
lemma subset_span : s ⊆ span R s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span R s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span R s ≤ span R t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p :=
le_antisymm (span_le.2 h₁) h₂
lemma span_eq : span R (p : set M) = p :=
span_eq_of_le _ (subset.refl _) subset_span
/-- A version of `submodule.span_eq` for when the span is by a smaller ring. -/
@[simp] lemma span_coe_eq_restrict_scalars
[semiring S] [has_scalar S R] [module S M] [is_scalar_tower S R M] :
span S (p : set M) = p.restrict_scalars S :=
span_eq (p.restrict_scalars S)
lemma map_span [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M) :
(span R s).map f = span R₂ (f '' s) :=
eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $
map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩
alias submodule.map_span ← linear_map.map_span
lemma map_span_le [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M)
(N : submodule R₂ M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N :=
begin
rw [f.map_span, span_le, set.image_subset_iff],
exact iff.rfl
end
alias submodule.map_span_le ← linear_map.map_span_le
@[simp] lemma span_insert_zero : span R (insert (0 : M) s) = span R s :=
begin
refine le_antisymm _ (submodule.span_mono (set.subset_insert 0 s)),
rw [span_le, set.insert_subset],
exact ⟨by simp only [set_like.mem_coe, submodule.zero_mem], submodule.subset_span⟩,
end
/- See also `span_preimage_eq` below. -/
lemma span_preimage_le (f : M →ₛₗ[σ₁₂] M₂) (s : set M₂) :
span R (f ⁻¹' s) ≤ (span R₂ s).comap f :=
by { rw [span_le, comap_coe], exact preimage_mono (subset_span), }
alias submodule.span_preimage_le ← linear_map.span_preimage_le
/-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is
preserved under addition and scalar multiplication, then `p` holds for all elements of the span of
`s`. -/
@[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (a:R) x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h
/-- A dependent version of `submodule.span_induction`. -/
lemma span_induction' {p : Π x, x ∈ span R s → Prop}
(Hs : ∀ x (h : x ∈ s), p x (subset_span h))
(H0 : p 0 (submodule.zero_mem _))
(H1 : ∀ x hx y hy, p x hx → p y hy → p (x + y) (submodule.add_mem _ ‹_› ‹_›))
(H2 : ∀ (a : R) x hx, p x hx → p (a • x) (submodule.smul_mem _ _ ‹_›)) {x} (hx : x ∈ span R s) :
p x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ span R s) (hc : p x hx), hc),
refine span_induction hx (λ m hm, ⟨subset_span hm, Hs m hm⟩) ⟨zero_mem _, H0⟩
(λ x y hx hy, exists.elim hx $ λ hx' hx, exists.elim hy $ λ hy' hy,
⟨add_mem _ hx' hy', H1 _ _ _ _ hx hy⟩) (λ r x hx, exists.elim hx $ λ hx' hx,
⟨smul_mem _ _ hx', H2 r _ _ hx⟩)
end
@[simp] lemma span_span_coe_preimage : span R ((coe : span R s → M) ⁻¹' s) = ⊤ :=
eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin
refine span_induction' (λ x hx, _) _ (λ x y _ _, _) (λ r x _, _) hx,
{ exact subset_span hx },
{ exact zero_mem _ },
{ exact add_mem _ },
{ exact smul_mem _ _ }
end
lemma span_nat_eq_add_submonoid_closure (s : set M) :
(span ℕ s).to_add_submonoid = add_submonoid.closure s :=
begin
refine eq.symm (add_submonoid.closure_eq_of_le subset_span _),
apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _,
rw span_le,
exact add_submonoid.subset_closure,
end
@[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s :=
by rw [span_nat_eq_add_submonoid_closure, s.closure_eq]
lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) :
(span ℤ s).to_add_subgroup = add_subgroup.closure s :=
eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx
(λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _)
(λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.zsmul_mem _ ‹_› _)
@[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) :
(span ℤ (s : set M)).to_add_subgroup = s :=
by rw [span_int_eq_add_subgroup_closure, s.closure_eq]
section
variables (R M)
/-- `span` forms a Galois insertion with the coercion from submodule to set. -/
protected def gi : galois_insertion (@span R M _ _ _) coe :=
{ choice := λ s _, span R s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
end
@[simp] lemma span_empty : span R (∅ : set M) = ⊥ :=
(submodule.gi R M).gc.l_bot
@[simp] lemma span_univ : span R (univ : set M) = ⊤ :=
eq_top_iff.2 $ set_like.le_def.2 $ subset_span
lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t :=
(submodule.gi R M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) :=
(submodule.gi R M).gc.l_supr
lemma span_attach_bUnion [decidable_eq M] {α : Type*} (s : finset α) (f : s → finset M) :
span R (s.attach.bUnion f : set M) = ⨆ x, span R (f x) :=
by simpa [span_Union]
lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} :=
by simp only [←span_Union, set.bUnion_of_singleton s]
lemma span_smul_le (s : set M) (r : R) :
span R (r • s) ≤ span R s :=
begin
rw span_le,
rintros _ ⟨x, hx, rfl⟩,
exact smul_mem (span R s) r (subset_span hx),
end
lemma subset_span_trans {U V W : set M} (hUV : U ⊆ submodule.span R V)
(hVW : V ⊆ submodule.span R W) :
U ⊆ submodule.span R W :=
(submodule.gi R M).gc.le_u_l_trans hUV hVW
/-- See `submodule.span_smul_eq` (in `ring_theory.ideal.operations`) for
`span R (r • s) = r • span R s` that holds for arbitrary `r` in a `comm_semiring`. -/
lemma span_smul_eq_of_is_unit (s : set M) (r : R) (hr : is_unit r) :
span R (r • s) = span R s :=
begin
apply le_antisymm,
{ apply span_smul_le },
{ convert span_smul_le (r • s) ((hr.unit ⁻¹ : _) : R),
rw smul_smul,
erw hr.unit.inv_val,
rw one_smul }
end
@[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι]
(S : ι → submodule R M) (H : directed (≤) S) :
((supr S : submodule R M) : set M) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i),
by simpa only [span_Union, span_eq] using this,
refine (λ x hx, span_induction hx (λ _, id) _ _ _);
simp only [mem_Union, exists_imp_distrib],
{ exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) },
{ intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ },
{ exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
@[simp] theorem mem_supr_of_directed {ι} [nonempty ι]
(S : ι → submodule R M) (H : directed (≤) S) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl }
theorem mem_Sup_of_directed {s : set (submodule R M)}
{z} (hs : s.nonempty) (hdir : directed_on (≤) s) :
z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y :=
begin
haveI : nonempty s := hs.to_subtype,
simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk]
end
@[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →o submodule R M) :
(↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) :=
coe_supr_of_directed a a.monotone.directed_le
/-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is
Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/
lemma coe_scott_continuous : omega_complete_partial_order.continuous'
(coe : submodule R M → set M) :=
⟨set_like.coe_mono, coe_supr_of_chain⟩
@[simp] lemma mem_supr_of_chain (a : ℕ →o submodule R M) (m : M) :
m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k :=
mem_supr_of_directed a a.monotone.directed_le
section
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x :=
mem_sup.trans $ by simp only [set_like.exists, coe_mk]
variables (p p')
lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) :=
by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, }
lemma sup_to_add_submonoid :
(p ⊔ p').to_add_submonoid = p.to_add_submonoid ⊔ p'.to_add_submonoid :=
begin
ext x,
rw [mem_to_add_submonoid, mem_sup, add_submonoid.mem_sup],
refl,
end
lemma sup_to_add_subgroup {R M : Type*} [ring R] [add_comm_group M] [module R M]
(p p' : submodule R M) :
(p ⊔ p').to_add_subgroup = p.to_add_subgroup ⊔ p'.to_add_subgroup :=
begin
ext x,
rw [mem_to_add_subgroup, mem_sup, add_subgroup.mem_sup],
refl,
end
end
/- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar
multiplication character `•`, with escape sequence `\bub`. -/
notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x)
lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl
lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) :=
⟨begin
use [0, x, submodule.mem_span_singleton_self x],
intros H,
rw [eq_comm, submodule.mk_eq_zero] at H,
exact h H
end⟩
lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} :
s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v :=
by simp_rw [set_like.le_def, mem_span_singleton]
lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v :=
by { rw [eq_top_iff, le_span_singleton_iff], tauto }
@[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ :=
by { ext, simp [mem_span_singleton, eq_comm] }
lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) :=
set.ext $ λ x, mem_span_singleton
lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x :=
begin
rw [span_le, set.singleton_subset_iff, set_like.mem_coe],
exact smul_mem _ _ (mem_span_singleton_self _)
end
lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x :=
begin
refine le_antisymm (span_singleton_smul_le r x) _,
convert span_singleton_smul_le r⁻¹ (r • x),
exact (inv_smul_smul₀ hr _).symm
end
lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{s : submodule K E} {x : E} :
disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) :=
begin
refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩,
assume H y hy hyx,
obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx,
subst y,
classical, by_cases hc : c = 0, by simp only [hc, zero_smul],
rw [s.smul_mem_iff hc] at hy,
rw [H hy, smul_zero]
end
lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E]
{p : submodule K E} {x : E} (x0 : x ≠ 0) :
disjoint p (K ∙ x) ↔ x ∉ p :=
disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩
lemma mem_span_singleton_trans {x y z : M} (hxy : x ∈ R ∙ y) (hyz : y ∈ R ∙ z) :
x ∈ R ∙ z :=
begin
rw [← set_like.mem_coe, ← singleton_subset_iff] at *,
exact submodule.subset_span_trans hxy hyz
end
lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z :=
begin
simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop,
exists_exists_eq_and],
rw [exists_comm],
simp only [eq_comm, add_comm, exists_and_distrib_left]
end
lemma span_insert (x) (s : set M) : span R (insert x s) = span R ({x} : set M) ⊔ span R s :=
by rw [insert_eq, span_union]
lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span R (span R s : set M) = span R s := span_eq _
variables (R S s)
/-- If `R` is "smaller" ring than `S` then the span by `R` is smaller than the span by `S`. -/
lemma span_le_restrict_scalars [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] :
span R s ≤ (span S s).restrict_scalars R :=
submodule.span_le.2 submodule.subset_span
/-- A version of `submodule.span_le_restrict_scalars` with coercions. -/
@[simp] lemma span_subset_span [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] :
↑(span R s) ⊆ (span S s : set M) :=
span_le_restrict_scalars R S s
/-- Taking the span by a large ring of the span by the small ring is the same as taking the span
by just the large ring. -/
lemma span_span_of_tower [semiring S] [has_scalar R S] [module S M] [is_scalar_tower R S M] :
span S (span R s : set M) = span S s :=
le_antisymm (span_le.2 $ span_subset_span R S s) (span_mono subset_span)
variables {R S s}
lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, (mem_bot R).1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩
@[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot]
@[simp] lemma span_image [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) :
span R₂ (f '' s) = map f (span R s) :=
(map_span f s).symm
lemma apply_mem_span_image_of_mem_span
[ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) :
f x ∈ submodule.span R₂ (f '' s) :=
begin
rw submodule.span_image,
exact submodule.mem_map_of_mem h
end
/-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/
lemma not_mem_span_of_apply_not_mem_span_image
[ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M}
(h : f x ∉ submodule.span R₂ (f '' s)) :
x ∉ submodule.span R s :=
h.imp (apply_mem_span_image_of_mem_span f)
lemma supr_eq_span {ι : Sort*} (p : ι → submodule R M) :
(⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) :=
le_antisymm
(supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span)
(span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm)
lemma supr_to_add_submonoid {ι : Sort*} (p : ι → submodule R M) :
(⨆ i, p i).to_add_submonoid = ⨆ i, (p i).to_add_submonoid :=
begin
refine le_antisymm (λ x, _) (supr_le $ λ i, to_add_submonoid_mono $ le_supr _ i),
simp_rw [supr_eq_span, add_submonoid.supr_eq_closure, mem_to_add_submonoid, coe_to_add_submonoid],
intros hx,
refine submodule.span_induction hx (λ x hx, _) _ (λ x y hx hy, _) (λ r x hx, _),
{ exact add_submonoid.subset_closure hx },
{ exact add_submonoid.zero_mem _ },
{ exact add_submonoid.add_mem _ hx hy },
{ apply add_submonoid.closure_induction hx,
{ rintros x ⟨_, ⟨i, rfl⟩, hix : x ∈ p i⟩,
apply add_submonoid.subset_closure (set.mem_Union.mpr ⟨i, _⟩),
exact smul_mem _ r hix },
{ rw smul_zero,
exact add_submonoid.zero_mem _ },
{ intros x y hx hy,
rw smul_add,
exact add_submonoid.add_mem _ hx hy, } }
end
/-- An induction principle for elements of `⨆ i, p i`.
If `C` holds for `0` and all elements of `p i` for all `i`, and is preserved under addition,
then it holds for all elements of the supremum of `p`. -/
@[elab_as_eliminator]
lemma supr_induction {ι : Sort*} (p : ι → submodule R M) {C : M → Prop} {x : M} (hx : x ∈ ⨆ i, p i)
(hp : ∀ i (x ∈ p i), C x)
(h0 : C 0)
(hadd : ∀ x y, C x → C y → C (x + y)) : C x :=
begin
rw [←mem_to_add_submonoid, supr_to_add_submonoid] at hx,
exact add_submonoid.supr_induction _ hx hp h0 hadd,
end
/-- A dependent version of `submodule.supr_induction`. -/
@[elab_as_eliminator]
lemma supr_induction' {ι : Sort*} (p : ι → submodule R M) {C : Π x, (x ∈ ⨆ i, p i) → Prop}
(hp : ∀ i (x ∈ p i), C x (mem_supr_of_mem i ‹_›))
(h0 : C 0 (zero_mem _))
(hadd : ∀ x y hx hy, C x hx → C y hy → C (x + y) (add_mem _ ‹_› ‹_›))
{x : M} (hx : x ∈ ⨆ i, p i) : C x hx :=
begin
refine exists.elim _ (λ (hx : x ∈ ⨆ i, p i) (hc : C x hx), hc),
refine supr_induction p hx (λ i x hx, _) _ (λ x y, _),
{ exact ⟨_, hp _ _ hx⟩ },
{ exact ⟨_, h0⟩ },
{ rintro ⟨_, Cx⟩ ⟨_, Cy⟩,
refine ⟨_, hadd _ _ _ _ Cx Cy⟩ },
end
lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p :=
by rw [span_le, singleton_subset_iff, set_like.mem_coe]
lemma singleton_span_is_compact_element (x : M) :
complete_lattice.is_compact_element (span R {x} : submodule R M) :=
begin
rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le,
intros d hemp hdir hsup,
have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x),
obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this,
exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩,
end
instance : is_compactly_generated (submodule R M) :=
⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin
rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩,
apply singleton_span_is_compact_element,
end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩
lemma lt_sup_iff_not_mem {I : submodule R M} {a : M} : I < I ⊔ (R ∙ a) ↔ a ∉ I :=
begin
split,
{ intro h,
by_contra akey,
have h1 : I ⊔ (R ∙ a) ≤ I,
{ simp only [sup_le_iff],
split,
{ exact le_refl I, },
{ exact (span_singleton_le_iff_mem a I).mpr akey, } },
have h2 := gt_of_ge_of_gt h1 h,
exact lt_irrefl I h2, },
{ intro h,
apply set_like.lt_iff_le_and_exists.mpr, split,
simp only [le_sup_left],
use a,
split, swap, { assumption, },
{ have : (R ∙ a) ≤ I ⊔ (R ∙ a) := le_sup_right,
exact this (mem_span_singleton_self a), } },
end
lemma mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} :
(m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) :=
begin
rw [← span_singleton_le_iff_mem, le_supr_iff],
simp only [span_singleton_le_iff_mem],
end
section
open_locale classical
/-- For every element in the span of a set, there exists a finite subset of the set
such that the element is contained in the span of the subset. -/
lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) :
∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) :=
begin
refine span_induction hx (λ x hx, _) _ _ _,
{ refine ⟨{x}, _, _⟩,
{ rwa [finset.coe_singleton, set.singleton_subset_iff] },
{ rw finset.coe_singleton,
exact submodule.mem_span_singleton_self x } },
{ use ∅, simp },
{ rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩,
refine ⟨X ∪ Y, _, _⟩,
{ rw finset.coe_union,
exact set.union_subset hX hY },
rw [finset.coe_union, span_union, mem_sup],
exact ⟨x, hxX, y, hyY, rfl⟩, },
{ rintros a x ⟨T, hT, h2⟩,
exact ⟨T, hT, smul_mem _ _ h2⟩ }
end
end
/-- The product of two submodules is a submodule. -/
def prod : submodule R (M × M') :=
{ carrier := (p : set M) ×ˢ (q₁ : set M'),
smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩,
.. p.to_add_submonoid.prod q₁.to_add_submonoid }
@[simp] lemma prod_coe :
(prod p q₁ : set (M × M')) = (p : set M) ×ˢ (q₁ : set M') := rfl
@[simp] lemma mem_prod {p : submodule R M} {q : submodule R M'} {x : M × M'} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set M) (t : set M') :
span R (s ×ˢ t) ≤ prod (span R s) (span R t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M')) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M')) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule R M} {q q' : submodule R M'} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q₁ ⊓ prod p' q₁' = prod (p ⊓ p') (q₁ ⊓ q₁') :=
set_like.coe_injective set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q₁ ⊔ prod p' q₁' = prod (p ⊔ p') (q₁ ⊔ q₁') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [set_like.le_def], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
end add_comm_monoid
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (p p' : submodule R M) (q q' : submodule R M₂)
variables {r : R} {x y : M}
open set
@[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff
@[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p :=
ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩,
λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩
@[simp] lemma span_neg (s : set M) : span R (-s) = span R s :=
calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp
... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm
... = span R s : by simp
lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ }
end
end submodule
namespace submodule
variables [field K]
variables [add_comm_group V] [module K V]
variables [add_comm_group V₂] [module K V₂]
lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) :
p.comap (a • f) = p.comap f :=
by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply]
lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) :
p.map (a • f) = p.map f :=
le_antisymm
begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_rfl end
begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_rfl end
lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) :
p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) :=
by classical; by_cases a = 0; simp [h, comap_smul]
lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) :
p.map (a • f) = (⨆ h : a ≠ 0, p.map f) :=
by classical; by_cases a = 0; simp [h, map_smul]
end submodule
/-! ### Properties of linear maps -/
namespace linear_map
section add_comm_monoid
variables [semiring R] [semiring R₂] [semiring R₃]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃}
variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃]
variables [module R M] [module R₂ M₂] [module R₃ M₃]
include R
open submodule
/-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`.
See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/
lemma eq_on_span {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) :
f x = g x :=
by apply span_induction h H; simp {contextual := tt}
/-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`.
This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`.
See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/
lemma eq_on_span' {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) :
set.eq_on f g (span R s : set M) :=
eq_on_span H
/-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are
equal. -/
lemma ext_on {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) :
f = g :=
linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _))
/-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at
each `v i`, then they are equal. -/
lemma ext_on_range {v : ι → M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R (set.range v) = ⊤)
(h : ∀i, f (v i) = g (v i)) : f = g :=
ext_on hv (set.forall_range_iff.2 h)
section finsupp
variables {γ : Type*} [has_zero γ]
@[simp] lemma map_finsupp_sum (f : M →ₛₗ[σ₁₂] M₂) {t : ι →₀ γ} {g : ι → γ → M} :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum
lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₛₗ[σ₁₂] M₂) :
⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _
@[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₛₗ[σ₁₂] M₂) (b : M) :
(t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _
end finsupp
section dfinsupp
open dfinsupp
variables {γ : ι → Type*} [decidable_eq ι]
section sum
variables [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)]
@[simp] lemma map_dfinsupp_sum (f : M →ₛₗ[σ₁₂] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum
lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₛₗ[σ₁₂] M₂) :
⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _
@[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₛₗ[σ₁₂] M₂) (b : M) :
(t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _
end sum
section sum_add_hom
variables [Π i, add_zero_class (γ i)]
@[simp] lemma map_dfinsupp_sum_add_hom (f : M →ₛₗ[σ₁₂] M₂) {t : Π₀ i, γ i} {g : Π i, γ i →+ M} :
f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_monoid_hom.comp (g i)) t :=
f.to_add_monoid_hom.map_dfinsupp_sum_add_hom _ _
end sum_add_hom
end dfinsupp
variables {σ₂₁ : R₂ →+* R} {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃}
variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃]
theorem map_cod_restrict [ring_hom_surjective σ₂₁] (p : submodule R M) (f : M₂ →ₛₗ[σ₂₁] M) (h p') :
submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) :=
submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val]
theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₛₗ[σ₂₁] M) (hf p') :
submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') :=
submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩
section
/-- The range of a linear map `f : M → M₂` is a submodule of `M₂`.
See Note [range copy pattern]. -/
def range [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : submodule R₂ M₂ :=
(map f ⊤).copy (set.range f) set.image_univ.symm
theorem range_coe [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) :
(range f : set M₂) = set.range f := rfl
@[simp] theorem mem_range [ring_hom_surjective τ₁₂]
{f : M →ₛₗ[τ₁₂] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x :=
iff.rfl
lemma range_eq_map [ring_hom_surjective τ₁₂]
(f : M →ₛₗ[τ₁₂] M₂) : f.range = map f ⊤ :=
by { ext, simp }
theorem mem_range_self [ring_hom_surjective τ₁₂]
(f : M →ₛₗ[τ₁₂] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩
@[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ :=
set_like.coe_injective set.range_id
theorem range_comp [ring_hom_surjective τ₁₂] [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃]
(f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) :
range (g.comp f : M →ₛₗ[τ₁₃] M₃) = map g (range f) :=
set_like.coe_injective (set.range_comp g f)
theorem range_comp_le_range [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃]
(f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) :
range (g.comp f : M →ₛₗ[τ₁₃] M₃) ≤ range g :=
set_like.coe_mono (set.range_comp_subset_range f g)
theorem range_eq_top [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} :
range f = ⊤ ↔ surjective f :=
by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective]
lemma range_le_iff_comap [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R₂ M₂} :
range f ≤ p ↔ comap f p = ⊤ :=
by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff]
lemma map_le_range [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} :
map f p ≤ range f :=
set_like.coe_mono (set.image_subset_range f p)
end
/--
The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map.
-/
@[simps]
def iterate_range (f : M →ₗ[R] M) : ℕ →o order_dual (submodule R M) :=
⟨λ n, (f ^ n).range, λ n m w x h, begin
obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w,
rw linear_map.mem_range at h,
obtain ⟨m, rfl⟩ := h,
rw linear_map.mem_range,
use (f ^ c) m,
rw [pow_add, linear_map.mul_apply],
end⟩
/-- Restrict the codomain of a linear map `f` to `f.range`.
This is the bundled version of `set.range_factorization`. -/
@[reducible] def range_restrict [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) :
M →ₛₗ[τ₁₂] f.range := f.cod_restrict f.range f.mem_range_self
--set_option trace.class_instances true
/-- The range of a linear map is finite if the domain is finite.
Note: this instance can form a diamond with `subtype.fintype` in the
presence of `fintype M₂`. -/
instance fintype_range [fintype M] [decidable_eq M₂] [ring_hom_surjective τ₁₂]
(f : M →ₛₗ[τ₁₂] M₂) : fintype (range f) :=
set.fintype_range f
section
variables (R) (M)
/-- Given an element `x` of a module `M` over `R`, the natural map from
`R` to scalar multiples of `x`.-/
@[simps] def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x
/-- The range of `to_span_singleton x` is the span of `x`.-/
lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range :=
submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton }
lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _
end
/-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the
set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/
def ker (f : M →ₛₗ[τ₁₂] M₂) : submodule R M := comap f ⊥
@[simp] theorem mem_ker {f : M →ₛₗ[τ₁₂] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R₂
@[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl
@[simp] theorem map_coe_ker (f : M →ₛₗ[τ₁₂] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2
lemma comp_ker_subtype (f : M →ₛₗ[τ₁₂] M₂) : f.comp f.ker.subtype = 0 :=
linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2
theorem ker_comp (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) :
ker (g.comp f : M →ₛₗ[τ₁₃] M₃) = comap f (ker g) := rfl
theorem ker_le_ker_comp (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) :
ker f ≤ ker (g.comp f : M →ₛₗ[τ₁₃] M₃) :=
by rw ker_comp; exact comap_mono bot_le
theorem disjoint_ker {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 :=
by simp [disjoint_def]
theorem ker_eq_bot' {f : M →ₛₗ[τ₁₂] M₂} :
ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) :=
by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ _ _ _ f ⊤
theorem ker_eq_bot_of_inverse {τ₂₁ : R₂ →+* R} [ring_hom_inv_pair τ₁₂ τ₂₁]
{f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₁] M} (h : (g.comp f : M →ₗ[R] M) = id) :
ker f = ⊥ :=
ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero]
lemma le_ker_iff_map [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} :
p ≤ ker f ↔ map f p = ⊥ :=
by rw [ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_cod_restrict {τ₂₁ : R₂ →+* R} (p : submodule R M) (f : M₂ →ₛₗ[τ₂₁] M) (hf) :
ker (cod_restrict p f hf) = ker f :=
by rw [ker, comap_cod_restrict, map_bot]; refl
lemma range_cod_restrict {τ₂₁ : R₂ →+* R} [ring_hom_surjective τ₂₁] (p : submodule R M)
(f : M₂ →ₛₗ[τ₂₁] M) (hf) :
range (cod_restrict p f hf) = comap p.subtype f.range :=
by simpa only [range_eq_map] using map_cod_restrict _ _ _ _
lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) :
ker (f.restrict hf) = (f.dom_restrict p).ker :=
by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict]
lemma _root_.submodule.map_comap_eq [ring_hom_surjective τ₁₂]
(f : M →ₛₗ[τ₁₂] M₂) (q : submodule R₂ M₂) : map f (comap f q) = range f ⊓ q :=
le_antisymm (le_inf map_le_range (map_comap_le _ _)) $
by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩
lemma _root_.submodule.map_comap_eq_self [ring_hom_surjective τ₁₂]
{f : M →ₛₗ[τ₁₂] M₂} {q : submodule R₂ M₂} (h : q ≤ range f) : map f (comap f q) = q :=
by rwa [submodule.map_comap_eq, inf_eq_right]
@[simp] theorem ker_zero : ker (0 : M →ₛₗ[τ₁₂] M₂) = ⊤ :=
eq_top_iff'.2 $ λ x, by simp
@[simp] theorem range_zero [ring_hom_surjective τ₁₂] : range (0 : M →ₛₗ[τ₁₂] M₂) = ⊥ :=
by simpa only [range_eq_map] using submodule.map_zero _
theorem ker_eq_top {f : M →ₛₗ[τ₁₂] M₂} : ker f = ⊤ ↔ f = 0 :=
⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩
section
variables [ring_hom_surjective τ₁₂]
lemma range_le_bot_iff (f : M →ₛₗ[τ₁₂] M₂) : range f ≤ ⊥ ↔ f = 0 :=
by rw [range_le_iff_comap]; exact ker_eq_top
theorem range_eq_bot {f : M →ₛₗ[τ₁₂] M₂} : range f = ⊥ ↔ f = 0 :=
by rw [← range_le_bot_iff, le_bot_iff]
lemma range_le_ker_iff {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₃] M₃} :
range f ≤ ker g ↔ (g.comp f : M →ₛₗ[τ₁₃] M₃) = 0 :=
⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩,
λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩
theorem comap_le_comap_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p p'} :
comap f p ≤ comap f p' ↔ p ≤ p' :=
⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩
theorem comap_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) : injective (comap f) :=
λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h))
((comap_le_comap_iff hf).1 (ge_of_eq h))
end
theorem ker_eq_bot_of_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : injective f) : ker f = ⊥ :=
begin
have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H },
simpa [disjoint]
end
/--
The increasing sequence of submodules consisting of the kernels of the iterates of a linear map.
-/
@[simps]
def iterate_ker (f : M →ₗ[R] M) : ℕ →o submodule R M :=
⟨λ n, (f ^ n).ker, λ n m w x h, begin
obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w,
rw linear_map.mem_ker at h,
rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero],
end⟩
end add_comm_monoid
section add_comm_group
variables [semiring R] [semiring R₂] [semiring R₃]
variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R₂ M₂] [module R₃ M₃]
variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃}
variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] [ring_hom_surjective τ₁₂]
include R
open submodule
lemma _root_.submodule.comap_map_eq (f : M →ₛₗ[τ₁₂] M₂) (p : submodule R M) :
comap f (map f p) = p ⊔ ker f :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma _root_.submodule.comap_map_eq_self {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} (h : ker f ≤ p) :
comap f (map f p) = p :=
by rw [submodule.comap_map_eq, sup_of_le_left h]
theorem map_le_map_iff (f : M →ₛₗ[τ₁₂] M₂) {p p'} :
map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f :=
by rw [map_le_iff_le_comap, submodule.comap_map_eq]
theorem map_le_map_iff' {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) {p p'} :
map f p ≤ map f p' ↔ p ≤ p' :=
by rw [map_le_map_iff, hf, sup_bot_eq]
theorem map_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h))
theorem map_eq_top_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p : submodule R M} :
p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ :=
by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff]
end add_comm_group
section ring
variables [ring R] [ring R₂] [ring R₃]
variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R₂ M₂] [module R₃ M₃]
variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃}
variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃]
variables {f : M →ₛₗ[τ₁₂] M₂}
include R
open submodule
theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y :=
by rw [mem_ker, map_sub, sub_eq_zero]
theorem disjoint_ker' {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y :=
disjoint_ker.trans
⟨λ H x hx y hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]),
λ H x h₁ h₂, H x h₁ 0 (zero_mem _) (by simpa using h₂)⟩
theorem inj_of_disjoint_ker {p : submodule R M}
{s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) :
∀ x y ∈ s, f x = f y → x = y :=
λ x hx y hy, disjoint_ker'.1 hd _ (h hx) _ (h hy)
theorem ker_eq_bot : ker f = ⊥ ↔ injective f :=
by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ _ _ _ f ⊤
lemma ker_le_iff [ring_hom_surjective τ₁₂] {p : submodule R M} :
ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p :=
begin
split,
{ intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, },
{ rintros ⟨y, h₁, h₂⟩,
rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz,
rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁,
have hx' : x ∈ p, { exact h₂ hx, },
have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], },
suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], },
exact p.sub_mem hxz hx', },
end
end ring
section field
variables [field K] [field K₂]
variables [add_comm_group V] [module K V]
variables [add_comm_group V₂] [module K V₂]
lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f :=
submodule.comap_smul f _ a h
lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f :=
submodule.comap_smul' f _ a
lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f :=
by simpa only [range_eq_map] using submodule.map_smul f _ a h
lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f :=
by simpa only [range_eq_map] using submodule.map_smul' f _ a
lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) :
(K ∙ x) ⊔ f.ker = ⊤ :=
eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x,
submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩,
⟨y - (f y * (f x)⁻¹) • x,
by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc,
inv_mul_cancel hx, mul_one, sub_self],
by simp only [add_sub_cancel'_right]⟩⟩)
end field
end linear_map
namespace is_linear_map
lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] :
is_linear_map R (λ (x : M × M), x.1 + x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp, cc },
{ intros x y,
simp [smul_add] }
end
lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]:
is_linear_map R (λ (x : M × M), x.1 - x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp [add_comm, add_left_comm, sub_eq_add_neg] },
{ intros x y,
simp [smul_sub] }
end
end is_linear_map
namespace submodule
section add_comm_monoid
variables [semiring R] [semiring R₂] [add_comm_monoid M] [add_comm_monoid M₂]
variables [module R M] [module R₂ M₂]
variables (p p' : submodule R M) (q : submodule R₂ M₂)
variables {τ₁₂ : R →+* R₂}
open linear_map
@[simp] theorem map_top [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : map f ⊤ = range f :=
f.range_eq_map.symm
@[simp] theorem comap_bot (f : M →ₛₗ[τ₁₂] M₂) : comap f ⊥ = ker f := rfl
@[simp] theorem ker_subtype : p.subtype.ker = ⊥ :=
ker_eq_bot_of_injective $ λ x y, subtype.ext_val
@[simp] theorem range_subtype : p.subtype.range = p :=
by simpa using map_comap_subtype p ⊤
lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p :=
by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range)
/-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the
maximal submodule of `p` is just `p `. -/
@[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p :=
by simp
@[simp] lemma comap_subtype_eq_top {p p' : submodule R M} :
comap p.subtype p' = ⊤ ↔ p ≤ p' :=
eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top]
@[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ :=
comap_subtype_eq_top.2 le_rfl
@[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ :=
by rw [of_le, ker_cod_restrict, ker_subtype]
lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p :=
by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype]
lemma disjoint_iff_comap_eq_bot {p q : submodule R M} :
disjoint p q ↔ comap p.subtype q = ⊥ :=
by rw [←(map_injective_of_injective (show injective p.subtype, from subtype.coe_injective)).eq_iff,
map_comap_subtype, map_bot, disjoint_iff]
/-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/
def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} :=
{ to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩,
inv_fun := λ q, comap p.subtype q,
left_inv := λ p', comap_map_eq_of_injective subtype.coe_injective p',
right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq],
map_rel_iff' := λ p₁ p₂, subtype.coe_le_coe.symm.trans begin
dsimp,
rw [map_le_iff_le_comap,
comap_map_eq_of_injective (show injective p.subtype, from subtype.coe_injective) p₂],
end }
/-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of
submodules of `M`. -/
def map_subtype.order_embedding : submodule R p ↪o submodule R M :=
(rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _)
@[simp] lemma map_subtype_embedding_eq (p' : submodule R p) :
map_subtype.order_embedding p p' = map p.subtype p' := rfl
end add_comm_monoid
end submodule
namespace linear_map
section semiring
variables [semiring R] [semiring R₂] [semiring R₃]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R₂ M₂] [module R₃ M₃]
variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃}
variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃]
/-- A monomorphism is injective. -/
lemma ker_eq_bot_of_cancel {f : M →ₛₗ[τ₁₂] M₂}
(h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ :=
begin
have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _,
rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)],
exact range_zero
end
lemma range_comp_of_range_eq_top [ring_hom_surjective τ₁₂] [ring_hom_surjective τ₂₃]
[ring_hom_surjective τ₁₃]
{f : M →ₛₗ[τ₁₂] M₂} (g : M₂ →ₛₗ[τ₂₃] M₃) (hf : range f = ⊤) :
range (g.comp f : M →ₛₗ[τ₁₃] M₃) = range g :=
by rw [range_comp, hf, submodule.map_top]
lemma ker_comp_of_ker_eq_bot (f : M →ₛₗ[τ₁₂] M₂) {g : M₂ →ₛₗ[τ₂₃] M₃}
(hg : ker g = ⊥) : ker (g.comp f : M →ₛₗ[τ₁₃] M₃) = ker f :=
by rw [ker_comp, hg, submodule.comap_bot]
section image
/-- If `O` is a submodule of `M`, and `Φ : O →ₗ M'` is a linear map,
then `(ϕ : O →ₗ M').submodule_image N` is `ϕ(N)` as a submodule of `M'` -/
def submodule_image {M' : Type*} [add_comm_monoid M'] [module R M']
{O : submodule R M} (ϕ : O →ₗ[R] M') (N : submodule R M) : submodule R M' :=
(N.comap O.subtype).map ϕ
@[simp] lemma mem_submodule_image {M' : Type*} [add_comm_monoid M'] [module R M']
{O : submodule R M} {ϕ : O →ₗ[R] M'} {N : submodule R M} {x : M'} :
x ∈ ϕ.submodule_image N ↔ ∃ y (yO : y ∈ O) (yN : y ∈ N), ϕ ⟨y, yO⟩ = x :=
begin
refine submodule.mem_map.trans ⟨_, _⟩; simp_rw submodule.mem_comap,
{ rintro ⟨⟨y, yO⟩, (yN : y ∈ N), h⟩,
exact ⟨y, yO, yN, h⟩ },
{ rintro ⟨y, yO, yN, h⟩,
exact ⟨⟨y, yO⟩, yN, h⟩ }
end
lemma mem_submodule_image_of_le {M' : Type*} [add_comm_monoid M'] [module R M']
{O : submodule R M} {ϕ : O →ₗ[R] M'} {N : submodule R M} (hNO : N ≤ O) {x : M'} :
x ∈ ϕ.submodule_image N ↔ ∃ y (yN : y ∈ N), ϕ ⟨y, hNO yN⟩ = x :=
begin
refine mem_submodule_image.trans ⟨_, _⟩,
{ rintro ⟨y, yO, yN, h⟩,
exact ⟨y, yN, h⟩ },
{ rintro ⟨y, yN, h⟩,
exact ⟨y, hNO yN, yN, h⟩ }
end
lemma submodule_image_apply_of_le {M' : Type*} [add_comm_group M'] [module R M']
{O : submodule R M} (ϕ : O →ₗ[R] M') (N : submodule R M) (hNO : N ≤ O) :
ϕ.submodule_image N = (ϕ.comp (submodule.of_le hNO)).range :=
by rw [submodule_image, range_comp, submodule.range_of_le]
end image
end semiring
end linear_map
@[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂]
[module R M] [module R M₂] (f : M →ₗ[R] M₂) :
f.range_restrict.range = ⊤ :=
by simp [f.range_cod_restrict _]
/-! ### Linear equivalences -/
namespace linear_equiv
section add_comm_monoid
section subsingleton
variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄]
variables [module R M] [module R₂ M₂]
variables [subsingleton M] [subsingleton M₂]
variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R}
variables [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
include σ₂₁
/-- Between two zero modules, the zero map is an equivalence. -/
instance : has_zero (M ≃ₛₗ[σ₁₂] M₂) :=
⟨{ to_fun := 0,
inv_fun := 0,
right_inv := λ x, subsingleton.elim _ _,
left_inv := λ x, subsingleton.elim _ _,
..(0 : M →ₛₗ[σ₁₂] M₂)}⟩
omit σ₂₁
-- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're
-- nice to have as `rfl`-lemmas for `dsimp`.
include σ₂₁
@[simp] lemma zero_symm : (0 : M ≃ₛₗ[σ₁₂] M₂).symm = 0 := rfl
@[simp] lemma coe_zero : ⇑(0 : M ≃ₛₗ[σ₁₂] M₂) = 0 := rfl
lemma zero_apply (x : M) : (0 : M ≃ₛₗ[σ₁₂] M₂) x = 0 := rfl
/-- Between two zero modules, the zero map is the only equivalence. -/
instance : unique (M ≃ₛₗ[σ₁₂] M₂) :=
{ uniq := λ f, to_linear_map_injective (subsingleton.elim _ _),
default := 0 }
omit σ₂₁
end subsingleton
section
variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄]
variables {module_M : module R M} {module_M₂ : module R₂ M₂}
variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R}
variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂}
variables (e e' : M ≃ₛₗ[σ₁₂] M₂)
lemma map_eq_comap {p : submodule R M} :
(p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂) = p.comap (e.symm : M₂ →ₛₗ[σ₂₁] M) :=
set_like.coe_injective $ by simp [e.image_eq_preimage]
/-- A linear equivalence of two modules restricts to a linear equivalence from any submodule
`p` of the domain onto the image of that submodule.
This is the linear version of `add_equiv.submonoid_map` and `add_equiv.subgroup_map`.
This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/
def submodule_map (p : submodule R M) :
p ≃ₛₗ[σ₁₂] ↥(p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂) :=
{ inv_fun := λ y, ⟨(e.symm : M₂ →ₛₗ[σ₂₁] M) y, by
{ rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy,
simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩,
left_inv := λ x, by simp,
right_inv := λ y, by { apply set_coe.ext, simp, },
..((e : M →ₛₗ[σ₁₂] M₂).dom_restrict p).cod_restrict (p.map (e : M →ₛₗ[σ₁₂] M₂))
(λ x, ⟨x, by simp⟩) }
include σ₂₁
@[simp] lemma submodule_map_apply (p : submodule R M) (x : p) :
↑(e.submodule_map p x) = e x := rfl
@[simp] lemma submodule_map_symm_apply (p : submodule R M)
(x : (p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂)) :
↑((e.submodule_map p).symm x) = e.symm x :=
rfl
omit σ₂₁
end
section finsupp
variables {γ : Type*}
variables [semiring R] [semiring R₂]
variables [add_comm_monoid M] [add_comm_monoid M₂]
variables [module R M] [module R₂ M₂] [has_zero γ]
variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R}
variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂]
include τ₂₁
@[simp] lemma map_finsupp_sum (f : M ≃ₛₗ[τ₁₂] M₂) {t : ι →₀ γ} {g : ι → γ → M} :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _
omit τ₂₁
end finsupp
section dfinsupp
open dfinsupp
variables [semiring R] [semiring R₂]
variables [add_comm_monoid M] [add_comm_monoid M₂]
variables [module R M] [module R₂ M₂]
variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R}
variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂]
variables {γ : ι → Type*} [decidable_eq ι]
include τ₂₁
@[simp] lemma map_dfinsupp_sum [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)]
(f : M ≃ₛₗ[τ₁₂] M₂) (t : Π₀ i, γ i) (g : Π i, γ i → M) :
f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _
@[simp] lemma map_dfinsupp_sum_add_hom [Π i, add_zero_class (γ i)] (f : M ≃ₛₗ[τ₁₂] M₂)
(t : Π₀ i, γ i) (g : Π i, γ i →+ M) :
f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_equiv.to_add_monoid_hom.comp (g i)) t :=
f.to_add_equiv.map_dfinsupp_sum_add_hom _ _
end dfinsupp
section uncurry
variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄]
variables (V V₂ R)
/-- Linear equivalence between a curried and uncurried function.
Differs from `tensor_product.curry`. -/
protected def curry :
(V × V₂ → R) ≃ₗ[R] (V → V₂ → R) :=
{ map_add' := λ _ _, by { ext, refl },
map_smul' := λ _ _, by { ext, refl },
.. equiv.curry _ _ _ }
@[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl
@[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl
end uncurry
section
variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄]
variables {module_M : module R M} {module_M₂ : module R₂ M₂} {module_M₃ : module R₃ M₃}
variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R}
variables {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃]
variables {σ₃₂ : R₃ →+* R₂}
variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂}
variables {re₂₃ : ring_hom_inv_pair σ₂₃ σ₃₂} {re₃₂ : ring_hom_inv_pair σ₃₂ σ₂₃}
variables (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₁] M) (e : M ≃ₛₗ[σ₁₂] M₂) (h : M₂ →ₛₗ[σ₂₃] M₃)
variables (e'' : M₂ ≃ₛₗ[σ₂₃] M₃)
variables (p q : submodule R M)
/-- Linear equivalence between two equal submodules. -/
def of_eq (h : p = q) : p ≃ₗ[R] q :=
{ map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) }
variables {p q}
@[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl
@[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl
include σ₂₁
/-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear
equivalence of the two submodules. -/
def of_submodules (p : submodule R M) (q : submodule R₂ M₂) (h : p.map (e : M →ₛₗ[σ₁₂] M₂) = q) :
p ≃ₛₗ[σ₁₂] q := (e.submodule_map p).trans (linear_equiv.of_eq _ _ h)
@[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R₂ M₂}
(h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl
@[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R₂ M₂}
(h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl
include re₁₂ re₂₁
/-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any
submodule to that submodule.
This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/
def of_submodule' [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) :
U.comap (f : M →ₛₗ[σ₁₂] M₂) ≃ₛₗ[σ₁₂] U :=
(f.symm.of_submodules _ _ f.symm.map_eq_comap).symm
lemma of_submodule'_to_linear_map [module R M] [module R₂ M₂]
(f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) :
(f.of_submodule' U).to_linear_map =
(f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop :=
by { ext, refl }
@[simp]
lemma of_submodule'_apply [module R M] [module R₂ M₂]
(f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) (x : U.comap (f : M →ₛₗ[σ₁₂] M₂)) :
(f.of_submodule' U x : M₂) = f (x : M) := rfl
@[simp]
lemma of_submodule'_symm_apply [module R M] [module R₂ M₂]
(f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) (x : U) :
((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl
variable (p)
omit σ₂₁ re₁₂ re₂₁
/-- The top submodule of `M` is linearly equivalent to `M`. -/
def of_top (h : p = ⊤) : p ≃ₗ[R] M :=
{ inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩,
left_inv := λ ⟨x, h⟩, rfl,
right_inv := λ x, rfl,
.. p.subtype }
@[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl
@[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl
theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl
include σ₂₁ re₁₂ re₂₁
/-- If a linear map has an inverse, it is a linear equivalence. -/
def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) :
M ≃ₛₗ[σ₁₂] M₂ :=
{ inv_fun := g,
left_inv := linear_map.ext_iff.1 h₂,
right_inv := linear_map.ext_iff.1 h₁,
..f }
omit σ₂₁ re₁₂ re₂₁
include σ₂₁ re₁₂ re₂₁
@[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl
omit σ₂₁ re₁₂ re₂₁
include σ₂₁ re₁₂ re₂₁
@[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x :=
rfl
omit σ₂₁ re₁₂ re₂₁
@[simp] protected theorem range : (e : M →ₛₗ[σ₁₂] M₂).range = ⊤ :=
linear_map.range_eq_top.2 e.to_equiv.surjective
include σ₂₁ re₁₂ re₂₁
lemma eq_bot_of_equiv [module R₂ M₂] (e : p ≃ₛₗ[σ₁₂] (⊥ : submodule R₂ M₂)) : p = ⊥ :=
begin
refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _),
rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff],
apply submodule.eq_zero_of_bot_submodule
end
omit σ₂₁ re₁₂ re₂₁
@[simp] protected theorem ker : (e : M →ₛₗ[σ₁₂] M₂).ker = ⊥ :=
linear_map.ker_eq_bot_of_injective e.to_equiv.injective
@[simp] theorem range_comp [ring_hom_surjective σ₁₂] [ring_hom_surjective σ₂₃]
[ring_hom_surjective σ₁₃] :
(h.comp (e : M →ₛₗ[σ₁₂] M₂) : M →ₛₗ[σ₁₃] M₃).range = h.range :=
linear_map.range_comp_of_range_eq_top _ e.range
include module_M
@[simp] theorem ker_comp (l : M →ₛₗ[σ₁₂] M₂) :
(((e'' : M₂ →ₛₗ[σ₂₃] M₃).comp l : M →ₛₗ[σ₁₃] M₃) : M →ₛₗ[σ₁₃] M₃).ker = l.ker :=
linear_map.ker_comp_of_ker_eq_bot _ e''.ker
omit module_M
variables {f g}
include σ₂₁
/-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear
equivalence between `M` and `f.range`.
This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of
`linear_map.range_restrict`. -/
def of_left_inverse [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
{g : M₂ → M} (h : function.left_inverse g f) : M ≃ₛₗ[σ₁₂] f.range :=
{ to_fun := f.range_restrict,
inv_fun := g ∘ f.range.subtype,
left_inv := h,
right_inv := λ x, subtype.ext $
let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in
show f (g x) = x, by rw [←hx', h x'],
.. f.range_restrict }
omit σ₂₁
@[simp] lemma of_left_inverse_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
(h : function.left_inverse g f) (x : M) :
↑(of_left_inverse h x) = f x := rfl
include σ₂₁
@[simp] lemma of_left_inverse_symm_apply [ring_hom_inv_pair σ₁₂ σ₂₁]
[ring_hom_inv_pair σ₂₁ σ₁₂] (h : function.left_inverse g f) (x : f.range) :
(of_left_inverse h).symm x = g x := rfl
omit σ₂₁
variables (f)
/-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence
between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/
noncomputable def of_injective [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
(h : injective f) : M ≃ₛₗ[σ₁₂] f.range :=
of_left_inverse $ classical.some_spec h.has_left_inverse
@[simp] theorem of_injective_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
{h : injective f} (x : M) : ↑(of_injective f h x) = f x := rfl
/-- A bijective linear map is a linear equivalence. -/
noncomputable def of_bijective [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
(hf₁ : injective f) (hf₂ : surjective f) : M ≃ₛₗ[σ₁₂] M₂ :=
(of_injective f hf₁).trans (of_top _ $ linear_map.range_eq_top.2 hf₂)
@[simp] theorem of_bijective_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂]
{hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl
end
end add_comm_monoid
section add_comm_group
variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄]
variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄]
variables {module_M : module R M} {module_M₂ : module R₂ M₂}
variables {module_M₃ : module R₃ M₃} {module_M₄ : module R₄ M₄}
variables {σ₁₂ : R →+* R₂} {σ₃₄ : R₃ →+* R₄}
variables {σ₂₁ : R₂ →+* R} {σ₄₃ : R₄ →+* R₃}
variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂}
variables {re₃₄ : ring_hom_inv_pair σ₃₄ σ₄₃} {re₄₃ : ring_hom_inv_pair σ₄₃ σ₃₄}
variables (e e₁ : M ≃ₛₗ[σ₁₂] M₂) (e₂ : M₃ ≃ₛₗ[σ₃₄] M₄)
@[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a
@[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b :=
e.to_linear_map.map_sub a b
end add_comm_group
section neg
variables (R) [semiring R] [add_comm_group M] [module R M]
/-- `x ↦ -x` as a `linear_equiv` -/
def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) }
variable {R}
@[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl
lemma neg_apply (x : M) : neg R x = -x := by simp
@[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl
end neg
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃]
variables [module R M] [module R M₂] [module R M₃]
open _root_.linear_map
/-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/
def smul_of_unit (a : Rˣ) : M ≃ₗ[R] M :=
of_linear ((a:R) • 1 : M →ₗ[R] M) (((a⁻¹ : Rˣ) : R) • 1 : M →ₗ[R] M)
(by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl)
(by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl)
/-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a
linear isomorphism between the two function spaces. -/
def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R]
[add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) :
(M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) :=
{ to_fun := λ f : M₁ →ₗ[R] M₂₁, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp (e₁.symm : M₂ →ₗ[R] M₁),
inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp (e₁ : M₁ →ₗ[R] M₂),
left_inv := λ f, by { ext x, simp only [symm_apply_apply, comp_app, coe_comp, coe_coe]},
right_inv := λ f, by { ext x, simp only [comp_app, apply_symm_apply, coe_comp, coe_coe]},
map_add' := λ f g, by { ext x, simp only [map_add, add_apply, comp_app, coe_comp, coe_coe]},
map_smul' := λ c f, by { ext x, simp only [smul_apply, comp_app, coe_comp, map_smulₛₗ, coe_coe]} }
@[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R]
[add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) :
arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) :=
rfl
@[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R]
[add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) :
(arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) :=
rfl
lemma arrow_congr_comp {N N₂ N₃ : Sort*}
[add_comm_monoid N] [add_comm_monoid N₂] [add_comm_monoid N₃]
[module R N] [module R N₂] [module R N₃]
(e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) :
arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) :=
by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], }
lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*}
[add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂]
[add_comm_monoid M₃] [module R M₃] [add_comm_monoid N₁] [module R N₁]
[add_comm_monoid N₂] [module R N₂] [add_comm_monoid N₃] [module R N₃]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) :
(arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) :=
rfl
/-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂`
and `M` into `M₃` are linearly isomorphic. -/
def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ[R] (M →ₗ[R] M₃) :=
arrow_congr (linear_equiv.refl R M) f
/-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to
themselves are linearly isomorphic. -/
def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e
lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) :
e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp (e.symm : M₂ →ₗ[R] M) := rfl
lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) :
e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp (e : M →ₗ[R] M₂) := rfl
lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) :
e.conj (g.comp f) = (e.conj g).comp (e.conj f) :=
arrow_congr_comp e e e f g
lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) :
e₁.conj.trans e₂.conj = (e₁.trans e₂).conj :=
by { ext f x, refl, }
@[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id :=
by { ext, simp [conj_apply], }
end comm_semiring
section field
variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module K M] [module K M₂] [module K M₃]
variables (K) (M)
open _root_.linear_map
/-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/
def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M :=
smul_of_unit $ units.mk0 a ha
section
noncomputable theory
open_locale classical
lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ :=
begin
ext c, split,
{ intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc',
have : x = 0,
calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul]
... = c⁻¹ • ((to_span_singleton K M x) c) : rfl
... = 0 : by rw [hc, smul_zero],
tauto },
{ rw [mem_ker, submodule.mem_bot], intros h, rw h, simp }
end
/-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural
map from `K` to the span of `x`, with invertibility check to consider it as an
isomorphism.-/
def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) :=
linear_equiv.trans
(linear_equiv.of_injective (to_span_singleton K M x) (ker_eq_bot.1 $ ker_to_span_singleton K M h))
(of_eq (to_span_singleton K M x).range (K ∙ x)
(span_singleton_eq_range K M x).symm)
lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1
= (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) :=
begin
apply set_like.coe_eq_coe.mp,
have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl,
rw [this, to_span_singleton_one, submodule.coe_mk],
end
/-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map
from the span of `x` to `K`.-/
abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K :=
(to_span_nonzero_singleton K M x h).symm
lemma coord_self (x : M) (h : x ≠ 0) :
(coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 :=
by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply]
end
end field
end linear_equiv
namespace submodule
section module
variables [semiring R] [add_comm_monoid M] [module R M]
/-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q`
is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/
def equiv_subtype_map (p : submodule R M) (q : submodule R p) :
q ≃ₗ[R] q.map p.subtype :=
{ inv_fun :=
begin
rintro ⟨x, hx⟩,
refine ⟨⟨x, _⟩, _⟩;
rcases hx with ⟨⟨_, h⟩, _, rfl⟩;
assumption
end,
left_inv := λ ⟨⟨_, _⟩, _⟩, rfl,
right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl,
.. (p.subtype.dom_restrict q).cod_restrict _
begin
rintro ⟨x, hx⟩,
refine ⟨x, hx, rfl⟩,
end }
@[simp]
lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) :
(p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x :=
rfl
@[simp]
lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) :
((p.equiv_subtype_map q).symm x : M) = x :=
by { cases x, refl }
/-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap
of `t.subtype`. -/
@[simps]
def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) :
comap q.subtype p ≃ₗ[R] p :=
{ to_fun := λ x, ⟨x, x.2⟩,
inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩,
left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe],
right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe],
map_add' := λ x y, rfl,
map_smul' := λ c x, rfl }
end module
end submodule
namespace submodule
variables [comm_semiring R] [comm_semiring R₂]
variables [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R₂ M₂]
variables [add_comm_monoid N] [add_comm_monoid N₂] [module R N] [module R N₂]
variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R}
variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂]
variables (p : submodule R M) (q : submodule R₂ M₂)
variables (pₗ : submodule R N) (qₗ : submodule R N₂)
include τ₂₁
@[simp] lemma mem_map_equiv {e : M ≃ₛₗ[τ₁₂] M₂} {x : M₂} : x ∈ p.map (e : M →ₛₗ[τ₁₂] M₂) ↔
e.symm x ∈ p :=
begin
rw submodule.mem_map, split,
{ rintros ⟨y, hy, hx⟩, simp [←hx, hy], },
{ intros hx, refine ⟨e.symm x, hx, by simp⟩, },
end
omit τ₂₁
lemma map_equiv_eq_comap_symm (e : M ≃ₛₗ[τ₁₂] M₂) (K : submodule R M) :
K.map (e : M →ₛₗ[τ₁₂] M₂) = K.comap (e.symm : M₂ →ₛₗ[τ₂₁] M) :=
submodule.ext (λ _, by rw [mem_map_equiv, mem_comap, linear_equiv.coe_coe])
lemma comap_equiv_eq_map_symm (e : M ≃ₛₗ[τ₁₂] M₂) (K : submodule R₂ M₂) :
K.comap (e : M →ₛₗ[τ₁₂] M₂) = K.map (e.symm : M₂ →ₛₗ[τ₂₁] M) :=
(map_equiv_eq_comap_symm e.symm K).symm
lemma comap_le_comap_smul (fₗ : N →ₗ[R] N₂) (c : R) :
comap fₗ qₗ ≤ comap (c • fₗ) qₗ :=
begin
rw set_like.le_def,
intros m h,
change c • (fₗ m) ∈ qₗ,
change fₗ m ∈ qₗ at h,
apply qₗ.smul_mem _ h,
end
lemma inf_comap_le_comap_add (f₁ f₂ : M →ₛₗ[τ₁₂] M₂) :
comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q :=
begin
rw set_like.le_def,
intros m h,
change f₁ m + f₂ m ∈ q,
change f₁ m ∈ q ∧ f₂ m ∈ q at h,
apply q.add_mem h.1 h.2,
end
/-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`,
the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/
def compatible_maps : submodule R (N →ₗ[R] N₂) :=
{ carrier := {fₗ | pₗ ≤ comap fₗ qₗ},
zero_mem' := by { change pₗ ≤ comap 0 qₗ, rw comap_zero, refine le_top, },
add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add qₗ f₁ f₂),
rw le_inf_iff, exact ⟨h₁, h₂⟩, },
smul_mem' := λ c fₗ h, le_trans h (comap_le_comap_smul qₗ fₗ c), }
end submodule
namespace equiv
variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂]
/-- An equivalence whose underlying function is linear is a linear equivalence. -/
def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ :=
{ .. e, .. h.mk' e}
end equiv
section fun_left
variables (R M) [semiring R] [add_comm_monoid M] [module R M]
variables {m n p : Type*}
namespace linear_map
/-- Given an `R`-module `M` and a function `m → n` between arbitrary types,
construct a linear map `(n → M) →ₗ[R] (m → M)` -/
def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) :=
{ to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl }
@[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) :=
rfl
@[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g :=
rfl
theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) :
fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) :=
rfl
theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) :
surjective (fun_left R M f) :=
begin
classical,
intro g,
refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩,
{ ext,
dsimp only [fun_left_apply],
split_ifs with w,
{ congr,
exact hf w.some_spec, },
{ simpa only [not_true, exists_apply_eq_apply] using w } },
end
theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) :
injective (fun_left R M f) :=
begin
obtain ⟨g, hg⟩ := hf.has_right_inverse,
suffices : left_inverse (fun_left R M g) (fun_left R M f),
{ exact this.injective },
intro x,
rw [←linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id],
end
end linear_map
namespace linear_equiv
open _root_.linear_map
/-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types,
construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/
def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) :=
linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm)
(linear_map.ext $ λ x, funext $ λ i,
by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id])
(linear_map.ext $ λ x, funext $ λ i,
by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id])
@[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) :
fun_congr_left R M e x = fun_left R M e x :=
rfl
@[simp] theorem fun_congr_left_id :
fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) :=
rfl
@[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) :
fun_congr_left R M (equiv.trans e₁ e₂) =
linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) :=
rfl
@[simp] lemma fun_congr_left_symm (e : m ≃ n) :
(fun_congr_left R M e).symm = fun_congr_left R M e.symm :=
rfl
end linear_equiv
end fun_left
namespace linear_map
variables [semiring R] [add_comm_monoid M] [module R M]
variables (R M)
/-- The group of invertible linear maps from `M` to itself -/
@[reducible] def general_linear_group := (M →ₗ[R] M)ˣ
namespace general_linear_group
variables {R M}
instance : has_coe_to_fun (general_linear_group R M) (λ _, M → M) := by apply_instance
/-- An invertible linear map `f` determines an equivalence from `M` to itself. -/
def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) :=
{ inv_fun := f.inv.to_fun,
left_inv := λ m, show (f.inv * f.val) m = m,
by erw f.inv_val; simp,
right_inv := λ m, show (f.val * f.inv) m = m,
by erw f.val_inv; simp,
..f.val }
/-- An equivalence from `M` to itself determines an invertible linear map. -/
def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M :=
{ val := f,
inv := (f.symm : M →ₗ[R] M),
val_inv := linear_map.ext $ λ _, f.apply_symm_apply _,
inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ }
variables (R M)
/-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear
equivalences between `M` and itself. -/
def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) :=
{ to_fun := to_linear_equiv,
inv_fun := of_linear_equiv,
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl },
map_mul' := λ x y, by {ext, refl} }
@[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) :
(general_linear_equiv R M f : M →ₗ[R] M) = f :=
by {ext, refl}
@[simp] lemma coe_fn_general_linear_equiv (f : general_linear_group R M) :
⇑(general_linear_equiv R M f) = (f : M → M) :=
rfl
end general_linear_group
end linear_map
namespace submodule
variables [ring R] [add_comm_group M] [module R M]
instance : is_modular_lattice (submodule R M) :=
⟨λ x y z xz a ha, begin
rw [mem_inf, mem_sup] at ha,
rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩,
rw mem_sup,
refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩,
rw [← add_sub_cancel c b, add_comm],
apply z.sub_mem haz (xz hb),
end⟩
end submodule
|
75744e2d3fce67e1cb0c14e90c40a4e0d5c74b03 | 35b83be3126daae10419b573c55e1fed009d3ae8 | /_target/deps/mathlib/analysis/normed_space.lean | bc576393f93e7e1942d297a1a56218fefeb22e8e | [] | no_license | AHassan1024/Lean_Playground | ccb25b72029d199c0d23d002db2d32a9f2689ebc | a00b004c3a2eb9e3e863c361aa2b115260472414 | refs/heads/master | 1,586,221,905,125 | 1,544,951,310,000 | 1,544,951,310,000 | 157,934,290 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,275 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Normed spaces.
Authors: Patrick Massot, Johannes Hölzl
-/
import algebra.pi_instances
import linear_algebra.prod_module
import analysis.nnreal
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter
local notation f `→_{`:50 a `}`:0 b := tendsto f (nhds a) (nhds b)
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) :=
begin
apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0;
simp [*]; exact filter.univ_mem_sets
end
class has_norm (α : Type*) := (norm : α → ℝ)
export has_norm (norm)
notation `∥`:1024 e:1 `∥`:1 := norm e
class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
section normed_group
variables [normed_group α] [normed_group β]
lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ :=
normed_group.dist_eq _ _
@[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ :=
by { rw[dist_eq_norm], simp }
lemma norm_triangle (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ :=
calc ∥g + h∥ = ∥g - (-h)∥ : by simp
... = dist g (-h) : by simp[dist_eq_norm]
... ≤ dist g 0 + dist 0 (-h) : by apply dist_triangle
... = ∥g∥ + ∥h∥ : by simp[dist_eq_norm]
@[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ :=
by { rw[←dist_zero_right], exact dist_nonneg }
lemma norm_eq_zero (g : α) : ∥g∥ = 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_eq_zero }
@[simp] lemma norm_zero : ∥(0:α)∥ = 0 := (norm_eq_zero _).2 (by simp)
lemma norm_pos_iff (g : α) : ∥ g ∥ > 0 ↔ g ≠ 0 :=
begin
split ; intro h ; rw[←dist_zero_right] at *,
{ exact dist_pos.1 h },
{ exact dist_pos.2 h }
end
lemma norm_le_zero_iff (g : α) : ∥g∥ ≤ 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_le_zero }
@[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ :=
calc ∥-g∥ = ∥0 - g∥ : by simp
... = dist 0 g : (dist_eq_norm 0 g).symm
... = dist g 0 : dist_comm _ _
... = ∥g - 0∥ : (dist_eq_norm g 0)
... = ∥g∥ : by simp
lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ :=
abs_le.2 $ and.intro
(suffices -∥g - h∥ ≤ -(∥h∥ - ∥g∥), by simpa,
neg_le_neg $ sub_right_le_of_le_add $
calc ∥h∥ = ∥h - g + g∥ : by simp
... ≤ ∥h - g∥ + ∥g∥ : norm_triangle _ _
... = ∥-(g - h)∥ + ∥g∥ : by simp
... = ∥g - h∥ + ∥g∥ : by { rw [norm_neg (g-h)] })
(sub_right_le_of_le_add $ calc ∥g∥ = ∥g - h + h∥ : by simp ... ≤ ∥g-h∥ + ∥h∥ : norm_triangle _ _)
lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ :=
abs_norm_sub_norm_le g h
lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ :=
by rw ←norm_neg; simp
section nnnorm
def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩
@[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl
lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _
lemma nnnorm_eq_zero (a : α) : nnnorm a = 0 ↔ a = 0 :=
by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero]
@[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 :=
nnreal.eq norm_zero
lemma nnnorm_triangle (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h :=
by simpa [nnreal.coe_le] using norm_triangle g h
@[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g :=
nnreal.eq $ norm_neg g
lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) :=
(nnreal.coe_le _ _).2 $ dist_norm_norm_le g h
end nnnorm
instance prod.normed_group [normed_group β] : normed_group (α × β) :=
{ norm := λx, max ∥x.1∥ ∥x.2∥,
dist_eq := assume (x y : α × β),
show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] }
lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ :=
begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_left] end
lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ :=
begin have : ∥x∥ = max (∥x.fst∥) (∥x.snd∥) := rfl, rw this, simp[le_max_right] end
instance fintype.normed_group {π : α → Type*} [fintype α] [∀i, normed_group (π i)] :
normed_group (Πb, π b) :=
{ norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ),
dist_eq := assume x y,
congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a,
show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ }
lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} :
tendsto f a (nhds b) ↔ tendsto (λ e, ∥ f e - b ∥) a (nhds 0) :=
by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm]
lemma lim_norm (x : α) : ((λ g, ∥g - x∥) : α → ℝ) →_{x} 0 :=
tendsto_iff_norm_tendsto_zero.1 (continuous_iff_tendsto.1 continuous_id x)
lemma lim_norm_zero : ((λ g, ∥g∥) : α → ℝ) →_{0} 0 :=
by simpa using lim_norm (0:α)
lemma continuous_norm : continuous ((λ g, ∥g∥) : α → ℝ) :=
begin
rw continuous_iff_tendsto,
intro x,
rw tendsto_iff_dist_tendsto_zero,
exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x)
end
instance normed_top_monoid : topological_add_monoid α :=
⟨continuous_iff_tendsto.2 $ λ ⟨x₁, x₂⟩,
tendsto_iff_norm_tendsto_zero.2
begin
refine squeeze_zero (by simp) _
(by simpa using tendsto_add (lim_norm (x₁, x₂)) (lim_norm (x₁, x₂))),
exact λ ⟨e₁, e₂⟩, calc
∥(e₁ + e₂) - (x₁ + x₂)∥ = ∥(e₁ - x₁) + (e₂ - x₂)∥ : by simp
... ≤ ∥e₁ - x₁∥ + ∥e₂ - x₂∥ : norm_triangle _ _
... ≤ max (∥e₁ - x₁∥) (∥e₂ - x₂∥) + max (∥e₁ - x₁∥) (∥e₂ - x₂∥) :
add_le_add (le_max_left _ _) (le_max_right _ _)
end⟩
instance normed_top_group : topological_add_group α :=
⟨continuous_iff_tendsto.2 $ λ x,
tendsto_iff_norm_tendsto_zero.2 begin
have : ∀ (e : α), ∥-e - -x∥ = ∥e - x∥,
{ intro, simpa using norm_neg (e - x) },
rw funext this, exact lim_norm x,
end⟩
end normed_group
section normed_ring
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β }
lemma norm_mul {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
normed_ring.norm_mul _ _
lemma norm_pow {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, n > 0 → ∥a^n∥ ≤ ∥a∥^n
| 1 h := by simp
| (n+2) h :=
le_trans (norm_mul a (a^(n+1)))
(mul_le_mul (le_refl _)
(norm_pow (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _))
instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) :=
{ norm_mul := assume x y,
calc
∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl
... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl
... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul (x.1) (y.1)) (norm_mul (x.2) (y.2))
... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm]
... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] }
... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm]
... = (∥x∥*∥y∥) : rfl,
..prod.normed_group }
end normed_ring
instance normed_ring_top_monoid [normed_ring α] : topological_monoid α :=
⟨ continuous_iff_tendsto.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd =
e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel,
begin
apply squeeze_zero,
{ intro, apply norm_nonneg },
{ simp only [this], intro, apply norm_triangle },
{ rw ←zero_add (0 : ℝ), apply tendsto_add,
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥,
rw ←mul_sub, apply norm_mul },
{ rw ←mul_zero (∥x.fst∥), apply tendsto_mul,
{ apply continuous_iff_tendsto.1,
apply continuous.comp,
{ apply continuous_fst },
{ apply continuous_norm }},
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_tendsto.1,
apply continuous_snd }}},
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥,
rw ←sub_mul, apply norm_mul },
{ rw ←zero_mul (∥x.snd∥), apply tendsto_mul,
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_tendsto.1,
apply continuous_fst },
{ apply tendsto_const_nhds }}}}
end ⟩
instance normed_top_ring [normed_ring α] : topological_ring α :=
⟨ continuous_iff_tendsto.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α, -e - -x = -(e - x), by intro; simp,
by simp only [this, norm_neg]; apply lim_norm ⟩
section normed_field
class normed_field (α : Type*) extends has_norm α, discrete_field α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) = norm a * norm b)
instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α :=
{ norm_mul := by finish [i.norm_mul], ..i }
@[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 :=
have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc
∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul
... = ∥(1 : α)∥ * 1 : by simp,
eq_of_mul_eq_mul_left (ne_of_gt ((norm_pos_iff _).2 (by simp))) this
@[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ :=
if hb : b = 0 then by simp [hb] else
begin
apply eq_div_of_mul_eq,
{ apply ne_of_gt, apply (norm_pos_iff _).mpr hb },
{ rw [←normed_field.norm_mul, div_mul_cancel _ hb] }
end
@[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ :=
by simp only [inv_eq_one_div, norm_div, norm_one]
@[simp] lemma normed_field.norm_pow {α : Type*} [normed_field α] (a : α) :
∀ n : ℕ, ∥a^n∥ = ∥a∥^n
| 0 := by simp
| (k+1) := calc
∥a ^ (k + 1)∥ = ∥a*(a^k)∥ : rfl
... = ∥a∥*∥a^k∥ : by rw normed_field.norm_mul
... = ∥a∥ ^ (k + 1) : by rw normed_field.norm_pow; simp [pow, monoid.pow]
instance : normed_field ℝ :=
{ norm := λ x, abs x,
dist_eq := assume x y, rfl,
norm_mul := abs_mul }
lemma real.norm_eq_abs (r : ℝ): norm r = abs r := rfl
end normed_field
section normed_space
class normed_space (α : out_param $ Type*) (β : Type*) [out_param $ normed_field α]
extends has_norm β , vector_space α β, metric_space β :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_smul : ∀ a b, norm (a • b) = has_norm.norm a * norm b)
variables [normed_field α]
instance normed_space.to_normed_group [i : normed_space α β] : normed_group β :=
by refine { add := (+),
dist_eq := normed_space.dist_eq,
zero := 0,
neg := λ x, -x,
..i, .. }; simp
instance normed_field.to_normed_space : normed_space α α :=
{ dist_eq := normed_field.dist_eq,
norm_smul := normed_field.norm_mul }
lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ :=
normed_space.norm_smul _ _
lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x :=
nnreal.eq $ norm_smul s x
variables {E : Type*} {F : Type*} [normed_space α E] [normed_space α F]
lemma tendsto_smul {f : γ → α} { g : γ → F} {e : filter γ} {s : α} {b : F} :
(tendsto f e (nhds s)) → (tendsto g e (nhds b)) → tendsto (λ x, (f x) • (g x)) e (nhds (s • b)) :=
begin
intros limf limg,
rw tendsto_iff_norm_tendsto_zero,
have ineq := λ x : γ, calc
∥f x • g x - s • b∥ = ∥(f x • g x - s • g x) + (s • g x - s • b)∥ : by simp[add_assoc]
... ≤ ∥f x • g x - s • g x∥ + ∥s • g x - s • b∥ : norm_triangle (f x • g x - s • g x) (s • g x - s • b)
... ≤ ∥f x - s∥*∥g x∥ + ∥s∥*∥g x - b∥ : by { rw [←smul_sub, ←sub_smul, norm_smul, norm_smul] },
apply squeeze_zero,
{ intro t, exact norm_nonneg _ },
{ exact ineq },
{ clear ineq,
have limf': tendsto (λ x, ∥f x - s∥) e (nhds 0) := tendsto_iff_norm_tendsto_zero.1 limf,
have limg' : tendsto (λ x, ∥g x∥) e (nhds ∥b∥) := filter.tendsto.comp limg (continuous_iff_tendsto.1 continuous_norm _),
have lim1 : tendsto (λ x, ∥f x - s∥ * ∥g x∥) e (nhds 0),
by simpa using tendsto_mul limf' limg',
have limg3 := tendsto_iff_norm_tendsto_zero.1 limg,
have lim2 : tendsto (λ x, ∥s∥ * ∥g x - b∥) e (nhds 0),
by simpa using tendsto_mul tendsto_const_nhds limg3,
rw [show (0:ℝ) = 0 + 0, by simp],
exact tendsto_add lim1 lim2 }
end
instance : normed_space α (E × F) :=
{ norm_smul :=
begin
intros s x,
cases x with x₁ x₂,
exact calc
∥s • (x₁, x₂)∥ = ∥ (s • x₁, s• x₂)∥ : rfl
... = max (∥s • x₁∥) (∥ s• x₂∥) : rfl
... = max (∥s∥ * ∥x₁∥) (∥s∥ * ∥x₂∥) : by simp [norm_smul s x₁, norm_smul s x₂]
... = ∥s∥ * max (∥x₁∥) (∥x₂∥) : by simp [mul_max_of_nonneg]
end,
add_smul := by simp[add_smul],
-- I have no idea why by simp[smul_add] is not enough for the next goal
smul_add := assume r x y, show (r•(x+y).fst, r•(x+y).snd) = (r•x.fst+r•y.fst, r•x.snd+r•y.snd),
by simp[smul_add],
..prod.normed_group,
..prod.vector_space }
instance fintype.normed_space {ι : Type*} {E : ι → Type*} [fintype ι] [∀i, normed_space α (E i)] :
normed_space α (Πi, E i) :=
{ norm := λf, ((finset.univ.sup (λb, nnnorm (f b)) : nnreal) : ℝ),
dist_eq :=
assume f g, congr_arg coe $ congr_arg (finset.sup finset.univ) $
by funext i; exact nndist_eq_nnnorm _ _,
norm_smul := λ a f,
show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) =
nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))),
by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul],
..metric_space_pi,
..pi.vector_space α }
end normed_space
|
e6a11f92e58efee0c276f3947818e16623609195 | 3f7026ea8bef0825ca0339a275c03b911baef64d | /src/data/bool.lean | 49617cc12a3c5b7ff3487a215e10607a735306c2 | [
"Apache-2.0"
] | permissive | rspencer01/mathlib | b1e3afa5c121362ef0881012cc116513ab09f18c | c7d36292c6b9234dc40143c16288932ae38fdc12 | refs/heads/master | 1,595,010,346,708 | 1,567,511,503,000 | 1,567,511,503,000 | 206,071,681 | 0 | 0 | Apache-2.0 | 1,567,513,643,000 | 1,567,513,643,000 | null | UTF-8 | Lean | false | false | 4,374 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad
-/
namespace bool
@[simp] theorem coe_sort_tt : coe_sort.{1 1} tt = true := eq_true_intro rfl
@[simp] theorem coe_sort_ff : coe_sort.{1 1} ff = false := eq_false_intro ff_ne_tt
@[simp] theorem to_bool_true {h} : @to_bool true h = tt :=
show _ = to_bool true, by congr
@[simp] theorem to_bool_false {h} : @to_bool false h = ff :=
show _ = to_bool false, by congr
@[simp] theorem to_bool_coe (b:bool) {h} : @to_bool b h = b :=
(show _ = to_bool b, by congr).trans (by cases b; refl)
@[simp] theorem coe_to_bool (p : Prop) [decidable p] : to_bool p ↔ p := to_bool_iff _
@[simp] lemma of_to_bool_iff {p : Prop} [decidable p] : to_bool p ↔ p :=
⟨of_to_bool_true, _root_.to_bool_true⟩
@[simp] lemma tt_eq_to_bool_iff {p : Prop} [decidable p] : tt = to_bool p ↔ p :=
eq_comm.trans of_to_bool_iff
@[simp] lemma ff_eq_to_bool_iff {p : Prop} [decidable p] : ff = to_bool p ↔ ¬ p :=
eq_comm.trans (to_bool_ff_iff _)
@[simp] theorem to_bool_not (p : Prop) [decidable p] : to_bool (¬ p) = bnot (to_bool p) :=
by by_cases p; simp *
@[simp] theorem to_bool_and (p q : Prop) [decidable p] [decidable q] :
to_bool (p ∧ q) = p && q :=
by by_cases p; by_cases q; simp *
@[simp] theorem to_bool_or (p q : Prop) [decidable p] [decidable q] :
to_bool (p ∨ q) = p || q :=
by by_cases p; by_cases q; simp *
@[simp] theorem to_bool_eq {p q : Prop} [decidable p] [decidable q] :
to_bool p = to_bool q ↔ (p ↔ q) :=
⟨λ h, (coe_to_bool p).symm.trans $ by simp [h], to_bool_congr⟩
lemma not_ff : ¬ ff := by simp
@[simp] theorem default_bool : default bool = ff := rfl
theorem dichotomy (b : bool) : b = ff ∨ b = tt :=
by cases b; simp
theorem forall_bool {p : bool → Prop} : (∀ b, p b) ↔ p ff ∧ p tt :=
⟨λ h, by simp [h], λ ⟨h₁, h₂⟩ b, by cases b; assumption⟩
theorem exists_bool {p : bool → Prop} : (∃ b, p b) ↔ p ff ∨ p tt :=
⟨λ ⟨b, h⟩, by cases b; [exact or.inl h, exact or.inr h],
λ h, by cases h; exact ⟨_, h⟩⟩
instance decidable_forall_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∀ b, p b) :=
decidable_of_decidable_of_iff and.decidable forall_bool.symm
instance decidable_exists_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∃ b, p b) :=
decidable_of_decidable_of_iff or.decidable exists_bool.symm
@[simp] theorem cond_ff {α} (t e : α) : cond ff t e = e := rfl
@[simp] theorem cond_tt {α} (t e : α) : cond tt t e = t := rfl
@[simp] theorem cond_to_bool {α} (p : Prop) [decidable p] (t e : α) :
cond (to_bool p) t e = if p then t else e :=
by by_cases p; simp *
theorem eq_tt_of_ne_ff : ∀ {a : bool}, a ≠ ff → a = tt := dec_trivial
theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff := dec_trivial
@[simp] theorem bor_comm : ∀ a b, a || b = b || a := dec_trivial
@[simp] theorem bor_assoc : ∀ a b c, (a || b) || c = a || (b || c) := dec_trivial
@[simp] theorem bor_left_comm : ∀ a b c, a || (b || c) = b || (a || c) := dec_trivial
theorem bor_inl {a b : bool} (H : a) : a || b :=
by simp [H]
theorem bor_inr {a b : bool} (H : b) : a || b :=
by simp [H]
@[simp] theorem band_comm : ∀ a b, a && b = b && a := dec_trivial
@[simp] theorem band_assoc : ∀ a b c, (a && b) && c = a && (b && c) := dec_trivial
@[simp] theorem band_left_comm : ∀ a b c, a && (b && c) = b && (a && c) := dec_trivial
theorem band_elim_left : ∀ {a b : bool}, a && b → a := dec_trivial
theorem band_intro : ∀ {a b : bool}, a → b → a && b := dec_trivial
theorem band_elim_right : ∀ {a b : bool}, a && b → b := dec_trivial
@[simp] theorem bnot_false : bnot ff = tt := rfl
@[simp] theorem bnot_true : bnot tt = ff := rfl
theorem eq_tt_of_bnot_eq_ff : ∀ {a : bool}, bnot a = ff → a = tt := dec_trivial
theorem eq_ff_of_bnot_eq_tt : ∀ {a : bool}, bnot a = tt → a = ff := dec_trivial
@[simp] theorem bxor_comm : ∀ a b, bxor a b = bxor b a := dec_trivial
@[simp] theorem bxor_assoc : ∀ a b c, bxor (bxor a b) c = bxor a (bxor b c) := dec_trivial
@[simp] theorem bxor_left_comm : ∀ a b c, bxor a (bxor b c) = bxor b (bxor a c) := dec_trivial
lemma bxor_iff_ne : ∀ {x y : bool}, bxor x y = tt ↔ x ≠ y := dec_trivial
end bool
|
92ddbef04b22e13667a6a1b943e3b443c51a6408 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /archive/imo/imo2001_q2.lean | 346adc3db71fd6c542d8071889e157b8b88e2f5a | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,834 | lean | /-
Copyright (c) 2021 Tian Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tian Chen
-/
import analysis.special_functions.pow.real
/-!
# IMO 2001 Q2
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Let $a$, $b$, $c$ be positive reals. Prove that
$$
\frac{a}{\sqrt{a^2 + 8bc}} +
\frac{b}{\sqrt{b^2 + 8ca}} +
\frac{c}{\sqrt{c^2 + 8ab}} ≥ 1.
$$
## Solution
This proof is based on the bound
$$
\frac{a}{\sqrt{a^2 + 8bc}} ≥
\frac{a^{\frac43}}{a^{\frac43} + b^{\frac43} + c^{\frac43}}.
$$
-/
open real
variables {a b c : ℝ}
namespace imo2001_q2
lemma denom_pos (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) :
0 < a ^ 4 + b ^ 4 + c ^ 4 :=
add_pos (add_pos (pow_pos ha 4) (pow_pos hb 4)) (pow_pos hc 4)
lemma bound (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) :
a ^ 4 / (a ^ 4 + b ^ 4 + c ^ 4) ≤
a ^ 3 / sqrt ((a ^ 3) ^ 2 + 8 * b ^ 3 * c ^ 3) :=
begin
have hsqrt := add_pos_of_nonneg_of_pos (sq_nonneg (a ^ 3))
(mul_pos (mul_pos (bit0_pos zero_lt_four) (pow_pos hb 3)) (pow_pos hc 3)),
have hdenom := denom_pos ha hb hc,
rw div_le_div_iff hdenom (sqrt_pos.mpr hsqrt),
conv_lhs { rw [pow_succ', mul_assoc] },
apply mul_le_mul_of_nonneg_left _ (pow_pos ha 3).le,
apply le_of_pow_le_pow _ hdenom.le zero_lt_two,
rw [mul_pow, sq_sqrt hsqrt.le, ← sub_nonneg],
calc (a ^ 4 + b ^ 4 + c ^ 4) ^ 2 - a ^ 2 * ((a ^ 3) ^ 2 + 8 * b ^ 3 * c ^ 3)
= 2 * (a ^ 2 * (b ^ 2 - c ^ 2)) ^ 2 + (b ^ 4 - c ^ 4) ^ 2 +
(2 * (a ^ 2 * b * c - b ^ 2 * c ^ 2)) ^ 2 : by ring
... ≥ 0 : add_nonneg (add_nonneg (mul_nonneg zero_le_two (sq_nonneg _))
(sq_nonneg _)) (sq_nonneg _)
end
theorem imo2001_q2' (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) :
1 ≤ a ^ 3 / sqrt ((a ^ 3) ^ 2 + 8 * b ^ 3 * c ^ 3) +
b ^ 3 / sqrt ((b ^ 3) ^ 2 + 8 * c ^ 3 * a ^ 3) +
c ^ 3 / sqrt ((c ^ 3) ^ 2 + 8 * a ^ 3 * b ^ 3) :=
have h₁ : b ^ 4 + c ^ 4 + a ^ 4 = a ^ 4 + b ^ 4 + c ^ 4,
by rw [add_comm, ← add_assoc],
have h₂ : c ^ 4 + a ^ 4 + b ^ 4 = a ^ 4 + b ^ 4 + c ^ 4,
by rw [add_assoc, add_comm],
calc _ ≥ _ : add_le_add (add_le_add (bound ha hb hc) (bound hb hc ha)) (bound hc ha hb)
... = 1 : by rw [h₁, h₂, ← add_div, ← add_div, div_self $ ne_of_gt $ denom_pos ha hb hc]
end imo2001_q2
open imo2001_q2
theorem imo2001_q2 (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) :
1 ≤ a / sqrt (a ^ 2 + 8 * b * c) +
b / sqrt (b ^ 2 + 8 * c * a) +
c / sqrt (c ^ 2 + 8 * a * b) :=
have h3 : ∀ {x : ℝ}, 0 < x → (x ^ (3 : ℝ)⁻¹) ^ 3 = x :=
λ x hx, show ↑3 = (3 : ℝ), by norm_num ▸ rpow_nat_inv_pow_nat hx.le three_ne_zero,
calc 1 ≤ _ : imo2001_q2' (rpow_pos_of_pos ha _) (rpow_pos_of_pos hb _) (rpow_pos_of_pos hc _)
... = _ : by rw [h3 ha, h3 hb, h3 hc]
|
788db02e025a9bb087ca8dc60992a30bbee87508 | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/solutions/monday/metaprogramming.lean | 7728935945d72d2b366a14677377a43d57723d5b | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 6,044 | lean | import tactic
open tactic
/-!
This file contains three tactic-programming exercises of increasing difficulty.
They were (hastily) written to follow the metaprogramming tutorial at
Lean for the Curious Mathematician 2020.
If you're looking for more (better) exercises, we strongly recommend the
exercises by Blanchette et al
for the course Logical Verification at the Vrije Universiteit Amsterdam,
and the corresponding chapter of the course notes:
https://github.com/blanchette/logical_verification_2020/blob/master/lean/love07_metaprogramming_exercise_sheet.lean
https://github.com/blanchette/logical_verification_2020/raw/master/hitchhikers_guide.pdf
## Exercise 1
Write a `contradiction` tactic.
The tactic should look through the hypotheses in the local context
trying to find two that contradict each other,
i.e. proving `P` and `¬ P` for some proposition `P`.
It should use this contradiction to close the goal.
Bonus: handle `P → false` as well as `¬ P`.
This exercise is to practice manipulating the hypotheses and goal.
Note: this exists as `tactic.interactive.contradiction`.
-/
/-
This solution is a "slick version."
We write a function `find_absurd_proof` that takes an expr e and a list of exprs.
For each expr h in the list,
it tries to apply e to h. If `e : ¬ P` and `h : P`, this will succeed
and result in a proof of `false`. Otherwise it will fail.
`find_absurd_proof` finds the first `h` such that it succeeds, and uses the proof of `false`
to close the goal.
If no such `h` exists, `find_absurd_proof` will fail.
-/
meta def find_absurd_proof (e : expr) (ctx : list expr) : tactic unit :=
do prf ← ctx.mfirst (λ h, to_expr ``(%%e %%h)),
exact prf
/-
`contr` maps over the local context `ctx`.
For every `e` in `ctx`, it calls `find_absurd_proof e ctx`.
Notice the double loop through `ctx`:
for each `e` in `ctx`, we search through all of `ctx` again!
`contr` calls the `exfalso` tactic before it begins,
to make sure the target is `false`.
-/
meta def tactic.interactive.contr : tactic unit :=
do exfalso,
ctx ← local_context,
ctx.mfirst (λ e, find_absurd_proof e ctx)
example (P Q R : Prop) (hp : P) (hq : Q) (hr : ¬ R) (hnq : ¬ Q) : false :=
by contr
example (P Q R : Prop) (hnq : ¬ Q) (hp : P) (hq : Q) (hr : ¬ R) : 0 = 1 :=
by contr
example (P Q R : Prop) (hp : P) (hq : Q) (hr : ¬ R) (hnq : Q → false) : false :=
by contr
/-!
## Exercise 2
Write a tactic that proves a given `nat`-valued declaration is nonnegative.
The tactic should take the name of a declaration whose return type is `ℕ`
(presumably with some arguments), e.g. `nat.add : ℕ → ℕ → ℕ`
or `list.length : Π α : Type, list α → ℕ`.
It should add a new declaration to the environment which proves all applications
of this function are nonnegative,
e.g. `nat.add_nonneg : ∀ m n : ℕ, 0 ≤ nat.add m n`.
Bonus: create reasonable names for these declarations, and/or take an optional argument
for the new name.
This tactic is not useful by itself, but it's a good way to practice
querying and modifying an environment and working under binders.
It is not a tactic to be used during a proof, but rather as a command.
Hints:
* For looking at declarations in the environment, you will need the `declaration` type,
as well as the tactics `get_decl` and `add_decl`.
* You will have to manipulate an expression under binders.
The tactics `mk_local_pis` and `pis`, or their lambda equivalents, will be helpful here.
* `mk_mapp` is a variant of `mk_app` that lets you provide implicit arguments.
-/
meta def add_nonneg_proof (n : name) : tactic unit :=
-- first we find the declaration named `n` in the environment.
do d ← get_decl n,
-- the type of d is `Π x y z ..., body`,
-- where body contains a bunch of free variables.
-- we instantiate the binders to get a body we can manipulate.
(args, body) ← mk_local_pis d.type,
-- args is a list of expressions, but we want a list of `option expr`s to give to `mk_mapp`.
let args_with_some := args.map some,
-- this line applies the expression named `n` to the variables we've created.
-- d_body is the natural number that we want to prove is nonnegative.
d_body ← mk_mapp n args_with_some,
-- so we prove that `d_body` is nonnegative by applying `nat.zero_le`.
nonneg_prf_body ← mk_app `nat.zero_le [d_body],
-- now we abstract away the local constants we created.
nonneg_prf ← lambdas args nonneg_prf_body,
-- we create a name for our new proof.
-- if `n` is `nat.add, we will call our new proof `nat.add.nonneg
let new_decl_name := n.append `nonneg,
-- we get the type of the proof we've constructed,
decl_tp ← infer_type nonneg_prf,
-- make a term of type `declaration`,
let new_decl := mk_theorem new_decl_name d.univ_params decl_tp nonneg_prf,
-- and add that declaration to the environment.
add_decl new_decl
run_cmd add_nonneg_proof `nat.add
run_cmd add_nonneg_proof `list.length
#check nat.add.nonneg
#check list.length.nonneg
/-!
## Exercise 3 (challenge!)
The mathlib tactic `cancel_denoms` is intended to get rid of division by numerals
in expressions where this makes sense. For example,
-/
example (q : ℚ) (h : q / 3 > 0) : q > 0 :=
begin
cancel_denoms at h, exact h
end
/-!
But it is not complete. In particular, it doesn't like nested division
or other operators in denominators. These all fail:
-/
example (q : ℚ) (h : q / (3 / 4) > 0) : false :=
begin
cancel_denoms at h,
end
example (p q : ℚ) (h : q / 2 / 3 < q) : false :=
begin
cancel_denoms at h,
end
example (p q : ℚ) (h : q / 2 < 3 / (4*q)) : false :=
begin
cancel_denoms at h,
end
-- this one succeeds but doesn't do what it should
example (p q : ℚ) (h : q / (2*3) < q) : false :=
begin
cancel_denoms at h,
end
/-!
Look at the code in `src/tactic/cancel_denoms.lean` and try to fix it.
See if you can solve any or all of these failing test cases.
If you succeed, a pull request to mathlib is strongly encouraged!
-/
|
71d8713adb52b1b6caf3022b512c308913028cb5 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/polynomial/basic.lean | 575307b9ce97f38994dde72fba8978f53287f34b | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 27,303 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import algebra.monoid_algebra.basic
/-!
# Theory of univariate polynomials
This file defines `polynomial R`, the type of univariate polynomials over the semiring `R`, builds
a semiring structure on it, and gives basic definitions that are expanded in other files in this
directory.
## Main definitions
* `monomial n a` is the polynomial `a X^n`. Note that `monomial n` is defined as an `R`-linear map.
* `C a` is the constant polynomial `a`. Note that `C` is defined as a ring homomorphism.
* `X` is the polynomial `X`, i.e., `monomial 1 1`.
* `p.sum f` is `∑ n in p.support, f n (p.coeff n)`, i.e., one sums the values of functions applied
to coefficients of the polynomial `p`.
* `p.erase n` is the polynomial `p` in which one removes the `c X^n` term.
There are often two natural variants of lemmas involving sums, depending on whether one acts on the
polynomials, or on the function. The naming convention is that one adds `index` when acting on
the polynomials. For instance,
* `sum_add_index` states that `(p + q).sum f = p.sum f + q.sum f`;
* `sum_add` states that `p.sum (λ n x, f n x + g n x) = p.sum f + p.sum g`.
## Implementation
Polynomials are defined using `add_monoid_algebra R ℕ`, where `R` is a commutative semiring, but
through a structure to make them irreducible from the point of view of the kernel. Most operations
are irreducible since Lean can not compute anyway with `add_monoid_algebra`. There are two
exceptions that we make semireducible:
* The zero polynomial, so that its coefficients are definitionally equal to `0`.
* The scalar action, to permit typeclass search to unfold it to resolve potential instance
diamonds.
The raw implementation of the equivalence between `polynomial R` and `add_monoid_algebra R ℕ` is
done through `of_finsupp` and `to_finsupp` (or, equivalently, `rcases p` when `p` is a polynomial
gives an element `q` of `add_monoid_algebra R ℕ`, and conversely `⟨q⟩` gives back `p`). The
equivalence is also registered as a ring equiv in `polynomial.to_finsupp_iso`. These should
in general not be used once the basic API for polynomials is constructed.
-/
noncomputable theory
/-- `polynomial R` is the type of univariate polynomials over `R`.
Polynomials should be seen as (semi-)rings with the additional constructor `X`.
The embedding from `R` is called `C`. -/
structure polynomial (R : Type*) [semiring R] := of_finsupp ::
(to_finsupp : add_monoid_algebra R ℕ)
open finsupp add_monoid_algebra
open_locale big_operators
namespace polynomial
universes u
variables {R : Type u} {a b : R} {m n : ℕ}
section semiring
variables [semiring R] {p q : polynomial R}
lemma forall_iff_forall_finsupp (P : polynomial R → Prop) :
(∀ p, P p) ↔ ∀ (q : add_monoid_algebra R ℕ), P ⟨q⟩ :=
⟨λ h q, h ⟨q⟩, λ h ⟨p⟩, h p⟩
lemma exists_iff_exists_finsupp (P : polynomial R → Prop) :
(∃ p, P p) ↔ ∃ (q : add_monoid_algebra R ℕ), P ⟨q⟩ :=
⟨λ ⟨⟨p⟩, hp⟩, ⟨p, hp⟩, λ ⟨q, hq⟩, ⟨⟨q⟩, hq⟩ ⟩
/-- The function version of `monomial`. Use `monomial` instead of this one. -/
@[irreducible] def monomial_fun (n : ℕ) (a : R) : polynomial R := ⟨finsupp.single n a⟩
@[irreducible] private def add : polynomial R → polynomial R → polynomial R
| ⟨a⟩ ⟨b⟩ := ⟨a + b⟩
@[irreducible] private def neg {R : Type u} [ring R] : polynomial R → polynomial R
| ⟨a⟩ := ⟨-a⟩
@[irreducible] private def mul : polynomial R → polynomial R → polynomial R
| ⟨a⟩ ⟨b⟩ := ⟨a * b⟩
instance : has_zero (polynomial R) := ⟨⟨0⟩⟩
instance : has_one (polynomial R) := ⟨monomial_fun 0 (1 : R)⟩
instance : has_add (polynomial R) := ⟨add⟩
instance {R : Type u} [ring R] : has_neg (polynomial R) := ⟨neg⟩
instance : has_mul (polynomial R) := ⟨mul⟩
instance {S : Type*} [monoid S] [distrib_mul_action S R] : has_scalar S (polynomial R) :=
⟨λ r p, ⟨r • p.to_finsupp⟩⟩
lemma zero_to_finsupp : (⟨0⟩ : polynomial R) = 0 :=
rfl
lemma one_to_finsupp : (⟨1⟩ : polynomial R) = 1 :=
begin
change (⟨1⟩ : polynomial R) = monomial_fun 0 (1 : R),
rw [monomial_fun],
refl
end
lemma add_to_finsupp {a b} : (⟨a⟩ + ⟨b⟩ : polynomial R) = ⟨a + b⟩ := show add _ _ = _, by rw add
lemma neg_to_finsupp {R : Type u} [ring R] {a} : (-⟨a⟩ : polynomial R) = ⟨-a⟩ :=
show neg _ = _, by rw neg
lemma mul_to_finsupp {a b} : (⟨a⟩ * ⟨b⟩ : polynomial R) = ⟨a * b⟩ := show mul _ _ = _, by rw mul
lemma smul_to_finsupp {S : Type*} [monoid S] [distrib_mul_action S R] {a : S} {b} :
(a • ⟨b⟩ : polynomial R) = ⟨a • b⟩ := rfl
lemma _root_.is_smul_regular.polynomial {S : Type*} [monoid S] [distrib_mul_action S R] {a : S}
(ha : is_smul_regular R a) : is_smul_regular (polynomial R) a
| ⟨x⟩ ⟨y⟩ h := congr_arg _ $ ha.finsupp (polynomial.of_finsupp.inj h)
instance : inhabited (polynomial R) := ⟨0⟩
instance : semiring (polynomial R) :=
by refine_struct
{ zero := (0 : polynomial R),
one := 1,
mul := (*),
add := (+),
nsmul := (•),
npow := npow_rec,
npow_zero' := λ x, rfl,
npow_succ' := λ n x, rfl };
{ repeat { rintro ⟨_⟩, };
simp [← zero_to_finsupp, ← one_to_finsupp, add_to_finsupp, mul_to_finsupp, mul_assoc, mul_add,
add_mul, smul_to_finsupp, nat.succ_eq_one_add]; abel }
instance {S} [monoid S] [distrib_mul_action S R] : distrib_mul_action S (polynomial R) :=
{ smul := (•),
one_smul := by { rintros ⟨⟩, simp [smul_to_finsupp] },
mul_smul := by { rintros _ _ ⟨⟩, simp [smul_to_finsupp, mul_smul], },
smul_add := by { rintros _ ⟨⟩ ⟨⟩, simp [smul_to_finsupp, add_to_finsupp] },
smul_zero := by { rintros _, simp [← zero_to_finsupp, smul_to_finsupp] } }
instance {S} [monoid S] [distrib_mul_action S R] [has_faithful_scalar S R] :
has_faithful_scalar S (polynomial R) :=
{ eq_of_smul_eq_smul := λ s₁ s₂ h, eq_of_smul_eq_smul $ λ a : ℕ →₀ R, congr_arg to_finsupp (h ⟨a⟩) }
instance {S} [semiring S] [module S R] : module S (polynomial R) :=
{ smul := (•),
add_smul := by { rintros _ _ ⟨⟩, simp [smul_to_finsupp, add_to_finsupp, add_smul] },
zero_smul := by { rintros ⟨⟩, simp [smul_to_finsupp, ← zero_to_finsupp] },
..polynomial.distrib_mul_action }
instance {S₁ S₂} [monoid S₁] [monoid S₂] [distrib_mul_action S₁ R] [distrib_mul_action S₂ R]
[smul_comm_class S₁ S₂ R] : smul_comm_class S₁ S₂ (polynomial R) :=
⟨by { rintros _ _ ⟨⟩, simp [smul_to_finsupp, smul_comm] }⟩
instance {S₁ S₂} [has_scalar S₁ S₂] [monoid S₁] [monoid S₂] [distrib_mul_action S₁ R]
[distrib_mul_action S₂ R] [is_scalar_tower S₁ S₂ R] : is_scalar_tower S₁ S₂ (polynomial R) :=
⟨by { rintros _ _ ⟨⟩, simp [smul_to_finsupp] }⟩
instance [subsingleton R] : unique (polynomial R) :=
{ uniq := by { rintros ⟨x⟩, change (⟨x⟩ : polynomial R) = 0, rw [← zero_to_finsupp], simp },
.. polynomial.inhabited }
variable (R)
/-- Ring isomorphism between `polynomial R` and `add_monoid_algebra R ℕ`. This is just an
implementation detail, but it can be useful to transfer results from `finsupp` to polynomials. -/
@[simps]
def to_finsupp_iso : polynomial R ≃+* add_monoid_algebra R ℕ :=
{ to_fun := λ p, p.to_finsupp,
inv_fun := λ p, ⟨p⟩,
left_inv := λ ⟨p⟩, rfl,
right_inv := λ p, rfl,
map_mul' := by { rintros ⟨⟩ ⟨⟩, simp [mul_to_finsupp] },
map_add' := by { rintros ⟨⟩ ⟨⟩, simp [add_to_finsupp] } }
/-- Ring isomorphism between `(polynomial R)ᵒᵖ` and `polynomial Rᵒᵖ`. -/
@[simps]
def op_ring_equiv : (polynomial R)ᵒᵖ ≃+* polynomial Rᵒᵖ :=
((to_finsupp_iso R).op.trans add_monoid_algebra.op_ring_equiv).trans (to_finsupp_iso _).symm
variable {R}
lemma sum_to_finsupp {ι : Type*} (s : finset ι) (f : ι → add_monoid_algebra R ℕ) :
∑ i in s, (⟨f i⟩ : polynomial R) = ⟨∑ i in s, f i⟩ :=
((to_finsupp_iso R).symm.to_add_monoid_hom.map_sum f s).symm
/--
The set of all `n` such that `X^n` has a non-zero coefficient.
-/
def support : polynomial R → finset ℕ
| ⟨p⟩ := p.support
@[simp] lemma support_zero : (0 : polynomial R).support = ∅ :=
rfl
@[simp] lemma support_eq_empty : p.support = ∅ ↔ p = 0 :=
by { rcases p, simp [support, ← zero_to_finsupp] }
lemma card_support_eq_zero : p.support.card = 0 ↔ p = 0 :=
by simp
/-- `monomial s a` is the monomial `a * X^s` -/
def monomial (n : ℕ) : R →ₗ[R] polynomial R :=
{ to_fun := monomial_fun n,
map_add' := by simp [monomial_fun, add_to_finsupp],
map_smul' := by simp [monomial_fun, smul_to_finsupp] }
@[simp]
lemma monomial_zero_right (n : ℕ) :
monomial n (0 : R) = 0 :=
by simp [monomial, monomial_fun]
-- This is not a `simp` lemma as `monomial_zero_left` is more general.
lemma monomial_zero_one : monomial 0 (1 : R) = 1 := rfl
lemma monomial_add (n : ℕ) (r s : R) :
monomial n (r + s) = monomial n r + monomial n s :=
by simp [monomial, monomial_fun]
lemma monomial_mul_monomial (n m : ℕ) (r s : R) :
monomial n r * monomial m s = monomial (n + m) (r * s) :=
by simp only [monomial, monomial_fun, linear_map.coe_mk, mul_to_finsupp,
add_monoid_algebra.single_mul_single]
@[simp]
lemma monomial_pow (n : ℕ) (r : R) (k : ℕ) :
(monomial n r)^k = monomial (n*k) (r^k) :=
begin
induction k with k ih,
{ simp [pow_zero, monomial_zero_one], },
{ simp [pow_succ, ih, monomial_mul_monomial, nat.succ_eq_add_one, mul_add, add_comm] },
end
lemma smul_monomial {S} [monoid S] [distrib_mul_action S R] (a : S) (n : ℕ) (b : R) :
a • monomial n b = monomial n (a • b) :=
by simp [monomial, monomial_fun, smul_to_finsupp]
@[simp] lemma to_finsupp_iso_monomial : (to_finsupp_iso R) (monomial n a) = single n a :=
by simp [to_finsupp_iso, monomial, monomial_fun]
@[simp] lemma to_finsupp_iso_symm_single : (to_finsupp_iso R).symm (single n a) = monomial n a :=
by simp [to_finsupp_iso, monomial, monomial_fun]
lemma monomial_injective (n : ℕ) :
function.injective (monomial n : R → polynomial R) :=
begin
convert (to_finsupp_iso R).symm.injective.comp (single_injective n),
ext,
simp
end
@[simp] lemma monomial_eq_zero_iff (t : R) (n : ℕ) :
monomial n t = 0 ↔ t = 0 :=
linear_map.map_eq_zero_iff _ (polynomial.monomial_injective n)
lemma support_add : (p + q).support ⊆ p.support ∪ q.support :=
begin
rcases p, rcases q,
simp only [add_to_finsupp, support],
exact support_add
end
/--
`C a` is the constant polynomial `a`.
`C` is provided as a ring homomorphism.
-/
def C : R →+* polynomial R :=
{ map_one' := by simp [monomial_zero_one],
map_mul' := by simp [monomial_mul_monomial],
map_zero' := by simp,
.. monomial 0 }
@[simp] lemma monomial_zero_left (a : R) : monomial 0 a = C a := rfl
lemma C_0 : C (0 : R) = 0 := by simp
lemma C_1 : C (1 : R) = 1 := rfl
lemma C_mul : C (a * b) = C a * C b := C.map_mul a b
lemma C_add : C (a + b) = C a + C b := C.map_add a b
@[simp] lemma smul_C {S} [monoid S] [distrib_mul_action S R] (s : S) (r : R) :
s • C r = C (s • r) :=
smul_monomial _ _ r
@[simp] lemma C_bit0 : C (bit0 a) = bit0 (C a) := C_add
@[simp] lemma C_bit1 : C (bit1 a) = bit1 (C a) := by simp [bit1, C_bit0]
lemma C_pow : C (a ^ n) = C a ^ n := C.map_pow a n
@[simp]
lemma C_eq_nat_cast (n : ℕ) : C (n : R) = (n : polynomial R) :=
C.map_nat_cast n
@[simp] lemma C_mul_monomial : C a * monomial n b = monomial n (a * b) :=
by simp only [←monomial_zero_left, monomial_mul_monomial, zero_add]
@[simp] lemma monomial_mul_C : monomial n a * C b = monomial n (a * b) :=
by simp only [←monomial_zero_left, monomial_mul_monomial, add_zero]
/-- `X` is the polynomial variable (aka indeterminate). -/
def X : polynomial R := monomial 1 1
lemma monomial_one_one_eq_X : monomial 1 (1 : R) = X := rfl
lemma monomial_one_right_eq_X_pow (n : ℕ) : monomial n (1 : R) = X^n :=
begin
induction n with n ih,
{ simp [monomial_zero_one], },
{ rw [pow_succ, ←ih, ←monomial_one_one_eq_X, monomial_mul_monomial, add_comm, one_mul], }
end
/-- `X` commutes with everything, even when the coefficients are noncommutative. -/
lemma X_mul : X * p = p * X :=
begin
rcases p,
simp only [X, monomial, monomial_fun, mul_to_finsupp, linear_map.coe_mk],
ext,
simp [add_monoid_algebra.mul_apply, sum_single_index, add_comm],
end
lemma X_pow_mul {n : ℕ} : X^n * p = p * X^n :=
begin
induction n with n ih,
{ simp, },
{ conv_lhs { rw pow_succ', },
rw [mul_assoc, X_mul, ←mul_assoc, ih, mul_assoc, ←pow_succ'], }
end
lemma X_pow_mul_assoc {n : ℕ} : (p * X^n) * q = (p * q) * X^n :=
by rw [mul_assoc, X_pow_mul, ←mul_assoc]
lemma commute_X (p : polynomial R) : commute X p := X_mul
@[simp]
lemma monomial_mul_X (n : ℕ) (r : R) : monomial n r * X = monomial (n+1) r :=
by erw [monomial_mul_monomial, mul_one]
@[simp]
lemma monomial_mul_X_pow (n : ℕ) (r : R) (k : ℕ) : monomial n r * X^k = monomial (n+k) r :=
begin
induction k with k ih,
{ simp, },
{ simp [ih, pow_succ', ←mul_assoc, add_assoc], },
end
@[simp]
lemma X_mul_monomial (n : ℕ) (r : R) : X * monomial n r = monomial (n+1) r :=
by rw [X_mul, monomial_mul_X]
@[simp]
lemma X_pow_mul_monomial (k n : ℕ) (r : R) : X^k * monomial n r = monomial (n+k) r :=
by rw [X_pow_mul, monomial_mul_X_pow]
/-- `coeff p n` (often denoted `p.coeff n`) is the coefficient of `X^n` in `p`. -/
def coeff : polynomial R → ℕ → R
| ⟨p⟩ n := p n
lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 :=
by { simp only [monomial, monomial_fun, coeff, linear_map.coe_mk], rw finsupp.single_apply }
@[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial R) n = 0 := rfl
@[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 :=
by { rw [← monomial_zero_one, coeff_monomial], simp }
@[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_monomial
@[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_monomial
@[simp] lemma coeff_monomial_succ : coeff (monomial (n+1) a) 0 = 0 :=
by simp [coeff_monomial]
lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_monomial
lemma coeff_X_of_ne_one {n : ℕ} (hn : n ≠ 1) : coeff (X : polynomial R) n = 0 :=
by rw [coeff_X, if_neg hn.symm]
@[simp] lemma mem_support_iff : n ∈ p.support ↔ p.coeff n ≠ 0 :=
by { rcases p, simp [support, coeff] }
lemma not_mem_support_iff : n ∉ p.support ↔ p.coeff n = 0 :=
by simp
lemma coeff_C : coeff (C a) n = ite (n = 0) a 0 :=
by { convert coeff_monomial using 2, simp [eq_comm], }
@[simp] lemma coeff_C_zero : coeff (C a) 0 = a := coeff_monomial
lemma coeff_C_ne_zero (h : n ≠ 0) : (C a).coeff n = 0 :=
by rw [coeff_C, if_neg h]
theorem nontrivial.of_polynomial_ne (h : p ≠ q) : nontrivial R :=
⟨⟨0, 1, λ h01 : 0 = 1, h $
by rw [← mul_one p, ← mul_one q, ← C_1, ← h01, C_0, mul_zero, mul_zero] ⟩⟩
lemma monomial_eq_C_mul_X : ∀{n}, monomial n a = C a * X^n
| 0 := (mul_one _).symm
| (n+1) :=
calc monomial (n + 1) a = monomial n a * X : by { rw [X, monomial_mul_monomial, mul_one], }
... = (C a * X^n) * X : by rw [monomial_eq_C_mul_X]
... = C a * X^(n+1) : by simp only [pow_add, mul_assoc, pow_one]
@[simp] lemma C_inj : C a = C b ↔ a = b :=
⟨λ h, coeff_C_zero.symm.trans (h.symm ▸ coeff_C_zero), congr_arg C⟩
@[simp] lemma C_eq_zero : C a = 0 ↔ a = 0 :=
calc C a = 0 ↔ C a = C 0 : by rw C_0
... ↔ a = 0 : C_inj
theorem ext_iff {p q : polynomial R} : p = q ↔ ∀ n, coeff p n = coeff q n :=
by { rcases p, rcases q, simp [coeff, finsupp.ext_iff] }
@[ext] lemma ext {p q : polynomial R} : (∀ n, coeff p n = coeff q n) → p = q :=
ext_iff.2
lemma add_hom_ext {M : Type*} [add_monoid M] {f g : polynomial R →+ M}
(h : ∀ n a, f (monomial n a) = g (monomial n a)) :
f = g :=
begin
set f' : add_monoid_algebra R ℕ →+ M := f.comp (to_finsupp_iso R).symm with hf',
set g' : add_monoid_algebra R ℕ →+ M := g.comp (to_finsupp_iso R).symm with hg',
have : ∀ n a, f' (single n a) = g' (single n a) := λ n, by simp [hf', hg', h n],
have A : f' = g' := finsupp.add_hom_ext this,
have B : f = f'.comp (to_finsupp_iso R), by { rw [hf', add_monoid_hom.comp_assoc], ext x,
simp only [ring_equiv.symm_apply_apply, add_monoid_hom.coe_comp, function.comp_app,
ring_hom.coe_add_monoid_hom, ring_equiv.coe_to_ring_hom, coe_coe]},
have C : g = g'.comp (to_finsupp_iso R), by { rw [hg', add_monoid_hom.comp_assoc], ext x,
simp only [ring_equiv.symm_apply_apply, add_monoid_hom.coe_comp, function.comp_app,
ring_hom.coe_add_monoid_hom, ring_equiv.coe_to_ring_hom, coe_coe]},
rw [B, C, A],
end
@[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : polynomial R →+ M}
(h : ∀ n, f.comp (monomial n).to_add_monoid_hom = g.comp (monomial n).to_add_monoid_hom) :
f = g :=
add_hom_ext (λ n, add_monoid_hom.congr_fun (h n))
@[ext] lemma lhom_ext' {M : Type*} [add_comm_monoid M] [module R M] {f g : polynomial R →ₗ[R] M}
(h : ∀ n, f.comp (monomial n) = g.comp (monomial n)) :
f = g :=
linear_map.to_add_monoid_hom_injective $ add_hom_ext $ λ n, linear_map.congr_fun (h n)
-- this has the same content as the subsingleton
lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : polynomial R) : p = 0 :=
by rw [←one_smul R p, ←h, zero_smul]
lemma support_monomial (n) (a : R) (H : a ≠ 0) : (monomial n a).support = singleton n :=
by simp [monomial, monomial_fun, support, finsupp.support_single_ne_zero H]
lemma support_monomial' (n) (a : R) : (monomial n a).support ⊆ singleton n :=
by simp [monomial, monomial_fun, support, finsupp.support_single_subset]
lemma X_pow_eq_monomial (n) : X ^ n = monomial n (1:R) :=
begin
induction n with n hn,
{ rw [pow_zero, monomial_zero_one] },
{ rw [pow_succ', hn, X, monomial_mul_monomial, one_mul] },
end
lemma monomial_eq_smul_X {n} : monomial n (a : R) = a • X^n :=
calc monomial n a = monomial n (a * 1) : by simp
... = a • monomial n 1 : by simp [monomial, monomial_fun, smul_to_finsupp]
... = a • X^n : by rw X_pow_eq_monomial
lemma support_X_pow (H : ¬ (1:R) = 0) (n : ℕ) : (X^n : polynomial R).support = singleton n :=
begin
convert support_monomial n 1 H,
exact X_pow_eq_monomial n,
end
lemma support_X_empty (H : (1:R)=0) : (X : polynomial R).support = ∅ :=
begin
rw [X, H, monomial_zero_right, support_zero],
end
lemma support_X (H : ¬ (1 : R) = 0) : (X : polynomial R).support = singleton 1 :=
begin
rw [← pow_one X, support_X_pow H 1],
end
lemma monomial_left_inj {R : Type*} [semiring R] {a : R} (ha : a ≠ 0) {i j : ℕ} :
(monomial i a) = (monomial j a) ↔ i = j :=
by simp [monomial, monomial_fun, finsupp.single_left_inj ha]
lemma nat_cast_mul {R : Type*} [semiring R] (n : ℕ) (p : polynomial R) :
(n : polynomial R) * p = n • p :=
(nsmul_eq_mul _ _).symm
/-- Summing the values of a function applied to the coefficients of a polynomial -/
def sum {S : Type*} [add_comm_monoid S] (p : polynomial R) (f : ℕ → R → S) : S :=
∑ n in p.support, f n (p.coeff n)
lemma sum_def {S : Type*} [add_comm_monoid S] (p : polynomial R) (f : ℕ → R → S) :
p.sum f = ∑ n in p.support, f n (p.coeff n) := rfl
lemma sum_eq_of_subset {S : Type*} [add_comm_monoid S] (p : polynomial R)
(f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) (s : finset ℕ) (hs : p.support ⊆ s) :
p.sum f = ∑ n in s, f n (p.coeff n) :=
begin
apply finset.sum_subset hs (λ n hn h'n, _),
rw not_mem_support_iff at h'n,
simp [h'n, hf]
end
/-- Expressing the product of two polynomials as a double sum. -/
lemma mul_eq_sum_sum :
p * q = ∑ i in p.support, q.sum (λ j a, (monomial (i + j)) (p.coeff i * a)) :=
begin
rcases p, rcases q,
simp [mul_to_finsupp, support, monomial, sum, monomial_fun, coeff, sum_to_finsupp],
refl
end
@[simp] lemma sum_zero_index {S : Type*} [add_comm_monoid S] (f : ℕ → R → S) :
(0 : polynomial R).sum f = 0 :=
by simp [sum]
@[simp] lemma sum_monomial_index {S : Type*} [add_comm_monoid S]
(n : ℕ) (a : R) (f : ℕ → R → S) (hf : f n 0 = 0) :
(monomial n a : polynomial R).sum f = f n a :=
begin
by_cases h : a = 0,
{ simp [h, hf] },
{ simp [sum, support_monomial, h, coeff_monomial] }
end
@[simp] lemma sum_C_index {a} {β} [add_comm_monoid β] {f : ℕ → R → β} (h : f 0 0 = 0) :
(C a).sum f = f 0 a :=
sum_monomial_index 0 a f h
-- the assumption `hf` is only necessary when the ring is trivial
@[simp] lemma sum_X_index {S : Type*} [add_comm_monoid S] {f : ℕ → R → S} (hf : f 1 0 = 0) :
(X : polynomial R).sum f = f 1 1 :=
sum_monomial_index 1 1 f hf
lemma sum_add_index {S : Type*} [add_comm_monoid S] (p q : polynomial R)
(f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) (h_add : ∀a b₁ b₂, f a (b₁ + b₂) = f a b₁ + f a b₂) :
(p + q).sum f = p.sum f + q.sum f :=
begin
rcases p, rcases q,
simp only [add_to_finsupp, sum, support, coeff, pi.add_apply, coe_add],
exact finsupp.sum_add_index hf h_add,
end
lemma sum_add' {S : Type*} [add_comm_monoid S] (p : polynomial R) (f g : ℕ → R → S) :
p.sum (f + g) = p.sum f + p.sum g :=
by simp [sum_def, finset.sum_add_distrib]
lemma sum_add {S : Type*} [add_comm_monoid S] (p : polynomial R) (f g : ℕ → R → S) :
p.sum (λ n x, f n x + g n x) = p.sum f + p.sum g :=
sum_add' _ _ _
lemma sum_smul_index {S : Type*} [add_comm_monoid S] (p : polynomial R) (b : R)
(f : ℕ → R → S) (hf : ∀ i, f i 0 = 0) : (b • p).sum f = p.sum (λ n a, f n (b * a)) :=
begin
rcases p,
simp [smul_to_finsupp, sum, support, coeff],
exact finsupp.sum_smul_index hf,
end
/-- `erase p n` is the polynomial `p` in which the `X^n` term has been erased. -/
@[irreducible] definition erase (n : ℕ) : polynomial R → polynomial R
| ⟨p⟩ := ⟨p.erase n⟩
@[simp] lemma support_erase (p : polynomial R) (n : ℕ) :
support (p.erase n) = (support p).erase n :=
by { rcases p, simp only [support, erase, support_erase], congr }
lemma monomial_add_erase (p : polynomial R) (n : ℕ) : monomial n (coeff p n) + p.erase n = p :=
begin
rcases p,
simp [add_to_finsupp, monomial, monomial_fun, coeff, erase],
exact finsupp.single_add_erase _ _
end
lemma coeff_erase (p : polynomial R) (n i : ℕ) :
(p.erase n).coeff i = if i = n then 0 else p.coeff i :=
begin
rcases p,
simp only [erase, coeff],
convert rfl
end
@[simp] lemma erase_zero (n : ℕ) : (0 : polynomial R).erase n = 0 :=
by simp [← zero_to_finsupp, erase]
@[simp] lemma erase_monomial {n : ℕ} {a : R} : erase n (monomial n a) = 0 :=
by simp [monomial, monomial_fun, erase, ← zero_to_finsupp]
@[simp] lemma erase_same (p : polynomial R) (n : ℕ) : coeff (p.erase n) n = 0 :=
by simp [coeff_erase]
@[simp] lemma erase_ne (p : polynomial R) (n i : ℕ) (h : i ≠ n) :
coeff (p.erase n) i = coeff p i :=
by simp [coeff_erase, h]
section update
/-- Replace the coefficient of a `p : polynomial p` at a given degree `n : ℕ`
by a given value `a : R`. If `a = 0`, this is equal to `p.erase n`
If `p.nat_degree < n` and `a ≠ 0`, this increases the degree to `n`. -/
def update (p : polynomial R) (n : ℕ) (a : R) :
polynomial R :=
polynomial.of_finsupp (p.to_finsupp.update n a)
lemma coeff_update (p : polynomial R) (n : ℕ) (a : R) :
(p.update n a).coeff = function.update p.coeff n a :=
begin
ext,
cases p,
simp only [coeff, update, function.update_apply, coe_update],
congr
end
lemma coeff_update_apply (p : polynomial R) (n : ℕ) (a : R) (i : ℕ) :
(p.update n a).coeff i = if (i = n) then a else p.coeff i :=
by rw [coeff_update, function.update_apply]
@[simp] lemma coeff_update_same (p : polynomial R) (n : ℕ) (a : R) :
(p.update n a).coeff n = a :=
by rw [p.coeff_update_apply, if_pos rfl]
lemma coeff_update_ne (p : polynomial R) {n : ℕ} (a : R) {i : ℕ} (h : i ≠ n) :
(p.update n a).coeff i = p.coeff i :=
by rw [p.coeff_update_apply, if_neg h]
@[simp] lemma update_zero_eq_erase (p : polynomial R) (n : ℕ) :
p.update n 0 = p.erase n :=
by { ext, rw [coeff_update_apply, coeff_erase] }
lemma support_update (p : polynomial R) (n : ℕ) (a : R) [decidable (a = 0)] :
support (p.update n a) = if a = 0 then p.support.erase n else insert n p.support :=
by { cases p, simp only [support, update, support_update], congr }
lemma support_update_zero (p : polynomial R) (n : ℕ) :
support (p.update n 0) = p.support.erase n :=
by rw [update_zero_eq_erase, support_erase]
lemma support_update_ne_zero (p : polynomial R) (n : ℕ) {a : R} (ha : a ≠ 0) :
support (p.update n a) = insert n p.support :=
by classical; rw [support_update, if_neg ha]
end update
end semiring
section comm_semiring
variables [comm_semiring R]
instance : comm_semiring (polynomial R) :=
{ mul_comm := by { rintros ⟨⟩ ⟨⟩, simp [mul_to_finsupp, mul_comm] }, .. polynomial.semiring }
end comm_semiring
section ring
variables [ring R]
instance : ring (polynomial R) :=
{ neg := has_neg.neg,
add_left_neg := by { rintros ⟨⟩, simp [neg_to_finsupp, add_to_finsupp, ← zero_to_finsupp] },
zsmul := (•),
zsmul_zero' := by { rintro ⟨⟩, simp [smul_to_finsupp, ← zero_to_finsupp] },
zsmul_succ' := by { rintros n ⟨⟩, simp [smul_to_finsupp, add_to_finsupp, add_smul, add_comm] },
zsmul_neg' := by { rintros n ⟨⟩,
simp only [smul_to_finsupp, neg_to_finsupp], simp [add_smul, add_mul] },
.. polynomial.semiring }
@[simp] lemma coeff_neg (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n :=
by { rcases p, simp [coeff, neg_to_finsupp] }
@[simp]
lemma coeff_sub (p q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n :=
by { rcases p, rcases q, simp [coeff, sub_eq_add_neg, add_to_finsupp, neg_to_finsupp] }
@[simp] lemma monomial_neg (n : ℕ) (a : R) : monomial n (-a) = -(monomial n a) :=
by rw [eq_neg_iff_add_eq_zero, ←monomial_add, neg_add_self, monomial_zero_right]
@[simp] lemma support_neg {p : polynomial R} : (-p).support = p.support :=
by { rcases p, simp [support, neg_to_finsupp] }
end ring
instance [comm_ring R] : comm_ring (polynomial R) :=
{ .. polynomial.comm_semiring, .. polynomial.ring }
section nonzero_semiring
variables [semiring R] [nontrivial R]
instance : nontrivial (polynomial R) :=
begin
have h : nontrivial (add_monoid_algebra R ℕ) := by apply_instance,
rcases h.exists_pair_ne with ⟨x, y, hxy⟩,
refine ⟨⟨⟨x⟩, ⟨y⟩, _⟩⟩,
simp [hxy],
end
lemma X_ne_zero : (X : polynomial R) ≠ 0 :=
mt (congr_arg (λ p, coeff p 1)) (by simp)
end nonzero_semiring
section repr
variables [semiring R]
open_locale classical
instance [has_repr R] : has_repr (polynomial R) :=
⟨λ p, if p = 0 then "0"
else (p.support.sort (≤)).foldr
(λ n a, a ++ (if a = "" then "" else " + ") ++
if n = 0
then "C (" ++ repr (coeff p n) ++ ")"
else if n = 1
then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X"
else if (coeff p n) = 1 then "X ^ " ++ repr n
else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩
end repr
end polynomial
|
591bd972ceaddef309e6c5fbb78e6cb7335a807d | 94e33a31faa76775069b071adea97e86e218a8ee | /src/order/upper_lower.lean | 6b303c11ff5c9571bae0d70a260ef39fd1914d6f | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 23,123 | lean | /-
Copyright (c) 2022 Yaël Dillies, Sara Rousta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Sara Rousta
-/
import data.set_like.basic
import order.hom.complete_lattice
/-!
# Up-sets and down-sets
This file defines upper and lower sets in an order.
## Main declarations
* `is_upper_set`: Predicate for a set to be an upper set. This means every element greater than a
member of the set is in the set itself.
* `is_lower_set`: Predicate for a set to be a lower set. This means every element less than a member
of the set is in the set itself.
* `upper_set`: The type of upper sets.
* `lower_set`: The type of lower sets.
* `upper_set.Ici`: Principal upper set. `set.Ici` as an upper set.
* `upper_set.Ioi`: Strict principal upper set. `set.Ioi` as an upper set.
* `lower_set.Iic`: Principal lower set. `set.Iic` as an lower set.
* `lower_set.Iio`: Strict principal lower set. `set.Iio` as an lower set.
## Notes
Upper sets are ordered by **reverse** inclusion. This convention is motivated by the fact that this
makes them order-isomorphic to lower sets and antichains, and matches the convention on `filter`.
## TODO
Lattice structure on antichains. Order equivalence between upper/lower sets and antichains.
-/
open order_dual set
variables {α : Type*} {ι : Sort*} {κ : ι → Sort*}
/-! ### Unbundled upper/lower sets -/
section has_le
variables [has_le α] {s t : set α}
/-- An upper set in an order `α` is a set such that any element greater than one of its members is
also a member. Also called up-set, upward-closed set. -/
def is_upper_set (s : set α) : Prop := ∀ ⦃a b : α⦄, a ≤ b → a ∈ s → b ∈ s
/-- A lower set in an order `α` is a set such that any element less than one of its members is also
a member. Also called down-set, downward-closed set. -/
def is_lower_set (s : set α) : Prop := ∀ ⦃a b : α⦄, b ≤ a → a ∈ s → b ∈ s
lemma is_upper_set_empty : is_upper_set (∅ : set α) := λ _ _ _, id
lemma is_lower_set_empty : is_lower_set (∅ : set α) := λ _ _ _, id
lemma is_upper_set_univ : is_upper_set (univ : set α) := λ _ _ _, id
lemma is_lower_set_univ : is_lower_set (univ : set α) := λ _ _ _, id
lemma is_upper_set.compl (hs : is_upper_set s) : is_lower_set sᶜ := λ a b h hb ha, hb $ hs h ha
lemma is_lower_set.compl (hs : is_lower_set s) : is_upper_set sᶜ := λ a b h hb ha, hb $ hs h ha
@[simp] lemma is_upper_set_compl : is_upper_set sᶜ ↔ is_lower_set s :=
⟨λ h, by { convert h.compl, rw compl_compl }, is_lower_set.compl⟩
@[simp] lemma is_lower_set_compl : is_lower_set sᶜ ↔ is_upper_set s :=
⟨λ h, by { convert h.compl, rw compl_compl }, is_upper_set.compl⟩
lemma is_upper_set.union (hs : is_upper_set s) (ht : is_upper_set t) : is_upper_set (s ∪ t) :=
λ a b h, or.imp (hs h) (ht h)
lemma is_lower_set.union (hs : is_lower_set s) (ht : is_lower_set t) : is_lower_set (s ∪ t) :=
λ a b h, or.imp (hs h) (ht h)
lemma is_upper_set.inter (hs : is_upper_set s) (ht : is_upper_set t) : is_upper_set (s ∩ t) :=
λ a b h, and.imp (hs h) (ht h)
lemma is_lower_set.inter (hs : is_lower_set s) (ht : is_lower_set t) : is_lower_set (s ∩ t) :=
λ a b h, and.imp (hs h) (ht h)
lemma is_upper_set_Union {f : ι → set α} (hf : ∀ i, is_upper_set (f i)) : is_upper_set (⋃ i, f i) :=
λ a b h, Exists₂.imp $ forall_range_iff.2 $ λ i, hf i h
lemma is_lower_set_Union {f : ι → set α} (hf : ∀ i, is_lower_set (f i)) : is_lower_set (⋃ i, f i) :=
λ a b h, Exists₂.imp $ forall_range_iff.2 $ λ i, hf i h
lemma is_upper_set_Union₂ {f : Π i, κ i → set α} (hf : ∀ i j, is_upper_set (f i j)) :
is_upper_set (⋃ i j, f i j) :=
is_upper_set_Union $ λ i, is_upper_set_Union $ hf i
lemma is_lower_set_Union₂ {f : Π i, κ i → set α} (hf : ∀ i j, is_lower_set (f i j)) :
is_lower_set (⋃ i j, f i j) :=
is_lower_set_Union $ λ i, is_lower_set_Union $ hf i
lemma is_upper_set_sUnion {S : set (set α)} (hf : ∀ s ∈ S, is_upper_set s) : is_upper_set (⋃₀ S) :=
λ a b h, Exists₂.imp $ λ s hs, hf s hs h
lemma is_lower_set_sUnion {S : set (set α)} (hf : ∀ s ∈ S, is_lower_set s) : is_lower_set (⋃₀ S) :=
λ a b h, Exists₂.imp $ λ s hs, hf s hs h
lemma is_upper_set_Inter {f : ι → set α} (hf : ∀ i, is_upper_set (f i)) : is_upper_set (⋂ i, f i) :=
λ a b h, forall₂_imp $ forall_range_iff.2 $ λ i, hf i h
lemma is_lower_set_Inter {f : ι → set α} (hf : ∀ i, is_lower_set (f i)) : is_lower_set (⋂ i, f i) :=
λ a b h, forall₂_imp $ forall_range_iff.2 $ λ i, hf i h
lemma is_upper_set_Inter₂ {f : Π i, κ i → set α} (hf : ∀ i j, is_upper_set (f i j)) :
is_upper_set (⋂ i j, f i j) :=
is_upper_set_Inter $ λ i, is_upper_set_Inter $ hf i
lemma is_lower_set_Inter₂ {f : Π i, κ i → set α} (hf : ∀ i j, is_lower_set (f i j)) :
is_lower_set (⋂ i j, f i j) :=
is_lower_set_Inter $ λ i, is_lower_set_Inter $ hf i
lemma is_upper_set_sInter {S : set (set α)} (hf : ∀ s ∈ S, is_upper_set s) : is_upper_set (⋂₀ S) :=
λ a b h, forall₂_imp $ λ s hs, hf s hs h
lemma is_lower_set_sInter {S : set (set α)} (hf : ∀ s ∈ S, is_lower_set s) : is_lower_set (⋂₀ S) :=
λ a b h, forall₂_imp $ λ s hs, hf s hs h
@[simp] lemma is_lower_set_preimage_of_dual_iff : is_lower_set (of_dual ⁻¹' s) ↔ is_upper_set s :=
iff.rfl
@[simp] lemma is_upper_set_preimage_of_dual_iff : is_upper_set (of_dual ⁻¹' s) ↔ is_lower_set s :=
iff.rfl
@[simp] lemma is_lower_set_preimage_to_dual_iff {s : set αᵒᵈ} :
is_lower_set (to_dual ⁻¹' s) ↔ is_upper_set s := iff.rfl
@[simp] lemma is_upper_set_preimage_to_dual_iff {s : set αᵒᵈ} :
is_upper_set (to_dual ⁻¹' s) ↔ is_lower_set s := iff.rfl
alias is_lower_set_preimage_of_dual_iff ↔ _ is_upper_set.of_dual
alias is_upper_set_preimage_of_dual_iff ↔ _ is_lower_set.of_dual
alias is_lower_set_preimage_to_dual_iff ↔ _ is_upper_set.to_dual
alias is_upper_set_preimage_to_dual_iff ↔ _ is_lower_set.to_dual
end has_le
section preorder
variables [preorder α] (a : α)
lemma is_upper_set_Ici : is_upper_set (Ici a) := λ _ _, ge_trans
lemma is_lower_set_Iic : is_lower_set (Iic a) := λ _ _, le_trans
lemma is_upper_set_Ioi : is_upper_set (Ioi a) := λ _ _, flip lt_of_lt_of_le
lemma is_lower_set_Iio : is_lower_set (Iio a) := λ _ _, lt_of_le_of_lt
section order_top
variables [order_top α] {s : set α}
lemma is_lower_set.top_mem (hs : is_lower_set s) : ⊤ ∈ s ↔ s = univ :=
⟨λ h, eq_univ_of_forall $ λ a, hs le_top h, λ h, h.symm ▸ mem_univ _⟩
lemma is_upper_set.top_mem (hs : is_upper_set s) : ⊤ ∈ s ↔ s.nonempty :=
⟨λ h, ⟨_, h⟩, λ ⟨a, ha⟩, hs le_top ha⟩
lemma is_upper_set.not_top_mem (hs : is_upper_set s) : ⊤ ∉ s ↔ s = ∅ :=
hs.top_mem.not.trans not_nonempty_iff_eq_empty
end order_top
section order_bot
variables [order_bot α] {s : set α}
lemma is_upper_set.bot_mem (hs : is_upper_set s) : ⊥ ∈ s ↔ s = univ :=
⟨λ h, eq_univ_of_forall $ λ a, hs bot_le h, λ h, h.symm ▸ mem_univ _⟩
lemma is_lower_set.bot_mem (hs : is_lower_set s) : ⊥ ∈ s ↔ s.nonempty :=
⟨λ h, ⟨_, h⟩, λ ⟨a, ha⟩, hs bot_le ha⟩
lemma is_lower_set.not_bot_mem (hs : is_lower_set s) : ⊥ ∉ s ↔ s = ∅ :=
hs.bot_mem.not.trans not_nonempty_iff_eq_empty
end order_bot
end preorder
/-! ### Bundled upper/lower sets -/
section has_le
variables [has_le α]
/-- The type of upper sets of an order. -/
structure upper_set (α : Type*) [has_le α] :=
(carrier : set α)
(upper' : is_upper_set carrier)
/-- The type of lower sets of an order. -/
structure lower_set (α : Type*) [has_le α] :=
(carrier : set α)
(lower' : is_lower_set carrier)
namespace upper_set
instance : set_like (upper_set α) α :=
{ coe := upper_set.carrier,
coe_injective' := λ s t h, by { cases s, cases t, congr' } }
@[ext] lemma ext {s t : upper_set α} : (s : set α) = t → s = t := set_like.ext'
@[simp] lemma carrier_eq_coe (s : upper_set α) : s.carrier = s := rfl
protected lemma upper (s : upper_set α) : is_upper_set (s : set α) := s.upper'
end upper_set
namespace lower_set
instance : set_like (lower_set α) α :=
{ coe := lower_set.carrier,
coe_injective' := λ s t h, by { cases s, cases t, congr' } }
@[ext] lemma ext {s t : lower_set α} : (s : set α) = t → s = t := set_like.ext'
@[simp] lemma carrier_eq_coe (s : lower_set α) : s.carrier = s := rfl
protected lemma lower (s : lower_set α) : is_lower_set (s : set α) := s.lower'
end lower_set
/-! #### Order -/
namespace upper_set
variables {S : set (upper_set α)} {s t : upper_set α} {a : α}
instance : has_sup (upper_set α) := ⟨λ s t, ⟨s ∩ t, s.upper.inter t.upper⟩⟩
instance : has_inf (upper_set α) := ⟨λ s t, ⟨s ∪ t, s.upper.union t.upper⟩⟩
instance : has_top (upper_set α) := ⟨⟨∅, is_upper_set_empty⟩⟩
instance : has_bot (upper_set α) := ⟨⟨univ, is_upper_set_univ⟩⟩
instance : has_Sup (upper_set α) :=
⟨λ S, ⟨⋂ s ∈ S, ↑s, is_upper_set_Inter₂ $ λ s _, s.upper⟩⟩
instance : has_Inf (upper_set α) :=
⟨λ S, ⟨⋃ s ∈ S, ↑s, is_upper_set_Union₂ $ λ s _, s.upper⟩⟩
instance : complete_distrib_lattice (upper_set α) :=
(to_dual.injective.comp $ set_like.coe_injective).complete_distrib_lattice _
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) rfl rfl
instance : inhabited (upper_set α) := ⟨⊥⟩
@[simp] lemma coe_top : ((⊤ : upper_set α) : set α) = ∅ := rfl
@[simp] lemma coe_bot : ((⊥ : upper_set α) : set α) = univ := rfl
@[simp] lemma coe_sup (s t : upper_set α) : (↑(s ⊔ t) : set α) = s ∩ t := rfl
@[simp] lemma coe_inf (s t : upper_set α) : (↑(s ⊓ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_Sup (S : set (upper_set α)) : (↑(Sup S) : set α) = ⋂ s ∈ S, ↑s := rfl
@[simp] lemma coe_Inf (S : set (upper_set α)) : (↑(Inf S) : set α) = ⋃ s ∈ S, ↑s := rfl
@[simp] lemma coe_supr (f : ι → upper_set α) : (↑(⨆ i, f i) : set α) = ⋂ i, f i := by simp [supr]
@[simp] lemma coe_infi (f : ι → upper_set α) : (↑(⨅ i, f i) : set α) = ⋃ i, f i := by simp [infi]
@[simp] lemma coe_supr₂ (f : Π i, κ i → upper_set α) : (↑(⨆ i j, f i j) : set α) = ⋂ i j, f i j :=
by simp_rw coe_supr
@[simp] lemma coe_infi₂ (f : Π i, κ i → upper_set α) : (↑(⨅ i j, f i j) : set α) = ⋃ i j, f i j :=
by simp_rw coe_infi
@[simp] lemma not_mem_top : a ∉ (⊤ : upper_set α) := id
@[simp] lemma mem_bot : a ∈ (⊥ : upper_set α) := trivial
@[simp] lemma mem_sup_iff : a ∈ s ⊔ t ↔ a ∈ s ∧ a ∈ t := iff.rfl
@[simp] lemma mem_inf_iff : a ∈ s ⊓ t ↔ a ∈ s ∨ a ∈ t := iff.rfl
@[simp] lemma mem_Sup_iff : a ∈ Sup S ↔ ∀ s ∈ S, a ∈ s := mem_Inter₂
@[simp] lemma mem_Inf_iff : a ∈ Inf S ↔ ∃ s ∈ S, a ∈ s := mem_Union₂
@[simp] lemma mem_supr_iff {f : ι → upper_set α} : a ∈ (⨆ i, f i) ↔ ∀ i, a ∈ f i :=
by { rw [←set_like.mem_coe, coe_supr], exact mem_Inter }
@[simp] lemma mem_infi_iff {f : ι → upper_set α} : a ∈ (⨅ i, f i) ↔ ∃ i, a ∈ f i :=
by { rw [←set_like.mem_coe, coe_infi], exact mem_Union }
@[simp] lemma mem_supr₂_iff {f : Π i, κ i → upper_set α} : a ∈ (⨆ i j, f i j) ↔ ∀ i j, a ∈ f i j :=
by simp_rw mem_supr_iff
@[simp] lemma mem_infi₂_iff {f : Π i, κ i → upper_set α} : a ∈ (⨅ i j, f i j) ↔ ∃ i j, a ∈ f i j :=
by simp_rw mem_infi_iff
end upper_set
namespace lower_set
variables {S : set (lower_set α)} {s t : lower_set α} {a : α}
instance : has_sup (lower_set α) := ⟨λ s t, ⟨s ∪ t, λ a b h, or.imp (s.lower h) (t.lower h)⟩⟩
instance : has_inf (lower_set α) := ⟨λ s t, ⟨s ∩ t, λ a b h, and.imp (s.lower h) (t.lower h)⟩⟩
instance : has_top (lower_set α) := ⟨⟨univ, λ a b h, id⟩⟩
instance : has_bot (lower_set α) := ⟨⟨∅, λ a b h, id⟩⟩
instance : has_Sup (lower_set α) := ⟨λ S, ⟨⋃ s ∈ S, ↑s, is_lower_set_Union₂ $ λ s _, s.lower⟩⟩
instance : has_Inf (lower_set α) := ⟨λ S, ⟨⋂ s ∈ S, ↑s, is_lower_set_Inter₂ $ λ s _, s.lower⟩⟩
instance : complete_distrib_lattice (lower_set α) :=
set_like.coe_injective.complete_distrib_lattice _
(λ _ _, rfl) (λ _ _, rfl) (λ _, rfl) (λ _, rfl) rfl rfl
instance : inhabited (lower_set α) := ⟨⊥⟩
@[simp] lemma coe_top : ((⊤ : lower_set α) : set α) = univ := rfl
@[simp] lemma coe_bot : ((⊥ : lower_set α) : set α) = ∅ := rfl
@[simp] lemma coe_sup (s t : lower_set α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_inf (s t : lower_set α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl
@[simp] lemma coe_Sup (S : set (lower_set α)) : (↑(Sup S) : set α) = ⋃ s ∈ S, ↑s := rfl
@[simp] lemma coe_Inf (S : set (lower_set α)) : (↑(Inf S) : set α) = ⋂ s ∈ S, ↑s := rfl
@[simp] lemma coe_supr (f : ι → lower_set α) : (↑(⨆ i, f i) : set α) = ⋃ i, f i :=
by simp_rw [supr, coe_Sup, mem_range, Union_exists, Union_Union_eq']
@[simp] lemma coe_infi (f : ι → lower_set α) : (↑(⨅ i, f i) : set α) = ⋂ i, f i :=
by simp_rw [infi, coe_Inf, mem_range, Inter_exists, Inter_Inter_eq']
@[simp] lemma coe_supr₂ (f : Π i, κ i → lower_set α) : (↑(⨆ i j, f i j) : set α) = ⋃ i j, f i j :=
by simp_rw coe_supr
@[simp] lemma coe_infi₂ (f : Π i, κ i → lower_set α) : (↑(⨅ i j, f i j) : set α) = ⋂ i j, f i j :=
by simp_rw coe_infi
@[simp] lemma mem_top : a ∈ (⊤ : lower_set α) := trivial
@[simp] lemma not_mem_bot : a ∉ (⊥ : lower_set α) := id
@[simp] lemma mem_sup_iff : a ∈ s ⊔ t ↔ a ∈ s ∨ a ∈ t := iff.rfl
@[simp] lemma mem_inf_iff : a ∈ s ⊓ t ↔ a ∈ s ∧ a ∈ t := iff.rfl
@[simp] lemma mem_Sup_iff : a ∈ Sup S ↔ ∃ s ∈ S, a ∈ s := mem_Union₂
@[simp] lemma mem_Inf_iff : a ∈ Inf S ↔ ∀ s ∈ S, a ∈ s := mem_Inter₂
@[simp] lemma mem_supr_iff {f : ι → lower_set α} : a ∈ (⨆ i, f i) ↔ ∃ i, a ∈ f i :=
by { rw [←set_like.mem_coe, coe_supr], exact mem_Union }
@[simp] lemma mem_infi_iff {f : ι → lower_set α} : a ∈ (⨅ i, f i) ↔ ∀ i, a ∈ f i :=
by { rw [←set_like.mem_coe, coe_infi], exact mem_Inter }
@[simp] lemma mem_supr₂_iff {f : Π i, κ i → lower_set α} : a ∈ (⨆ i j, f i j) ↔ ∃ i j, a ∈ f i j :=
by simp_rw mem_supr_iff
@[simp] lemma mem_infi₂_iff {f : Π i, κ i → lower_set α} : a ∈ (⨅ i j, f i j) ↔ ∀ i j, a ∈ f i j :=
by simp_rw mem_infi_iff
end lower_set
/-! #### Complement -/
/-- The complement of a lower set as an upper set. -/
def upper_set.compl (s : upper_set α) : lower_set α := ⟨sᶜ, s.upper.compl⟩
/-- The complement of a lower set as an upper set. -/
def lower_set.compl (s : lower_set α) : upper_set α := ⟨sᶜ, s.lower.compl⟩
namespace upper_set
variables {s t : upper_set α} {a : α}
@[simp] lemma coe_compl (s : upper_set α) : (s.compl : set α) = sᶜ := rfl
@[simp] lemma mem_compl_iff : a ∈ s.compl ↔ a ∉ s := iff.rfl
@[simp] lemma compl_compl (s : upper_set α) : s.compl.compl = s := upper_set.ext $ compl_compl _
@[simp] lemma compl_le_compl : s.compl ≤ t.compl ↔ s ≤ t := compl_subset_compl
@[simp] protected lemma compl_sup (s t : upper_set α) : (s ⊔ t).compl = s.compl ⊔ t.compl :=
lower_set.ext compl_inf
@[simp] protected lemma compl_inf (s t : upper_set α) : (s ⊓ t).compl = s.compl ⊓ t.compl :=
lower_set.ext compl_sup
@[simp] protected lemma compl_top : (⊤ : upper_set α).compl = ⊤ := lower_set.ext compl_empty
@[simp] protected lemma compl_bot : (⊥ : upper_set α).compl = ⊥ := lower_set.ext compl_univ
@[simp] protected lemma compl_Sup (S : set (upper_set α)) :
(Sup S).compl = ⨆ s ∈ S, upper_set.compl s :=
lower_set.ext $ by simp only [coe_compl, coe_Sup, compl_Inter₂, lower_set.coe_supr₂]
@[simp] protected lemma compl_Inf (S : set (upper_set α)) :
(Inf S).compl = ⨅ s ∈ S, upper_set.compl s :=
lower_set.ext $ by simp only [coe_compl, coe_Inf, compl_Union₂, lower_set.coe_infi₂]
@[simp] protected lemma compl_supr (f : ι → upper_set α) : (⨆ i, f i).compl = ⨆ i, (f i).compl :=
lower_set.ext $ by simp only [coe_compl, coe_supr, compl_Inter, lower_set.coe_supr]
@[simp] protected lemma compl_infi (f : ι → upper_set α) : (⨅ i, f i).compl = ⨅ i, (f i).compl :=
lower_set.ext $ by simp only [coe_compl, coe_infi, compl_Union, lower_set.coe_infi]
@[simp] lemma compl_supr₂ (f : Π i, κ i → upper_set α) :
(⨆ i j, f i j).compl = ⨆ i j, (f i j).compl :=
by simp_rw upper_set.compl_supr
@[simp] lemma compl_infi₂ (f : Π i, κ i → upper_set α) :
(⨅ i j, f i j).compl = ⨅ i j, (f i j).compl :=
by simp_rw upper_set.compl_infi
end upper_set
namespace lower_set
variables {s t : lower_set α} {a : α}
@[simp] lemma coe_compl (s : lower_set α) : (s.compl : set α) = sᶜ := rfl
@[simp] lemma mem_compl_iff : a ∈ s.compl ↔ a ∉ s := iff.rfl
@[simp] lemma compl_compl (s : lower_set α) : s.compl.compl = s := lower_set.ext $ compl_compl _
@[simp] lemma compl_le_compl : s.compl ≤ t.compl ↔ s ≤ t := compl_subset_compl
protected lemma compl_sup (s t : lower_set α) : (s ⊔ t).compl = s.compl ⊔ t.compl :=
upper_set.ext compl_sup
protected lemma compl_inf (s t : lower_set α) : (s ⊓ t).compl = s.compl ⊓ t.compl :=
upper_set.ext compl_inf
protected lemma compl_top : (⊤ : lower_set α).compl = ⊤ := upper_set.ext compl_univ
protected lemma compl_bot : (⊥ : lower_set α).compl = ⊥ := upper_set.ext compl_empty
protected lemma compl_Sup (S : set (lower_set α)) : (Sup S).compl = ⨆ s ∈ S, lower_set.compl s :=
upper_set.ext $ by simp only [coe_compl, coe_Sup, compl_Union₂, upper_set.coe_supr₂]
protected lemma compl_Inf (S : set (lower_set α)) : (Inf S).compl = ⨅ s ∈ S, lower_set.compl s :=
upper_set.ext $ by simp only [coe_compl, coe_Inf, compl_Inter₂, upper_set.coe_infi₂]
protected lemma compl_supr (f : ι → lower_set α) : (⨆ i, f i).compl = ⨆ i, (f i).compl :=
upper_set.ext $ by simp only [coe_compl, coe_supr, compl_Union, upper_set.coe_supr]
protected lemma compl_infi (f : ι → lower_set α) : (⨅ i, f i).compl = ⨅ i, (f i).compl :=
upper_set.ext $ by simp only [coe_compl, coe_infi, compl_Inter, upper_set.coe_infi]
@[simp] lemma compl_supr₂ (f : Π i, κ i → lower_set α) :
(⨆ i j, f i j).compl = ⨆ i j, (f i j).compl :=
by simp_rw lower_set.compl_supr
@[simp] lemma compl_infi₂ (f : Π i, κ i → lower_set α) :
(⨅ i j, f i j).compl = ⨅ i j, (f i j).compl :=
by simp_rw lower_set.compl_infi
end lower_set
/-- Upper sets are order-isomorphic to lower sets under complementation. -/
@[simps] def upper_set_iso_lower_set : upper_set α ≃o lower_set α :=
{ to_fun := upper_set.compl,
inv_fun := lower_set.compl,
left_inv := upper_set.compl_compl,
right_inv := lower_set.compl_compl,
map_rel_iff' := λ _ _, upper_set.compl_le_compl }
end has_le
/-! #### Principal sets -/
namespace upper_set
section preorder
variables [preorder α] {a b : α}
/-- The smallest upper set containing a given element. -/
def Ici (a : α) : upper_set α := ⟨Ici a, is_upper_set_Ici a⟩
/-- The smallest upper set containing a given element. -/
def Ioi (a : α) : upper_set α := ⟨Ioi a, is_upper_set_Ioi a⟩
@[simp] lemma coe_Ici (a : α) : ↑(Ici a) = set.Ici a := rfl
@[simp] lemma coe_Ioi (a : α) : ↑(Ioi a) = set.Ioi a := rfl
@[simp] lemma mem_Ici_iff : b ∈ Ici a ↔ a ≤ b := iff.rfl
@[simp] lemma mem_Ioi_iff : b ∈ Ioi a ↔ a < b := iff.rfl
lemma Icoi_le_Ioi (a : α) : Ici a ≤ Ioi a := Ioi_subset_Ici_self
@[simp] lemma Ioi_top [order_top α] : Ioi (⊤ : α) = ⊤ := set_like.coe_injective Ioi_top
@[simp] lemma Ici_bot [order_bot α] : Ici (⊥ : α) = ⊥ := set_like.coe_injective Ici_bot
end preorder
section semilattice_sup
variables [semilattice_sup α]
@[simp] lemma Ici_sup (a b : α) : Ici (a ⊔ b) = Ici a ⊔ Ici b := ext Ici_inter_Ici.symm
/-- `upper_set.Ici` as a `sup_hom`. -/
def Ici_sup_hom : sup_hom α (upper_set α) := ⟨Ici, Ici_sup⟩
@[simp] lemma Ici_sup_hom_apply (a : α) : Ici_sup_hom a = (Ici a) := rfl
end semilattice_sup
section complete_lattice
variables [complete_lattice α]
@[simp] lemma Ici_Sup (S : set α) : Ici (Sup S) = ⨆ a ∈ S, Ici a :=
set_like.ext $ λ c, by simp only [mem_Ici_iff, mem_supr_iff, Sup_le_iff]
@[simp] lemma Ici_supr (f : ι → α) : Ici (⨆ i, f i) = ⨆ i, Ici (f i) :=
set_like.ext $ λ c, by simp only [mem_Ici_iff, mem_supr_iff, supr_le_iff]
@[simp] lemma Ici_supr₂ (f : Π i, κ i → α) : Ici (⨆ i j, f i j) = ⨆ i j, Ici (f i j) :=
by simp_rw Ici_supr
/-- `upper_set.Ici` as a `Sup_hom`. -/
def Ici_Sup_hom : Sup_hom α (upper_set α) := ⟨Ici, λ s, (Ici_Sup s).trans Sup_image.symm⟩
@[simp] lemma Ici_Sup_hom_apply (a : α) : Ici_Sup_hom a = to_dual (Ici a) := rfl
end complete_lattice
end upper_set
namespace lower_set
section preorder
variables [preorder α] {a b : α}
/-- Principal lower set. `set.Iic` as a lower set. The smallest lower set containing a given
element. -/
def Iic (a : α) : lower_set α := ⟨Iic a, is_lower_set_Iic a⟩
/-- Strict principal lower set. `set.Iio` as a lower set. -/
def Iio (a : α) : lower_set α := ⟨Iio a, is_lower_set_Iio a⟩
@[simp] lemma coe_Iic (a : α) : ↑(Iic a) = set.Iic a := rfl
@[simp] lemma coe_Iio (a : α) : ↑(Iio a) = set.Iio a := rfl
@[simp] lemma mem_Iic_iff : b ∈ Iic a ↔ b ≤ a := iff.rfl
@[simp] lemma mem_Iio_iff : b ∈ Iio a ↔ b < a := iff.rfl
lemma Ioi_le_Ici (a : α) : Ioi a ≤ Ici a := Ioi_subset_Ici_self
@[simp] lemma Iic_top [order_top α] : Iic (⊤ : α) = ⊤ := set_like.coe_injective Iic_top
@[simp] lemma Iio_bot [order_bot α] : Iio (⊥ : α) = ⊥ := set_like.coe_injective Iio_bot
end preorder
section semilattice_inf
variables [semilattice_inf α]
@[simp] lemma Iic_inf (a b : α) : Iic (a ⊓ b) = Iic a ⊓ Iic b :=
set_like.coe_injective Iic_inter_Iic.symm
/-- `lower_set.Iic` as an `inf_hom`. -/
def Iic_inf_hom : inf_hom α (lower_set α) := ⟨Iic, Iic_inf⟩
@[simp] lemma coe_Iic_inf_hom : (Iic_inf_hom : α → lower_set α) = Iic := rfl
@[simp] lemma Iic_inf_hom_apply (a : α) : Iic_inf_hom a = Iic a := rfl
end semilattice_inf
section complete_lattice
variables [complete_lattice α]
@[simp] lemma Iic_Inf (S : set α) : Iic (Inf S) = ⨅ a ∈ S, Iic a :=
set_like.ext $ λ c, by simp only [mem_Iic_iff, mem_infi₂_iff, le_Inf_iff]
@[simp] lemma Iic_infi (f : ι → α) : Iic (⨅ i, f i) = ⨅ i, Iic (f i) :=
set_like.ext $ λ c, by simp only [mem_Iic_iff, mem_infi_iff, le_infi_iff]
@[simp] lemma Iic_infi₂ (f : Π i, κ i → α) : Iic (⨅ i j, f i j) = ⨅ i j, Iic (f i j) :=
by simp_rw Iic_infi
/-- `lower_set.Iic` as an `Inf_hom`. -/
def Iic_Inf_hom : Inf_hom α (lower_set α) := ⟨Iic, λ s, (Iic_Inf s).trans Inf_image.symm⟩
@[simp] lemma coe_Iic_Inf_hom : (Iic_Inf_hom : α → lower_set α) = Iic := rfl
@[simp] lemma Iic_Inf_hom_apply (a : α) : Iic_Inf_hom a = Iic a := rfl
end complete_lattice
end lower_set
|
5c89abc5464b9bd79cac09a92ced0eace65e7df1 | cc060cf567f81c404a13ee79bf21f2e720fa6db0 | /lean/20170502-monadic-if.lean | 6d2315f3a0df1a1993abd5a4e4fcb3ba723d007d | [
"Apache-2.0"
] | permissive | semorrison/proof | cf0a8c6957153bdb206fd5d5a762a75958a82bca | 5ee398aa239a379a431190edbb6022b1a0aa2c70 | refs/heads/master | 1,610,414,502,842 | 1,518,696,851,000 | 1,518,696,851,000 | 78,375,937 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 629 | lean |
private meta def if_then_else { α β : Type } ( i : tactic unit ) ( t : tactic β ) ( e : tactic β ) : tactic β :=
do r ← tactic.try_core i,
match r with
| some _ := t
| none := e
end
private meta def if_dthen_else { α β : Type } ( i : tactic α ) ( t : α → tactic β ) ( e : tactic β ) : tactic β :=
do r ← tactic.try_core i,
match r with
| some a := t a
| none := e
end
open tactic
meta def foo : tactic unit := if_dthen_else dsimp (λ x, dsimp) dsimp
-- def mcond {m : Type → Type} [monad m] {α : Type} (mbool : m bool) (tm fm : m α) : m α :=
-- do b ← mbool, cond b tm fm
|
43f4fdb1e533d2356b8d97d02ea2a27a30531c46 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/metric_space/gromov_hausdorff.lean | 9033f3d784633be898fd59c48ddbfe8d9e57f183 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 55,286 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import set_theory.cardinal.basic
import topology.metric_space.closeds
import topology.metric_space.completion
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.kuratowski
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topological_space ennreal
local notation `ℓ_infty_ℝ`:= lp (λ n : ℕ, ℝ) ∞
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat int Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private def isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λ x y, nonempty (x ≃ᵢ y)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λ x, ⟨isometric.refl _⟩, λ x y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (X : Type u) [metric_space X] [compact_space X] [nonempty X] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding X⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨⟨{0}, is_compact_singleton⟩, singleton_nonempty _⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
@[nolint has_inhabited_instance]
def GH_space.rep (p : GH_space) : Type := (quotient.out p : nonempty_compacts ℓ_infty_ℝ)
lemma eq_to_GH_space_iff {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space X ↔ ∃ Ψ : X → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p :=
begin
simp only [to_GH_space, quotient.eq],
refine ⟨λ h, _, _⟩,
{ rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry X).isometric_on_range.trans e,
use [λ x, f x, isometry_subtype_coe.comp f.isometry],
rw [range_comp, f.range_eq_univ, set.image_univ, subtype.range_coe],
refl },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry X).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ ≃ᵢ nonempty_compacts.Kuratowski_embedding X) =
(p ≃ᵢ range (Kuratowski_embedding X)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
exact ⟨cast E f⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p :=
eq_to_GH_space_iff.2 ⟨λ x, x, isometry_subtype_coe, subtype.range_coe⟩
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space p.rep := by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space p.rep := by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty p.rep := by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space p.rep = p :=
begin
change to_GH_space (quot.out p : nonempty_compacts ℓ_infty_ℝ) = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are
isometric. -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {X : Type u} [metric_space X] [compact_space X]
[nonempty X] {Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
to_GH_space X = to_GH_space Y ↔ nonempty (X ≃ᵢ Y) :=
⟨begin
simp only [to_GH_space, quotient.eq],
rintro ⟨e⟩,
have I : ((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y))
= ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have f := (Kuratowski_embedding.isometry X).isometric_on_range,
have g := (Kuratowski_embedding.isometry Y).isometric_on_range.symm,
exact ⟨f.trans $ (cast I e).trans g⟩
end,
begin
rintro ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding.isometry X).isometric_on_range.symm,
have g := (Kuratowski_embedding.isometry Y).isometric_on_range,
have I : ((range (Kuratowski_embedding X)) ≃ᵢ (range (Kuratowski_embedding Y))) =
((nonempty_compacts.Kuratowski_embedding X) ≃ᵢ
(nonempty_compacts.Kuratowski_embedding Y)),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
exact ⟨cast I ((f.trans e).trans g)⟩
end⟩
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λ x y, Inf $
(λ p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ,
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) '' ({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (X : Type u) (Y : Type v) [metric_space X] [nonempty X] [compact_space X]
[metric_space Y] [nonempty Y] [compact_space Y] : ℝ := dist (to_GH_space X) (to_GH_space Y)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist p.rep (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
{γ : Type w} [metric_space γ] {Φ : X → γ} {Ψ : Y → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist X Y ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `X` and `Y` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : X → subtype s := λ y, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : Y → subtype s := λ y, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λ x y, ha x y,
have IΨ' : isometry Ψ' := λ x y, hb x y,
have : is_compact s, from (is_compact_range ha.continuous).union (is_compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨is_compact_iff_is_compact_univ.1 ‹is_compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xX⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_coe) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) =
Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `X` and `Y` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Φ'), (is_compact_range IΦ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨⟨F '' (range Ψ'), (is_compact_range IΨ'.continuous).image
(Kuratowski_embedding.isometry _).continuous⟩, (range_nonempty _).image _⟩,
have AX : ⟦A⟧ = to_GH_space X,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Φ' x), (Kuratowski_embedding.isometry _).comp IΦ', range_comp _ _⟩ },
have BY : ⟦B⟧ = to_GH_space Y,
{ rw eq_to_GH_space_iff,
exact ⟨λ x, F (Ψ' x), (Kuratowski_embedding.isometry _).comp IΨ', range_comp _ _⟩ },
refine cInf_le ⟨0,
begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _,
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [AX, BY],
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y] :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) = GH_dist X Y :=
begin
inhabit X, inhabit Y,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `X ⊕ Y` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y) →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y),
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : ∃ y ∈ range Ψ, dist (Φ xX) y < diam (univ : set X) + 1 + diam (univ : set Y),
{ rw Ψrange,
have : Φ xX ∈ ↑p := Φrange.subst (mem_range_self _),
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.compact.bounded q.compact.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set X) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set Y) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xX) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set X) + (diam (univ : set X) + 1 + diam (univ : set Y)) +
diam (univ : set Y) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add le_rfl (le_of_lt dy)) le_rfl }
... = 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : by ring },
let f : X ⊕ Y → ℓ_infty_ℝ := λ x, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (X ⊕ Y) × (X ⊕ Y) → ℝ := λ p, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates X Y,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λ x y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λ x y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λ x y, dist_comm _ _ },
{ exact λ x y z, dist_triangle _ _ _ },
{ exact λ x y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀ z : X ⊕ Y, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p ⊔ q).compact.bounded,
end
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λ r hr, _)),
have I1 : ∀ x : X, (⨅ y, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ ↑p := Φrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.compact.bounded q.compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc (⨅ y, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux1 0) y
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀ y : Y, (⨅ x, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ ↑q := Ψrange.subst (mem_range_self _),
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.nonempty q.nonempty
p.compact.bounded q.compact.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc (⨅ x, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux2 0) x
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp [HD, csupr_le I1, csupr_le I2] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀ p q : nonempty_compacts ℓ_infty_ℝ, ⟦p⟧ = to_GH_space X → ⟦q⟧ = to_GH_space Y →
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤
Hausdorff_dist (p : set ℓ_infty_ℝ) q,
{ assume p q hp hq,
by_cases h :
Hausdorff_dist (p : set ℓ_infty_ℝ) q < diam (univ : set X) + 1 + diam (univ : set Y),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y))
≤ HD (candidates_b_dist X Y) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p : set ℓ_infty_ℝ) q : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl X Y) (isometry_optimal_GH_injr X Y) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (X : Type u) [metric_space X] [compact_space X] [nonempty X]
(Y : Type v) [metric_space Y] [compact_space Y] [nonempty Y] :
∃ Φ : X → ℓ_infty_ℝ, ∃ Ψ : Y → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist X Y = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling X Y),
let Φ := F ∘ optimal_GH_injl X Y,
let Ψ := F ∘ optimal_GH_injr X Y,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl X Y) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr X Y) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr X Y),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance : metric_space GH_space :=
{ dist := dist,
dist_self := λ x, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp, existsi [y, y], simpa } },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λ x y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist (p.1 : set ℓ_infty_ℝ) p.2) ∘ prod.swap) ''
({a | ⟦a⟧ = x} ×ˢ {b | ⟦b⟧ = y}) :=
by { congr, funext, simp, rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, image_swap_prod],
end,
eq_of_dist_eq_zero := λ x y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : is_compact (range Φ) := is_compact_range Φisom.continuous,
have hΨ : is_compact (range Ψ) := is_compact_range Ψisom.continuous,
apply (is_closed.Hausdorff_dist_zero_iff_eq _ _ _).1 (DΦΨ.symm),
{ exact hΦ.is_closed },
{ exact hΨ.is_closed },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λ x y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y` and `Z` in a space
`γ2`. Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) =
(to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (is_compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [← range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {X : Type u} [metric_space X]
(p : nonempty_compacts X) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {X : Type u} [metric_space X]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts X) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (coe : p → X) := isometry_subtype_coe,
have hb : isometry (coe : q → X) := isometry_subtype_coe,
have A : dist p q = Hausdorff_dist (p : set X) q := rfl,
have I : ↑p = range (coe : p → X) := subtype.range_coe_subtype.symm,
have J : ↑q = range (coe : q → X) := subtype.range_coe_subtype.symm,
rw [A, I, J],
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts X → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff
distance between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable
coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {X : Type u} [metric_space X] [compact_space X] [nonempty X]
{Y : Type v} [metric_space Y] [compact_space Y] [nonempty Y]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set X} (Φ : s → Y) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀ x : X, ∃ y ∈ s, dist x y ≤ ε₁) (hs' : ∀ x : Y, ∃ y : s, dist x (Φ y) ≤ ε₃)
(H : ∀ x y : s, |dist x y - dist (Φ x) (Φ y)| ≤ ε₂) :
GH_dist X Y ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine le_of_forall_pos_le_add (λ δ δ0, _),
rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
rcases hs xX with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, |dist p q - dist (Φ p) (Φ q)| ≤ 2 * (ε₂/2 + δ) := λ p q, calc
|dist p q - dist (Φ p) (Φ q)| ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `X` and `Y` along the almost matching subsets
letI : metric_space (X ⊕ Y) :=
glue_metric_approx (λ x:s, (x:X)) (λ x, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl X Y,
let Fr := @sum.inr X Y,
have Il : isometry Fl := isometry_emetric_iff_metric.2 (λ x y, rfl),
have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λ x y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images
in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff
distances of `X` and `s` (in the coupling or, equivalently in the original space), of `s` and
`Φ s`, and of `Φ s` and `Y` (in the coupling or, equivalently, in the original space). The first
term is bounded by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is
bounded by `ε₂/2` as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by
construction of the coupling (in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive
constant where positivity is used to ensure that the coupling is really a metric space and not a
premetric space on `X ⊕ Y`). -/
have : GH_dist X Y ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (is_compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.mono (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (is_compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.mono (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, hs x)
(λ x hx, ⟨x, mem_univ _, by simpa⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:X)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val X s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty Y with ⟨xY, _⟩,
rcases hs' xY with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λ x hx, ⟨x, mem_univ _, by simpa⟩) (λ x _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λ δ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀ p:GH_space, ∃ s : set p.rep, s.finite ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λ p, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀ p:GH_space, ∀ t:set p.rep, t.finite → ∃ n:ℕ, ∃ e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
exact ⟨fintype.card t, fintype.equiv_fin t, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λ p:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λ p:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋⟩,
refine ⟨Σ n, fin n → fin n → ℤ, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).is_lt,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀ p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀ p ∈ t, ∀ n:ℕ, ∃ s : set (GH_space.rep p),
cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λ δ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n le_rfl,
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀ p:GH_space, ∃ s : set p.rep, ∃ N ≤ K n, ∃ E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set p.rep) (fin 0)),
{ rw ← fintype.card_eq, simp },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_aleph_0.1 (lt_of_le_of_lt scard (cardinal.nat_lt_aleph_0 _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp [hp, scover] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := ⌊ε⁻¹ * max C 0⌋₊,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λ p, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λ a b, ⟨min M ⌊ε⁻¹ * dist ((E p).symm a) ((E p).symm b)⌋₊,
( min_le_left _ _).trans_lt (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, _, (λ p, F p), _⟩, apply_instance,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λ x, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λ x, Ψ x,
have main : GH_dist p.rep (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀ x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀ x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_Union₂.1 this with ⟨y, ys, hy⟩,
let i : ℕ := E q ⟨y, ys⟩,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw [fin.ext_iff, fin.coe_mk],
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩,
by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀ x y : s p, |dist x y - dist (Φ x) (Φ y)| ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i : ℕ := E p x,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)), by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j : ℕ := E p y,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)), by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ⌊ε⁻¹ * dist x y⌋₊ := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M ⌊ε⁻¹ * dist x y⌋₊ :
by simp only [F, (E p).symm_apply_apply]
... = ⌊ε⁻¹ * dist x y⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }
... = min M ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
by simp only [F, (E q).symm_apply_apply]
... = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋₊ :
begin
refine min_eq_right (nat.floor_mono _),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) ((inv_pos.2 εpos).le),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : ⌊ε⁻¹ * dist x y⌋ = ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋,
{ rw [Ap, Aq] at this,
have D : 0 ≤ ⌊ε⁻¹ * dist x y⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : 0 ≤ ⌊ε⁻¹ * dist (Ψ x) (Ψ y)⌋ :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', int.floor_to_nat,int.floor_to_nat,
this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)| =
|ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))| : (abs_mul _ _).symm
... = |(ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))| : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
|dist x y - dist (Ψ x) (Ψ y)| = (ε * ε⁻¹) * |dist x y - dist (Ψ x) (Ψ y)| :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (|ε⁻¹| * |dist x y - dist (Ψ x) (Ψ y)|) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist p.rep (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp [ε], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀ n, metric_space (X n)] [∀ n, compact_space (X n)] [∀ n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
instance (A : Type) [metric_space A] : inhabited (aux_gluing_struct A) :=
⟨{ space := A,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }⟩
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λ x y, rfl }
(λ n Y, by letI : metric_space Y.space := Y.metric; exact
{ space := glue_space Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))),
metric := by apply_instance,
embed := (to_glue_r Y.isom (isometry_optimal_GH_injl (X n) (X (n+1))))
∘ (optimal_GH_injr (X n) (X (n+1))),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X (n+1))) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space GH_space :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λ n, (1/2)^n) this (λ u hu, _),
-- `X n` is a representative of `u n`
let X := λ n, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
letI : ∀ n, metric_space (Y n).space := λ n, (Y n).metric,
have E : ∀ n : ℕ,
glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λ n, by { simp [Y, aux_gluing], refl },
let c := λ n, cast (E n),
have ic : ∀ n, isometry (c n) := λ n x y, rfl,
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λ n, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀ n, isometry (f n),
{ assume n,
apply isometry.comp,
{ assume x y, refl },
{ apply to_glue_l_isometry } },
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λ n, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀ n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
refine uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp (Y n).isom },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀ n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply uniform_space.completion.coe_isometry.comp _,
exact (to_inductive_limit_isometry _ _).comp ((ic n).comp (to_glue_r_isometry _ _)) } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λ n,
⟨⟨X2 n, is_compact_range (isom n).continuous⟩, range_nonempty _⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λ n, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λ n, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀ n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
constructor,
convert (isom n).isometric_on_range.symm, },
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
fcde6f0e09ecbc149ff2491c43f6546642b8ba95 | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /src/Init/Lean/Compiler/IR/Basic.lean | a85f56e7daac55768d3ecf998f9140bd9cfcdb72 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 25,720 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.Data.Array
import Init.Lean.Data.KVMap
import Init.Lean.Data.Name
import Init.Lean.Data.Format
import Init.Lean.Compiler.ExternAttr
/-
Implements (extended) λPure and λRc proposed in the article
"Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura.
The Lean to IR transformation produces λPure code, and
this part is implemented in C++. The procedures described in the paper
above are implemented in Lean.
-/
namespace Lean
namespace IR
/- Function identifier -/
abbrev FunId := Name
abbrev Index := Nat
/- Variable identifier -/
structure VarId :=
(idx : Index)
/- Join point identifier -/
structure JoinPointId :=
(idx : Index)
abbrev Index.lt (a b : Index) : Bool := a < b
namespace VarId
instance : HasBeq VarId := ⟨fun a b => a.idx == b.idx⟩
instance : HasToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩
instance : HasFormat VarId := ⟨fun a => toString a⟩
instance : Hashable VarId := ⟨fun a => hash a.idx⟩
end VarId
namespace JoinPointId
instance : HasBeq JoinPointId := ⟨fun a b => a.idx == b.idx⟩
instance : HasToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩
instance : HasFormat JoinPointId := ⟨fun a => toString a⟩
instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩
end JoinPointId
abbrev MData := KVMap
namespace MData
abbrev empty : MData := {KVMap .}
instance : HasEmptyc MData := ⟨empty⟩
end MData
/- Low Level IR types. Most are self explanatory.
- `usize` represents the C++ `size_t` Type. We have it here
because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines,
and we want the C++ backend for our Compiler to generate platform independent code.
- `irrelevant` for Lean types, propositions and proofs.
- `object` a pointer to a value in the heap.
- `tobject` a pointer to a value in the heap or tagged pointer
(i.e., the least significant bit is 1) storing a scalar value.
- `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`)
on the stack.
Remark: the RC operations for `tobject` are slightly more expensive because we
first need to test whether the `tobject` is really a pointer or not.
Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT).
Lean cannot be compiled on old platforms where this is not True.
Since values of type `struct` and `union` are only used to return values,
We assume they must be used/consumed "linearly". We use the term "linear" here
to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct,
then one of the following must hold in each (execution) branch.
1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned.
2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`.
3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each
of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union
fields that do not contain object fields.
-/
inductive IRType
| float | uint8 | uint16 | uint32 | uint64 | usize
| irrelevant | object | tobject
| struct (leanTypeName : Option Name) (types : Array IRType) : IRType
| union (leanTypeName : Name) (types : Array IRType) : IRType
namespace IRType
partial def beq : IRType → IRType → Bool
| float, float => true
| uint8, uint8 => true
| uint16, uint16 => true
| uint32, uint32 => true
| uint64, uint64 => true
| usize, usize => true
| irrelevant, irrelevant => true
| object, object => true
| tobject, tobject => true
| struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| _, _ => false
instance HasBeq : HasBeq IRType := ⟨beq⟩
def isScalar : IRType → Bool
| float => true
| uint8 => true
| uint16 => true
| uint32 => true
| uint64 => true
| usize => true
| _ => false
def isObj : IRType → Bool
| object => true
| tobject => true
| _ => false
def isIrrelevant : IRType → Bool
| irrelevant => true
| _ => false
def isStruct : IRType → Bool
| struct _ _ => true
| _ => false
def isUnion : IRType → Bool
| union _ _ => true
| _ => false
end IRType
/- Arguments to applications, constructors, etc.
We use `irrelevant` for Lean types, propositions and proofs that have been erased.
Recall that for a Function `f`, we also generate `f._rarg` which does not take
`irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/
inductive Arg
| var (id : VarId)
| irrelevant
namespace Arg
protected def beq : Arg → Arg → Bool
| var x, var y => x == y
| irrelevant, irrelevant => true
| _, _ => false
instance : HasBeq Arg := ⟨Arg.beq⟩
instance : Inhabited Arg := ⟨irrelevant⟩
end Arg
@[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id
inductive LitVal
| num (v : Nat)
| str (v : String)
def LitVal.beq : LitVal → LitVal → Bool
| LitVal.num v₁, LitVal.num v₂ => v₁ == v₂
| LitVal.str v₁, LitVal.str v₂ => v₁ == v₂
| _, _ => false
instance LitVal.HasBeq : HasBeq LitVal := ⟨LitVal.beq⟩
/- Constructor information.
- `name` is the Name of the Constructor in Lean.
- `cidx` is the Constructor index (aka tag).
- `size` is the number of arguments of type `object/tobject`.
- `usize` is the number of arguments of type `usize`.
- `ssize` is the number of bytes used to store scalar values.
Recall that a Constructor object contains a header, then a sequence of
pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`)
scalar values, and a sequence of other scalar values. -/
structure CtorInfo :=
(name : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat)
def CtorInfo.beq : CtorInfo → CtorInfo → Bool
| ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ =>
n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂
instance CtorInfo.HasBeq : HasBeq CtorInfo := ⟨CtorInfo.beq⟩
def CtorInfo.isRef (info : CtorInfo) : Bool :=
info.size > 0 || info.usize > 0 || info.ssize > 0
def CtorInfo.isScalar (info : CtorInfo) : Bool :=
!info.isRef
inductive Expr
/- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime.
This instruction is also used to creat `struct` and `union` return values.
For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/
| ctor (i : CtorInfo) (ys : Array Arg)
| reset (n : Nat) (x : VarId)
/- `reuse x in ctor_i ys` instruction in the paper. -/
| reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg)
/- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`.
We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/
| proj (i : Nat) (x : VarId)
/- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/
| uproj (i : Nat) (x : VarId)
/- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/
| sproj (n : Nat) (offset : Nat) (x : VarId)
/- Full application. -/
| fap (c : FunId) (ys : Array Arg)
/- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/
| pap (c : FunId) (ys : Array Arg)
/- Application. `x` must be a `pap` value. -/
| ap (x : VarId) (ys : Array Arg)
/- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`.
For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/
| box (ty : IRType) (x : VarId)
/- Given `x : [t]object`, obtain the scalar value. -/
| unbox (x : VarId)
| lit (v : LitVal)
/- Return `1 : uint8` Iff `RC(x) > 1` -/
| isShared (x : VarId)
/- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/
| isTaggedPtr (x : VarId)
@[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys
@[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x
@[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x
@[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x
@[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys
@[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys
@[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys
@[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v)
@[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v)
structure Param :=
(x : VarId) (borrow : Bool) (ty : IRType)
instance paramInh : Inhabited Param := ⟨{ x := { idx := 0 }, borrow := false, ty := IRType.object }⟩
@[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩
inductive AltCore (FnBody : Type) : Type
| ctor (info : CtorInfo) (b : FnBody) : AltCore
| default (b : FnBody) : AltCore
inductive FnBody
/- `let x : ty := e; b` -/
| vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody)
/- Join point Declaration `block_j (xs) := e; b` -/
| jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody)
/- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
This operation is not part of λPure is only used during optimization. -/
| set (x : VarId) (i : Nat) (y : Arg) (b : FnBody)
| setTag (x : VarId) (cidx : Nat) (b : FnBody)
/- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/
| uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody)
/- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
`ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/
| sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody)
/- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
/- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
| del (x : VarId) (b : FnBody)
| mdata (d : MData) (b : FnBody)
| case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody))
| ret (x : Arg)
/- Jump to join point `j` -/
| jmp (j : JoinPointId) (ys : Array Arg)
| unreachable
instance : Inhabited FnBody := ⟨FnBody.unreachable⟩
abbrev FnBody.nil := FnBody.unreachable
@[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b
@[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b
@[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b
@[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b
@[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody :=
-- Tyhe field `xType` is set by `explicitBoxing` compiler pass.
FnBody.case tid x IRType.object cs
@[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x
@[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys
@[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable
abbrev Alt := AltCore FnBody
@[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody
@[matchPattern] abbrev Alt.default := @AltCore.default FnBody
instance altInh : Inhabited Alt :=
⟨Alt.default (arbitrary _)⟩
def FnBody.isTerminal : FnBody → Bool
| FnBody.case _ _ _ _ => true
| FnBody.ret _ => true
| FnBody.jmp _ _ => true
| FnBody.unreachable => true
| _ => false
def FnBody.body : FnBody → FnBody
| FnBody.vdecl _ _ _ b => b
| FnBody.jdecl _ _ _ b => b
| FnBody.set _ _ _ b => b
| FnBody.uset _ _ _ b => b
| FnBody.sset _ _ _ _ _ b => b
| FnBody.setTag _ _ b => b
| FnBody.inc _ _ _ _ b => b
| FnBody.dec _ _ _ _ b => b
| FnBody.del _ b => b
| FnBody.mdata _ b => b
| other => other
def FnBody.setBody : FnBody → FnBody → FnBody
| FnBody.vdecl x t v _, b => FnBody.vdecl x t v b
| FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b
| FnBody.set x i y _, b => FnBody.set x i y b
| FnBody.uset x i y _, b => FnBody.uset x i y b
| FnBody.sset x i o y t _, b => FnBody.sset x i o y t b
| FnBody.setTag x i _, b => FnBody.setTag x i b
| FnBody.inc x n c p _, b => FnBody.inc x n c p b
| FnBody.dec x n c p _, b => FnBody.dec x n c p b
| FnBody.del x _, b => FnBody.del x b
| FnBody.mdata d _, b => FnBody.mdata d b
| other, b => other
@[inline] def FnBody.resetBody (b : FnBody) : FnBody :=
b.setBody FnBody.nil
/- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`,
and c.body == FnBody.nil -/
@[inline] def FnBody.split (b : FnBody) : FnBody × FnBody :=
let b' := b.body;
let c := b.resetBody;
(c, b')
def AltCore.body : Alt → FnBody
| Alt.ctor _ b => b
| Alt.default b => b
def AltCore.setBody : Alt → FnBody → Alt
| Alt.ctor c _, b => Alt.ctor c b
| Alt.default _, b => Alt.default b
@[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt
| Alt.ctor c b => Alt.ctor c (f b)
| Alt.default b => Alt.default (f b)
@[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt
| Alt.ctor c b => Alt.ctor c <$> f b
| Alt.default b => Alt.default <$> f b
def Alt.isDefault : Alt → Bool
| Alt.ctor _ _ => false
| Alt.default _ => true
def push (bs : Array FnBody) (b : FnBody) : Array FnBody :=
let b := b.resetBody;
bs.push b
partial def flattenAux : FnBody → Array FnBody → (Array FnBody) × FnBody
| b, r =>
if b.isTerminal then (r, b)
else flattenAux b.body (push r b)
def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody :=
flattenAux b #[]
partial def reshapeAux : Array FnBody → Nat → FnBody → FnBody
| a, i, b =>
if i == 0 then b
else
let i := i - 1;
let (curr, a) := a.swapAt! i (arbitrary _);
let b := curr.setBody b;
reshapeAux a i b
def reshape (bs : Array FnBody) (term : FnBody) : FnBody :=
reshapeAux bs bs.size term
@[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody :=
bs.map $ fun b => match b with
| FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k
| other => other
@[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) :=
bs.mapM $ fun b => match b with
| FnBody.jdecl j xs v k => do v ← f v; pure $ FnBody.jdecl j xs v k
| other => pure other
@[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b
inductive Decl
| fdecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody)
| extern (f : FunId) (xs : Array Param) (ty : IRType) (ext : ExternAttrData)
namespace Decl
instance : Inhabited Decl :=
⟨fdecl (arbitrary _) (arbitrary _) IRType.irrelevant (arbitrary _)⟩
def name : Decl → FunId
| Decl.fdecl f _ _ _ => f
| Decl.extern f _ _ _ => f
def params : Decl → Array Param
| Decl.fdecl _ xs _ _ => xs
| Decl.extern _ xs _ _ => xs
def resultType : Decl → IRType
| Decl.fdecl _ _ t _ => t
| Decl.extern _ _ t _ => t
def isExtern : Decl → Bool
| Decl.extern _ _ _ _ => true
| _ => false
end Decl
@[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b
@[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl :=
Decl.extern f xs ty e
/-- Set of variable and join point names -/
abbrev IndexSet := RBTree Index Index.lt
instance vsetInh : Inhabited IndexSet := ⟨{}⟩
def mkIndexSet (idx : Index) : IndexSet :=
RBTree.empty.insert idx
inductive LocalContextEntry
| param : IRType → LocalContextEntry
| localVar : IRType → Expr → LocalContextEntry
| joinPoint : Array Param → FnBody → LocalContextEntry
abbrev LocalContext := RBMap Index LocalContextEntry Index.lt
def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext :=
ctx.insert x.idx (LocalContextEntry.localVar t v)
def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext :=
ctx.insert j.idx (LocalContextEntry.joinPoint xs b)
def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext :=
ctx.insert p.x.idx (LocalContextEntry.param p.ty)
def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext :=
ps.foldl LocalContext.addParam ctx
def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.joinPoint _ _) => true
| other => false
def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint _ b) => some b
| other => none
def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint ys _) => some ys
| other => none
def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.param _) => true
| other => false
def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.localVar _ _) => true
| other => false
def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool :=
ctx.contains idx
def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext :=
ctx.erase j.idx
def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType :=
match ctx.find? x.idx with
| some (LocalContextEntry.param t) => some t
| some (LocalContextEntry.localVar t _) => some t
| other => none
def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr :=
match ctx.find? x.idx with
| some (LocalContextEntry.localVar _ v) => some v
| other => none
abbrev IndexRenaming := RBMap Index Index Index.lt
class HasAlphaEqv (α : Type) :=
(aeqv : IndexRenaming → α → α → Bool)
export HasAlphaEqv (aeqv)
def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool :=
match ρ.find? v₁.idx with
| some v => v == v₂.idx
| none => v₁ == v₂
instance VarId.hasAeqv : HasAlphaEqv VarId := ⟨VarId.alphaEqv⟩
def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool
| Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂
| Arg.irrelevant, Arg.irrelevant => true
| _, _ => false
instance Arg.hasAeqv : HasAlphaEqv Arg := ⟨Arg.alphaEqv⟩
def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool :=
Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b)
instance args.hasAeqv : HasAlphaEqv (Array Arg) := ⟨args.alphaEqv⟩
def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool
| Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂
| Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂
| Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂
| Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂
| Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₂ ys₂
| Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂
| Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂
| Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂
| Expr.lit v₁, Expr.lit v₂ => v₁ == v₂
| Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂
| Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂
| _, _ => false
instance Expr.hasAeqv : HasAlphaEqv Expr:= ⟨Expr.alphaEqv⟩
def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) :=
if x₁ == x₂ then ρ else ρ.insert x₁ x₂
def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming :=
if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx)
else none
def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming :=
if ps₁.size != ps₂.size then none
else Array.foldl₂ (fun ρ p₁ p₂ => do ρ ← ρ; addParamRename ρ p₁ p₂) (some ρ) ps₁ ps₂
partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool
| ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && FnBody.alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂
| ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with
| some ρ' => FnBody.alphaEqv ρ' v₁ v₂ && FnBody.alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂
| none => false
| ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ =>
aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ =>
match alt₁, alt₂ with
| Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && FnBody.alphaEqv ρ b₁ b₂
| Alt.default b₁, Alt.default b₂ => FnBody.alphaEqv ρ b₁ b₂
| _, _ => false)
| ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂
| ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂
| _, FnBody.unreachable, FnBody.unreachable => true
| _, _, _ => false
def FnBody.beq (b₁ b₂ : FnBody) : Bool :=
FnBody.alphaEqv ∅ b₁ b₂
instance FnBody.HasBeq : HasBeq FnBody := ⟨FnBody.beq⟩
abbrev VarIdSet := RBTree VarId (fun x y => x.idx < y.idx)
namespace VarIdSet
instance : Inhabited VarIdSet := ⟨{}⟩
end VarIdSet
def mkIf (x : VarId) (t e : FnBody) : FnBody :=
FnBody.case `Bool x IRType.uint8 #[
Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e,
Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t
]
end IR
end Lean
|
1f9cf189edd2e51262e60618d276291641b9e52b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/instances/rat.lean | 7cf21dd48f17751ad01bb5516f735bf44607d7c1 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 4,108 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import topology.metric_space.basic
import topology.algebra.order.archimedean
import topology.instances.int
import topology.instances.nat
import topology.instances.real
/-!
# Topology on the ratonal numbers
The structure of a metric space on `ℚ` is introduced in this file, induced from `ℝ`.
-/
open metric set filter
namespace rat
-- without the `by exact` this is noncomputable
instance : metric_space ℚ :=
metric_space.induced coe (by exact rat.cast_injective) real.metric_space
theorem dist_eq (x y : ℚ) : dist x y = |x - y| := rfl
@[norm_cast, simp] lemma dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl
theorem uniform_continuous_coe_real : uniform_continuous (coe : ℚ → ℝ) :=
uniform_continuous_comap
theorem uniform_embedding_coe_real : uniform_embedding (coe : ℚ → ℝ) :=
uniform_embedding_comap rat.cast_injective
theorem dense_embedding_coe_real : dense_embedding (coe : ℚ → ℝ) :=
uniform_embedding_coe_real.dense_embedding rat.dense_range_cast
theorem embedding_coe_real : embedding (coe : ℚ → ℝ) := dense_embedding_coe_real.to_embedding
theorem continuous_coe_real : continuous (coe : ℚ → ℝ) := uniform_continuous_coe_real.continuous
end rat
@[norm_cast, simp] theorem nat.dist_cast_rat (x y : ℕ) : dist (x : ℚ) y = dist x y :=
by rw [← nat.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast
lemma nat.uniform_embedding_coe_rat : uniform_embedding (coe : ℕ → ℚ) :=
uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using nat.pairwise_one_le_dist
lemma nat.closed_embedding_coe_rat : closed_embedding (coe : ℕ → ℚ) :=
closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using nat.pairwise_one_le_dist
@[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y :=
by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast
lemma int.uniform_embedding_coe_rat : uniform_embedding (coe : ℤ → ℚ) :=
uniform_embedding_bot_of_pairwise_le_dist zero_lt_one $ by simpa using int.pairwise_one_le_dist
lemma int.closed_embedding_coe_rat : closed_embedding (coe : ℤ → ℚ) :=
closed_embedding_of_pairwise_le_dist zero_lt_one $ by simpa using int.pairwise_one_le_dist
namespace rat
instance : noncompact_space ℚ := int.closed_embedding_coe_rat.noncompact_space
-- TODO(Mario): Find a way to use rat_add_continuous_lemma
theorem uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) :=
rat.uniform_embedding_coe_real.to_uniform_inducing.uniform_continuous_iff.2 $
by simp only [(∘), rat.cast_add]; exact real.uniform_continuous_add.comp
(rat.uniform_continuous_coe_real.prod_map rat.uniform_continuous_coe_real)
theorem uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) :=
metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h,
by rw dist_comm at h; simpa [rat.dist_eq] using h⟩
instance : uniform_add_group ℚ :=
uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg
instance : topological_add_group ℚ := by apply_instance
instance : order_topology ℚ :=
induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _)
lemma uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) :=
metric.uniform_continuous_iff.2 $ λ ε ε0,
⟨ε, ε0, λ a b h, lt_of_le_of_lt
(by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩
lemma continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) :=
rat.embedding_coe_real.continuous_iff.2 $ by simp [(∘)]; exact
real.continuous_mul.comp ((rat.continuous_coe_real.prod_map rat.continuous_coe_real))
instance : topological_ring ℚ :=
{ continuous_mul := rat.continuous_mul, ..rat.topological_add_group }
lemma totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) :=
by simpa only [preimage_cast_Icc]
using totally_bounded_preimage rat.uniform_embedding_coe_real (totally_bounded_Icc a b)
end rat
|
fc7dafd7ea35212eae326cc9f5d409f7670fb0fd | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /old/realization.lean | 4bbe475d999105e61b433f28d27d1db80a7f733b | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 23,279 | lean | /-
Copyright (c) 2019 The Flypitch Project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jesse Han, Floris van Doorn
-/
import .fol data.zmod.basic
open fol
-- local attribute [instance, priority 0] classical.prop_decidable
--local attribute [instance] classical.prop_decidable
local notation h :: t := dvector.cons h t
local notation `[]` := dvector.nil
local notation `[` l:(foldr `, ` (h t, dvector.cons h t) dvector.nil `]`) := l
namespace realization
/- Note: maybe some of the _irrel lemmas should be called something_elim instead -/
-- section fin_lemmas
-- open fin
-- variable n : ℕ
-- @[simp]lemma of_nat_zero : @of_nat n 0 = 0 := rfl
-- @[simp]lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n :=
-- show (fin.add a b).val = (a.val + b.val) % n, from
-- by cases a; cases b; simp [fin.add]
-- @[simp]lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n :=
-- show (fin.mul a b).val = (a.val * b.val) % n, from
-- by cases a; cases b; simp [fin.mul]
-- @[simp]lemma sub_def (a b : fin n) : (a - b).val = a.val - b.val :=
-- show (fin.sub a b).val = a.val - b.val, from
-- by cases a; cases b; simp [fin.sub]
-- @[simp]lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val :=
-- show (fin.mod a b).val = a.val % b.val, from
-- by cases a; cases b; simp [fin.mod]
-- @[simp]lemma div_def (a b : fin n) : (a / b).val = a.val / b.val :=
-- show (fin.div a b).val = a.val / b.val, from
-- by cases a; cases b; simp [fin.div]
-- @[simp]lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) :=
-- show (fin.lt a b) = (a.val < b.val), from
-- by cases a; cases b; simp [fin.lt]
-- @[simp]lemma le_def (a b : fin n) : (a ≤ b) = (a.val ≤ b.val) :=
-- show (fin.le a b) = (a.val ≤ b.val), from
-- by cases a; cases b; simp [fin.le]
-- @[simp]lemma val_zero : (0 : fin (nat.succ n)).val = 0 := rfl
-- end fin_lemmas
-- set_option pp.notation true
-- set_option pp.all false
/- To finish this, we need to port some of the zmod lemmas
should write an elimination principle which reduces to the 0 case and the pos case, which then hands it off to zmod...
-/
lemma succ_of_fin_val_succ_and_lt : ∀ {m k : ℕ} {h : k < (m + 1 + 1)}, ((k : fin (m+1+1)) + 1).val = k + 1
| 0 0 h := rfl
| 0 (k + 1) h := by {induction k, simp, rw[fin.add_def], change _ % (2) = 2, repeat{sorry}}
| (m+1) 0 h := rfl
| (m+1) (k+1) h := sorry
lemma var_subst_cast_irrel {L : Language} {n n' m} {h : m = n+ n' + 1} {k : fin m} {t : bounded_term L n'} :
subst_bounded_term ((&k : bounded_term L m).cast_eq h) t = subst_bounded_term (&k : bounded_term L (n + n' + 1)) t :=
begin
ext, simp, rcases k with ⟨k_val, k_H⟩, induction m generalizing n' k_val, cases k_H,
cases k_val,
{refl},
{tidy, congr, subst h_1, change _ = fin.val ((nat.cast k_val) + 1 : fin (n + n' + 1)), sorry},
-- to apply the above lemma, need to case on n to access the constructor.
--induction k_val, unfold coe lift_t has_lift_t.lift coe_t has_coe_t.coe coe_b has_coe.coe nat.cast, conv {to_rhs, congr,
end
@[simp]lemma func_subst_cast_irrel {L : Language} {n n' l m} {h : m = n + n' + 1} {f : L.functions l} {t : bounded_term L n'} :
subst_bounded_term ((bd_func f : bounded_preterm L m l).cast_eq h) t = subst_bounded_term (bd_func f) t := by refl
@[simp]lemma func_subst_irrel {L : Language} {n n' l} {f : L.functions l} {t : bounded_term L n'} :
subst_bounded_term (bd_func f : bounded_preterm L (n + n' + 1) l) t = (bd_func f) := by refl
@[simp]lemma func_subst0_irrel {L : Language} {n l} {f : L.functions l} {t : bounded_term L n} : (bd_func f)[t /0] = (bd_func f) := by refl
-- i wonder why this is by refl while rel_subst0_irrel isn't...
@[simp]lemma subst_bounded_term_bd_apps {L} {n n' l} (f : bounded_preterm L (n + n' + 1) l) {t : bounded_term L n'} {ts : dvector (bounded_term L (n + n' + 1)) l} :
(bd_apps f ts)[t /// _] = bd_apps (f[t /// _]) (ts.map $ λ t', subst_bounded_term (t') t) := by {induction ts generalizing f, refl, simp[bd_apps, ts_ih (bd_app f ts_x)]}
@[simp]lemma subst0_bounded_term_bd_apps {L} {n l} (f : bounded_preterm L (n+1) l) {t : closed_term L} {ts : dvector (bounded_term L (n+1)) l} :
(bd_apps f ts)[(t.cast0 n) /0] = bd_apps (f[(t.cast0 n) /0]) (ts.map $ λ t', t'[(t.cast0 n) /0]) := by {induction ts generalizing f, refl, simp[bd_apps, ts_ih (bd_app f ts_x)], refl}
lemma realize_func_irrel {L} {S : Structure L} {n n' l : ℕ} {t : bounded_term L n'} {f : L.functions l} {xs : dvector ↥S l} {v : dvector ↥S (n + n' + 1)} : realize_bounded_term v (bd_func f) xs = S.fun_map f xs := by refl
@[simp]lemma subst_falsum {L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L n'} : bd_falsum[t // n // h] = bd_falsum :=
by ext; simp
@[simp]lemma subst0_falsum {L} {n} {t : bounded_term L n} : bd_falsum[t /0] = bd_falsum :=
by ext; simp
@[simp]lemma subst_eq {L} {n n' n''} {h : n + n' + 1 = n''} {t₁ t₂ : bounded_term L n''} {t : bounded_term L n'} : (t₁ ≃ t₂)[t // n // h] = subst_bounded_term (t₁.cast_eq h.symm) t ≃ subst_bounded_term (t₂.cast_eq h.symm) t := by ext; simp
@[simp]lemma subst0_eq {L} {n} {t : bounded_term L n} {t₁ t₂ : bounded_term L (n+1)} : (t₁ ≃ t₂)[t /0] = (t₁[t /0] ≃ t₂[t /0]) :=
by {unfold subst0_bounded_formula, simpa only [subst_eq]}
@[simp]lemma subst_imp {L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L n'} {f₁ f₂ : bounded_formula L (n'')} : (f₁ ⟹ f₂)[t // n // h] = (f₁[t // n // h] ⟹ f₂[t // n // h]) := by {ext1, induction h, refl}
@[simp]lemma subst0_imp {L} {n} {t : bounded_term L n} {f₁ f₂ : bounded_formula L (n+1)} : (f₁ ⟹ f₂)[t /0] = f₁[t /0] ⟹ f₂[t /0] :=
by {unfold subst0_bounded_formula, simpa only [subst_imp]}
@[simp]lemma subst_all' {L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L n'} {f : bounded_formula L (n'' + 1)} :
(∀'f)[t // n // (by {simp[h]})]
= ∀'(f[(t : bounded_term L n') // (n+1) // (by {subst h; simp})]).cast_eq (by simp) := by ext; simp
@[simp]lemma subst_all {L} {n n' n''} {h : n + n' + 1 = n''} {t : closed_term L} {f : bounded_formula L (n'' + 1)} :
(∀'f)[t.cast0 n' // n // (by {simp[h]})]
= ∀'(f[(t.cast0 n' : bounded_term L n') // (n+1) // (by subst h; simp)]).cast_eq (by simp) :=
by {apply subst_all'}
@[simp]lemma subst0_all {L} {n} {t : closed_term L} {f : bounded_formula L (n+2)} :
((∀'f)[t.cast (by simp) /0] : bounded_formula L n) = ∀'((f[t.cast0 n // 1 // (by {simp} : 1 + n + 1 = n + 2)]).cast_eq (by simp)) :=
by ext; simp
@[simp]lemma subst0_all_base {L} {t : closed_term L} {f : bounded_formula L 2} : (∀' f)[t /0] = ∀'(f[t // 1 // (by simp)]) :=
by ext; simp
@[simp]lemma rel_subst_irrel {L : Language} {n n' l} {R : L.relations l} {t : bounded_term L n'} : (bd_rel R)[t // n // (by refl)] = (bd_rel R) := by ext; simp
@[simp]lemma rel_subst_irrel1 {L : Language} {n n' n'' l} {h : n + n' + 1 = n''} {R : L.relations l} {t : bounded_term L n'} : (@bd_rel L (n + n' + 1 + 1) _ R)[t // (n+1) // (by subst h; simp)] = (bd_rel R) := by ext; simp
@[simp]lemma rel_subst_irrel' {L : Language} {n n' n'' l} {h : n + n' + 1 = n''} {R : L.relations l} {t : bounded_term L n'} : (bd_rel R)[t // n // h] = (bd_rel R) := by subst h; apply rel_subst_irrel
@[simp]lemma rel_subst0_irrel {L : Language} {n l} {R : L.relations l} {t : bounded_term L n} : (bd_rel R)[t /0] = (bd_rel R) := by ext; simp
lemma realize_rel_irrel {L} {S : Structure L} {n n' l : ℕ} {t : bounded_term L n'} {R : L.relations l} {xs : dvector ↥S l} {v : dvector ↥S (n + n' + 1)} : realize_bounded_formula v (bounded_preformula.cast_eq (by refl) (bd_rel R)) xs = S.rel_map R xs := by refl
@[simp]lemma subst_bounded_formula_bd_apprel {L} {n n' n'' l} {h : n + n' + 1 = n''} (f : bounded_preformula L (n'') (l + 1))
{t : bounded_term L n'} {s : bounded_term L (n'')} :
(bd_apprel f s)[t // n // h] = (bd_apprel (f[t // n // h]) (subst_bounded_term (s.cast_eq h.symm) t))
:= by ext; simp
@[simp]lemma subst_bounded_formula_bd_apps_rel {L} {n n' n'' l} {h : n + n' + 1 = n''} (f : bounded_preformula L (n''+1) l)
{t : bounded_term L n'} {ts : dvector (bounded_term L (n'' + 1)) l } :
(bd_apps_rel f ts)[t // (n+1) // (by {subst h, simp})] = bd_apps_rel (f[t // (n+1) // by {subst h, simp}]) (ts.map $ λ t', subst_bounded_term (t'.cast_eq (by subst h; simp)) t) :=
by {induction ts generalizing f, refl, simp[bd_apps_rel, ts_ih (bd_apprel f ts_x)]}
@[simp]lemma subst0_bounded_formula_bd_apps_rel {L} {n l} (f : bounded_preformula L (n+1) l)
(t : closed_term L) (ts : dvector (bounded_term L (n+1)) l) :
subst0_bounded_formula (bd_apps_rel f ts) (t.cast (by simp)) =
bd_apps_rel (subst0_bounded_formula f (t.cast (by simp))) (ts.map $ λt', subst0_bounded_term t' (t.cast (by simp))) :=
by {induction ts generalizing f, refl, simp[bd_apps_rel, ts_ih (bd_apprel f ts_x)], congr, ext, simp}
lemma zero_of_lt_one (n : nat) (h : n < 1) : n = 0 :=
by {cases h, refl, cases nat.lt_of_succ_le h_a}
-- lemma asjh'_term {L} {S : Structure L} {n n'} {s : bounded_term L (n + n' + 1 + 1)} {t : bounded_term L n'} {v : dvector S (n + n' + 1)} :
-- S[(@subst_bounded_term _ (n+1) n' 0 (s.cast_eq (by simp)) t).cast_eq (by simp) ;;; v] = S[s ;;; (v.insert (S[t.cast (by linarith) ;;; v]) (n+1))]
-- :=
-- begin
-- revert s, refine bounded_term.rec1 _ _; intros,
-- {sorry},
-- {sorry}
-- end
-- set_option pp.implicit false
-- lemma asjh' {L} {S : Structure L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L (n')} {f : bounded_formula L (n''+1)} (v : dvector S n'') : (S[(f[t // (n+1) // (by {induction h, simp})]).cast_eq (by induction h; simp) ;; v])
-- = (S[f ;; (v.insert (S[t.cast (by {induction h, linarith}) ;;; v]) (n+1))]) :=
-- begin
-- revert n'' f v, refine bounded_formula.rec1 _ _ _ _ _; intros,
-- {ext, subst h, simp[subst_falsum], intros a, exact a},
-- {ext, -- simp[realize_subst_preterm, asjh'_term],
-- conv {to_lhs, rw[realize_bounded_formula_cast_eq_irrel]},
-- simp[realize_subst_preterm], induction v, simp,
-- sorry, simp*, repeat{sorry}
-- -- tidy,
-- -- sorry
-- -- -- conv {to_lhs, congr, skip, congr, congr, rw[asjh'_term],},
-- },
-- {sorry},
-- {sorry},
-- {have : n + 1 + n' + 1 = n_1 + 1, by subst h; simp, conv {to_lhs, congr, skip, congr, rw[subst_all'], skip, rw[this]}, rw[bounded_preformula.cast_eq_all], dsimp, ext, apply forall_congr, intro x, repeat{rw[realize_bounded_formula_cast_eq_irrel]}, rw[dvector.cast_trans], have := ih (x::v), simp at *,
-- },
-- end
set_option pp.implicit false
lemma dvector_cast_push_in {α : Type*} {n : ℕ} {m} {h : n = m} {h' : n+1 = m+1} {x : α} {v : dvector α n} :
(x::v).cast h' = x::(v.cast h) := by subst h; refl
lemma dvector_cast_pull_out {α : Type*} {n : ℕ} {m} {h : n = m} {h' : n+1 = m+1} {x : α} {v : dvector α n} : (x :: (v.cast h)) = (x::v).cast (h') := by subst h; refl
set_option pp.implicit false
lemma gen_realize_bounded_term {L : Language} {S : Structure L} : ∀ {n n' n'' : ℕ} {l f_n : ℕ} (s : bounded_term L f_n) (t : closed_term L) (v : dvector ↥S n'') {h : n + n' + 1 = n''} {h' : n'' + 1 = f_n} (xs : dvector ↥S 0), realize_bounded_term (dvector.cast (by substs h h'; simp : n'' = n + 1 + n') v)
(subst_bounded_term (bounded_preterm.cast_eq (by {subst h; rw[<-h'],simp}) s) (bounded_preterm.cast (zero_le n') t))
xs =
realize_bounded_term (dvector.cast (h') (dvector.insert (realize_closed_term S t) (n + 1) v)) s xs :=
begin
intros, revert s, refine bounded_term.rec _ _; intros,
{rcases k with ⟨k_val, k_H⟩,
-- unfold realize_bounded_term realize_closed_term, simp,
induction n generalizing k_val; subst h', swap,
by_cases k_val = n'',
{subst h, simp, tidy, sorry}, -- looks like here we need to case on k_val's relation to n_n + 1...
-- {have : k_val < n'',
-- by {apply nat.lt_of_le_and_ne, exact nat.le_of_lt_succ k_H, exact h},
-- have := @n_ih (v.trunc _ (rfl)) k_val this,
-- rw[dvector.nth_irrel1] at this, swap, dedup, apply nat.lt_of_lt_of_le, exact this,
-- exact nat.le_succ (n_n + 1),
-- rw[<-this], apply realize_bounded_term_irrel', swap, simp,
-- intros, simp only [dvector.trunc_nth]
repeat{sorry}},
{rw[dvector.zero_eq xs], substs h h',simp[subst_bounded_term_bd_apps,
realize_bounded_term_bd_apps, func_subst_irrel], congr' 1,
apply dvector.map_congr_pmem, intros x Hx, have := ih_ts x Hx, rwa[dvector.zero_eq xs] at this}
end
set_option pp.implicit false
lemma gen_realize_bounded_formula {L} {S : Structure L} : ∀ {n n' n'' : ℕ} {n'''} {l} {h : n + n' + 1 = n''} {h' : n'' + 1 = n'''} (f : bounded_preformula L (n''') l) (t : closed_term L) (v : dvector S n'') (xs : dvector S l), (S[(f[t.cast0 n' // (n+1) // (by {substs h h', simp})]).cast_eq (by {subst h, simp}) ;; v ;; xs]) ↔ (S[f.cast_eq (by substs h h'; simp) ;; (v.insert (S[t.cast (by {substs h h', linarith}) ;;; v]) (n+1)) ;; xs])
:=
begin
intros,
induction f generalizing n n' n'' v,
{intros, simp},
{simp, apply iff_of_eq, congr' 1; apply gen_realize_bounded_term _ t v xs, all_goals{try{exact 0}, try{exact h}}},
{simp},
{rw[realize_bounded_formula_cast_eq_irrel,subst_bounded_formula_bd_apprel],
conv {to_rhs, rw[realize_bounded_formula_cast_eq_irrel]},
have := @f_ih (realize_bounded_term (dvector.cast h' (dvector.insert (realize_closed_term S t) (n + 1) v)) f_t [] :: xs) n n' n'' v h h',
simp only [fol.realize_bounded_formula_cast_eq_irrel, add_zero, dvector.insert, neg_nonpos, int.coe_nat_zero, fol.subst_bounded_formula,
int.coe_nat_add, add_comm, int.coe_nat_one, fol.bounded_preterm.cast, eq_self_iff_true, zero_le, fol.realize_bounded_formula,
fol.bounded_preterm.cast_irrel, fol.realize_closed_term_v_irrel, zero_add, add_right_inj, fol.realize_bounded_term, add_left_comm,
fol.closed_preterm.cast_of_cast0] at *,
erw[gen_realize_bounded_term], tactic.rotate 1, exact f_l, exact h, exact h',
apply this},
{have this_f := f_ih_f₁ xs v, have this_g := f_ih_f₂ xs v, simp, simp at this_f this_g, rw[<-this_f,<-this_g]},
{substs h h', conv{to_lhs, congr, skip, congr,
rw[@subst_all' L (n+1) n' (n + n' + 1 + 1) (by {simp}) (t.cast0 n') f_f]}, rw[cast_eq_all], dsimp, apply forall_congr, intro x,
have := @f_ih xs (n+1) n' ((n+1) + n' + 1) (x::(v.cast (by simp))) (by simp) (by simp),
rw[<-dvector_cast_push_in] at this, swap, {simp},
repeat{rw[realize_bounded_formula_cast_eq_irrel]},
rw[realize_bounded_formula_cast_eq_irrel] at this, rw[dvector.cast_trans] at *,
rw[this], clear this, clear f_ih, rw[dvector.insert_cons], apply iff_of_eq,
congr' 1, {simp}, simp [realize_bounded_term_irrel, -dvector.cast],
{rw[dvector.insert_cons], congr' 1, simp, apply dvector.cast_hrfl},
{simp[bounded_preformula.cast_eq_rfl], apply bounded_preformula.cast_eq_hrfl}}
end
-- /- The statement of this isn't quite right -/
-- lemma asjh'' {L} {S : Structure L} : ∀ {n n' n'' : ℕ} {n'''} {l} {h : n + n' + 1 = n''} {h' : n'' + 1 = n'''} (f : bounded_preformula L (n''') l) (t : bounded_term L n') (v : dvector S n'') (xs : dvector S l), (S[(f[t // (n+1) // (by {substs h h', simp})]).cast_eq (by {subst h, simp}) ;; v ;; xs]) = (S[f.cast_eq (by substs h h'; simp) ;; (v.insert (S[t.cast (by {substs h h', linarith}) ;;; v]) (n+1)) ;; xs])
-- :=
-- begin
-- intros,
-- induction f generalizing n n' n'' v,
-- {intros, simp},
-- {sorry},
-- {simp},
-- {sorry},
-- {have this_f := f_ih_f₁ xs v t, have this_g := f_ih_f₂ xs v t, simp, simp at this_f this_g, rw[<-this_f,<-this_g]},
-- {substs h h', have := @subst_all' L (n+1) n' (n + n' + 1 + 1) (by {simp}) t (f_f), ext, simp[this], let k, swap, change realize_bounded_formula v (bounded_preformula.cast_eq k _) _ ↔ _,
-- let j, swap, change realize_bounded_formula v (bounded_preformula.cast_eq k (∀' j)) _ ↔ _,
-- rw[cast_eq_all], dsimp[k,j], clear k j, apply forall_congr, intro x,
-- have := @f_ih xs (n+1) n' ((n+1) + n' + 1) (x::(v.cast (by simp))) (by simp) (by simp) t,
-- rw[cast_eq_trans], rw[<-dvector_cast_push_in] at this, swap, simp, swap, simp, simp,
-- rw[realize_bounded_formula_cast_eq_irrel], rw[realize_bounded_formula_cast_eq_irrel] at this, rw[dvector.cast_trans] at this, rw[this], clear this, clear this f_ih,
-- rw[dvector.insert_cons], apply iff_of_eq, congr' 1, simp, swap, {apply cast_eq_hrfl},
-- {swap, simp, rw[dvector.insert_cons], simp, rw[dvector.insert_cons],-- let p, swap,
-- -- let q, swap, change p == q,
-- -- apply (@heq_iff_eq _ p (q.cast (by simp))).mpr, }}
-- congr' 1, simp, sorry, sorry}}
-- end
-- AHA! so we can see here that the term itself actually needs to be lifted... by 1.
-- note: doing just t ↦ t ↑ 1 doesn't work. need to lift the formula instead
-- #check (((&0 ≃ &1) : bounded_formula L_empty 2) ⟹ (∀'((&0 ≃ &1 : bounded_formula L_empty 3) ⊓ (&0 ≃ &2 : bounded_formula L_empty 3)) : bounded_formula L_empty 2))
-- TODO : figure out the correct statement of this lemma
-- lemma asjh'' {L} {S : Structure L} : ∀ {n n' n'' : ℕ} {l} {h : n + n' + 1 = n''} (f : bounded_preformula L n'' l) (t : bounded_term L n') (v : dvector S n'') (xs : dvector S l), (S[((f ↑' 1 # (n+1))[t // (n+1) // (by {subst h, simp})]).cast_eq (by {subst h, simp}) ;; v ;; xs]) ↔ (S[f.cast (by {subst h, repeat{constructor} }) ;; (v.insert (S[t.cast (by {subst h, linarith}) ;;; v]) (n+1)) ;; xs])
-- :=
-- begin
-- intros,
-- induction f generalizing n n' v,
-- {intros, simp},
-- {sorry},
-- {simp},
-- {sorry},
-- {-- have this_f := f_ih_f₁ xs v t, have this_g := f_ih_f₂ xs v t, simp, simp at this_f this_g, simp*
-- sorry
-- },
-- {rw[subst_all'],
-- }
-- substs h h', have := @subst_all' L (n+1) n' (n + n' + 1 + 1) (by {simp}) t (f_f), simp[this], let k, swap, change realize_bounded_formula v (bounded_preformula.cast_eq k _) _ ↔ _,
-- let j, swap, change realize_bounded_formula v (bounded_preformula.cast_eq k (∀' j)) _ ↔ _,
-- rw[cast_eq_all], dsimp[k,j], clear k j, apply forall_congr, intro x,
-- have := @f_ih xs (n+1) n' ((n+1) + n' + 1) (x::(v.cast (by simp))) (by simp) (by simp) t,
-- rw[cast_eq_trans], rw[dvector_cast_pull_out] at this, swap, simp, swap, simp, simp,
-- rw[realize_bounded_formula_cast_eq_irrel], rw[realize_bounded_formula_cast_eq_irrel] at this, rw[dvector.cast_trans] at this, rw[this], clear this, clear this f_ih,
-- rw[dvector.insert_cons], apply iff_of_eq, congr' 2; simp,
-- -- congr' 1, simp, swap, {apply cast_eq_hrfl},
-- -- {swap, simp, rw[dvector.insert_cons], simp, rw[dvector.insert_cons], let p, swap,
-- -- let q, swap, change p == q, apply (@heq_iff_eq _ p (q.cast (by simp))).mpr, }
-- }
-- -- congr' 2, simp, simp, {apply realize_bounded_term_irrel', swap, simp, tidy, },
-- -- {apply dvector.cast_hrfl}, {apply cast_eq_hrfl},
-- have := @subst_all' L (n+1) n' (n'' + 1) (by {subst h, simp}) t (f_f.cast_eq (by simp[h'])),ext, simp[-subst_all'] at this,
-- @[simp]lemma subst_all' {L} {n n' n''} {h : n + n' + 1 = n''} {t : bounded_term L n'} {f : bounded_formula L (n'' + 1)} :
-- (∀'f)[t // n // (by {simp[h]})]
-- = ∀'(f[(t : bounded_term L n') // (n+1) // (by {subst h; simp})]).cast_eq (by simp) := by ext; simp
-- | _ _ _ _ _ _ _ bd_falsum t v xs := by {intros; simp}
-- | _ _ _ _ _ _ _ (t₁ ≃ t₂) t v xs := by {sorry} -- follows from term version
-- | _ _ _ _ _ _ _ (bd_rel R) t v xs := by simp
-- | _ _ _ _ _ _ _ (bd_apprel f s) t v xs := by sorry
-- | _ _ _ n'' l h h' (f ⟹ g) t v xs := by {have this_f := asjh'' f t v xs, have this_g := asjh'' g t v xs, simp[*, -asjh''], simp at this_f this_g, rw[<-this_f,<-this_g]}
-- | n n' n'' n''' l h h' (∀' f) t v xs := begin
-- -- clear asjh'',
-- substs h h',
-- simp,
-- let k, swap, change _ = k, let j, tactic.rotate 1, change realize_bounded_formula v (bounded_preformula.cast_eq _ ∀'j) _ = k, swap, by simp,
-- conv {to_lhs, congr, skip, rw[bounded_preformula.cast_eq_all],}, dsimp[k,j], clear k j,
-- ext, apply forall_congr, intro x, repeat{rw[realize_bounded_formula_cast_eq_irrel]},
-- rw[dvector.cast_trans], rw[<-dvector.insert],
-- swap,
-- have := @asjh'' (n+1) n' (n + n' + 1 + 1) (n + n' + 1 + 1 + 1) 0 (by {simp}) (by refl) f t (x::v) xs, simp at this,
-- sorry --- might need to lift, actually
@[simp]lemma realize_bounded_term_subst0 {L} {S : Structure L} {n} (s : bounded_term L (n+1)) {v : dvector S n} (t : closed_term L) : realize_bounded_term v (s[(t.cast (by simp)) /0]) [] = realize_bounded_term ((realize_closed_term S t)::v) s [] :=
begin
revert s, refine bounded_term.rec1 _ _,
{intro k, rcases k with ⟨k_val, k_H⟩, simp,
induction n generalizing k_val, swap,
by_cases k_val = n_n + 1,
{subst h, refl},
{have : k_val < n_n + 1,
by {apply nat.lt_of_le_and_ne, exact nat.le_of_lt_succ k_H, exact h},
have := @n_ih (v.trunc _ (nat.le_succ n_n)) k_val this,
rw[dvector.nth_irrel1] at this, swap, dedup, apply nat.lt_of_lt_of_le, exact this,
exact nat.le_succ (n_n + 1),
rw[<-this], apply realize_bounded_term_irrel', swap, simp,
intros, simp only [dvector.trunc_nth]},
have := zero_of_lt_one k_val (by exact k_H), subst this,
congr, {apply dvector.zero_eq}, {ext, simp}},
{intros, simp[subst0_bounded_term_bd_apps,realize_bounded_term_bd_apps, func_subst0_irrel],
congr' 1, apply dvector.map_congr_pmem, intros x Hx, exact ih_ts x Hx}
end
-- /-- realization of a subst0 is the realization with the substituted term prepended to the realizing vector --/
lemma realize_bounded_formula_subst0 {L} {S : Structure L} {n} (f : bounded_formula L (n+1)) {v : dvector S n} (t : closed_term L) : realize_bounded_formula v (f[(t.cast0 n) /0]) [] ↔ realize_bounded_formula ((realize_closed_term S t)::v) f [] :=
begin
revert n f v, refine bounded_formula.rec1 _ _ _ _ _; intros,
{simp},
{simp},
{rw[subst0_bounded_formula_bd_apps_rel], simp[realize_bounded_formula_bd_apps_rel, rel_subst0_irrel]},
{simp*},
{simp[-realize_bounded_formula_cast_eq_irrel], apply forall_congr, clear ih, intro x, have := @gen_realize_bounded_formula L S 0 n (n+1) (n+2) 0 (by simp) (by simp) f t (x::v) [], simpa using this}
end
lemma realize_bounded_formula_subst0' {L} {S : Structure L} {n} (f : bounded_formula L (n+1)) {v : dvector S n} (t : bounded_term L 1) (x : S) : realize_bounded_formula (x :: v) ((f ↑' 1 # 1)[(t.cast (by simp)) /0]) [] ↔ realize_bounded_formula ((realize_bounded_term ([x] : dvector S 1) t []) :: v) f [] :=
begin
revert f n v, refine bounded_formula.rec1 _ _ _ _ _; intros,
{simp},
{sorry}, -- this requires a version of this lemma for terms
{sorry}, -- same issue as the corresponding case above
{sorry}, -- this one should be easy, just need a lemma about commutation with bd_imp
{sorry}, -- same issues as the corresponding case above
end
end realization
export fol realization
|
d1ff149b2784c4898bd2911650fca19ac99e0c77 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/category_theory/endomorphism.lean | cf9ad16917d5a2610715a17a127e9bc2d3bb7822 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,921 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Scott Morrison, Simon Hudon
-/
import category_theory.groupoid
import data.equiv.mul_add
/-!
# Endomorphisms
Definition and basic properties of endomorphisms and automorphisms of an object in a category.
For each `X : C`, we provide `End X := X ⟶ X` with a monoid structure,
and `Aut X := X ≅ X ` with a group structure.
-/
universes v v' u u'
namespace category_theory
/-- Endomorphisms of an object in a category. Arguments order in multiplication agrees with
`function.comp`, not with `category.comp`. -/
def End {C : Type u} [category_struct.{v} C] (X : C) := X ⟶ X
namespace End
section struct
variables {C : Type u} [category_struct.{v} C] (X : C)
instance has_one : has_one (End X) := ⟨𝟙 X⟩
instance inhabited : inhabited (End X) := ⟨𝟙 X⟩
/-- Multiplication of endomorphisms agrees with `function.comp`, not `category_struct.comp`. -/
instance has_mul : has_mul (End X) := ⟨λ x y, y ≫ x⟩
variable {X}
/-- Assist the typechecker by expressing a morphism `X ⟶ X` as a term of `End X`. -/
def of (f : X ⟶ X) : End X := f
/-- Assist the typechecker by expressing an endomorphism `f : End X` as a term of `X ⟶ X`. -/
def as_hom (f : End X) : X ⟶ X := f
@[simp] lemma one_def : (1 : End X) = 𝟙 X := rfl
@[simp] lemma mul_def (xs ys : End X) : xs * ys = ys ≫ xs := rfl
end struct
/-- Endomorphisms of an object form a monoid -/
instance monoid {C : Type u} [category.{v} C] {X : C} : monoid (End X) :=
{ mul_one := category.id_comp,
one_mul := category.comp_id,
mul_assoc := λ x y z, (category.assoc z y x).symm,
..End.has_mul X, ..End.has_one X }
/-- In a groupoid, endomorphisms form a group -/
instance group {C : Type u} [groupoid.{v} C] (X : C) : group (End X) :=
{ mul_left_inv := groupoid.comp_inv, inv := groupoid.inv, ..End.monoid }
end End
lemma is_unit_iff_is_iso {C : Type u} [category.{v} C] {X : C} (f : End X) :
is_unit (f : End X) ↔ is_iso f :=
⟨λ h, { out := ⟨h.unit.inv, ⟨h.unit.inv_val, h.unit.val_inv⟩⟩ },
λ h, by exactI ⟨⟨f, inv f, by simp, by simp⟩, rfl⟩⟩
variables {C : Type u} [category.{v} C] (X : C)
/--
Automorphisms of an object in a category.
The order of arguments in multiplication agrees with
`function.comp`, not with `category.comp`.
-/
def Aut (X : C) := X ≅ X
attribute [ext Aut] iso.ext
namespace Aut
instance inhabited : inhabited (Aut X) := ⟨iso.refl X⟩
instance : group (Aut X) :=
by refine_struct
{ one := iso.refl X,
inv := iso.symm,
mul := flip iso.trans,
div := _,
npow := @npow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩,
gpow := @gpow_rec (Aut X) ⟨iso.refl X⟩ ⟨flip iso.trans⟩ ⟨iso.symm⟩ };
intros; try { refl }; ext;
simp [flip, (*), monoid.mul, mul_one_class.mul, mul_one_class.one, has_one.one, monoid.one,
has_inv.inv]
/--
Units in the monoid of endomorphisms of an object
are (multiplicatively) equivalent to automorphisms of that object.
-/
def units_End_equiv_Aut : units (End X) ≃* Aut X :=
{ to_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
inv_fun := λ f, ⟨f.1, f.2, f.4, f.3⟩,
left_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
right_inv := λ ⟨f₁, f₂, f₃, f₄⟩, rfl,
map_mul' := λ f g, by rcases f; rcases g; refl }
end Aut
namespace functor
variables {D : Type u'} [category.{v'} D] (f : C ⥤ D) (X)
/-- `f.map` as a monoid hom between endomorphism monoids. -/
@[simps] def map_End : End X →* End (f.obj X) :=
{ to_fun := functor.map f,
map_mul' := λ x y, f.map_comp y x,
map_one' := f.map_id X }
/-- `f.map_iso` as a group hom between automorphism groups. -/
def map_Aut : Aut X →* Aut (f.obj X) :=
{ to_fun := f.map_iso,
map_mul' := λ x y, f.map_iso_trans y x,
map_one' := f.map_iso_refl X }
end functor
end category_theory
|
7f8524a3391fb2d289da3542d8743ebceb7a5d3e | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/defeq_simp_lemmas1.lean | ece08b3b86364542b67142f99a60c8394ca7b91a | [
"Apache-2.0"
] | permissive | soonhokong/lean-osx | 4a954262c780e404c1369d6c06516161d07fcb40 | 3670278342d2f4faa49d95b46d86642d7875b47c | refs/heads/master | 1,611,410,334,552 | 1,474,425,686,000 | 1,474,425,686,000 | 12,043,103 | 5 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 643 | lean | namespace foo
universe l
constants (A : Type.{l})
noncomputable definition q (x : A) := x
noncomputable definition h (x : A) : A := q x
noncomputable definition g (x y : A) := h y
noncomputable definition f (x y z : A) := g (g x y) z
noncomputable definition d (x y z w : A) := f (f x y z) (f y z w) (f x w z)
attribute [defeq]
definition h.def (x : A) : h x = q x := rfl
attribute [defeq]
definition g.def (x y : A) : g x y = h y := rfl
attribute [defeq]
definition f.def (x y z : A) : f x y z = g (g x y) z := rfl
attribute [defeq]
definition d.def (x y z w : A) : d x y z w = f (f x y z) (f y z w) (f x w z) := rfl
print [defeq]
end foo
|
048ba4eb56098906882eed4f731029354c0fdd87 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /library/logic/quantifiers.lean | f9eeb3a19ec71afc8af4a2742875ff72e39fc4b9 | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,790 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: logic.quantifiers
Authors: Leonardo de Moura, Jeremy Avigad
Universal and existential quantifiers. See also init.logic.
-/
open inhabited nonempty
theorem not_forall_not_of_exists {A : Type} {p : A → Prop} (H : ∃x, p x) : ¬∀x, ¬p x :=
assume H1 : ∀x, ¬p x,
obtain (w : A) (Hw : p w), from H,
absurd Hw (H1 w)
theorem not_exists_not_of_forall {A : Type} {p : A → Prop} (H2 : ∀x, p x) : ¬∃x, ¬p x :=
assume H1 : ∃x, ¬p x,
obtain (w : A) (Hw : ¬p w), from H1,
absurd (H2 w) Hw
theorem forall_congr {A : Type} {φ ψ : A → Prop} (H : ∀x, φ x ↔ ψ x) : (∀x, φ x) ↔ (∀x, ψ x) :=
iff.intro
(assume Hl, take x, iff.elim_left (H x) (Hl x))
(assume Hr, take x, iff.elim_right (H x) (Hr x))
theorem exists_congr {A : Type} {φ ψ : A → Prop} (H : ∀x, φ x ↔ ψ x) : (∃x, φ x) ↔ (∃x, ψ x) :=
iff.intro
(assume Hex, obtain w Pw, from Hex,
exists.intro w (iff.elim_left (H w) Pw))
(assume Hex, obtain w Qw, from Hex,
exists.intro w (iff.elim_right (H w) Qw))
theorem forall_true_iff_true (A : Type) : (∀x : A, true) ↔ true :=
iff.intro (assume H, trivial) (assume H, take x, trivial)
theorem forall_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∀x : A, p) ↔ p :=
iff.intro (assume Hl, inhabited.destruct H (take x, Hl x)) (assume Hr, take x, Hr)
theorem exists_p_iff_p (A : Type) [H : inhabited A] (p : Prop) : (∃x : A, p) ↔ p :=
iff.intro
(assume Hl, obtain a Hp, from Hl, Hp)
(assume Hr, inhabited.destruct H (take a, exists.intro a Hr))
theorem forall_and_distribute {A : Type} (φ ψ : A → Prop) :
(∀x, φ x ∧ ψ x) ↔ (∀x, φ x) ∧ (∀x, ψ x) :=
iff.intro
(assume H, and.intro (take x, and.elim_left (H x)) (take x, and.elim_right (H x)))
(assume H, take x, and.intro (and.elim_left H x) (and.elim_right H x))
theorem exists_or_distribute {A : Type} (φ ψ : A → Prop) :
(∃x, φ x ∨ ψ x) ↔ (∃x, φ x) ∨ (∃x, ψ x) :=
iff.intro
(assume H, obtain (w : A) (Hw : φ w ∨ ψ w), from H,
or.elim Hw
(assume Hw1 : φ w, or.inl (exists.intro w Hw1))
(assume Hw2 : ψ w, or.inr (exists.intro w Hw2)))
(assume H, or.elim H
(assume H1, obtain (w : A) (Hw : φ w), from H1,
exists.intro w (or.inl Hw))
(assume H2, obtain (w : A) (Hw : ψ w), from H2,
exists.intro w (or.inr Hw)))
theorem nonempty_of_exists {A : Type} {P : A → Prop} (H : ∃x, P x) : nonempty A :=
obtain w Hw, from H, nonempty.intro w
section
open decidable eq.ops
variables {A : Type} (P : A → Prop) (a : A) [H : decidable (P a)]
include H
definition decidable_forall_eq [instance] : decidable (∀ x, x = a → P x) :=
decidable.rec_on H
(λ pa, inl (λ x heq, eq.rec_on (eq.rec_on heq rfl) pa))
(λ npa, inr (λ h, absurd (h a rfl) npa))
definition decidable_exists_eq [instance] : decidable (∃ x, x = a ∧ P x) :=
decidable.rec_on H
(λ pa, inl (exists.intro a (and.intro rfl pa)))
(λ npa, inr (λ h,
obtain (w : A) (Hw : w = a ∧ P w), from h,
absurd (and.rec_on Hw (λ h₁ h₂, h₁ ▸ h₂)) npa))
end
/- exists_unique -/
definition exists_unique {A : Type} (p : A → Prop) :=
∃x, p x ∧ ∀y, p y → y = x
notation `∃!` binders `,` r:(scoped P, exists_unique P) := r
theorem exists_unique.intro {A : Type} {p : A → Prop} (w : A) (H1 : p w) (H2 : ∀y, p y → y = w) :
∃!x, p x :=
exists.intro w (and.intro H1 H2)
theorem exists_unique.elim {A : Type} {p : A → Prop} {b : Prop}
(H2 : ∃!x, p x) (H1 : ∀x, p x → (∀y, p y → y = x) → b) : b :=
obtain w Hw, from H2,
H1 w (and.elim_left Hw) (and.elim_right Hw)
|
95d9da049b7a8bf69ceb7d3f5a6ba9eb695406b0 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/geometry/euclidean/monge_point.lean | a1a0065595c86d685dae42d70c4fdf8ec762565b | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 38,569 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import geometry.euclidean.circumcenter
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
/-!
# Monge point and orthocenter
This file defines the orthocenter of a triangle, via its n-dimensional
generalization, the Monge point of a simplex.
## Main definitions
* `monge_point` is the Monge point of a simplex, defined in terms of
its position on the Euler line and then shown to be the point of
concurrence of the Monge planes.
* `monge_plane` is a Monge plane of an (n+2)-simplex, which is the
(n+1)-dimensional affine subspace of the subspace spanned by the
simplex that passes through the centroid of an n-dimensional face
and is orthogonal to the opposite edge (in 2 dimensions, this is the
same as an altitude).
* `altitude` is the line that passes through a vertex of a simplex and
is orthogonal to the opposite face.
* `orthocenter` is defined, for the case of a triangle, to be the same
as its Monge point, then shown to be the point of concurrence of the
altitudes.
* `orthocentric_system` is a predicate on sets of points that says
whether they are four points, one of which is the orthocenter of the
other three (in which case various other properties hold, including
that each is the orthocenter of the other three).
## References
* <https://en.wikipedia.org/wiki/Altitude_(triangle)>
* <https://en.wikipedia.org/wiki/Monge_point>
* <https://en.wikipedia.org/wiki/Orthocentric_system>
* Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point
Sphere of an
n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf)
-/
namespace affine
namespace simplex
open finset affine_subspace euclidean_geometry points_with_circumcenter_index
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- The Monge point of a simplex (in 2 or more dimensions) is a
generalization of the orthocenter of a triangle. It is defined to be
the intersection of the Monge planes, where a Monge plane is the
(n-1)-dimensional affine subspace of the subspace spanned by the
simplex that passes through the centroid of an (n-2)-dimensional face
and is orthogonal to the opposite edge (in 2 dimensions, this is the
same as an altitude). The circumcenter O, centroid G and Monge point
M are collinear in that order on the Euler line, with OG : GM = (n-1)
: 2. Here, we use that ratio to define the Monge point (so resulting
in a point that equals the centroid in 0 or 1 dimensions), and then
show in subsequent lemmas that the point so defined lies in the Monge
planes and is their unique point of intersection. -/
def monge_point {n : ℕ} (s : simplex ℝ P n) : P :=
(((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) •
((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ
s.circumcenter
/-- The position of the Monge point in relation to the circumcenter
and centroid. -/
lemma monge_point_eq_smul_vsub_vadd_circumcenter {n : ℕ} (s : simplex ℝ P n) :
s.monge_point = (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) •
((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ
s.circumcenter :=
rfl
/-- The Monge point lies in the affine span. -/
lemma monge_point_mem_affine_span {n : ℕ} (s : simplex ℝ P n) :
s.monge_point ∈ affine_span ℝ (set.range s.points) :=
smul_vsub_vadd_mem _ _
(centroid_mem_affine_span_of_card_eq_add_one ℝ _ (card_fin (n + 1)))
s.circumcenter_mem_affine_span
s.circumcenter_mem_affine_span
/-- Two simplices with the same points have the same Monge point. -/
lemma monge_point_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n}
(h : set.range s₁.points = set.range s₂.points) : s₁.monge_point = s₂.monge_point :=
by simp_rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_of_range_eq h,
circumcenter_eq_of_range_eq h]
omit V
/-- The weights for the Monge point of an (n+2)-simplex, in terms of
`points_with_circumcenter`. -/
def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + 2) → ℝ
| (point_index i) := (((n + 1) : ℕ) : ℝ)⁻¹
| circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ))
/-- `monge_point_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_monge_point_weights_with_circumcenter (n : ℕ) :
∑ i, monge_point_weights_with_circumcenter n i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, monge_point_weights_with_circumcenter, sum_const,
card_fin, nsmul_eq_mul],
have hn1 : (n + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
field_simp [hn1],
ring
end
include V
/-- The Monge point of an (n+2)-simplex, in terms of
`points_with_circumcenter`. -/
lemma monge_point_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P (n + 2)) :
s.monge_point = (univ : finset (points_with_circumcenter_index (n + 2))).affine_combination
s.points_with_circumcenter (monge_point_weights_with_circumcenter n) :=
begin
rw [monge_point_eq_smul_vsub_vadd_circumcenter,
centroid_eq_affine_combination_of_points_with_circumcenter,
circumcenter_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub, ←linear_map.map_smul,
weighted_vsub_vadd_affine_combination],
congr' with i,
rw [pi.add_apply, pi.smul_apply, smul_eq_mul, pi.sub_apply],
have hn1 : (n + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
cases i;
simp_rw [centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter,
monge_point_weights_with_circumcenter];
rw [nat.add_sub_assoc (dec_trivial : 1 ≤ 2), (dec_trivial : 2 - 1 = 1)],
{ rw [if_pos (mem_univ _), sub_zero, add_zero, card_fin],
have hn3 : (n + 2 + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
field_simp [hn1, hn3, mul_comm] },
{ field_simp [hn1],
ring }
end
omit V
/-- The weights for the Monge point of an (n+2)-simplex, minus the
centroid of an n-dimensional face, in terms of
`points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/
def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 3)) :
points_with_circumcenter_index (n + 2) → ℝ
| (point_index i) := if i = i₁ ∨ i = i₂ then (((n + 1) : ℕ) : ℝ)⁻¹ else 0
| circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ))
/-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the
result of subtracting `centroid_weights_with_circumcenter` from
`monge_point_weights_with_circumcenter`. -/
lemma monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ}
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ =
monge_point_weights_with_circumcenter n -
centroid_weights_with_circumcenter ({i₁, i₂}ᶜ) :=
begin
ext i,
cases i,
{ rw [pi.sub_apply, monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter,
monge_point_vsub_face_centroid_weights_with_circumcenter],
have hu : card ({i₁, i₂}ᶜ : finset (fin (n + 3))) = n + 1,
{ simp [card_compl, fintype.card_fin, h] },
rw hu,
by_cases hi : i = i₁ ∨ i = i₂;
simp [compl_eq_univ_sdiff, hi] },
{ simp [monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter,
monge_point_vsub_face_centroid_weights_with_circumcenter] }
end
/-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/
@[simp] lemma sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ}
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
∑ i, monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i = 0 :=
begin
rw monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h,
simp_rw [pi.sub_apply, sum_sub_distrib, sum_monge_point_weights_with_circumcenter],
rw [sum_centroid_weights_with_circumcenter, sub_self],
simp [←card_pos, card_compl, h]
end
include V
/-- The Monge point of an (n+2)-simplex, minus the centroid of an
n-dimensional face, in terms of `points_with_circumcenter`. -/
lemma monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points =
(univ : finset (points_with_circumcenter_index (n + 2))).weighted_vsub
s.points_with_circumcenter (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) :=
by simp_rw [monge_point_eq_affine_combination_of_points_with_circumcenter,
centroid_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub,
monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h]
/-- The Monge point of an (n+2)-simplex, minus the centroid of an
n-dimensional face, is orthogonal to the difference of the two
vertices not in that face. -/
lemma inner_monge_point_vsub_face_centroid_vsub {n : ℕ} (s : simplex ℝ P (n + 2))
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
⟪s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points,
s.points i₁ -ᵥ s.points i₂⟫ = 0 :=
begin
simp_rw [monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter s h,
point_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub],
have hs : ∑ i, (point_weights_with_circumcenter i₁ - point_weights_with_circumcenter i₂) i = 0,
{ simp },
rw [inner_weighted_vsub _ (sum_monge_point_vsub_face_centroid_weights_with_circumcenter h) _ hs,
sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter],
simp only [monge_point_vsub_face_centroid_weights_with_circumcenter,
points_with_circumcenter_point],
let fs : finset (fin (n + 3)) := {i₁, i₂},
have hfs : ∀ i : fin (n + 3),
i ∉ fs → (i ≠ i₁ ∧ i ≠ i₂),
{ intros i hi,
split ; { intro hj, simpa [←hj] using hi } },
rw ←sum_subset fs.subset_univ _,
{ simp_rw [sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter,
points_with_circumcenter_point, pi.sub_apply, point_weights_with_circumcenter],
rw [←sum_subset fs.subset_univ _],
{ simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton],
repeat { rw ←sum_subset fs.subset_univ _ },
{ simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton],
simp [h, h.symm, dist_comm (s.points i₁)] },
all_goals { intros i hu hi, simp [hfs i hi] } },
{ intros i hu hi,
simp [hfs i hi, point_weights_with_circumcenter] } },
{ intros i hu hi,
simp [hfs i hi] }
end
/-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine
subspace of the subspace spanned by the simplex that passes through
the centroid of an n-dimensional face and is orthogonal to the
opposite edge (in 2 dimensions, this is the same as an altitude).
This definition is only intended to be used when `i₁ ≠ i₂`. -/
def monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
affine_subspace ℝ P :=
mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points)
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
affine_span ℝ (set.range s.points)
/-- The definition of a Monge plane. -/
lemma monge_plane_def {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
s.monge_plane i₁ i₂ = mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points)
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
affine_span ℝ (set.range s.points) :=
rfl
/-- The Monge plane associated with vertices `i₁` and `i₂` equals that
associated with `i₂` and `i₁`. -/
lemma monge_plane_comm {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
s.monge_plane i₁ i₂ = s.monge_plane i₂ i₁ :=
begin
simp_rw monge_plane_def,
congr' 3,
{ congr' 1,
exact insert_singleton_comm _ _ },
{ ext,
simp_rw submodule.mem_span_singleton,
split,
all_goals { rintros ⟨r, rfl⟩, use -r, rw [neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev] } }
end
/-- The Monge point lies in the Monge planes. -/
lemma monge_point_mem_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)}
(h : i₁ ≠ i₂) : s.monge_point ∈ s.monge_plane i₁ i₂ :=
begin
rw [monge_plane_def, mem_inf_iff, ←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _),
direction_mk', submodule.mem_orthogonal'],
refine ⟨_, s.monge_point_mem_affine_span⟩,
intros v hv,
rcases submodule.mem_span_singleton.mp hv with ⟨r, rfl⟩,
rw [inner_smul_right, s.inner_monge_point_vsub_face_centroid_vsub h, mul_zero]
end
-- This doesn't actually need the `i₁ ≠ i₂` hypothesis, but it's
-- convenient for the proof and `monge_plane` isn't intended to be
-- useful without that hypothesis.
/-- The direction of a Monge plane. -/
lemma direction_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
(s.monge_plane i₁ i₂).direction = (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
vector_span ℝ (set.range s.points) :=
by rw [monge_plane_def, direction_inf_of_mem_inf (s.monge_point_mem_monge_plane h), direction_mk',
direction_affine_span]
/-- The Monge point is the only point in all the Monge planes from any
one vertex. -/
lemma eq_monge_point_of_forall_mem_monge_plane {n : ℕ} {s : simplex ℝ P (n + 2)}
{i₁ : fin (n + 3)} {p : P} (h : ∀ i₂, i₁ ≠ i₂ → p ∈ s.monge_plane i₁ i₂) :
p = s.monge_point :=
begin
rw ←@vsub_eq_zero_iff_eq V,
have h' : ∀ i₂, i₁ ≠ i₂ → p -ᵥ s.monge_point ∈
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points),
{ intros i₂ hne,
rw [←s.direction_monge_plane hne,
vsub_right_mem_direction_iff_mem (s.monge_point_mem_monge_plane hne)],
exact h i₂ hne },
have hi : p -ᵥ s.monge_point ∈ ⨅ (i₂ : {i // i₁ ≠ i}),
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ,
{ rw submodule.mem_infi,
exact λ i, (submodule.mem_inf.1 (h' i i.property)).1 },
rw [submodule.infi_orthogonal, ←submodule.span_Union] at hi,
have hu : (⋃ (i : {i // i₁ ≠ i}), ({s.points i₁ -ᵥ s.points i} : set V)) =
(-ᵥ) (s.points i₁) '' (s.points '' (set.univ \ {i₁})),
{ rw [set.image_image],
ext x,
simp_rw [set.mem_Union, set.mem_image, set.mem_singleton_iff, set.mem_diff_singleton],
split,
{ rintros ⟨i, rfl⟩,
use [i, ⟨set.mem_univ _, i.property.symm⟩] },
{ rintros ⟨i, ⟨hiu, hi⟩, rfl⟩,
use [⟨i, hi.symm⟩, rfl] } },
rw [hu, ←vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_univ _),
set.image_univ] at hi,
have hv : p -ᵥ s.monge_point ∈ vector_span ℝ (set.range s.points),
{ let s₁ : finset (fin (n + 3)) := univ.erase i₁,
obtain ⟨i₂, h₂⟩ :=
card_pos.1 (show 0 < card s₁, by simp [card_erase_of_mem]),
have h₁₂ : i₁ ≠ i₂ := (ne_of_mem_erase h₂).symm,
exact (submodule.mem_inf.1 (h' i₂ h₁₂)).2 },
exact submodule.disjoint_def.1 ((vector_span ℝ (set.range s.points)).orthogonal_disjoint)
_ hv hi,
end
/-- An altitude of a simplex is the line that passes through a vertex
and is orthogonal to the opposite face. -/
def altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : affine_subspace ℝ P :=
mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓
affine_span ℝ (set.range s.points)
/-- The definition of an altitude. -/
lemma altitude_def {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
s.altitude i = mk' (s.points i)
(affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓
affine_span ℝ (set.range s.points) :=
rfl
/-- A vertex lies in the corresponding altitude. -/
lemma mem_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
s.points i ∈ s.altitude i :=
(mem_inf_iff _ _ _).2 ⟨self_mem_mk' _ _, mem_affine_span ℝ (set.mem_range_self _)⟩
/-- The direction of an altitude. -/
lemma direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
(s.altitude i).direction = (vector_span ℝ (s.points '' ↑(finset.univ.erase i)))ᗮ ⊓
vector_span ℝ (set.range s.points) :=
by rw [altitude_def,
direction_inf_of_mem (self_mem_mk' (s.points i) _)
(mem_affine_span ℝ (set.mem_range_self _)), direction_mk', direction_affine_span,
direction_affine_span]
/-- The vector span of the opposite face lies in the direction
orthogonal to an altitude. -/
lemma vector_span_le_altitude_direction_orthogonal {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) :
vector_span ℝ (s.points '' ↑(finset.univ.erase i)) ≤ (s.altitude i).directionᗮ :=
begin
rw direction_altitude,
exact le_trans
(vector_span ℝ (s.points '' ↑(finset.univ.erase i))).le_orthogonal_orthogonal
(submodule.orthogonal_le inf_le_left)
end
open finite_dimensional
/-- An altitude is finite-dimensional. -/
instance finite_dimensional_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) : finite_dimensional ℝ ((s.altitude i).direction) :=
begin
rw direction_altitude,
apply_instance
end
/-- An altitude is one-dimensional (i.e., a line). -/
@[simp] lemma findim_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
findim ℝ ((s.altitude i).direction) = 1 :=
begin
rw direction_altitude,
have h := submodule.findim_add_inf_findim_orthogonal
(vector_span_mono ℝ (set.image_subset_range s.points ↑(univ.erase i))),
have hc : card (univ.erase i) = n + 1, { rw card_erase_of_mem (mem_univ _), simp },
rw [findim_vector_span_of_affine_independent s.independent (fintype.card_fin _),
findim_vector_span_image_finset_of_affine_independent s.independent hc] at h,
simpa using h
end
/-- A line through a vertex is the altitude through that vertex if and
only if it is orthogonal to the opposite face. -/
lemma affine_span_insert_singleton_eq_altitude_iff {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) (p : P) :
affine_span ℝ {p, s.points i} = s.altitude i ↔ (p ≠ s.points i ∧
p ∈ affine_span ℝ (set.range s.points) ∧
p -ᵥ s.points i ∈ (affine_span ℝ (s.points '' ↑(finset.univ.erase i))).directionᗮ) :=
begin
rw [eq_iff_direction_eq_of_mem
(mem_affine_span ℝ (set.mem_insert_of_mem _ (set.mem_singleton _))) (s.mem_altitude _),
←vsub_right_mem_direction_iff_mem (mem_affine_span ℝ (set.mem_range_self i)) p,
direction_affine_span, direction_affine_span, direction_affine_span],
split,
{ intro h,
split,
{ intro heq,
rw [heq, set.pair_eq_singleton, vector_span_singleton] at h,
have hd : findim ℝ (s.altitude i).direction = 0,
{ rw [←h, findim_bot] },
simpa using hd },
{ rw [←submodule.mem_inf, inf_comm, ←direction_altitude, ←h],
exact vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (set.mem_singleton _)) } },
{ rintro ⟨hne, h⟩,
rw [←submodule.mem_inf, inf_comm, ←direction_altitude] at h,
rw [vector_span_eq_span_vsub_set_left_ne ℝ (set.mem_insert _ _),
set.insert_diff_of_mem _ (set.mem_singleton _),
set.diff_singleton_eq_self (λ h, hne (set.mem_singleton_iff.1 h)), set.image_singleton],
refine eq_of_le_of_findim_eq _ _,
{ rw submodule.span_le,
simpa using h },
{ rw [findim_direction_altitude, findim_span_set_eq_card],
{ simp },
{ refine linear_independent_singleton _,
simpa using hne } } }
end
end simplex
namespace triangle
open euclidean_geometry finset simplex affine_subspace finite_dimensional
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- The orthocenter of a triangle is the intersection of its
altitudes. It is defined here as the 2-dimensional case of the
Monge point. -/
def orthocenter (t : triangle ℝ P) : P := t.monge_point
/-- The orthocenter equals the Monge point. -/
lemma orthocenter_eq_monge_point (t : triangle ℝ P) : t.orthocenter = t.monge_point := rfl
/-- The position of the orthocenter in relation to the circumcenter
and centroid. -/
lemma orthocenter_eq_smul_vsub_vadd_circumcenter (t : triangle ℝ P) :
t.orthocenter = (3 : ℝ) •
((univ : finset (fin 3)).centroid ℝ t.points -ᵥ t.circumcenter : V) +ᵥ t.circumcenter :=
begin
rw [orthocenter_eq_monge_point, monge_point_eq_smul_vsub_vadd_circumcenter],
norm_num
end
/-- The orthocenter lies in the affine span. -/
lemma orthocenter_mem_affine_span (t : triangle ℝ P) :
t.orthocenter ∈ affine_span ℝ (set.range t.points) :=
t.monge_point_mem_affine_span
/-- Two triangles with the same points have the same orthocenter. -/
lemma orthocenter_eq_of_range_eq {t₁ t₂ : triangle ℝ P}
(h : set.range t₁.points = set.range t₂.points) : t₁.orthocenter = t₂.orthocenter :=
monge_point_eq_of_range_eq h
/-- In the case of a triangle, altitudes are the same thing as Monge
planes. -/
lemma altitude_eq_monge_plane (t : triangle ℝ P) {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂)
(h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : t.altitude i₁ = t.monge_plane i₂ i₃ :=
begin
have hs : ({i₂, i₃}ᶜ : finset (fin 3)) = {i₁}, by dec_trivial!,
have he : univ.erase i₁ = {i₂, i₃}, by dec_trivial!,
rw [monge_plane_def, altitude_def, direction_affine_span, hs, he, centroid_singleton,
coe_insert, coe_singleton,
vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_insert i₂ _)],
simp [h₂₃, submodule.span_insert_eq_span]
end
/-- The orthocenter lies in the altitudes. -/
lemma orthocenter_mem_altitude (t : triangle ℝ P) {i₁ : fin 3} :
t.orthocenter ∈ t.altitude i₁ :=
begin
obtain ⟨i₂, i₃, h₁₂, h₂₃, h₁₃⟩ : ∃ i₂ i₃, i₁ ≠ i₂ ∧ i₂ ≠ i₃ ∧ i₁ ≠ i₃, by dec_trivial!,
rw [orthocenter_eq_monge_point, t.altitude_eq_monge_plane h₁₂ h₁₃ h₂₃],
exact t.monge_point_mem_monge_plane h₂₃
end
/-- The orthocenter is the only point lying in any two of the
altitudes. -/
lemma eq_orthocenter_of_forall_mem_altitude {t : triangle ℝ P} {i₁ i₂ : fin 3} {p : P}
(h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ t.altitude i₁) (h₂ : p ∈ t.altitude i₂) : p = t.orthocenter :=
begin
obtain ⟨i₃, h₂₃, h₁₃⟩ : ∃ i₃, i₂ ≠ i₃ ∧ i₁ ≠ i₃, { clear h₁ h₂, dec_trivial! },
rw t.altitude_eq_monge_plane h₁₃ h₁₂ h₂₃.symm at h₁,
rw t.altitude_eq_monge_plane h₂₃ h₁₂.symm h₁₃.symm at h₂,
rw orthocenter_eq_monge_point,
have ha : ∀ i, i₃ ≠ i → p ∈ t.monge_plane i₃ i,
{ intros i hi,
have hi₁₂ : i₁ = i ∨ i₂ = i, { clear h₁ h₂, dec_trivial! },
cases hi₁₂,
{ exact hi₁₂ ▸ h₂ },
{ exact hi₁₂ ▸ h₁ } },
exact eq_monge_point_of_forall_mem_monge_plane ha
end
/-- The distance from the orthocenter to the reflection of the
circumcenter in a side equals the circumradius. -/
lemma dist_orthocenter_reflection_circumcenter (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) :
dist t.orthocenter (reflection (affine_span ℝ (t.points '' {i₁, i₂})) t.circumcenter) =
t.circumradius :=
begin
rw [←mul_self_inj_of_nonneg dist_nonneg t.circumradius_nonneg,
t.reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter h,
t.orthocenter_eq_monge_point,
monge_point_eq_affine_combination_of_points_with_circumcenter,
dist_affine_combination t.points_with_circumcenter
(sum_monge_point_weights_with_circumcenter _)
(sum_reflection_circumcenter_weights_with_circumcenter h)],
simp_rw [sum_points_with_circumcenter, pi.sub_apply, monge_point_weights_with_circumcenter,
reflection_circumcenter_weights_with_circumcenter],
have hu : ({i₁, i₂} : finset (fin 3)) ⊆ univ := subset_univ _,
obtain ⟨i₃, hi₃, hi₃₁, hi₃₂⟩ :
∃ i₃, univ \ ({i₁, i₂} : finset (fin 3)) = {i₃} ∧ i₃ ≠ i₁ ∧ i₃ ≠ i₂, by dec_trivial!,
simp_rw [←sum_sdiff hu, hi₃],
simp [hi₃₁, hi₃₂],
norm_num
end
/-- The distance from the orthocenter to the reflection of the
circumcenter in a side equals the circumradius, variant using a
`finset`. -/
lemma dist_orthocenter_reflection_circumcenter_finset (t : triangle ℝ P) {i₁ i₂ : fin 3}
(h : i₁ ≠ i₂) :
dist t.orthocenter (reflection (affine_span ℝ (t.points '' ↑({i₁, i₂} : finset (fin 3))))
t.circumcenter) =
t.circumradius :=
by { convert dist_orthocenter_reflection_circumcenter _ h, simp }
/-- The affine span of the orthocenter and a vertex is contained in
the altitude. -/
lemma affine_span_orthocenter_point_le_altitude (t : triangle ℝ P) (i : fin 3) :
affine_span ℝ {t.orthocenter, t.points i} ≤ t.altitude i :=
begin
refine span_points_subset_coe_of_subset_coe _,
rw [set.insert_subset, set.singleton_subset_iff],
exact ⟨t.orthocenter_mem_altitude, t.mem_altitude i⟩
end
/-- Suppose we are given a triangle `t₁`, and replace one of its
vertices by its orthocenter, yielding triangle `t₂` (with vertices not
necessarily listed in the same order). Then an altitude of `t₂` from
a vertex that was not replaced is the corresponding side of `t₁`. -/
lemma altitude_replace_orthocenter_eq_affine_span {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3}
(hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃)
(hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂)
(h₃ : t₂.points j₃ = t₁.points i₃) :
t₂.altitude j₂ = affine_span ℝ {t₁.points i₁, t₁.points i₂} :=
begin
symmetry,
rw [←h₂, t₂.affine_span_insert_singleton_eq_altitude_iff],
rw [h₂],
use (injective_of_affine_independent t₁.independent).ne hi₁₂,
have he : affine_span ℝ (set.range t₂.points) = affine_span ℝ (set.range t₁.points),
{ refine ext_of_direction_eq _
⟨t₁.points i₃, mem_affine_span ℝ ⟨j₃, h₃⟩, mem_affine_span ℝ (set.mem_range_self _)⟩,
refine eq_of_le_of_findim_eq (direction_le (span_points_subset_coe_of_subset_coe _)) _,
{ have hu : (finset.univ : finset (fin 3)) = {j₁, j₂, j₃}, { clear h₁ h₂ h₃, dec_trivial! },
rw [←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert,
finset.coe_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton,
h₁, h₂, h₃, set.insert_subset, set.insert_subset, set.singleton_subset_iff],
exact ⟨t₁.orthocenter_mem_affine_span,
mem_affine_span ℝ (set.mem_range_self _),
mem_affine_span ℝ (set.mem_range_self _)⟩ },
{ rw [direction_affine_span, direction_affine_span,
findim_vector_span_of_affine_independent t₁.independent (fintype.card_fin _),
findim_vector_span_of_affine_independent t₂.independent (fintype.card_fin _)] } },
rw he,
use mem_affine_span ℝ (set.mem_range_self _),
have hu : finset.univ.erase j₂ = {j₁, j₃}, { clear h₁ h₂ h₃, dec_trivial! },
rw [hu, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton,
h₁, h₃],
have hle : (t₁.altitude i₃).directionᗮ ≤
(affine_span ℝ ({t₁.orthocenter, t₁.points i₃} : set P)).directionᗮ :=
submodule.orthogonal_le (direction_le (affine_span_orthocenter_point_le_altitude _ _)),
refine hle ((t₁.vector_span_le_altitude_direction_orthogonal i₃) _),
have hui : finset.univ.erase i₃ = {i₁, i₂}, { clear hle h₂ h₃, dec_trivial! },
rw [hui, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton],
refine vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (set.mem_singleton _))
end
/-- Suppose we are given a triangle `t₁`, and replace one of its
vertices by its orthocenter, yielding triangle `t₂` (with vertices not
necessarily listed in the same order). Then the orthocenter of `t₂`
is the vertex of `t₁` that was replaced. -/
lemma orthocenter_replace_orthocenter_eq_point {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3}
(hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃)
(hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂)
(h₃ : t₂.points j₃ = t₁.points i₃) :
t₂.orthocenter = t₁.points i₁ :=
begin
refine (triangle.eq_orthocenter_of_forall_mem_altitude hj₂₃ _ _).symm,
{ rw altitude_replace_orthocenter_eq_affine_span hi₁₂ hi₁₃ hi₂₃ hj₁₂ hj₁₃ hj₂₃ h₁ h₂ h₃,
exact mem_affine_span ℝ (set.mem_insert _ _) },
{ rw altitude_replace_orthocenter_eq_affine_span hi₁₃ hi₁₂ hi₂₃.symm hj₁₃ hj₁₂ hj₂₃.symm h₁ h₃ h₂,
exact mem_affine_span ℝ (set.mem_insert _ _) }
end
end triangle
end affine
namespace euclidean_geometry
open affine affine_subspace finite_dimensional
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- Four points form an orthocentric system if they consist of the
vertices of a triangle and its orthocenter. -/
def orthocentric_system (s : set P) : Prop :=
∃ t : triangle ℝ P,
t.orthocenter ∉ set.range t.points ∧ s = insert t.orthocenter (set.range t.points)
/-- This is an auxiliary lemma giving information about the relation
of two triangles in an orthocentric system; it abstracts some
reasoning, with no geometric content, that is common to some other
lemmas. Suppose the orthocentric system is generated by triangle `t`,
and we are given three points `p` in the orthocentric system. Then
either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p
i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂`
and `j₃` of `t`, or `p` has the same points as `t`. -/
lemma exists_of_range_subset_orthocentric_system {t : triangle ℝ P}
(ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P}
(hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) :
(∃ (i₁ i₂ i₃ j₂ j₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧
(∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = t.orthocenter ∧ j₂ ≠ j₃ ∧
t.points j₂ = p i₂ ∧ t.points j₃ = p i₃) ∨ set.range p = set.range t.points :=
begin
by_cases h : t.orthocenter ∈ set.range p,
{ left,
rcases h with ⟨i₁, h₁⟩,
obtain ⟨i₂, i₃, h₁₂, h₁₃, h₂₃, h₁₂₃⟩ :
∃ (i₂ i₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃,
{ clear h₁, dec_trivial! },
have h : ∀ i, i₁ ≠ i → ∃ (j : fin 3), t.points j = p i,
{ intros i hi,
replace hps := set.mem_of_mem_insert_of_ne
(set.mem_of_mem_of_subset (set.mem_range_self i) hps) (h₁ ▸ hpi.ne hi.symm),
exact hps },
rcases h i₂ h₁₂ with ⟨j₂, h₂⟩,
rcases h i₃ h₁₃ with ⟨j₃, h₃⟩,
have hj₂₃ : j₂ ≠ j₃,
{ intro he,
rw [he, h₃] at h₂,
exact h₂₃.symm (hpi h₂) },
exact ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ },
{ right,
have hs := set.subset_diff_singleton hps h,
rw set.insert_diff_self_of_not_mem ho at hs,
refine set.eq_of_subset_of_card_le hs _,
rw [set.card_range_of_injective hpi,
set.card_range_of_injective (injective_of_affine_independent t.independent)] }
end
/-- For any three points in an orthocentric system generated by
triangle `t`, there is a point in the subspace spanned by the triangle
from which the distance of all those three points equals the circumradius. -/
lemma exists_dist_eq_circumradius_of_subset_insert_orthocenter {t : triangle ℝ P}
(ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P}
(hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) :
∃ c ∈ affine_span ℝ (set.range t.points), ∀ p₁ ∈ set.range p, dist p₁ c = t.circumradius :=
begin
rcases exists_of_range_subset_orthocentric_system ho hps hpi with
⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs,
{ use [reflection (affine_span ℝ (t.points '' {j₂, j₃})) t.circumcenter,
reflection_mem_of_le_of_mem (affine_span_mono ℝ (set.image_subset_range _ _))
t.circumcenter_mem_affine_span],
intros p₁ hp₁,
rcases hp₁ with ⟨i, rfl⟩,
replace h₁₂₃ := h₁₂₃ i,
repeat { cases h₁₂₃ },
{ rw h₁,
exact triangle.dist_orthocenter_reflection_circumcenter t hj₂₃ },
{ rw [←h₂,
dist_reflection_eq_of_mem _
(mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert _ _)))],
exact t.dist_circumcenter_eq_circumradius _ },
{ rw [←h₃,
dist_reflection_eq_of_mem _
(mem_affine_span ℝ (set.mem_image_of_mem _
(set.mem_insert_of_mem _ (set.mem_singleton _))))],
exact t.dist_circumcenter_eq_circumradius _ } },
{ use [t.circumcenter, t.circumcenter_mem_affine_span],
intros p₁ hp₁,
rw hs at hp₁,
rcases hp₁ with ⟨i, rfl⟩,
exact t.dist_circumcenter_eq_circumradius _ }
end
/-- Any three points in an orthocentric system are affinely independent. -/
lemma orthocentric_system.affine_independent {s : set P} (ho : orthocentric_system s)
{p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_independent ℝ p :=
begin
rcases ho with ⟨t, hto, hst⟩,
rw hst at hps,
rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto hps hpi with ⟨c, hcs, hc⟩,
exact cospherical.affine_independent ⟨c, t.circumradius, hc⟩ set.subset.rfl hpi
end
/-- Any three points in an orthocentric system span the same subspace
as the whole orthocentric system. -/
lemma affine_span_of_orthocentric_system {s : set P} (ho : orthocentric_system s)
{p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_span ℝ (set.range p) = affine_span ℝ s :=
begin
have ha := ho.affine_independent hps hpi,
rcases ho with ⟨t, hto, hts⟩,
have hs : affine_span ℝ s = affine_span ℝ (set.range t.points),
{ rw [hts, affine_span_insert_eq_affine_span ℝ t.orthocenter_mem_affine_span] },
refine ext_of_direction_eq _
⟨p 0, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (hps (set.mem_range_self _))⟩,
have hfd : finite_dimensional ℝ (affine_span ℝ s).direction, { rw hs, apply_instance },
haveI := hfd,
refine eq_of_le_of_findim_eq (direction_le (affine_span_mono ℝ hps)) _,
rw [hs, direction_affine_span, direction_affine_span,
findim_vector_span_of_affine_independent ha (fintype.card_fin _),
findim_vector_span_of_affine_independent t.independent (fintype.card_fin _)]
end
/-- All triangles in an orthocentric system have the same circumradius. -/
lemma orthocentric_system.exists_circumradius_eq {s : set P} (ho : orthocentric_system s) :
∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r :=
begin
rcases ho with ⟨t, hto, hts⟩,
use t.circumradius,
intros t₂ ht₂,
have ht₂s := ht₂,
rw hts at ht₂,
rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto ht₂
(injective_of_affine_independent t₂.independent) with ⟨c, hc, h⟩,
rw set.forall_range_iff at h,
have hs : set.range t.points ⊆ s,
{ rw hts,
exact set.subset_insert _ _ },
rw [affine_span_of_orthocentric_system ⟨t, hto, hts⟩ hs
(injective_of_affine_independent t.independent),
←affine_span_of_orthocentric_system ⟨t, hto, hts⟩ ht₂s
(injective_of_affine_independent t₂.independent)] at hc,
exact (t₂.eq_circumradius_of_dist_eq hc h).symm
end
/-- Given any triangle in an orthocentric system, the fourth point is
its orthocenter. -/
lemma orthocentric_system.eq_insert_orthocenter {s : set P} (ho : orthocentric_system s)
{t : triangle ℝ P} (ht : set.range t.points ⊆ s) :
s = insert t.orthocenter (set.range t.points) :=
begin
rcases ho with ⟨t₀, ht₀o, ht₀s⟩,
rw ht₀s at ht,
rcases exists_of_range_subset_orthocentric_system ht₀o ht
(injective_of_affine_independent t.independent) with
⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs,
{ obtain ⟨j₁, hj₁₂, hj₁₃, hj₁₂₃⟩ :
∃ j₁ : fin 3, j₁ ≠ j₂ ∧ j₁ ≠ j₃ ∧ ∀ j : fin 3, j = j₁ ∨ j = j₂ ∨ j = j₃,
{ clear h₂ h₃, dec_trivial! },
suffices h : t₀.points j₁ = t.orthocenter,
{ have hui : (set.univ : set (fin 3)) = {i₁, i₂, i₃}, { ext x, simpa using h₁₂₃ x },
have huj : (set.univ : set (fin 3)) = {j₁, j₂, j₃}, { ext x, simpa using hj₁₂₃ x },
rw [←h, ht₀s, ←set.image_univ, huj, ←set.image_univ, hui],
simp_rw [set.image_insert_eq, set.image_singleton, h₁, ←h₂, ←h₃],
rw set.insert_comm },
exact (triangle.orthocenter_replace_orthocenter_eq_point
hj₁₂ hj₁₃ hj₂₃ h₁₂ h₁₃ h₂₃ h₁ h₂.symm h₃.symm).symm },
{ rw hs,
convert ht₀s using 2,
exact triangle.orthocenter_eq_of_range_eq hs }
end
end euclidean_geometry
|
de33c699cd57a59e0811a35a7d52f041cf2203fc | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/destructive_let_issue.lean | 2116c14c8f6f75b9df3457f75a61e01e73d5012e | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 833 | lean | /- Bug documented at https://github.com/leanprover-community/lean/issues/55 -/
-- set_option trace.elaborator_detail true
-- set_option trace.type_context.is_def_eq true
-- set_option trace.type_context.is_def_eq_detail true
example : bool :=
let x : false → Prop := λ x, match x with end in
let x : bool := match 4 with
| j := @to_bool (j = j) _
end in tt
example : bool :=
let x := match 0 with y := ff end in
match 0 with
| k := k = k
end
example : ℕ → bool
| 0 := tt
| (k+1) := k = k
example : ℕ → bool
| 0 := let x := tt in tt
| (k+1) := k = k
example : ℕ → bool
| 0 := let _ := tt in tt
| (k+1) := k = k
example : ℕ → bool
| 0 := let _ := tt in tt
| (k+1) := if k = k then tt else ff
example : ℕ → bool
| 0 := let _ := tt in tt
| (k+1) := if h : k = k then tt else ff -- succeeds |
5d281440c3047971748422e2aae4b2530d77efe9 | 8b9f17008684d796c8022dab552e42f0cb6fb347 | /tests/lean/run/tactic9.lean | ea0c237901fb77d414a41d276305ade7d4cf111a | [
"Apache-2.0"
] | permissive | chubbymaggie/lean | 0d06ae25f9dd396306fb02190e89422ea94afd7b | d2c7b5c31928c98f545b16420d37842c43b4ae9a | refs/heads/master | 1,611,313,622,901 | 1,430,266,839,000 | 1,430,267,083,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 174 | lean | import logic
open tactic
theorem tst {A B : Prop} (H1 : A) (H2 : B) : ((fun x : Prop, x) A) ∧ B ∧ A
:= by apply and.intro; beta; assumption; apply and.intro; assumption
|
4003c8ea5a27877b7c444835cafe03fdbc68fa82 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/combinatorics/partition.lean | 496c745fb6d7c5b9be9d136bbfba1f99cfc52ed6 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,102 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.combinatorics.composition
import Mathlib.data.nat.parity
import Mathlib.tactic.apply_fun
import Mathlib.PostPort
universes l
namespace Mathlib
/-!
# Partitions
A partition of a natural number `n` is a way of writing `n` as a sum of positive integers, where the
order does not matter: two sums that differ only in the order of their summands are considered the
same partition. This notion is closely related to that of a composition of `n`, but in a composition
of `n` the order does matter.
A summand of the partition is called a part.
## Main functions
* `p : partition n` is a structure, made of a multiset of integers which are all positive and
add up to `n`.
## Implementation details
The main motivation for this structure and its API is to show Euler's partition theorem, and
related results.
The representation of a partition as a multiset is very handy as multisets are very flexible and
already have a well-developed API.
## Tags
Partition
## References
<https://en.wikipedia.org/wiki/Partition_(number_theory)>
-/
/-- A partition of `n` is a multiset of positive integers summing to `n`. -/
structure partition (n : ℕ)
where
parts : multiset ℕ
parts_pos : ∀ {i : ℕ}, i ∈ parts → 0 < i
parts_sum : multiset.sum parts = n
namespace partition
/-- A composition induces a partition (just convert the list to a multiset). -/
def of_composition (n : ℕ) (c : composition n) : partition n :=
mk ↑(composition.blocks c) sorry sorry
theorem of_composition_surj {n : ℕ} : function.surjective (of_composition n) := sorry
/--
Given a multiset which sums to `n`, construct a partition of `n` with the same multiset, but
without the zeros.
-/
-- The argument `n` is kept explicit here since it is useful in tactic mode proofs to generate the
-- proof obligation `l.sum = n`.
def of_sums (n : ℕ) (l : multiset ℕ) (hl : multiset.sum l = n) : partition n :=
mk (multiset.filter (fun (_x : ℕ) => _x ≠ 0) l) sorry sorry
/-- A `multiset ℕ` induces a partition on its sum. -/
def of_multiset (l : multiset ℕ) : partition (multiset.sum l) :=
of_sums (multiset.sum l) l sorry
/-- The partition of exactly one part. -/
def indiscrete_partition (n : ℕ) : partition n :=
of_sums n (singleton n) sorry
protected instance inhabited {n : ℕ} : Inhabited (partition n) :=
{ default := indiscrete_partition n }
/--
The number of times a positive integer `i` appears in the partition `of_sums n l hl` is the same
as the number of times it appears in the multiset `l`.
(For `i = 0`, `partition.non_zero` combined with `multiset.count_eq_zero_of_not_mem` gives that
this is `0` instead.)
-/
theorem count_of_sums_of_ne_zero {n : ℕ} {l : multiset ℕ} (hl : multiset.sum l = n) {i : ℕ} (hi : i ≠ 0) : multiset.count i (parts (of_sums n l hl)) = multiset.count i l :=
multiset.count_filter_of_pos hi
theorem count_of_sums_zero {n : ℕ} {l : multiset ℕ} (hl : multiset.sum l = n) : multiset.count 0 (parts (of_sums n l hl)) = 0 :=
multiset.count_filter_of_neg fun (h : 0 ≠ 0) => h rfl
/--
Show there are finitely many partitions by considering the surjection from compositions to
partitions.
-/
protected instance fintype (n : ℕ) : fintype (partition n) :=
fintype.of_surjective (of_composition n) of_composition_surj
/-- The finset of those partitions in which every part is odd. -/
def odds (n : ℕ) : finset (partition n) :=
finset.filter (fun (c : partition n) => ∀ (i : ℕ), i ∈ parts c → ¬even i) finset.univ
/-- The finset of those partitions in which each part is used at most once. -/
def distincts (n : ℕ) : finset (partition n) :=
finset.filter (fun (c : partition n) => multiset.nodup (parts c)) finset.univ
/-- The finset of those partitions in which every part is odd and used at most once. -/
def odd_distincts (n : ℕ) : finset (partition n) :=
odds n ∩ distincts n
|
a056a7287311dac6ddc96306fd9da0e4d5604c61 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/LCNF/Simp.lean | 9679e29548bb87dd2ff07a0a5621d6ebf25b684c | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 3,538 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Compiler.LCNF.ReduceJpArity
import Lean.Compiler.LCNF.Renaming
import Lean.Compiler.LCNF.Simp.Basic
import Lean.Compiler.LCNF.Simp.FunDeclInfo
import Lean.Compiler.LCNF.Simp.JpCases
import Lean.Compiler.LCNF.Simp.Config
import Lean.Compiler.LCNF.Simp.InlineCandidate
import Lean.Compiler.LCNF.Simp.SimpM
import Lean.Compiler.LCNF.Simp.Main
import Lean.Compiler.LCNF.Simp.InlineProj
import Lean.Compiler.LCNF.Simp.DefaultAlt
import Lean.Compiler.LCNF.Simp.SimpValue
import Lean.Compiler.LCNF.Simp.Used
namespace Lean.Compiler.LCNF
open Simp
def Decl.simp? (decl : Decl) : SimpM (Option Decl) := do
updateFunDeclInfo decl.value
traceM `Compiler.simp.inline.info do return m!"{decl.name}:{Format.nest 2 (← (← get).funDeclInfoMap.format)}"
traceM `Compiler.simp.step do ppDecl decl
let value ← simp decl.value
let s ← get
let value ← value.applyRenaming s.binderRenaming
traceM `Compiler.simp.step.new do return m!"{decl.name} :=\n{← ppCode value}"
trace[Compiler.simp.stat] "{decl.name}, size: {value.size}, # visited: {s.visited}, # inline: {s.inline}, # inline local: {s.inlineLocal}"
if let some value ← simpJpCases? value then
let decl := { decl with value }
decl.reduceJpArity
else if (← get).simplified then
return some { decl with value }
else
return none
partial def Decl.simp (decl : Decl) (config : Config) : CompilerM Decl := do
let mut config := config
if (← isTemplateLike decl) then
let mut inlineDefs := config.inlineDefs
/-
At the base phase, we don't inline definitions occurring in instances.
Reason: we eagerly lambda lift local functions occurring at instances before saving their code at the end of the base
phase. The goal is to make them cheap to inline in actual code. By inlining definitions we would be just generating extra
work for the lambda lifter.
There is an exception: inlineable instances. This is important for auxiliary instances such as
```
@[always_inline]
instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind }
```
by keeping `inlineDefs := true`, we can pre-compute the `pure` and `bind` methods for `TermElabM`.
-/
if (← inBasePhase <&&> Meta.isInstance decl.name) then
unless decl.inlineable do
inlineDefs := false
/-
We do not eta-expand or inline partial applications in template like code.
Recall we don't want to generate code for them.
Remark: by eta-expanding partial applications in instances, we also make the simplifier
work harder when inlining instance projections.
-/
config := { config with etaPoly := false, inlinePartial := false, inlineDefs }
go decl config
where
go (decl : Decl) (config : Config) : CompilerM Decl := do
if let some decl ← decl.simp? |>.run { config, declName := decl.name } |>.run' {} |>.run {} then
-- TODO: bound number of steps?
go decl config
else
return decl
def simp (config : Config := {}) (occurrence : Nat := 0) (phase := Phase.base) : Pass :=
.mkPerDeclaration `simp (Decl.simp · config) phase (occurrence := occurrence)
builtin_initialize
registerTraceClass `Compiler.simp (inherited := true)
registerTraceClass `Compiler.simp.stat
registerTraceClass `Compiler.simp.step
registerTraceClass `Compiler.simp.step.new
|
66128675d9122ed6b091a47e9c74e93dd55bebe7 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/geometry/manifold/instances/real.lean | 65f01d24a5f95667b3da4a9c3ea0c9a8363668bb | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 13,775 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import geometry.manifold.smooth_manifold_with_corners
import analysis.inner_product_space.pi_L2
/-!
# Constructing examples of manifolds over ℝ
We introduce the necessary bits to be able to define manifolds modelled over `ℝ^n`, boundaryless
or with boundary or with corners. As a concrete example, we construct explicitly the manifold with
boundary structure on the real interval `[x, y]`.
More specifically, we introduce
* `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n)` for the model space
used to define `n`-dimensional real manifolds with boundary
* `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_quadrant n)` for the model space used
to define `n`-dimensional real manifolds with corners
## Notations
In the locale `manifold`, we introduce the notations
* `𝓡 n` for the identity model with corners on `euclidean_space ℝ (fin n)`
* `𝓡∂ n` for `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n)`.
For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space ℝ (fin m)`,
and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M → N` is a smooth
map, then the derivative of `f` can be written simply as `mfderiv (𝓡 m) (𝓡∂ n) f` (as to why the
model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`).
## Implementation notes
The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a
typeclass. We provide it as `[fact (x < y)]`.
-/
noncomputable theory
open set function
open_locale manifold
/--
The half-space in `ℝ^n`, used to model manifolds with boundary. We only define it when
`1 ≤ n`, as the definition only makes sense in this case.
-/
def euclidean_half_space (n : ℕ) [has_zero (fin n)] : Type :=
{x : euclidean_space ℝ (fin n) // 0 ≤ x 0}
/--
The quadrant in `ℝ^n`, used to model manifolds with corners, made of all vectors with nonnegative
coordinates.
-/
def euclidean_quadrant (n : ℕ) : Type := {x : euclidean_space ℝ (fin n) // ∀i:fin n, 0 ≤ x i}
section
/- Register class instances for euclidean half-space and quadrant, that can not be noticed
without the following reducibility attribute (which is only set in this section). -/
local attribute [reducible] euclidean_half_space euclidean_quadrant
variable {n : ℕ}
instance [has_zero (fin n)] : topological_space (euclidean_half_space n) := by apply_instance
instance : topological_space (euclidean_quadrant n) := by apply_instance
instance [has_zero (fin n)] : inhabited (euclidean_half_space n) := ⟨⟨0, le_rfl⟩⟩
instance : inhabited (euclidean_quadrant n) := ⟨⟨0, λ i, le_rfl⟩⟩
lemma range_half_space (n : ℕ) [has_zero (fin n)] :
range (λx : euclidean_half_space n, x.val) = {y | 0 ≤ y 0} :=
by simp
lemma range_quadrant (n : ℕ) :
range (λx : euclidean_quadrant n, x.val) = {y | ∀i:fin n, 0 ≤ y i} :=
by simp
end
/--
Definition of the model with corners `(euclidean_space ℝ (fin n), euclidean_half_space n)`, used as
a model for manifolds with boundary. In the locale `manifold`, use the shortcut `𝓡∂ n`.
-/
def model_with_corners_euclidean_half_space (n : ℕ) [has_zero (fin n)] :
model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n) :=
{ to_fun := subtype.val,
inv_fun := λx, ⟨update x 0 (max (x 0) 0), by simp [le_refl]⟩,
source := univ,
target := {x | 0 ≤ x 0},
map_source' := λx hx, x.property,
map_target' := λx hx, mem_univ _,
left_inv' := λ ⟨xval, xprop⟩ hx, begin
rw [subtype.mk_eq_mk, update_eq_iff],
exact ⟨max_eq_left xprop, λ i _, rfl⟩
end,
right_inv' := λx hx, update_eq_iff.2 ⟨max_eq_left hx, λ i _, rfl⟩,
source_eq := rfl,
unique_diff' :=
have this : unique_diff_on ℝ _ :=
unique_diff_on.pi (fin n) (λ _, ℝ) _ _ (λ i ∈ ({0} : set (fin n)), unique_diff_on_Ici 0),
by simpa only [singleton_pi] using this,
continuous_to_fun := continuous_subtype_val,
continuous_inv_fun := (continuous_id.update 0 $
(continuous_apply 0).max continuous_const).subtype_mk _ }
/--
Definition of the model with corners `(euclidean_space ℝ (fin n), euclidean_quadrant n)`, used as a
model for manifolds with corners -/
def model_with_corners_euclidean_quadrant (n : ℕ) :
model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_quadrant n) :=
{ to_fun := subtype.val,
inv_fun := λx, ⟨λi, max (x i) 0, λi, by simp only [le_refl, or_true, le_max_iff]⟩,
source := univ,
target := {x | ∀ i, 0 ≤ x i},
map_source' := λx hx, by simpa only [subtype.range_val] using x.property,
map_target' := λx hx, mem_univ _,
left_inv' := λ ⟨xval, xprop⟩ hx, by { ext i, simp only [subtype.coe_mk, xprop i, max_eq_left] },
right_inv' := λ x hx, by { ext1 i, simp only [hx i, max_eq_left] },
source_eq := rfl,
unique_diff' :=
have this : unique_diff_on ℝ _ :=
unique_diff_on.univ_pi (fin n) (λ _, ℝ) _ (λ i, unique_diff_on_Ici 0),
by simpa only [pi_univ_Ici] using this,
continuous_to_fun := continuous_subtype_val,
continuous_inv_fun := continuous.subtype_mk (continuous_pi $ λ i,
(continuous_id.max continuous_const).comp (continuous_apply i)) _ }
localized "notation (name := model_with_corners_self.euclidean) `𝓡 `n :=
(model_with_corners_self ℝ (euclidean_space ℝ (fin n)) :
model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_space ℝ (fin n)))" in manifold
localized "notation (name := model_with_corners_euclidean_half_space.euclidean) `𝓡∂ `n :=
(model_with_corners_euclidean_half_space n :
model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n))" in manifold
/--
The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in
`euclidean_half_space 1`.
-/
def Icc_left_chart (x y : ℝ) [fact (x < y)] :
local_homeomorph (Icc x y) (euclidean_half_space 1) :=
{ source := {z : Icc x y | z.val < y},
target := {z : euclidean_half_space 1 | z.val 0 < y - x},
to_fun := λ(z : Icc x y), ⟨λi, z.val - x, sub_nonneg.mpr z.property.1⟩,
inv_fun := λz, ⟨min (z.val 0 + x) y, by simp [le_refl, z.prop, le_of_lt (fact.out (x < y))]⟩,
map_source' := by simp only [imp_self, sub_lt_sub_iff_right, mem_set_of_eq, forall_true_iff],
map_target' :=
by { simp only [min_lt_iff, mem_set_of_eq], assume z hz, left,
dsimp [-subtype.val_eq_coe] at hz, linarith },
left_inv' := begin
rintros ⟨z, hz⟩ h'z,
simp only [mem_set_of_eq, mem_Icc] at hz h'z,
simp only [hz, min_eq_left, sub_add_cancel]
end,
right_inv' := begin
rintros ⟨z, hz⟩ h'z,
rw subtype.mk_eq_mk,
funext,
dsimp at hz h'z,
have A : x + z 0 ≤ y, by linarith,
rw subsingleton.elim i 0,
simp only [A, add_comm, add_sub_cancel', min_eq_left],
end,
open_source := begin
have : is_open {z : ℝ | z < y} := is_open_Iio,
exact this.preimage continuous_subtype_val
end,
open_target := begin
have : is_open {z : ℝ | z < y - x} := is_open_Iio,
have : is_open {z : euclidean_space ℝ (fin 1) | z 0 < y - x} :=
this.preimage (@continuous_apply (fin 1) (λ _, ℝ) _ 0),
exact this.preimage continuous_subtype_val
end,
continuous_to_fun := begin
apply continuous.continuous_on,
apply continuous.subtype_mk,
have : continuous (λ (z : ℝ) (i : fin 1), z - x) :=
continuous.sub (continuous_pi $ λi, continuous_id) continuous_const,
exact this.comp continuous_subtype_val,
end,
continuous_inv_fun := begin
apply continuous.continuous_on,
apply continuous.subtype_mk,
have A : continuous (λ z : ℝ, min (z + x) y) :=
(continuous_id.add continuous_const).min continuous_const,
have B : continuous (λz : euclidean_space ℝ (fin 1), z 0) := continuous_apply 0,
exact (A.comp B).comp continuous_subtype_val
end }
/--
The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in
`euclidean_half_space 1`.
-/
def Icc_right_chart (x y : ℝ) [fact (x < y)] :
local_homeomorph (Icc x y) (euclidean_half_space 1) :=
{ source := {z : Icc x y | x < z.val},
target := {z : euclidean_half_space 1 | z.val 0 < y - x},
to_fun := λ(z : Icc x y), ⟨λi, y - z.val, sub_nonneg.mpr z.property.2⟩,
inv_fun := λz,
⟨max (y - z.val 0) x, by simp [le_refl, z.prop, le_of_lt (fact.out (x < y)), sub_eq_add_neg]⟩,
map_source' := by simp only [imp_self, mem_set_of_eq, sub_lt_sub_iff_left, forall_true_iff],
map_target' :=
by { simp only [lt_max_iff, mem_set_of_eq], assume z hz, left,
dsimp [-subtype.val_eq_coe] at hz, linarith },
left_inv' := begin
rintros ⟨z, hz⟩ h'z,
simp only [mem_set_of_eq, mem_Icc] at hz h'z,
simp only [hz, sub_eq_add_neg, max_eq_left, add_add_neg_cancel'_right, neg_add_rev, neg_neg]
end,
right_inv' := begin
rintros ⟨z, hz⟩ h'z,
rw subtype.mk_eq_mk,
funext,
dsimp at hz h'z,
have A : x ≤ y - z 0, by linarith,
rw subsingleton.elim i 0,
simp only [A, sub_sub_cancel, max_eq_left],
end,
open_source := begin
have : is_open {z : ℝ | x < z} := is_open_Ioi,
exact this.preimage continuous_subtype_val
end,
open_target := begin
have : is_open {z : ℝ | z < y - x} := is_open_Iio,
have : is_open {z : euclidean_space ℝ (fin 1) | z 0 < y - x} :=
this.preimage (@continuous_apply (fin 1) (λ _, ℝ) _ 0),
exact this.preimage continuous_subtype_val
end,
continuous_to_fun := begin
apply continuous.continuous_on,
apply continuous.subtype_mk,
have : continuous (λ (z : ℝ) (i : fin 1), y - z) :=
continuous_const.sub (continuous_pi (λi, continuous_id)),
exact this.comp continuous_subtype_val,
end,
continuous_inv_fun := begin
apply continuous.continuous_on,
apply continuous.subtype_mk,
have A : continuous (λ z : ℝ, max (y - z) x) :=
(continuous_const.sub continuous_id).max continuous_const,
have B : continuous (λz : euclidean_space ℝ (fin 1), z 0) := continuous_apply 0,
exact (A.comp B).comp continuous_subtype_val
end }
/--
Charted space structure on `[x, y]`, using only two charts taking values in
`euclidean_half_space 1`.
-/
instance Icc_manifold (x y : ℝ) [fact (x < y)] : charted_space (euclidean_half_space 1) (Icc x y) :=
{ atlas := {Icc_left_chart x y, Icc_right_chart x y},
chart_at := λz, if z.val < y then Icc_left_chart x y else Icc_right_chart x y,
mem_chart_source := λz, begin
by_cases h' : z.val < y,
{ simp only [h', if_true],
exact h' },
{ simp only [h', if_false],
apply lt_of_lt_of_le (fact.out (x < y)),
simpa only [not_lt] using h'}
end,
chart_mem_atlas := λ z, by by_cases h' : (z : ℝ) < y; simp [h'] }
/--
The manifold structure on `[x, y]` is smooth.
-/
instance Icc_smooth_manifold (x y : ℝ) [fact (x < y)] :
smooth_manifold_with_corners (𝓡∂ 1) (Icc x y) :=
begin
have M : cont_diff_on ℝ ∞ (λz : euclidean_space ℝ (fin 1), - z + (λi, y - x)) univ,
{ rw cont_diff_on_univ,
exact cont_diff_id.neg.add cont_diff_const },
apply smooth_manifold_with_corners_of_cont_diff_on,
assume e e' he he',
simp only [atlas, mem_singleton_iff, mem_insert_iff] at he he',
/- We need to check that any composition of two charts gives a `C^∞` function. Each chart can be
either the left chart or the right chart, leaving 4 possibilities that we handle successively.
-/
rcases he with rfl | rfl; rcases he' with rfl | rfl,
{ -- `e = left chart`, `e' = left chart`
exact (mem_groupoid_of_pregroupoid.mpr (symm_trans_mem_cont_diff_groupoid _ _ _)).1 },
{ -- `e = left chart`, `e' = right chart`
apply M.congr_mono _ (subset_univ _),
rintro _ ⟨⟨hz₁, hz₂⟩, ⟨⟨z, hz₀⟩, rfl⟩⟩,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart,
update_same, max_eq_left, hz₀, lt_sub_iff_add_lt] with mfld_simps at hz₁ hz₂,
rw [min_eq_left hz₁.le, lt_add_iff_pos_left] at hz₂,
ext i,
rw subsingleton.elim i 0,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, *,
pi_Lp.add_apply, pi_Lp.neg_apply, max_eq_left, min_eq_left hz₁.le, update_same]
with mfld_simps,
abel },
{ -- `e = right chart`, `e' = left chart`
apply M.congr_mono _ (subset_univ _),
rintro _ ⟨⟨hz₁, hz₂⟩, ⟨z, hz₀⟩, rfl⟩,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, max_lt_iff,
update_same, max_eq_left hz₀] with mfld_simps at hz₁ hz₂,
rw lt_sub_comm at hz₁,
ext i,
rw subsingleton.elim i 0,
simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart,
pi_Lp.add_apply, pi_Lp.neg_apply, update_same, max_eq_left, hz₀, hz₁.le] with mfld_simps,
abel },
{ -- `e = right chart`, `e' = right chart`
exact (mem_groupoid_of_pregroupoid.mpr (symm_trans_mem_cont_diff_groupoid _ _ _)).1 }
end
/-! Register the manifold structure on `Icc 0 1`, and also its zero and one. -/
section
lemma fact_zero_lt_one : fact ((0 : ℝ) < 1) := ⟨zero_lt_one⟩
local attribute [instance] fact_zero_lt_one
instance : charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1) := by apply_instance
instance : smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1) := by apply_instance
end
|
a8fab982996fa9f13a807efc82b5da9362f95eed | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/testing/slim_check/sampleable.lean | 80495ac90cdc911496bc0c76c8d8448cc9b4fcbf | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 31,384 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import data.lazy_list.basic
import data.tree
import data.int.basic
import control.bifunctor
import control.ulift
import tactic.linarith
import testing.slim_check.gen
/-!
# `sampleable` Class
This class permits the creation samples of a given type
controlling the size of those values using the `gen` monad`. It also
helps minimize examples by creating smaller versions of given values.
When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`,
`slim_check` requires that `ℕ` have an instance of `sampleable` and for
`prime n` to be decidable. `slim_check` will then use the instance of
`sampleable` to generate small examples of ℕ and progressively increase
in size. For each example `n`, `prime n` is tested. If it is false,
the example will be rejected (not a test success nor a failure) and
`slim_check` will move on to other examples. If `prime n` is true, `n
≤ 100` will be tested. If it is false, `n` is a counter-example of `∀
n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true,
the test passes and `slim_check` moves on to trying more examples.
This is a port of the Haskell QuickCheck library.
## Main definitions
* `sampleable` class
* `sampleable_functor` and `sampleable_bifunctor` class
* `sampleable_ext` class
### `sampleable`
`sampleable α` provides ways of creating examples of type `α`,
and given such an example `x : α`, gives us a way to shrink it
and find simpler examples.
### `sampleable_ext`
`sampleable_ext` generalizes the behavior of `sampleable`
and makes it possible to express instances for types that
do not lend themselves to introspection, such as `ℕ → ℕ`.
If we test a quantification over functions the
counter-examples cannot be shrunken or printed meaningfully.
For that purpose, `sampleable_ext` provides a proxy representation
`proxy_repr` that can be printed and shrunken as well
as interpreted (using `interp`) as an object of the right type.
### `sampleable_functor` and `sampleable_bifunctor`
`sampleable_functor F` and `sampleable_bifunctor F` makes it possible
to create samples of and shrink `F α` given a sampling function and a
shrinking function for arbitrary `α`.
This allows us to separate the logic for generating the shape of a
collection from the logic for generating its contents. Specifically,
the contents could be generated using either `sampleable` or
`sampleable_ext` instance and the `sampleable_(bi)functor` does not
need to use that information
## Shrinking
Shrinking happens when `slim_check` find a counter-example to a
property. It is likely that the example will be more complicated than
necessary so `slim_check` proceeds to shrink it as much as
possible. Although equally valid, a smaller counter-example is easier
for a user to understand and use.
The `sampleable` class, beside having the `sample` function, has a
`shrink` function so that we can use specialized knowledge while
shrinking a value. It is not responsible for the whole shrinking process
however. It only has to take one step in the shrinking process.
`slim_check` will repeatedly call `shrink` until no more steps can
be taken. Because `shrink` guarantees that the size of the candidates
it produces is strictly smaller than the argument, we know that
`slim_check` is guaranteed to terminate.
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v w
namespace slim_check
variables (α : Type u)
local infix ` ≺ `:50 := has_well_founded.r
/-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/
def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y
/-- `shrink_fn α` is the type of functions that shrink an
argument of type `α` -/
@[reducible]
def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x }
/-- `sampleable α` provides ways of creating examples of type `α`,
and given such an example `x : α`, gives us a way to shrink it
and find simpler examples. -/
class sampleable :=
[wf : has_sizeof α]
(sample [] : gen α)
(shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil)
attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof
attribute [instance, priority 200] sampleable.wf
/-- `sampleable_functor F` makes it possible to create samples of and
shrink `F α` given a sampling function and a shrinking function for
arbitrary `α` -/
class sampleable_functor (F : Type u → Type v) [functor F] :=
[wf : Π α [has_sizeof α], has_sizeof (F α)]
(sample [] : ∀ {α}, gen α → gen (F α))
(shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α))
(p_repr : ∀ α, has_repr α → has_repr (F α))
/-- `sampleable_bifunctor F` makes it possible to create samples of
and shrink `F α β` given a sampling function and a shrinking function
for arbitrary `α` and `β` -/
class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] :=
[wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)]
(sample [] : ∀ {α β}, gen α → gen β → gen (F α β))
(shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β))
(p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β))
export sampleable (sample shrink)
/-- This function helps infer the proxy representation and
interpretation in `sampleable_ext` instances. -/
meta def sampleable.mk_trivial_interp : tactic unit :=
tactic.refine ``(id)
/-- `sampleable_ext` generalizes the behavior of `sampleable`
and makes it possible to express instances for types that
do not lend themselves to introspection, such as `ℕ → ℕ`.
If we test a quantification over functions the
counter-examples cannot be shrunken or printed meaningfully.
For that purpose, `sampleable_ext` provides a proxy representation
`proxy_repr` that can be printed and shrunken as well
as interpreted (using `interp`) as an object of the right type. -/
class sampleable_ext (α : Sort u) :=
(proxy_repr : Type v)
[wf : has_sizeof proxy_repr]
(interp [] : proxy_repr → α . sampleable.mk_trivial_interp)
[p_repr : has_repr proxy_repr]
(sample [] : gen proxy_repr)
(shrink : shrink_fn proxy_repr)
attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf
open nat lazy_list
section prio
open sampleable_ext
set_option default_priority 50
instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α :=
{ proxy_repr := α,
sample := sampleable.sample α,
shrink := shrink }
instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] :
sampleable (F α) :=
{ wf := _,
sample := sampleable_functor.sample F (sampleable.sample α),
shrink := sampleable_functor.shrink α sampleable.shrink }
instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α]
[sampleable β] : sampleable (F α β) :=
{ wf := _,
sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β),
shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink }
set_option default_priority 100
instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] :
sampleable_ext (F α) :=
{ wf := _,
proxy_repr := F (proxy_repr α),
interp := functor.map (interp _),
sample := sampleable_functor.sample F (sampleable_ext.sample α),
shrink := sampleable_functor.shrink _ sampleable_ext.shrink,
p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr }
instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F]
[sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) :=
{ wf := _,
proxy_repr := F (proxy_repr α) (proxy_repr β),
interp := bifunctor.bimap (interp _) (interp _),
sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β),
shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink,
p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr }
end prio
/-- `nat.shrink' k n` creates a list of smaller natural numbers by
successively dividing `n` by 2 and subtracting the difference from
`k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/
def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k →
list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k }
| n hn ls :=
if h : n ≤ 1
then ls.reverse
else
have h₂ : 0 < n, by linarith,
have 1 * n / 2 < n,
from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂),
have n / 2 < n, by simpa,
let m := n / 2 in
have h₀ : m ≤ k, from le_trans (le_of_lt this) hn,
have h₃ : 0 < m,
by simp only [m, lt_iff_add_one_le, zero_add]; rw [nat.le_div_iff_mul_le]; linarith,
have h₁ : k - m < k,
from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃,
nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls)
/-- `nat.shrink n` creates a list of smaller natural numbers by
successively dividing by 2 and subtracting the difference from
`n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/
def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } :=
if h : n > 0 then
have ∀ k, 1 < k → n / k < n, from
λ k hk,
nat.div_lt_of_lt_mul
(suffices 1 * n < k * n, by simpa,
nat.mul_lt_mul_of_pos_right hk h),
⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n (le_refl _) []
else
[]
open gen
/--
Transport a `sampleable` instance from a type `α` to a type `β` using
functions between the two, going in both directions.
Function `g` is used to define the well-founded order that
`shrink` is expected to follow.
-/
def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α)
(h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β :=
{ wf := ⟨ sizeof ∘ g ⟩,
sample := f <$> sample α,
shrink := λ x,
have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x),
by introv h'; solve_by_elim [lt_of_le_of_lt],
subtype.map f this <$> shrink (g x) }
instance nat.sampleable : sampleable ℕ :=
{ sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))),
(3, coe <$> choose_any (fin $ succ sz))] dec_trivial,
shrink := λ x, lazy_list.of_list $ nat.shrink x }
/-- `iterate_shrink p x` takes a decidable predicate `p` and a
value `x` of some sampleable type and recursively shrinks `x`.
It first calls `shrink x` to get a list of candidate sample,
finds the first that satisfies `p` and recursively tries
to shrink that one. -/
def iterate_shrink {α} [has_to_string α] [sampleable α]
(p : α → Prop) [decidable_pred p] :
α → option α :=
well_founded.fix has_well_founded.wf $ λ x f_rec,
do trace sformat!"{x} : {(shrink x).to_list}" $ pure (),
y ← (shrink x).find (λ a, p a),
f_rec y y.property <|> some y.val .
instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) :=
sampleable.lift ℕ fin.of_nat' subtype.val $
λ i, (mod_le _ _ : i % n ≤ i)
@[priority 100]
instance fin.sampleable' {n} : sampleable (fin (succ n)) :=
sampleable.lift ℕ fin.of_nat subtype.val $
λ i, (mod_le _ _ : i % succ n ≤ i)
instance pnat.sampleable : sampleable ℕ+ :=
sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a,
by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, tsub_zero, succ_sub_succ_eq_sub]
/-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/
def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩
local attribute [instance, priority 2000] int.has_sizeof
instance int.sampleable : sampleable ℤ :=
{ wf := _,
sample := sized $ λ sz,
freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)),
(3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))]
dec_trivial,
shrink :=
λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $
λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] }
instance bool.sampleable : sampleable bool :=
{ wf := ⟨ λ b, if b then 1 else 0 ⟩,
sample := do { x ← choose_any bool,
return x },
shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩
else lazy_list.nil }
/--
Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by
first shrinking `x` and pairing the results with `y` and then shrinking
`y` and pairing the results with `x`.
All pairs either contain `x` untouched or `y` untouched. We rely on
shrinking being repeated for `x` to get maximally shrunken and then
for `y` to get shrunken too.
-/
def prod.shrink {α β} [has_sizeof α] [has_sizeof β]
(shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β)
| ⟨x₀,x₁⟩ :=
let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } :=
(shr_a x₀).map $ subtype.map (λ a, (a, x₁))
(λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h),
xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } :=
(shr_b x₁).map $ subtype.map (λ a, (x₀, a))
(λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in
xs₀.append xs₁
instance prod.sampleable : sampleable_bifunctor.{u v} prod :=
{ wf := _,
sample := λ α β sama samb, do
{ ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)),
⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)),
pure (x,y) },
shrink := @prod.shrink,
p_repr := @prod.has_repr }
instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) :=
sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_refl _
/-- shrinking function for sum types -/
def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α)
(shrink_β : shrink_fn β) : shrink_fn (α ⊕ β)
| (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a,
by dsimp [sizeof_lt]; unfold_wf; solve_by_elim
| (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a,
by dsimp [sizeof_lt]; unfold_wf; solve_by_elim
instance sum.sampleable : sampleable_bifunctor.{u v} sum :=
{ wf := _,
sample := λ (α : Type u) (β : Type v) sam_α sam_β,
(@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|>
@uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β),
shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β,
p_repr := @sum.has_repr }
instance rat.sampleable : sampleable ℚ :=
sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $
begin
intro i,
rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf;
dsimp [rat.mk_pnat],
mono*,
{ rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs],
apply int.abs_div_le_abs },
{ change _ - 1 ≤ y-1,
apply tsub_le_tsub_right,
apply nat.div_le_of_le_mul,
suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa },
apply nat.mul_le_mul_right,
apply gcd_pos_of_pos_right _ hy }
end
/-- `sampleable_char` can be specialized into customized `sampleable char` instances.
The resulting instance has `1 / length` chances of making an unrestricted choice of characters
and it otherwise chooses a character from `characters` with uniform probabilities. -/
def sampleable_char (length : nat) (characters : string) : sampleable char :=
{ sample := do { x ← choose_nat 0 length dec_trivial,
if x.val = 0 then do
n ← sample ℕ,
pure $ char.of_nat n
else do
i ← choose_nat 0 (characters.length - 1) dec_trivial,
pure (characters.mk_iterator.nextn i).curr },
shrink := λ _, lazy_list.nil }
instance char.sampleable : sampleable char :=
sampleable_char 3 " 0123abcABC:,;`\\/"
variables {α}
section list_shrink
variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x })
lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k}
(hk : 0 < k) (hk' : k < xs.length) :
sizeof (list.drop k xs) < sizeof xs :=
begin
induction xs with x xs generalizing k,
{ cases hk' },
cases k,
{ cases hk },
have : sizeof xs < sizeof (x :: xs),
{ unfold_wf, linarith },
cases k,
{ simp only [this, list.drop] },
{ simp only [list.drop],
transitivity,
{ solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] },
{ assumption } }
end
lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) :
sizeof (a :: xs) < sizeof (b :: xs) :=
by unfold_wf; assumption
lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') :
sizeof (x :: xs) < sizeof (x :: xs') :=
by unfold_wf; assumption
lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') :
sizeof (xs ++ ys) < sizeof (xs ++ ys') :=
begin
induction xs,
{ apply h },
{ unfold_wf,
simp only [list.sizeof, add_lt_add_iff_left],
exact xs_ih }
end
lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs :=
by cases xs; unfold_wf; linarith
/--
`list.shrink_removes` shrinks a list by removing chunks of size `k` in
the middle of the list.
-/
def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n,
n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs }
| xs n hn :=
if hkn : k > n then lazy_list.nil
else
if hkn' : k = n then
have 1 < xs.sizeof,
by { subst_vars, cases xs, { contradiction },
unfold_wf, apply lt_of_lt_of_le,
show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith },
{ mono, apply list.one_le_sizeof, } },
lazy_list.singleton ⟨[], this ⟩
else
have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn',
match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with
| ⟨xs₁,xs₂⟩, h :=
have h₄ : xs₁ = xs.take k,
by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto,
have h₃ : xs₂ = xs.drop k,
by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto,
have sizeof xs₂ < sizeof xs,
by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length],
have h₁ : n - k = xs₂.length,
by simp only [h₃, ←hn, list.length_drop],
have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs,
by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄];
solve_by_elim [list.sizeof_append_lt_left],
lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁
end
/--
`list.shrink_one xs` shrinks list `xs` by shrinking only one item in
the list.
-/
def list.shrink_one : shrink_fn (list α)
| [] := lazy_list.nil
| (x :: xs) :=
lazy_list.append
(subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x)
(subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs)
/-- `list.shrink_with shrink_f xs` shrinks `xs` by first
considering `xs` with chunks removed in the middle (starting with
chunks of size `xs.length` and halving down to `1`) and then
shrinks only one element of the list.
This strategy is taken directly from Haskell's QuickCheck -/
def list.shrink_with (xs : list α) :
lazy_list { ys : list α // sizeof_lt ys xs } :=
let n := xs.length in
lazy_list.append
((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k,
if hk : 0 < k
then list.shrink_removes k hk xs n rfl
else lazy_list.nil ))
(list.shrink_one shr _)
end list_shrink
instance list.sampleable : sampleable_functor list.{u} :=
{ wf := _,
sample := λ α sam_α, list_of sam_α,
shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α,
p_repr := @list.has_repr }
instance Prop.sampleable_ext : sampleable_ext Prop :=
{ proxy_repr := bool,
interp := coe,
sample := choose_any bool,
shrink := λ _, lazy_list.nil }
/-- `no_shrink` is a type annotation to signal that
a certain type is not to be shrunk. It can be useful in
combination with other types: e.g. `xs : list (no_shrink ℤ)`
will result in the list being cut down but individual
integers being kept as is. -/
def no_shrink (α : Type*) := α
instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) :=
⟨ (default α : α) ⟩
/-- Introduction of the `no_shrink` type. -/
def no_shrink.mk {α} (x : α) : no_shrink α := x
/-- Selector of the `no_shrink` type. -/
def no_shrink.get {α} (x : no_shrink α) : α := x
instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) :=
{ sample := no_shrink.mk <$> sample α }
instance string.sampleable : sampleable string :=
{ sample := do { x ← list_of (sample char), pure x.as_string },
.. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_refl _ }
/-- implementation of `sampleable (tree α)` -/
def tree.sample (sample : gen α) : ℕ → gen (tree α) | n :=
if h : n > 0
then have n / 2 < n, from div_lt_self h (by norm_num),
tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2)
else pure tree.nil
/-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced
by `well_founded.fix` and turns it into a shrinking function whose
result is adequate to use in a recursive call. -/
def rec_shrink {α : Type*} [has_sizeof α] (t : α)
(sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) :
shrink_fn { t' : α // sizeof_lt t' t }
| ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' },
⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht'
lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t :=
by cases t; unfold_wf; linarith
instance : functor tree :=
{ map := @tree.map }
/--
Recursion principle for shrinking tree-like structures.
-/
def rec_shrink_with [has_sizeof α]
(shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } →
list (lazy_list { y : α // sizeof_lt y x })) :
shrink_fn α :=
well_founded.fix (sizeof_measure_wf _) $ λ t f_rec,
lazy_list.join
(lazy_list.of_list $
shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _)
lemma rec_shrink_with_eq [has_sizeof α]
(shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } →
list (lazy_list { y : α // sizeof_lt y x }))
(x : α) :
rec_shrink_with shrink_a x =
lazy_list.join
(lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) :=
begin
conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], },
congr, ext ⟨y, h⟩, refl
end
/-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree,
each subtrees, and by shrinking the subtree to recombine them.
This strategy is taken directly from Haskell's QuickCheck -/
def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) :=
rec_shrink_with $ λ t,
match t with
| tree.nil := λ f_rec, []
| (tree.node x t₀ t₁) :=
λ f_rec,
have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁),
by clear _match; have := tree.one_le_sizeof t₀;
dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *;
unfold_wf; linarith,
have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁),
by dsimp [sizeof_lt]; unfold_wf; linarith,
have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁),
by dsimp [sizeof_lt]; unfold_wf; linarith,
[lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩],
(prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map
$ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁,
by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩]
end
instance sampleable_tree : sampleable_functor tree :=
{ wf := _,
sample := λ α sam_α, sized $ tree.sample sam_α,
shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α,
p_repr := @tree.has_repr }
/-- Type tag that signals to `slim_check` to use small values for a given type. -/
def small (α : Type*) := α
/-- Add the `small` type tag -/
def small.mk {α} (x : α) : small α := x
/-- Type tag that signals to `slim_check` to use large values for a given type. -/
def large (α : Type*) := α
/-- Add the `large` type tag -/
def large.mk {α} (x : α) : large α := x
instance small.functor : functor small := id.monad.to_functor
instance large.functor : functor large := id.monad.to_functor
instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default α : α) ⟩
instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default α : α) ⟩
instance small.sampleable_functor : sampleable_functor small :=
{ wf := _,
sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp,
shrink := λ α _, id,
p_repr := λ α, id }
instance large.sampleable_functor : sampleable_functor large :=
{ wf := _,
sample := λ α samp, gen.resize (λ n, n * 5) samp,
shrink := λ α _, id,
p_repr := λ α, id }
instance ulift.sampleable_functor : sampleable_functor ulift.{u v} :=
{ wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩,
sample := λ α samp, uliftable.up_map ulift.up $ samp,
shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)),
p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ }
/-!
## Subtype instances
The following instances are meant to improve the testing of properties of the form
`∀ i j, i ≤ j, ...`
The naive way to test them is to choose two numbers `i` and `j` and check that
the proper ordering is satisfied. Instead, the following instances make it
so that `j` will be chosen with considerations to the required ordering
constraints. The benefit is that we will not have to discard any choice
of `j`.
-/
/-! ### Subtypes of `ℕ` -/
instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } :=
{ sample :=
do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial,
pure ⟨x, h.2⟩},
shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $
λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x }
instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } :=
{ sample :=
do { (y : ℕ) ← slim_check.sampleable.sample ℕ,
pure ⟨x+y, by norm_num⟩ },
shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) },
subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, lt_tsub_iff_left.mp h'⟩) <$>
shrink (y - x) }
/- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice
to satisfy `x < y` -/
instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } :=
{ sample :=
do { (y : ℕ) ← slim_check.sampleable.sample ℕ,
pure ⟨x+y+1, by linarith⟩ },
shrink := λ x, shrink _ }
/-! ### Subtypes of any `linear_ordered_add_comm_group` -/
instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] :
slim_check.sampleable { x : α // x ≤ y } :=
{ sample :=
do { x ← sample α,
pure ⟨y - |x|, sub_le_self _ (abs_nonneg _) ⟩ },
shrink := λ _, lazy_list.nil }
instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] :
slim_check.sampleable { y : α // x ≤ y } :=
{ sample :=
do { y ← sample α,
pure ⟨x + |y|, by norm_num [abs_nonneg]⟩ },
shrink := λ _, lazy_list.nil }
/-!
### Subtypes of `ℤ`
Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search.
-/
instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } :=
sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs)
(λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring)
instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } :=
sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs)
(λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring)
instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } :=
sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $
by linarith [int.coe_nat_nonneg n]⟩)
(λ ⟨i, h⟩, (y - i - 1).nat_abs)
(λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring)
instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } :=
sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs)
(λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring)
/-! ### Subtypes of any `list` -/
instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } :=
{ sample := permutation_of xs,
shrink := λ _, lazy_list.nil }
instance perm'.slim_check {xs : list α} :
slim_check.sampleable { ys : list α // list.perm ys xs } :=
{ sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs,
shrink := λ _, lazy_list.nil }
setup_tactic_parser
open tactic
/--
Print (at most) 10 samples of a given type to stdout for debugging.
-/
def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do
xs ← io.run_rand $ uliftable.down $
do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up,
pure ⟨xs.map repr⟩ },
xs.mmap' io.put_str_ln
/-- Create a `gen α` expression from the argument of `#sample` -/
meta def mk_generator (e : expr) : tactic (expr × expr) := do
t ← infer_type e,
match t with
| `(gen %%t) := do
repr_inst ← mk_app ``has_repr [t] >>= mk_instance,
pure (repr_inst, e)
| _ := do
samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance,
repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst],
gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst],
pure (repr_inst, gen)
end
/--
`#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random
values of type `my_type` of using an increasing size parameter.
```lean
#sample nat
-- prints
-- 0
-- 0
-- 2
-- 24
-- 64
-- 76
-- 5
-- 132
-- 8
-- 449
-- or some other sequence of numbers
#sample list int
-- prints
-- []
-- [1, 1]
-- [-7, 9, -6]
-- [36]
-- [-500, 105, 260]
-- [-290]
-- [17, 156]
-- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968]
-- [-643]
-- [11892, 16329, -15095, -15461]
-- or whatever
```
-/
@[user_command]
meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit :=
do e ← texpr,
of_tactic $ do
e ← i_to_expr e,
(repr_inst, gen) ← mk_generator e,
print_samples ← mk_mapp ``print_samples [none, repr_inst, gen],
sample ← eval_expr (io unit) print_samples,
unsafe_run_io sample
end slim_check
|
f947bbb3b405cf7d69381db6ca25c5d4df8b6b27 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/measure_theory/content.lean | 0e8a2c269ba86c158db0dbce53ab9f42f8e7132d | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,570 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import measure_theory.measure_space
import measure_theory.borel_space
import topology.opens
import topology.compacts
/-!
# Contents
In this file we work with *contents*. A content `λ` is a function from a certain class of subsets
(such as the the compact subsets) to `ennreal` (or `ℝ≥0`) that is
* additive: If `K₁` and `K₂` are disjoint sets in the domain of `λ`,
then `λ(K₁ ∪ K₂) = λ(K₁) + λ(K₂)`;
* subadditive: If `K₁` and `K₂` are in the domain of `λ`, then `λ(K₁ ∪ K₂) ≤ λ(K₁) + λ(K₂)`;
* monotone: If `K₁ ⊆ K₂` are in the domain of `λ`, then `λ(K₁) ≤ λ(K₂)`.
We show that:
* Given a content `λ` on compact sets, we get a countably subadditive map that vanishes at `∅`.
In Halmos (1950) this is called the *inner content* `λ*` of `λ`.
* Given an inner content, we define an outer measure.
We don't explicitly define the type of contents.
In this file we only work on contents on compact sets, and inner contents on open sets, and both
contents and inner contents map into the extended nonnegative reals. However, in other applications
other choices can be made, and it is not a priori clear what the best interface should be.
## Main definitions
* `measure_theory.inner_content`: define an inner content from an content
* `measure_theory.outer_measure.of_content`: construct an outer measure from a content
## References
* Paul Halmos (1950), Measure Theory, §53
* https://en.wikipedia.org/wiki/Content_(measure_theory)
-/
universe variables u v w
noncomputable theory
open set topological_space
open_locale nnreal
namespace measure_theory
variables {G : Type w} [topological_space G]
/-- Constructing the inner content of a content. From a content defined on the compact sets, we
obtain a function defined on all open sets, by taking the supremum of the content of all compact
subsets. -/
def inner_content (μ : compacts G → ennreal) (U : opens G) : ennreal :=
⨆ (K : compacts G) (h : K.1 ⊆ U), μ K
lemma le_inner_content {μ : compacts G → ennreal} (K : compacts G) (U : opens G)
(h2 : K.1 ⊆ U) : μ K ≤ inner_content μ U :=
le_supr_of_le K $ le_supr _ h2
lemma inner_content_le {μ : compacts G → ennreal}
(h : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂)
(U : opens G) (K : compacts G)
(h2 : (U : set G) ⊆ K.1) : inner_content μ U ≤ μ K :=
bsupr_le $ λ K' hK', h _ _ (subset.trans hK' h2)
lemma inner_content_of_is_compact {μ : compacts G → ennreal}
(h : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂) {K : set G} (h1K : is_compact K)
(h2K : is_open K) : inner_content μ ⟨K, h2K⟩ = μ ⟨K, h1K⟩ :=
le_antisymm (bsupr_le $ λ K' hK', h _ ⟨K, h1K⟩ hK')
(le_inner_content _ _ subset.rfl)
lemma inner_content_empty {μ : compacts G → ennreal} (h : μ ⊥ = 0) :
inner_content μ ∅ = 0 :=
begin
refine le_antisymm _ (zero_le _), rw ←h,
refine bsupr_le (λ K hK, _),
have : K = ⊥, { ext1, rw [subset_empty_iff.mp hK, compacts.bot_val] }, rw this, refl'
end
/-- This is "unbundled", because that it required for the API of `induced_outer_measure`. -/
lemma inner_content_mono {μ : compacts G → ennreal} ⦃U V : set G⦄ (hU : is_open U) (hV : is_open V)
(h2 : U ⊆ V) : inner_content μ ⟨U, hU⟩ ≤ inner_content μ ⟨V, hV⟩ :=
supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2
lemma inner_content_exists_compact {μ : compacts G → ennreal} {U : opens G}
(hU : inner_content μ U < ⊤) {ε : ℝ≥0} (hε : 0 < ε) :
∃ K : compacts G, K.1 ⊆ U ∧ inner_content μ U ≤ μ K + ε :=
begin
have h'ε := ennreal.zero_lt_coe_iff.2 hε,
cases le_or_lt (inner_content μ U) ε,
{ exact ⟨⊥, empty_subset _, le_trans h (le_add_of_nonneg_left (zero_le _))⟩ },
have := ennreal.sub_lt_self (ne_of_lt hU) (ne_of_gt $ lt_trans h'ε h) h'ε,
conv at this {to_rhs, rw inner_content }, simp only [lt_supr_iff] at this,
rcases this with ⟨U, h1U, h2U⟩, refine ⟨U, h1U, _⟩,
rw [← ennreal.sub_le_iff_le_add], exact le_of_lt h2U
end
/-- The inner content of a supremum of opens is at most the sum of the individual inner
contents. -/
lemma inner_content_Sup_nat [t2_space G] {μ : compacts G → ennreal}
(h1 : μ ⊥ = 0)
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂) (U : ℕ → opens G) :
inner_content μ (⨆ (i : ℕ), U i) ≤ ∑' (i : ℕ), inner_content μ (U i) :=
begin
have h3 : ∀ (t : finset ℕ) (K : ℕ → compacts G), μ (t.sup K) ≤ t.sum (λ i, μ (K i)),
{ intros t K, refine finset.induction_on t _ _,
{ simp only [h1, nonpos_iff_eq_zero, finset.sum_empty, finset.sup_empty] },
{ intros n s hn ih, rw [finset.sup_insert, finset.sum_insert hn],
exact le_trans (h2 _ _) (add_le_add_left ih _) }},
refine bsupr_le (λ K hK, _),
rcases is_compact.elim_finite_subcover K.2 _ (λ i, (U i).prop) _ with ⟨t, ht⟩, swap,
{ convert hK, rw [opens.supr_def, subtype.coe_mk] },
rcases K.2.finite_compact_cover t (coe ∘ U) (λ i _, (U _).prop) (by simp only [ht])
with ⟨K', h1K', h2K', h3K'⟩,
let L : ℕ → compacts G := λ n, ⟨K' n, h1K' n⟩,
convert le_trans (h3 t L) _,
{ ext1, rw [h3K', compacts.finset_sup_val, finset.sup_eq_supr] },
refine le_trans (finset.sum_le_sum _) (ennreal.sum_le_tsum t),
intros i hi, refine le_trans _ (le_supr _ (L i)),
refine le_trans _ (le_supr _ (h2K' i)), refl'
end
/-- The inner content of a union of sets is at most the sum of the individual inner contents.
This is the "unbundled" version of `inner_content_Sup_nat`.
It required for the API of `induced_outer_measure`. -/
lemma inner_content_Union_nat [t2_space G] {μ : compacts G → ennreal}
(h1 : μ ⊥ = 0)
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂)
⦃U : ℕ → set G⦄ (hU : ∀ (i : ℕ), is_open (U i)) :
inner_content μ ⟨⋃ (i : ℕ), U i, is_open_Union hU⟩ ≤ ∑' (i : ℕ), inner_content μ ⟨U i, hU i⟩ :=
by { have := inner_content_Sup_nat h1 h2 (λ i, ⟨U i, hU i⟩), rwa [opens.supr_def] at this }
lemma inner_content_comap {μ : compacts G → ennreal} (f : G ≃ₜ G)
(h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K) (U : opens G) :
inner_content μ (U.comap f.continuous) = inner_content μ U :=
begin
refine supr_congr _ ((compacts.equiv f).surjective) _,
intro K, refine supr_congr_Prop image_subset_iff _,
intro hK, simp only [equiv.coe_fn_mk, subtype.mk_eq_mk, ennreal.coe_eq_coe, compacts.equiv],
apply h,
end
@[to_additive]
lemma is_mul_left_invariant_inner_content [group G] [topological_group G] {μ : compacts G → ennreal}
(h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G)
(U : opens G) : inner_content μ (U.comap $ continuous_mul_left g) = inner_content μ U :=
by convert inner_content_comap (homeomorph.mul_left g) (λ K, h g) U
-- @[to_additive] (fails for now)
lemma inner_content_pos_of_is_mul_left_invariant [t2_space G] [group G] [topological_group G]
{μ : compacts G → ennreal}
(h1 : μ ⊥ = 0)
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂)
(h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K)
(K : compacts G) (hK : 0 < μ K) (U : opens G) (hU : (U : set G).nonempty) :
0 < inner_content μ U :=
begin
have : (interior (U : set G)).nonempty, rwa [U.prop.interior_eq],
rcases compact_covered_by_mul_left_translates K.2 this with ⟨s, hs⟩,
suffices : μ K ≤ s.card * inner_content μ U,
{ exact (ennreal.mul_pos.mp $ lt_of_lt_of_le hK this).2 },
have : K.1 ⊆ ↑⨆ (g ∈ s), U.comap $ continuous_mul_left g,
{ simpa only [opens.supr_def, opens.coe_comap, subtype.coe_mk] },
refine (le_inner_content _ _ this).trans _,
refine (rel_supr_sum (inner_content μ) (inner_content_empty h1) (≤)
(inner_content_Sup_nat h1 h2) _ _).trans _,
simp only [is_mul_left_invariant_inner_content h3, finset.sum_const, nsmul_eq_mul, le_refl]
end
lemma inner_content_mono' {μ : compacts G → ennreal} ⦃U V : set G⦄
(hU : is_open U) (hV : is_open V) (h2 : U ⊆ V) :
inner_content μ ⟨U, hU⟩ ≤ inner_content μ ⟨V, hV⟩ :=
supr_le_supr $ λ K, supr_le_supr_const $ λ hK, subset.trans hK h2
namespace outer_measure
/-- Extending a content on compact sets to an outer measure on all sets. -/
def of_content [t2_space G] (μ : compacts G → ennreal) (h1 : μ ⊥ = 0) : outer_measure G :=
induced_outer_measure (λ U hU, inner_content μ ⟨U, hU⟩) is_open_empty (inner_content_empty h1)
variables [t2_space G] {μ : compacts G → ennreal} {h1 : μ ⊥ = 0}
(h2 : ∀ (K₁ K₂ : compacts G), μ (K₁ ⊔ K₂) ≤ μ K₁ + μ K₂)
include h2
lemma of_content_opens (U : opens G) : of_content μ h1 U = inner_content μ U :=
induced_outer_measure_eq' (λ _, is_open_Union) (inner_content_Union_nat h1 h2)
inner_content_mono U.2
lemma of_content_le (h : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂)
(U : opens G) (K : compacts G) (hUK : (U : set G) ⊆ K.1) : of_content μ h1 U ≤ μ K :=
(of_content_opens h2 U).le.trans $ inner_content_le h U K hUK
lemma le_of_content_compacts (K : compacts G) : μ K ≤ of_content μ h1 K.1 :=
begin
rw [of_content, induced_outer_measure_eq_infi],
{ exact le_infi (λ U, le_infi $ λ hU, le_infi $ le_inner_content K ⟨U, hU⟩) },
{ exact inner_content_Union_nat h1 h2 },
{ exact inner_content_mono }
end
lemma of_content_eq_infi (A : set G) :
of_content μ h1 A = ⨅ (U : set G) (hU : is_open U) (h : A ⊆ U), inner_content μ ⟨U, hU⟩ :=
induced_outer_measure_eq_infi _ (inner_content_Union_nat h1 h2) inner_content_mono A
lemma of_content_interior_compacts (h3 : ∀ (K₁ K₂ : compacts G), K₁.1 ⊆ K₂.1 → μ K₁ ≤ μ K₂)
(K : compacts G) : of_content μ h1 (interior K.1) ≤ μ K :=
le_trans (le_of_eq $ of_content_opens h2 (opens.interior K.1))
(inner_content_le h3 _ _ interior_subset)
lemma of_content_exists_compact {U : opens G} (hU : of_content μ h1 U < ⊤) {ε : ℝ≥0}
(hε : 0 < ε) : ∃ K : compacts G, K.1 ⊆ U ∧ of_content μ h1 U ≤ of_content μ h1 K.1 + ε :=
begin
rw [of_content_opens h2] at hU ⊢,
rcases inner_content_exists_compact hU hε with ⟨K, h1K, h2K⟩,
exact ⟨K, h1K, le_trans h2K $ add_le_add_right (le_of_content_compacts h2 K) _⟩,
end
lemma of_content_exists_open {A : set G} (hA : of_content μ h1 A < ⊤) {ε : ℝ≥0} (hε : 0 < ε) :
∃ U : opens G, A ⊆ U ∧ of_content μ h1 U ≤ of_content μ h1 A + ε :=
begin
rcases induced_outer_measure_exists_set _ _ inner_content_mono hA hε with ⟨U, hU, h2U, h3U⟩,
exact ⟨⟨U, hU⟩, h2U, h3U⟩, swap, exact inner_content_Union_nat h1 h2
end
lemma of_content_preimage (f : G ≃ₜ G) (h : ∀ ⦃K : compacts G⦄, μ (K.map f f.continuous) = μ K)
(A : set G) : of_content μ h1 (f ⁻¹' A) = of_content μ h1 A :=
begin
refine induced_outer_measure_preimage _ (inner_content_Union_nat h1 h2) inner_content_mono _
(λ s, f.is_open_preimage) _,
intros s hs, convert inner_content_comap f h ⟨s, hs⟩
end
@[to_additive]
lemma is_mul_left_invariant_of_content [group G] [topological_group G]
(h : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K) (g : G)
(A : set G) : of_content μ h1 ((λ h, g * h) ⁻¹' A) = of_content μ h1 A :=
by convert of_content_preimage h2 (homeomorph.mul_left g) (λ K, h g) A
lemma of_content_caratheodory (A : set G) :
(of_content μ h1).caratheodory.is_measurable' A ↔ ∀ (U : opens G),
of_content μ h1 (U ∩ A) + of_content μ h1 (U \ A) ≤ of_content μ h1 U :=
begin
dsimp [opens], rw subtype.forall,
apply induced_outer_measure_caratheodory,
apply inner_content_Union_nat h1 h2,
apply inner_content_mono'
end
-- @[to_additive] (fails for now)
lemma of_content_pos_of_is_mul_left_invariant [group G] [topological_group G]
(h3 : ∀ (g : G) {K : compacts G}, μ (K.map _ $ continuous_mul_left g) = μ K)
(K : compacts G) (hK : 0 < μ K) {U : set G} (h1U : is_open U) (h2U : U.nonempty) :
0 < of_content μ h1 U :=
by { convert inner_content_pos_of_is_mul_left_invariant h1 h2 h3 K hK ⟨U, h1U⟩ h2U,
exact of_content_opens h2 ⟨U, h1U⟩ }
end outer_measure
end measure_theory
|
f2bbfe7f09030852b3e8727daae51caccdc9dff1 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/ring_theory/algebra_tower.lean | bddda52cab1e3b50b782c88fe85b32b5f9eea477 | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 6,740 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import ring_theory.adjoin
universes u v w u₁
variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁)
/-- Typeclass for a tower of three algebras. -/
class is_algebra_tower [comm_semiring R] [comm_semiring S] [semiring A]
[algebra R S] [algebra S A] [algebra R A] : Prop :=
(smul_assoc : ∀ (x : R) (y : S) (z : A), (x • y) • z = x • (y • z))
namespace is_algebra_tower
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra R A] [algebra S B] [algebra R B]
theorem algebra_map_eq [is_algebra_tower R S A] :
algebra_map R A = (algebra_map S A).comp (algebra_map R S) :=
ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one,
smul_assoc, one_smul]
theorem algebra_map_apply [is_algebra_tower R S A] (x : R) :
algebra_map R A x = algebra_map S A (algebra_map R S x) :=
by rw [algebra_map_eq R S A, ring_hom.comp_apply]
variables {R S A}
theorem of_algebra_map_eq (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) :
is_algebra_tower R S A :=
⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩
@[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A]
(h1 h2 : algebra S A) (h : ∀ {r : S} {x : A}, (by clear h2; exact r • x) = r • x) : h1 = h2 :=
begin
unfreezingI { cases h1 with f1 g1 h11 h12, cases h2 with f2 g2 h21 h22,
cases f1, cases f2, congr', { ext r x, exact h },
ext r, erw [← mul_one (g1 r), ← h12, ← mul_one (g2 r), ← h22, h], refl }
end
variables [is_algebra_tower R S A] [is_algebra_tower R S B]
variables (R S A)
theorem comap_eq : algebra.comap.algebra R S A = ‹_› :=
algebra.ext _ _ $ λ x (z : A),
calc algebra_map R S x • z
= (x • 1 : S) • z : by rw algebra.algebra_map_eq_smul_one
... = x • (1 : S) • z : by rw smul_assoc
... = (by exact x • z : A) : by rw one_smul
/-- In a tower, the canonical map from the middle element to the top element is an
algebra homomorphism over the bottom element. -/
def to_alg_hom : S →ₐ[R] A :=
{ commutes' := λ _, (algebra_map_apply _ _ _ _).symm,
.. algebra_map S A }
@[simp] lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl
variables (R) {S A B}
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def restrict_base (f : A →ₐ[S] B) : A →ₐ[R] B :=
{ commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B],
exact f.commutes (algebra_map R S r) },
.. (f : A →+* B) }
@[simp] lemma restrict_base_apply (f : A →ₐ[S] B) (x : A) : restrict_base R f x = f x := rfl
instance left : is_algebra_tower S S A :=
of_algebra_map_eq $ λ x, rfl
instance right : is_algebra_tower R S S :=
of_algebra_map_eq $ λ x, rfl
instance nat : is_algebra_tower ℕ S A :=
of_algebra_map_eq $ λ x, ((algebra_map S A).map_nat_cast x).symm
instance comap {R S A : Type*} [comm_semiring R] [comm_semiring S] [semiring A]
[algebra R S] [algebra S A] : is_algebra_tower R S (algebra.comap R S A) :=
of_algebra_map_eq $ λ x, rfl
instance subsemiring (U : subsemiring S) : is_algebra_tower U S A :=
of_algebra_map_eq $ λ x, rfl
instance subring {S A : Type*} [comm_ring S] [ring A] [algebra S A]
(U : set S) [is_subring U] : is_algebra_tower U S A :=
of_algebra_map_eq $ λ x, rfl
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [algebra R A]
variables [comm_semiring B] [algebra A B] [algebra R B] [is_algebra_tower R A B]
instance subalgebra (S : subalgebra R A) : is_algebra_tower R S A :=
of_algebra_map_eq $ λ x, rfl
instance polynomial : is_algebra_tower R A (polynomial B) :=
of_algebra_map_eq $ λ x, congr_arg polynomial.C $ algebra_map_apply R A B x
theorem aeval_apply (x : B) (p) : polynomial.aeval R B x p =
polynomial.aeval A B x (polynomial.map (algebra_map R A) p) :=
by rw [polynomial.aeval_def, polynomial.aeval_def, polynomial.eval₂_map, algebra_map_eq R A B]
end comm_semiring
section ring
variables [comm_ring R] [comm_ring S] [ring A] [algebra R S] [algebra S A] [algebra R A]
variables [is_algebra_tower R S A]
/-- If A/S/R is a tower of algebras then any S-subalgebra of A gives an R-subalgebra of A. -/
def subalgebra_comap (U : subalgebra S A) : subalgebra R A :=
{ carrier := U,
algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ } }
theorem subalgebra_comap_top : subalgebra_comap R S A ⊤ = ⊤ :=
algebra.eq_top_iff.2 $ λ _, show _ ∈ (⊤ : subalgebra S A), from algebra.mem_top
end ring
section comm_ring
variables [comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A]
variables [is_algebra_tower R S A]
theorem range_under_adjoin (t : set A) :
(to_alg_hom R S A).range.under (algebra.adjoin _ t) =
subalgebra_comap R S A (algebra.adjoin S t) :=
subalgebra.ext $ λ z,
show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔
z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A),
from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A),
by rw this,
by { ext z, exact ⟨λ ⟨⟨x, y, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, hy⟩, rfl⟩⟩ }
instance int : is_algebra_tower ℤ S A :=
of_algebra_map_eq $ λ x, ((algebra_map S A).map_int_cast x).symm
end comm_ring
section division_ring
variables [field R] [division_ring S] [algebra R S] [char_zero R] [char_zero S]
instance rat : is_algebra_tower ℚ R S :=
of_algebra_map_eq $ λ x, ((algebra_map R S).map_rat_cast x).symm
end division_ring
end is_algebra_tower
namespace algebra
theorem adjoin_algebra_map' {R : Type u} {S : Type v} {A : Type w}
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] (s : set S) :
adjoin R (algebra_map S (comap R S A) '' s) = subalgebra.map (adjoin R s) (to_comap R S A) :=
le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩)
(subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩)
theorem adjoin_algebra_map (R : Type u) (S : Type v) (A : Type w)
[comm_ring R] [comm_ring S] [comm_ring A] [algebra R S] [algebra S A] [algebra R A]
[is_algebra_tower R S A] (s : set S) :
adjoin R (algebra_map S A '' s) = subalgebra.map (adjoin R s) (is_algebra_tower.to_alg_hom R S A) :=
le_antisymm (adjoin_le $ set.image_subset_iff.2 $ λ y hy, ⟨y, subset_adjoin hy, rfl⟩)
(subalgebra.map_le.2 $ adjoin_le $ λ y hy, subset_adjoin ⟨y, hy, rfl⟩)
end algebra
|
860d857fd184579f8014934c1f14104dddc1d9fc | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/limits/shapes/comm_sq.lean | a58826108945ccb7e5139f4d62ae54cf22fe2e24 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 22,227 | lean | /-
Copyright (c) 2022 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Joël Riou
-/
import category_theory.comm_sq
import category_theory.limits.preserves.shapes.pullbacks
import category_theory.limits.shapes.zero_morphisms
import category_theory.limits.constructions.binary_products
import category_theory.limits.opposites
/-!
# Pullback and pushout squares
We provide another API for pullbacks and pushouts.
`is_pullback fst snd f g` is the proposition that
```
P --fst--> X
| |
snd f
| |
v v
Y ---g---> Z
```
is a pullback square.
(And similarly for `is_pushout`.)
We provide the glue to go back and forth to the usual `is_limit` API for pullbacks, and prove
`is_pullback (pullback.fst : pullback f g ⟶ X) (pullback.snd : pullback f g ⟶ Y) f g`
for the usual `pullback f g` provided by the `has_limit` API.
We don't attempt to restate everything we know about pullbacks in this language,
but do restate the pasting lemmas.
## Future work
Bicartesian squares, and
show that the pullback and pushout squares for a biproduct are bicartesian.
-/
noncomputable theory
open category_theory
open category_theory.limits
universes v₁ v₂ u₁ u₂
namespace category_theory
variables {C : Type u₁} [category.{v₁} C]
namespace comm_sq
variables {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
/--
The (not necessarily limiting) `pullback_cone h i` implicit in the statement
that we have `comm_sq f g h i`.
-/
def cone (s : comm_sq f g h i) : pullback_cone h i := pullback_cone.mk _ _ s.w
/--
The (not necessarily limiting) `pushout_cocone f g` implicit in the statement
that we have `comm_sq f g h i`.
-/
def cocone (s : comm_sq f g h i) : pushout_cocone f g := pushout_cocone.mk _ _ s.w
/-- The pushout cocone in the opposite category associated to the cone of
a commutative square identifies to the cocone of the flipped commutative square in
the opposite category -/
def cone_op (p : comm_sq f g h i) : p.cone.op ≅ p.flip.op.cocone :=
pushout_cocone.ext (iso.refl _) (by tidy) (by tidy)
/-- The pullback cone in the opposite category associated to the cocone of
a commutative square identifies to the cone of the flipped commutative square in
the opposite category -/
def cocone_op (p : comm_sq f g h i) : p.cocone.op ≅ p.flip.op.cone :=
pullback_cone.ext (iso.refl _) (by tidy) (by tidy)
/-- The pushout cocone obtained from the pullback cone associated to a
commutative square in the opposite category identifies to the cocone associated
to the flipped square. -/
def cone_unop {W X Y Z : Cᵒᵖ} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
(p : comm_sq f g h i) : p.cone.unop ≅ p.flip.unop.cocone :=
pushout_cocone.ext (iso.refl _) (by tidy) (by tidy)
/-- The pullback cone obtained from the pushout cone associated to a
commutative square in the opposite category identifies to the cone associated
to the flipped square. -/
def cocone_unop {W X Y Z : Cᵒᵖ} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
(p : comm_sq f g h i) : p.cocone.unop ≅ p.flip.unop.cone :=
pullback_cone.ext (iso.refl _) (by tidy) (by tidy)
end comm_sq
/-- The proposition that a square
```
P --fst--> X
| |
snd f
| |
v v
Y ---g---> Z
```
is a pullback square.
-/
structure is_pullback
{P X Y Z : C} (fst : P ⟶ X) (snd : P ⟶ Y) (f : X ⟶ Z) (g : Y ⟶ Z)
extends comm_sq fst snd f g : Prop :=
(is_limit' : nonempty (is_limit (pullback_cone.mk _ _ w)))
/-- The proposition that a square
```
Z ---f---> X
| |
g inl
| |
v v
Y --inr--> P
```
is a pushout square.
-/
structure is_pushout
{Z X Y P : C} (f : Z ⟶ X) (g : Z ⟶ Y) (inl : X ⟶ P) (inr : Y ⟶ P)
extends comm_sq f g inl inr : Prop :=
(is_colimit' : nonempty (is_colimit (pushout_cocone.mk _ _ w)))
/-!
We begin by providing some glue between `is_pullback` and the `is_limit` and `has_limit` APIs.
(And similarly for `is_pushout`.)
-/
namespace is_pullback
variables {P X Y Z : C} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z}
/--
The (limiting) `pullback_cone f g` implicit in the statement
that we have a `is_pullback fst snd f g`.
-/
def cone (h : is_pullback fst snd f g) : pullback_cone f g := h.to_comm_sq.cone
/--
The cone obtained from `is_pullback fst snd f g` is a limit cone.
-/
noncomputable def is_limit (h : is_pullback fst snd f g) : is_limit h.cone :=
h.is_limit'.some
/-- If `c` is a limiting pullback cone, then we have a `is_pullback c.fst c.snd f g`. -/
lemma of_is_limit {c : pullback_cone f g} (h : limits.is_limit c) :
is_pullback c.fst c.snd f g :=
{ w := c.condition,
is_limit' := ⟨is_limit.of_iso_limit h
(limits.pullback_cone.ext (iso.refl _) (by tidy) (by tidy))⟩, }
/-- A variant of `of_is_limit` that is more useful with `apply`. -/
lemma of_is_limit' (w : comm_sq fst snd f g) (h : limits.is_limit w.cone) :
is_pullback fst snd f g :=
of_is_limit h
/-- The pullback provided by `has_pullback f g` fits into a `is_pullback`. -/
lemma of_has_pullback (f : X ⟶ Z) (g : Y ⟶ Z) [has_pullback f g] :
is_pullback (pullback.fst : pullback f g ⟶ X) (pullback.snd : pullback f g ⟶ Y) f g :=
of_is_limit (limit.is_limit (cospan f g))
/-- If `c` is a limiting binary product cone, and we have a terminal object,
then we have `is_pullback c.fst c.snd 0 0`
(where each `0` is the unique morphism to the terminal object). -/
lemma of_is_product {c : binary_fan X Y} (h : limits.is_limit c) (t : is_terminal Z) :
is_pullback c.fst c.snd (t.from _) (t.from _) :=
of_is_limit (is_pullback_of_is_terminal_is_product _ _ _ _ t
(is_limit.of_iso_limit h (limits.cones.ext (iso.refl c.X) (by rintro ⟨⟨⟩⟩; { dsimp, simp, }))))
variables (X Y)
lemma of_has_binary_product' [has_binary_product X Y] [has_terminal C] :
is_pullback limits.prod.fst limits.prod.snd (terminal.from X) (terminal.from Y) :=
of_is_product (limit.is_limit _) terminal_is_terminal
open_locale zero_object
lemma of_has_binary_product [has_binary_product X Y] [has_zero_object C] [has_zero_morphisms C] :
is_pullback limits.prod.fst limits.prod.snd (0 : X ⟶ 0) (0 : Y ⟶ 0) :=
by convert of_is_product (limit.is_limit _) has_zero_object.zero_is_terminal
variables {X Y}
/-- Any object at the top left of a pullback square is
isomorphic to the pullback provided by the `has_limit` API. -/
noncomputable
def iso_pullback (h : is_pullback fst snd f g) [has_pullback f g] : P ≅ pullback f g :=
(limit.iso_limit_cone ⟨_, h.is_limit⟩).symm
@[simp] lemma iso_pullback_hom_fst (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.hom ≫ pullback.fst = fst :=
by { dsimp [iso_pullback, cone, comm_sq.cone], simp, }
@[simp] lemma iso_pullback_hom_snd (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.hom ≫ pullback.snd = snd :=
by { dsimp [iso_pullback, cone, comm_sq.cone], simp, }
@[simp] lemma iso_pullback_inv_fst (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.inv ≫ fst = pullback.fst :=
by simp [iso.inv_comp_eq]
@[simp] lemma iso_pullback_inv_snd (h : is_pullback fst snd f g) [has_pullback f g] :
h.iso_pullback.inv ≫ snd = pullback.snd :=
by simp [iso.inv_comp_eq]
lemma of_iso_pullback (h : comm_sq fst snd f g) [has_pullback f g] (i : P ≅ pullback f g)
(w₁ : i.hom ≫ pullback.fst = fst) (w₂ : i.hom ≫ pullback.snd = snd) : is_pullback fst snd f g :=
of_is_limit' h (limits.is_limit.of_iso_limit (limit.is_limit _)
(@pullback_cone.ext _ _ _ _ _ _ _ (pullback_cone.mk _ _ _) _ i w₁.symm w₂.symm).symm)
lemma of_horiz_is_iso [is_iso fst] [is_iso g] (sq : comm_sq fst snd f g) :
is_pullback fst snd f g := of_is_limit' sq
begin
refine pullback_cone.is_limit.mk _ (λ s, s.fst ≫ inv fst) (by tidy) (λ s, _) (by tidy),
simp only [← cancel_mono g, category.assoc, ← sq.w, is_iso.inv_hom_id_assoc, s.condition],
end
end is_pullback
namespace is_pushout
variables {Z X Y P : C} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P}
/--
The (colimiting) `pushout_cocone f g` implicit in the statement
that we have a `is_pushout f g inl inr`.
-/
def cocone (h : is_pushout f g inl inr) : pushout_cocone f g := h.to_comm_sq.cocone
/--
The cocone obtained from `is_pushout f g inl inr` is a colimit cocone.
-/
noncomputable def is_colimit (h : is_pushout f g inl inr) : is_colimit h.cocone :=
h.is_colimit'.some
/-- If `c` is a colimiting pushout cocone, then we have a `is_pushout f g c.inl c.inr`. -/
lemma of_is_colimit {c : pushout_cocone f g} (h : limits.is_colimit c) :
is_pushout f g c.inl c.inr :=
{ w := c.condition,
is_colimit' := ⟨is_colimit.of_iso_colimit h
(limits.pushout_cocone.ext (iso.refl _) (by tidy) (by tidy))⟩, }
/-- A variant of `of_is_colimit` that is more useful with `apply`. -/
lemma of_is_colimit' (w : comm_sq f g inl inr) (h : limits.is_colimit w.cocone) :
is_pushout f g inl inr :=
of_is_colimit h
/-- The pushout provided by `has_pushout f g` fits into a `is_pushout`. -/
lemma of_has_pushout (f : Z ⟶ X) (g : Z ⟶ Y) [has_pushout f g] :
is_pushout f g (pushout.inl : X ⟶ pushout f g) (pushout.inr : Y ⟶ pushout f g) :=
of_is_colimit (colimit.is_colimit (span f g))
/-- If `c` is a colimiting binary coproduct cocone, and we have an initial object,
then we have `is_pushout 0 0 c.inl c.inr`
(where each `0` is the unique morphism from the initial object). -/
lemma of_is_coproduct {c : binary_cofan X Y} (h : limits.is_colimit c) (t : is_initial Z) :
is_pushout (t.to _) (t.to _) c.inl c.inr :=
of_is_colimit (is_pushout_of_is_initial_is_coproduct _ _ _ _ t
(is_colimit.of_iso_colimit h
(limits.cocones.ext (iso.refl c.X) (by rintro ⟨⟨⟩⟩; { dsimp, simp, }))))
variables (X Y)
lemma of_has_binary_coproduct' [has_binary_coproduct X Y] [has_initial C] :
is_pushout (initial.to _) (initial.to _) (coprod.inl : X ⟶ _) (coprod.inr : Y ⟶ _) :=
of_is_coproduct (colimit.is_colimit _) initial_is_initial
open_locale zero_object
lemma of_has_binary_coproduct
[has_binary_coproduct X Y] [has_zero_object C] [has_zero_morphisms C] :
is_pushout (0 : 0 ⟶ X) (0 : 0 ⟶ Y) coprod.inl coprod.inr :=
by convert of_is_coproduct (colimit.is_colimit _) has_zero_object.zero_is_initial
variables {X Y}
/-- Any object at the top left of a pullback square is
isomorphic to the pullback provided by the `has_limit` API. -/
noncomputable
def iso_pushout (h : is_pushout f g inl inr) [has_pushout f g] : P ≅ pushout f g :=
(colimit.iso_colimit_cocone ⟨_, h.is_colimit⟩).symm
@[simp] lemma inl_iso_pushout_inv (h : is_pushout f g inl inr) [has_pushout f g] :
pushout.inl ≫ h.iso_pushout.inv = inl :=
by { dsimp [iso_pushout, cocone, comm_sq.cocone], simp, }
@[simp] lemma inr_iso_pushout_inv (h : is_pushout f g inl inr) [has_pushout f g] :
pushout.inr ≫ h.iso_pushout.inv = inr :=
by { dsimp [iso_pushout, cocone, comm_sq.cocone], simp, }
@[simp] lemma inl_iso_pushout_hom (h : is_pushout f g inl inr) [has_pushout f g] :
inl ≫ h.iso_pushout.hom = pushout.inl :=
by simp [←iso.eq_comp_inv]
@[simp] lemma inr_iso_pushout_hom (h : is_pushout f g inl inr) [has_pushout f g] :
inr ≫ h.iso_pushout.hom = pushout.inr :=
by simp [←iso.eq_comp_inv]
lemma of_iso_pushout (h : comm_sq f g inl inr) [has_pushout f g] (i : P ≅ pushout f g)
(w₁ : inl ≫ i.hom = pushout.inl) (w₂ : inr ≫ i.hom = pushout.inr) : is_pushout f g inl inr :=
of_is_colimit' h (limits.is_colimit.of_iso_colimit (colimit.is_colimit _)
(@pushout_cocone.ext _ _ _ _ _ _ _ (pushout_cocone.mk _ _ _) _ i w₁ w₂).symm)
end is_pushout
namespace is_pullback
variables {P X Y Z : C} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z}
lemma flip (h : is_pullback fst snd f g) : is_pullback snd fst g f :=
of_is_limit (@pullback_cone.flip_is_limit _ _ _ _ _ _ _ _ _ _ h.w.symm h.is_limit)
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
/-- The square with `0 : 0 ⟶ 0` on the left and `𝟙 X` on the right is a pullback square. -/
lemma zero_left (X : C) : is_pullback (0 : 0 ⟶ X) (0 : 0 ⟶ 0) (𝟙 X) (0 : 0 ⟶ X) :=
{ w := by simp,
is_limit' :=
⟨{ lift := λ s, 0,
fac' := λ s, by simpa using @pullback_cone.equalizer_ext _ _ _ _ _ _ _ s _ 0 (𝟙 _)
(by simpa using (pullback_cone.condition s).symm), }⟩ }
/-- The square with `0 : 0 ⟶ 0` on the top and `𝟙 X` on the bottom is a pullback square. -/
lemma zero_top (X : C) : is_pullback (0 : 0 ⟶ 0) (0 : 0 ⟶ X) (0 : 0 ⟶ X) (𝟙 X) :=
(zero_left X).flip
end
/-- Paste two pullback squares "vertically" to obtain another pullback square. -/
-- Objects here are arranged in a 3x2 grid, and indexed by their xy coordinates.
-- Morphisms are named `hᵢⱼ` for a horizontal morphism starting at `(i,j)`,
-- and `vᵢⱼ` for a vertical morphism starting at `(i,j)`.
lemma paste_vert {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pullback h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) :
is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ :=
(of_is_limit
(big_square_is_pullback _ _ _ _ _ _ _ s.w t.w t.is_limit s.is_limit))
/-- Paste two pullback squares "horizontally" to obtain another pullback square. -/
lemma paste_horiz {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pullback h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) :
is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) :=
(paste_vert s.flip t.flip).flip
/-- Given a pullback square assembled from a commuting square on the top and
a pullback square on the bottom, the top square is a pullback square. -/
lemma of_bot {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pullback h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁) (p : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁)
(t : is_pullback h₂₁ v₂₁ v₂₂ h₃₁) :
is_pullback h₁₁ v₁₁ v₁₂ h₂₁ :=
of_is_limit (left_square_is_pullback _ _ _ _ _ _ _ p _ t.is_limit s.is_limit)
/-- Given a pullback square assembled from a commuting square on the left and
a pullback square on the right, the left square is a pullback square. -/
lemma of_right {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pullback (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂)) (p : h₁₁ ≫ v₁₂ = v₁₁ ≫ h₂₁)
(t : is_pullback h₁₂ v₁₂ v₁₃ h₂₂) :
is_pullback h₁₁ v₁₁ v₁₂ h₂₁ :=
(of_bot s.flip p.symm t.flip).flip
lemma op (h : is_pullback fst snd f g) : is_pushout g.op f.op snd.op fst.op :=
is_pushout.of_is_colimit (is_colimit.of_iso_colimit
(limits.pullback_cone.is_limit_equiv_is_colimit_op h.flip.cone h.flip.is_limit)
h.to_comm_sq.flip.cone_op)
lemma unop {P X Y Z : Cᵒᵖ} {fst : P ⟶ X} {snd : P ⟶ Y} {f : X ⟶ Z} {g : Y ⟶ Z}
(h : is_pullback fst snd f g) : is_pushout g.unop f.unop snd.unop fst.unop :=
is_pushout.of_is_colimit (is_colimit.of_iso_colimit
(limits.pullback_cone.is_limit_equiv_is_colimit_unop h.flip.cone h.flip.is_limit)
h.to_comm_sq.flip.cone_unop)
lemma of_vert_is_iso [is_iso snd] [is_iso f] (sq : comm_sq fst snd f g) :
is_pullback fst snd f g := is_pullback.flip (of_horiz_is_iso sq.flip)
end is_pullback
namespace is_pushout
variables {Z X Y P : C} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P}
lemma flip (h : is_pushout f g inl inr) : is_pushout g f inr inl :=
of_is_colimit (@pushout_cocone.flip_is_colimit _ _ _ _ _ _ _ _ _ _ h.w.symm h.is_colimit)
section
variables [has_zero_object C] [has_zero_morphisms C]
open_locale zero_object
/-- The square with `0 : 0 ⟶ 0` on the right and `𝟙 X` on the left is a pushout square. -/
lemma zero_right (X : C) : is_pushout (0 : X ⟶ 0) (𝟙 X) (0 : 0 ⟶ 0) (0 : X ⟶ 0) :=
{ w := by simp,
is_colimit' :=
⟨{ desc := λ s, 0,
fac' := λ s, begin
have c := @pushout_cocone.coequalizer_ext _ _ _ _ _ _ _ s _ 0 (𝟙 _) (by simp)
(by simpa using (pushout_cocone.condition s)),
dsimp at c,
simpa using c,
end }⟩ }
/-- The square with `0 : 0 ⟶ 0` on the bottom and `𝟙 X` on the top is a pushout square. -/
lemma zero_bot (X : C) : is_pushout (𝟙 X) (0 : X ⟶ 0) (0 : X ⟶ 0) (0 : 0 ⟶ 0) :=
(zero_right X).flip
end
/-- Paste two pushout squares "vertically" to obtain another pushout square. -/
-- Objects here are arranged in a 3x2 grid, and indexed by their xy coordinates.
-- Morphisms are named `hᵢⱼ` for a horizontal morphism starting at `(i,j)`,
-- and `vᵢⱼ` for a vertical morphism starting at `(i,j)`.
lemma paste_vert {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pushout h₂₁ v₂₁ v₂₂ h₃₁) :
is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁ :=
(of_is_colimit
(big_square_is_pushout _ _ _ _ _ _ _ s.w t.w t.is_colimit s.is_colimit))
/-- Paste two pushout squares "horizontally" to obtain another pushout square. -/
lemma paste_horiz {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) (t : is_pushout h₁₂ v₁₂ v₁₃ h₂₂) :
is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂) :=
(paste_vert s.flip t.flip).flip
/-- Given a pushout square assembled from a pushout square on the top and
a commuting square on the bottom, the bottom square is a pushout square. -/
lemma of_bot {X₁₁ X₁₂ X₂₁ X₂₂ X₃₁ X₃₂ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₂₁ : X₂₁ ⟶ X₂₂} {h₃₁ : X₃₁ ⟶ X₃₂}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₂₁ : X₂₁ ⟶ X₃₁} {v₂₂ : X₂₂ ⟶ X₃₂}
(s : is_pushout h₁₁ (v₁₁ ≫ v₂₁) (v₁₂ ≫ v₂₂) h₃₁) (p : h₂₁ ≫ v₂₂ = v₂₁ ≫ h₃₁)
(t : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) :
is_pushout h₂₁ v₂₁ v₂₂ h₃₁ :=
of_is_colimit (right_square_is_pushout _ _ _ _ _ _ _ _ p t.is_colimit s.is_colimit)
/-- Given a pushout square assembled from a pushout square on the left and
a commuting square on the right, the right square is a pushout square. -/
lemma of_right {X₁₁ X₁₂ X₁₃ X₂₁ X₂₂ X₂₃ : C}
{h₁₁ : X₁₁ ⟶ X₁₂} {h₁₂ : X₁₂ ⟶ X₁₃} {h₂₁ : X₂₁ ⟶ X₂₂} {h₂₂ : X₂₂ ⟶ X₂₃}
{v₁₁ : X₁₁ ⟶ X₂₁} {v₁₂ : X₁₂ ⟶ X₂₂} {v₁₃ : X₁₃ ⟶ X₂₃}
(s : is_pushout (h₁₁ ≫ h₁₂) v₁₁ v₁₃ (h₂₁ ≫ h₂₂)) (p : h₁₂ ≫ v₁₃ = v₁₂ ≫ h₂₂)
(t : is_pushout h₁₁ v₁₁ v₁₂ h₂₁) :
is_pushout h₁₂ v₁₂ v₁₃ h₂₂ :=
(of_bot s.flip p.symm t.flip).flip
lemma op (h : is_pushout f g inl inr) : is_pullback inr.op inl.op g.op f.op :=
is_pullback.of_is_limit (is_limit.of_iso_limit
(limits.pushout_cocone.is_colimit_equiv_is_limit_op h.flip.cocone h.flip.is_colimit)
h.to_comm_sq.flip.cocone_op)
lemma unop {Z X Y P : Cᵒᵖ} {f : Z ⟶ X} {g : Z ⟶ Y} {inl : X ⟶ P} {inr : Y ⟶ P}
(h : is_pushout f g inl inr) : is_pullback inr.unop inl.unop g.unop f.unop :=
is_pullback.of_is_limit (is_limit.of_iso_limit
(limits.pushout_cocone.is_colimit_equiv_is_limit_unop h.flip.cocone h.flip.is_colimit)
h.to_comm_sq.flip.cocone_unop)
end is_pushout
namespace functor
variables {D : Type u₂} [category.{v₂} D]
variables (F : C ⥤ D) {W X Y Z : C} {f : W ⟶ X} {g : W ⟶ Y} {h : X ⟶ Z} {i : Y ⟶ Z}
lemma map_is_pullback [preserves_limit (cospan h i) F] (s : is_pullback f g h i) :
is_pullback (F.map f) (F.map g) (F.map h) (F.map i) :=
-- This is made slightly awkward because `C` and `D` have different universes,
-- and so the relevant `walking_cospan` diagrams live in different universes too!
begin
refine is_pullback.of_is_limit' (F.map_comm_sq s.to_comm_sq)
(is_limit.equiv_of_nat_iso_of_iso (cospan_comp_iso F h i) _ _ (walking_cospan.ext _ _ _)
(is_limit_of_preserves F s.is_limit)),
{ refl, },
{ dsimp, simp, refl, },
{ dsimp, simp, refl, },
end
lemma map_is_pushout [preserves_colimit (span f g) F] (s : is_pushout f g h i) :
is_pushout (F.map f) (F.map g) (F.map h) (F.map i) :=
begin
refine is_pushout.of_is_colimit' (F.map_comm_sq s.to_comm_sq)
(is_colimit.equiv_of_nat_iso_of_iso (span_comp_iso F f g) _ _ (walking_span.ext _ _ _)
(is_colimit_of_preserves F s.is_colimit)),
{ refl, },
{ dsimp, simp, refl, },
{ dsimp, simp, refl, },
end
end functor
alias functor.map_is_pullback ← is_pullback.map
alias functor.map_is_pushout ← is_pushout.map
end category_theory
|
0170e4e64bd0831e7c218a9ee513d97b5aec0607 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/alias.lean | 1174ec65aa63b8e1a92aab66f61f332300b16bc0 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 317 | lean | def Set (α : Type) := α → Prop
def Set.union (s₁ s₂ : Set α) : Set α :=
fun a => s₁ a ∨ s₂ a
def FinSet (n : Nat) := Fin n → Prop
namespace FinSet
export Set (union)
end FinSet
example (x y : FinSet 10) : FinSet 10 :=
FinSet.union x y
example (x y : FinSet 10) : FinSet 10 :=
x.union y
|
5abbd09e23912478393d923ef2b8017126792a1c | 130c49f47783503e462c16b2eff31933442be6ff | /stage0/src/Lean/Elab/Binders.lean | 55b8bcedd219c6ce9cac993e9cbd99ba82276fc9 | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,502 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Quotation.Precheck
import Lean.Elab.Term
import Lean.Elab.BindersUtil
import Lean.Parser.Term
namespace Lean.Elab.Term
open Meta
open Lean.Parser.Term
/--
Given syntax of the forms
a) (`:` term)?
b) `:` term
return `term` if it is present, or a hole if not. -/
private def expandBinderType (ref : Syntax) (stx : Syntax) : Syntax :=
if stx.getNumArgs == 0 then
mkHole ref
else
stx[1]
/-- Given syntax of the form `ident <|> hole`, return `ident`. If `hole`, then we create a new anonymous name. -/
private def expandBinderIdent (stx : Syntax) : TermElabM Syntax :=
match stx with
| `(_) => mkFreshIdent stx
| _ => pure stx
/-- Given syntax of the form `(ident >> " : ")?`, return `ident`, or a new instance name. -/
private def expandOptIdent (stx : Syntax) : TermElabM Syntax := do
if stx.isNone then
let id ← withFreshMacroScope <| MonadQuotation.addMacroScope `inst
return mkIdentFrom stx id
else
return stx[0]
structure BinderView where
id : Syntax
type : Syntax
bi : BinderInfo
partial def quoteAutoTactic : Syntax → TermElabM Syntax
| stx@(Syntax.ident _ _ _ _) => throwErrorAt stx "invalid auto tactic, identifier is not allowed"
| stx@(Syntax.node k args) => do
if stx.isAntiquot then
throwErrorAt stx "invalid auto tactic, antiquotation is not allowed"
else
let mut quotedArgs ← `(Array.empty)
for arg in args do
if k == nullKind && (arg.isAntiquotSuffixSplice || arg.isAntiquotSplice) then
throwErrorAt arg "invalid auto tactic, antiquotation is not allowed"
else
let quotedArg ← quoteAutoTactic arg
quotedArgs ← `(Array.push $quotedArgs $quotedArg)
`(Syntax.node $(quote k) $quotedArgs)
| Syntax.atom info val => `(mkAtom $(quote val))
| Syntax.missing => unreachable!
def declareTacticSyntax (tactic : Syntax) : TermElabM Name :=
withFreshMacroScope do
let name ← MonadQuotation.addMacroScope `_auto
let type := Lean.mkConst `Lean.Syntax
let tactic ← quoteAutoTactic tactic
let val ← elabTerm tactic type
let val ← instantiateMVars val
trace[Elab.autoParam] val
let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := val, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.safe }
addDecl decl
compileDecl decl
return name
/-
Expand `optional (binderTactic <|> binderDefault)`
def binderTactic := leading_parser " := " >> " by " >> tacticParser
def binderDefault := leading_parser " := " >> termParser
-/
private def expandBinderModifier (type : Syntax) (optBinderModifier : Syntax) : TermElabM Syntax := do
if optBinderModifier.isNone then
return type
else
let modifier := optBinderModifier[0]
let kind := modifier.getKind
if kind == `Lean.Parser.Term.binderDefault then
let defaultVal := modifier[1]
`(optParam $type $defaultVal)
else if kind == `Lean.Parser.Term.binderTactic then
let tac := modifier[2]
let name ← declareTacticSyntax tac
`(autoParam $type $(mkIdentFrom tac name))
else
throwUnsupportedSyntax
private def getBinderIds (ids : Syntax) : TermElabM (Array Syntax) :=
ids.getArgs.mapM fun id =>
let k := id.getKind
if k == identKind || k == `Lean.Parser.Term.hole then
return id
else
throwErrorAt id "identifier or `_` expected"
private def matchBinder (stx : Syntax) : TermElabM (Array BinderView) := do
let k := stx.getKind
if k == ``Lean.Parser.Term.simpleBinder then
-- binderIdent+ >> optType
let ids ← getBinderIds stx[0]
let type := expandOptType (mkNullNode ids) stx[1]
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default }
else if k == ``Lean.Parser.Term.explicitBinder then
-- `(` binderIdent+ binderType (binderDefault <|> binderTactic)? `)`
let ids ← getBinderIds stx[1]
let type := expandBinderType (mkNullNode ids) stx[2]
let optModifier := stx[3]
let type ← expandBinderModifier type optModifier
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.default }
else if k == ``Lean.Parser.Term.implicitBinder then
-- `{` binderIdent+ binderType `}`
let ids ← getBinderIds stx[1]
let type := expandBinderType (mkNullNode ids) stx[2]
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.implicit }
else if k == ``Lean.Parser.Term.strictImplicitBinder then
-- `⦃` binderIdent+ binderType `⦄`
let ids ← getBinderIds stx[1]
let type := expandBinderType (mkNullNode ids) stx[2]
ids.mapM fun id => do pure { id := (← expandBinderIdent id), type := type, bi := BinderInfo.strictImplicit }
else if k == ``Lean.Parser.Term.instBinder then
-- `[` optIdent type `]`
let id ← expandOptIdent stx[1]
let type := stx[2]
pure #[ { id := id, type := type, bi := BinderInfo.instImplicit } ]
else
throwUnsupportedSyntax
private def registerFailedToInferBinderTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit :=
registerCustomErrorIfMVar type ref "failed to infer binder type"
private def addLocalVarInfo (stx : Syntax) (fvar : Expr) : TermElabM Unit := do
addTermInfo (isBinder := true) stx fvar
private def ensureAtomicBinderName (binderView : BinderView) : TermElabM Unit :=
let n := binderView.id.getId.eraseMacroScopes
unless n.isAtomic do
throwErrorAt binderView.id "invalid binder name '{n}', it must be atomic"
register_builtin_option checkBinderAnnotations : Bool := {
defValue := true
descr := "check whether type is a class instance whenever the binder annotation `[...]` is used"
}
private partial def elabBinderViews {α} (binderViews : Array BinderView) (fvars : Array Expr) (k : Array Expr → TermElabM α)
: TermElabM α :=
let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do
if h : i < binderViews.size then
let binderView := binderViews.get ⟨i, h⟩
ensureAtomicBinderName binderView
let type ← elabType binderView.type
registerFailedToInferBinderTypeInfo type binderView.type
if binderView.bi.isInstImplicit && checkBinderAnnotations.get (← getOptions) then
unless (← isClass? type).isSome do
throwErrorAt binderView.type "invalid binder annotation, type is not a class instance{indentExpr type}\nuse the command `set_option checkBinderAnnotations false` to disable the check"
withLocalDecl binderView.id.getId binderView.bi type fun fvar => do
addLocalVarInfo binderView.id fvar
loop (i+1) (fvars.push fvar)
else
k fvars
loop 0 fvars
private partial def elabBindersAux {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α :=
let rec loop (i : Nat) (fvars : Array Expr) : TermElabM α := do
if h : i < binders.size then
let binderViews ← matchBinder (binders.get ⟨i, h⟩)
elabBinderViews binderViews fvars <| loop (i+1)
else
k fvars
loop 0 #[]
/--
Elaborate the given binders (i.e., `Syntax` objects for `simpleBinder <|> bracketedBinder`),
update the local context, set of local instances, reset instance chache (if needed), and then
execute `x` with the updated context. -/
def elabBinders {α} (binders : Array Syntax) (k : Array Expr → TermElabM α) : TermElabM α :=
withoutPostponingUniverseConstraints do
if binders.isEmpty then
k #[]
else
elabBindersAux binders k
def elabBinder {α} (binder : Syntax) (x : Expr → TermElabM α) : TermElabM α :=
elabBinders #[binder] fun fvars => x fvars[0]
@[builtinTermElab «forall»] def elabForall : TermElab := fun stx _ =>
match stx with
| `(forall $binders*, $term) =>
elabBinders binders fun xs => do
let e ← elabType term
mkForallFVars xs e
| _ => throwUnsupportedSyntax
@[builtinTermElab arrow] def elabArrow : TermElab := fun stx _ =>
match stx with
| `($dom:term -> $rng) => do
-- elaborate independently from each other
let dom ← elabType dom
let rng ← elabType rng
mkForall (← MonadQuotation.addMacroScope `a) BinderInfo.default dom rng
| _ => throwUnsupportedSyntax
@[builtinTermElab depArrow] def elabDepArrow : TermElab := fun stx _ =>
-- bracketedBinder `->` term
let binder := stx[0]
let term := stx[2]
elabBinders #[binder] fun xs => do
mkForallFVars xs (← elabType term)
/--
Auxiliary functions for converting `id_1 ... id_n` application into `#[id_1, ..., id_m]`
It is used at `expandFunBinders`. -/
private partial def getFunBinderIds? (stx : Syntax) : OptionT MacroM (Array Syntax) :=
let convertElem (stx : Syntax) : OptionT MacroM Syntax :=
match stx with
| `(_) => do let ident ← mkFreshIdent stx; pure ident
| `($id:ident) => return id
| _ => failure
match stx with
| `($f $args*) => do
let mut acc := #[].push (← convertElem f)
for arg in args do
acc := acc.push (← convertElem arg)
return acc
| _ =>
return #[].push (← convertElem stx)
/--
Auxiliary function for expanding `fun` notation binders. Recall that `fun` parser is defined as
```
def funBinder : Parser := implicitBinder <|> instBinder <|> termParser maxPrec
leading_parser unicodeSymbol "λ" "fun" >> many1 funBinder >> "=>" >> termParser
```
to allow notation such as `fun (a, b) => a + b`, where `(a, b)` should be treated as a pattern.
The result is a pair `(explicitBinders, newBody)`, where `explicitBinders` is syntax of the form
```
`(` ident `:` term `)`
```
which can be elaborated using `elabBinders`, and `newBody` is the updated `body` syntax.
We update the `body` syntax when expanding the pattern notation.
Example: `fun (a, b) => a + b` expands into `fun _a_1 => match _a_1 with | (a, b) => a + b`.
See local function `processAsPattern` at `expandFunBindersAux`.
The resulting `Bool` is true if a pattern was found. We use it "mark" a macro expansion. -/
partial def expandFunBinders (binders : Array Syntax) (body : Syntax) : MacroM (Array Syntax × Syntax × Bool) :=
let rec loop (body : Syntax) (i : Nat) (newBinders : Array Syntax) := do
if h : i < binders.size then
let binder := binders.get ⟨i, h⟩
let processAsPattern : Unit → MacroM (Array Syntax × Syntax × Bool) := fun _ => do
let pattern := binder
let major ← mkFreshIdent binder
let (binders, newBody, _) ← loop body (i+1) (newBinders.push $ mkExplicitBinder major (mkHole binder))
let newBody ← `(match $major:ident with | $pattern => $newBody)
pure (binders, newBody, true)
match binder with
| Syntax.node ``Lean.Parser.Term.implicitBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node ``Lean.Parser.Term.strictImplicitBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node ``Lean.Parser.Term.instBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node ``Lean.Parser.Term.explicitBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node ``Lean.Parser.Term.simpleBinder _ => loop body (i+1) (newBinders.push binder)
| Syntax.node ``Lean.Parser.Term.hole _ =>
let ident ← mkFreshIdent binder
let type := binder
loop body (i+1) (newBinders.push <| mkExplicitBinder ident type)
| Syntax.node ``Lean.Parser.Term.paren args =>
-- `(` (termParser >> parenSpecial)? `)`
-- parenSpecial := (tupleTail <|> typeAscription)?
let binderBody := binder[1]
if binderBody.isNone then
processAsPattern ()
else
let idents := binderBody[0]
let special := binderBody[1]
if special.isNone then
processAsPattern ()
else if special[0].getKind != `Lean.Parser.Term.typeAscription then
processAsPattern ()
else
-- typeAscription := `:` term
let type := special[0][1]
match (← getFunBinderIds? idents) with
| some idents => loop body (i+1) (newBinders ++ idents.map (fun ident => mkExplicitBinder ident type))
| none => processAsPattern ()
| Syntax.ident .. =>
let type := mkHole binder
loop body (i+1) (newBinders.push <| mkExplicitBinder binder type)
| _ => processAsPattern ()
else
pure (newBinders, body, false)
loop body 0 #[]
namespace FunBinders
structure State where
fvars : Array Expr := #[]
lctx : LocalContext
localInsts : LocalInstances
expectedType? : Option Expr := none
private def propagateExpectedType (fvar : Expr) (fvarType : Expr) (s : State) : TermElabM State := do
match s.expectedType? with
| none => pure s
| some expectedType =>
let expectedType ← whnfForall expectedType
match expectedType with
| Expr.forallE _ d b _ =>
discard <| isDefEq fvarType d
let b := b.instantiate1 fvar
pure { s with expectedType? := some b }
| _ =>
pure { s with expectedType? := none }
private partial def elabFunBinderViews (binderViews : Array BinderView) (i : Nat) (s : State) : TermElabM State := do
if h : i < binderViews.size then
let binderView := binderViews.get ⟨i, h⟩
ensureAtomicBinderName binderView
withRef binderView.type <| withLCtx s.lctx s.localInsts do
let type ← elabType binderView.type
registerFailedToInferBinderTypeInfo type binderView.type
let fvarId ← mkFreshFVarId
let fvar := mkFVar fvarId
let s := { s with fvars := s.fvars.push fvar }
-- dbgTrace (toString binderView.id.getId ++ " : " ++ toString type)
/-
We do **not** want to support default and auto arguments in lambda abstractions.
Example: `fun (x : Nat := 10) => x+1`.
We do not believe this is an useful feature, and it would complicate the logic here.
-/
let lctx := s.lctx.mkLocalDecl fvarId binderView.id.getId type binderView.bi
addTermInfo (lctx? := some lctx) (isBinder := true) binderView.id fvar
let s ← withRef binderView.id <| propagateExpectedType fvar type s
let s := { s with lctx := lctx }
match (← isClass? type) with
| none => elabFunBinderViews binderViews (i+1) s
| some className =>
resettingSynthInstanceCache do
let localInsts := s.localInsts.push { className := className, fvar := mkFVar fvarId }
elabFunBinderViews binderViews (i+1) { s with localInsts := localInsts }
else
pure s
partial def elabFunBindersAux (binders : Array Syntax) (i : Nat) (s : State) : TermElabM State := do
if h : i < binders.size then
let binderViews ← matchBinder (binders.get ⟨i, h⟩)
let s ← elabFunBinderViews binderViews 0 s
elabFunBindersAux binders (i+1) s
else
pure s
end FunBinders
def elabFunBinders {α} (binders : Array Syntax) (expectedType? : Option Expr) (x : Array Expr → Option Expr → TermElabM α) : TermElabM α :=
if binders.isEmpty then
x #[] expectedType?
else do
let lctx ← getLCtx
let localInsts ← getLocalInstances
let s ← FunBinders.elabFunBindersAux binders 0 { lctx := lctx, localInsts := localInsts, expectedType? := expectedType? }
resettingSynthInstanceCacheWhen (s.localInsts.size > localInsts.size) <| withLCtx s.lctx s.localInsts <|
x s.fvars s.expectedType?
/- Helper function for `expandEqnsIntoMatch` -/
private def getMatchAltsNumPatterns (matchAlts : Syntax) : Nat :=
let alt0 := matchAlts[0][0]
let pats := alt0[1].getSepArgs
pats.size
def expandWhereDecls (whereDecls : Syntax) (body : Syntax) : MacroM Syntax :=
match whereDecls with
| `(whereDecls|where $[$decls:letRecDecl $[;]?]*) => `(let rec $decls:letRecDecl,*; $body)
| _ => Macro.throwUnsupported
def expandWhereDeclsOpt (whereDeclsOpt : Syntax) (body : Syntax) : MacroM Syntax :=
if whereDeclsOpt.isNone then
body
else
expandWhereDecls whereDeclsOpt[0] body
/- Helper function for `expandMatchAltsIntoMatch` -/
private def expandMatchAltsIntoMatchAux (matchAlts : Syntax) (matchTactic : Bool) : Nat → Array Syntax → MacroM Syntax
| 0, discrs => do
if matchTactic then
`(tactic|match $[$discrs:term],* with $matchAlts:matchAlts)
else
`(match $[$discrs:term],* with $matchAlts:matchAlts)
| n+1, discrs => withFreshMacroScope do
let x ← `(x)
let d ← `(@$x:ident) -- See comment below
let body ← expandMatchAltsIntoMatchAux matchAlts matchTactic n (discrs.push d)
if matchTactic then
`(tactic| intro $x:term; $body:tactic)
else
`(@fun $x => $body)
/--
Expand `matchAlts` syntax into a full `match`-expression.
Example
```
| 0, true => alt_1
| i, _ => alt_2
```
expands into (for tactic == false)
```
fun x_1 x_2 =>
match @x_1, @x_2 with
| 0, true => alt_1
| i, _ => alt_2
```
and (for tactic == true)
```
intro x_1; intro x_2;
match @x_1, @x_2 with
| 0, true => alt_1
| i, _ => alt_2
```
Remark: we add `@` to make sure we don't consume implicit arguments, and to make the behavior consistent with `fun`.
Example:
```
inductive T : Type 1 :=
| mkT : (forall {a : Type}, a -> a) -> T
def makeT (f : forall {a : Type}, a -> a) : T :=
mkT f
def makeT' : (forall {a : Type}, a -> a) -> T
| f => mkT f
```
The two definitions should be elaborated without errors and be equivalent.
-/
def expandMatchAltsIntoMatch (ref : Syntax) (matchAlts : Syntax) (tactic := false) : MacroM Syntax :=
withRef ref <| expandMatchAltsIntoMatchAux matchAlts tactic (getMatchAltsNumPatterns matchAlts) #[]
def expandMatchAltsIntoMatchTactic (ref : Syntax) (matchAlts : Syntax) : MacroM Syntax :=
withRef ref <| expandMatchAltsIntoMatchAux matchAlts true (getMatchAltsNumPatterns matchAlts) #[]
/--
Similar to `expandMatchAltsIntoMatch`, but supports an optional `where` clause.
Expand `matchAltsWhereDecls` into `let rec` + `match`-expression.
Example
```
| 0, true => ... f 0 ...
| i, _ => ... f i + g i ...
where
f x := g x + 1
g : Nat → Nat
| 0 => 1
| x+1 => f x
```
expands into
```
fux x_1 x_2 =>
let rec
f x := g x + 1,
g : Nat → Nat
| 0 => 1
| x+1 => f x
match x_1, x_2 with
| 0, true => ... f 0 ...
| i, _ => ... f i + g i ...
```
-/
def expandMatchAltsWhereDecls (matchAltsWhereDecls : Syntax) : MacroM Syntax :=
let matchAlts := matchAltsWhereDecls[0]
let whereDeclsOpt := matchAltsWhereDecls[1]
let rec loop (i : Nat) (discrs : Array Syntax) : MacroM Syntax :=
match i with
| 0 => do
let matchStx ← `(match $[$discrs:term],* with $matchAlts:matchAlts)
if whereDeclsOpt.isNone then
return matchStx
else
expandWhereDeclsOpt whereDeclsOpt matchStx
| n+1 => withFreshMacroScope do
let d ← `(@x) -- See comment at `expandMatchAltsIntoMatch`
let body ← loop n (discrs.push d)
`(@fun x => $body)
loop (getMatchAltsNumPatterns matchAlts) #[]
@[builtinMacro Lean.Parser.Term.fun] partial def expandFun : Macro
| `(fun $binders* => $body) => do
let (binders, body, expandedPattern) ← expandFunBinders binders body
if expandedPattern then
`(fun $binders* => $body)
else
Macro.throwUnsupported
| stx@`(fun $m:matchAlts) => expandMatchAltsIntoMatch stx m
| _ => Macro.throwUnsupported
open Lean.Elab.Term.Quotation in
@[builtinQuotPrecheck Lean.Parser.Term.fun] def precheckFun : Precheck
| `(fun $binders* => $body) => do
let (binders, body, expandedPattern) ← liftMacroM <| expandFunBinders binders body
let mut ids := #[]
for b in binders do
for v in ← matchBinder b do
Quotation.withNewLocals ids <| precheck v.type
ids := ids.push v.id.getId
Quotation.withNewLocals ids <| precheck body
| _ => throwUnsupportedSyntax
@[builtinTermElab «fun»] partial def elabFun : TermElab := fun stx expectedType? =>
match stx with
| `(fun $binders* => $body) => do
-- We can assume all `match` binders have been iteratively expanded by the above macro here, though
-- we still need to call `expandFunBinders` once to obtain `binders` in a normal form
-- expected by `elabFunBinder`.
let (binders, body, expandedPattern) ← liftMacroM <| expandFunBinders binders body
elabFunBinders binders expectedType? fun xs expectedType? => do
/- We ensure the expectedType here since it will force coercions to be applied if needed.
If we just use `elabTerm`, then we will need to a coercion `Coe (α → β) (α → δ)` whenever there is a coercion `Coe β δ`,
and another instance for the dependent version. -/
let e ← elabTermEnsuringType body expectedType?
mkLambdaFVars xs e
| _ => throwUnsupportedSyntax
/- If `useLetExpr` is true, then a kernel let-expression `let x : type := val; body` is created.
Otherwise, we create a term of the form `(fun (x : type) => body) val`
The default elaboration order is `binders`, `typeStx`, `valStx`, and `body`.
If `elabBodyFirst == true`, then we use the order `binders`, `typeStx`, `body`, and `valStx`. -/
def elabLetDeclAux (id : Syntax) (binders : Array Syntax) (typeStx : Syntax) (valStx : Syntax) (body : Syntax)
(expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do
let (type, val, arity) ← elabBinders binders fun xs => do
let type ← elabType typeStx
registerCustomErrorIfMVar type typeStx "failed to infer 'let' declaration type"
if elabBodyFirst then
let type ← mkForallFVars xs type
let val ← mkFreshExprMVar type
pure (type, val, xs.size)
else
let val ← elabTermEnsuringType valStx type
let type ← mkForallFVars xs type
/- By default `mkLambdaFVars` and `mkLetFVars` create binders only for let-declarations that are actually used
in the body. This generates counterintuitive behavior in the elaborator since users will not be notified
about holes such as
```
def ex : Nat :=
let x := _
42
```
-/
let val ← mkLambdaFVars xs val (usedLetOnly := false)
pure (type, val, xs.size)
trace[Elab.let.decl] "{id.getId} : {type} := {val}"
let result ←
if useLetExpr then
withLetDecl id.getId type val fun x => do
addLocalVarInfo id x
let body ← elabTermEnsuringType body expectedType?
let body ← instantiateMVars body
mkLetFVars #[x] body (usedLetOnly := false)
else
let f ← withLocalDecl id.getId BinderInfo.default type fun x => do
addLocalVarInfo id x
let body ← elabTermEnsuringType body expectedType?
let body ← instantiateMVars body
mkLambdaFVars #[x] body (usedLetOnly := false)
pure <| mkApp f val
if elabBodyFirst then
forallBoundedTelescope type arity fun xs type => do
let valResult ← elabTermEnsuringType valStx type
let valResult ← mkLambdaFVars xs valResult (usedLetOnly := false)
unless (← isDefEq val valResult) do
throwError "unexpected error when elaborating 'let'"
pure result
structure LetIdDeclView where
id : Syntax
binders : Array Syntax
type : Syntax
value : Syntax
def mkLetIdDeclView (letIdDecl : Syntax) : LetIdDeclView :=
-- `letIdDecl` is of the form `ident >> many bracketedBinder >> optType >> " := " >> termParser
let id := letIdDecl[0]
let binders := letIdDecl[1].getArgs
let optType := letIdDecl[2]
let type := expandOptType id optType
let value := letIdDecl[4]
{ id := id, binders := binders, type := type, value := value }
def expandLetEqnsDecl (letDecl : Syntax) : MacroM Syntax := do
let ref := letDecl
let matchAlts := letDecl[3]
let val ← expandMatchAltsIntoMatch ref matchAlts
return Syntax.node `Lean.Parser.Term.letIdDecl #[letDecl[0], letDecl[1], letDecl[2], mkAtomFrom ref " := ", val]
def elabLetDeclCore (stx : Syntax) (expectedType? : Option Expr) (useLetExpr : Bool) (elabBodyFirst : Bool) : TermElabM Expr := do
let ref := stx
let letDecl := stx[1][0]
let body := stx[3]
if letDecl.getKind == `Lean.Parser.Term.letIdDecl then
let { id := id, binders := binders, type := type, value := val } := mkLetIdDeclView letDecl
elabLetDeclAux id binders type val body expectedType? useLetExpr elabBodyFirst
else if letDecl.getKind == `Lean.Parser.Term.letPatDecl then
-- node `Lean.Parser.Term.letPatDecl $ try (termParser >> pushNone >> optType >> " := ") >> termParser
let pat := letDecl[0]
let optType := letDecl[2]
let type := expandOptType pat optType
let val := letDecl[4]
let stxNew ← `(let x : $type := $val; match x with | $pat => $body)
let stxNew := match useLetExpr, elabBodyFirst with
| true, false => stxNew
| true, true => stxNew.setKind `Lean.Parser.Term.«let_delayed»
| false, false => stxNew.setKind `Lean.Parser.Term.«let_fun»
| false, true => unreachable!
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
else if letDecl.getKind == `Lean.Parser.Term.letEqnsDecl then
let letDeclIdNew ← liftMacroM <| expandLetEqnsDecl letDecl
let declNew := stx[1].setArg 0 letDeclIdNew
let stxNew := stx.setArg 1 declNew
withMacroExpansion stx stxNew <| elabTerm stxNew expectedType?
else
throwUnsupportedSyntax
@[builtinTermElab «let»] def elabLetDecl : TermElab :=
fun stx expectedType? => elabLetDeclCore stx expectedType? true false
@[builtinTermElab «let_fun»] def elabLetFunDecl : TermElab :=
fun stx expectedType? => elabLetDeclCore stx expectedType? false false
@[builtinTermElab «let_delayed»] def elabLetDelayedDecl : TermElab :=
fun stx expectedType? => elabLetDeclCore stx expectedType? true true
builtin_initialize registerTraceClass `Elab.let
end Lean.Elab.Term
|
9be9502b58415f7bc24b77292715472502983716 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/reserved_notation.lean | d503fb85703d32a44c00fecdd0de99e618a9c6d3 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 264 | lean | /-
Copyright (c) 2020 Bryan Gin-ge Chen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bryan Gin-ge Chen
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.PostPort
namespace Mathlib
|
c1a818efa5c0b43f49a3f11ebaefefec27e19332 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/etaStructIssue.lean | e495024470e1910ca1767a74e680a7ddc2d8a062 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 580 | lean | inductive E where
| mk : E → E
inductive F : E → Prop
| mk : F e → F (E.mk e)
theorem dec (x : F (E.mk e)) : F e ∧ True :=
match x with
| F.mk h => ⟨h, trivial⟩
def mkNat (e : E) (x : F e) : Nat :=
match e with
| E.mk e' =>
match dec x with
| ⟨h, _⟩ => mkNat e' h
theorem fail (e : E) (x₁ : F e) (x₂ : F (E.mk e)) : mkNat e x₁ = mkNat (E.mk e) x₂ :=
/- The following rfl was succeeding in the elaborator but failing in the kernel because
of a discrepancy in the implementation for Eta-for-structures. -/
rfl -- should fail
|
205012d8590e9561bb83ab6cfe28abfd20227399 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Meta/SizeOf.lean | ef5919b2215fea9e21fc1cca1657675e543e0b24 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 21,992 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.AppBuilder
import Lean.Meta.Instances
namespace Lean.Meta
/-- Create `SizeOf` local instances for applicable parameters, and execute `k` using them. -/
private partial def mkLocalInstances {α} (params : Array Expr) (k : Array Expr → MetaM α) : MetaM α :=
loop 0 #[]
where
loop (i : Nat) (insts : Array Expr) : MetaM α := do
if i < params.size then
let param := params[i]
let paramType ← inferType param
let instType? ← forallTelescopeReducing paramType fun xs _ => do
let type ← mkAppN param xs
try
let sizeOf ← mkAppM `SizeOf #[type]
let instType ← mkForallFVars xs sizeOf
return some instType
catch _ =>
return none
match instType? with
| none => loop (i+1) insts
| some instType =>
let instName ← mkFreshUserName `inst
withLocalDecl instName BinderInfo.instImplicit instType fun inst =>
loop (i+1) (insts.push inst)
else
k insts
/--
Return `some x` if `fvar` has type of the form `... -> motive ... fvar` where `motive` in `motiveFVars`.
That is, `x` "produces" one of the recursor motives.
-/
private def isInductiveHypothesis? (motiveFVars : Array Expr) (fvar : Expr) : MetaM (Option Expr) := do
forallTelescopeReducing (← inferType fvar) fun _ type =>
if type.isApp && motiveFVars.contains type.getAppFn then
return some type.appArg!
else
return none
private def isInductiveHypothesis (motiveFVars : Array Expr) (fvar : Expr) : MetaM Bool :=
return (← isInductiveHypothesis? motiveFVars fvar).isSome
/--
Let `motiveFVars` be free variables for each motive in a kernel recursor, and `minorFVars` the free variables for a minor premise.
Then, return `some idx` if `minorFVars[idx]` has a type of the form `... -> motive ... fvar` for some `motive` in `motiveFVars`.
-/
private def isRecField? (motiveFVars : Array Expr) (minorFVars : Array Expr) (fvar : Expr) : MetaM (Option Nat) := do
let mut idx := 0
for minorFVar in minorFVars do
if let some fvar' ← isInductiveHypothesis? motiveFVars minorFVar then
if fvar == fvar' then
return some idx
idx := idx + 1
return none
private partial def mkSizeOfMotives {α} (motiveFVars : Array Expr) (k : Array Expr → MetaM α) : MetaM α :=
loop 0 #[]
where
loop (i : Nat) (motives : Array Expr) : MetaM α := do
if i < motiveFVars.size then
let type ← inferType motiveFVars[i]
let motive ← forallTelescopeReducing type fun xs _ => do
mkLambdaFVars xs <| mkConst ``Nat
trace[Meta.sizeOf] "motive: {motive}"
loop (i+1) (motives.push motive)
else
k motives
private partial def mkSizeOfMinors {α} (motiveFVars : Array Expr) (minorFVars : Array Expr) (minorFVars' : Array Expr) (k : Array Expr → MetaM α) : MetaM α :=
assert! minorFVars.size == minorFVars'.size
loop 0 #[]
where
loop (i : Nat) (minors : Array Expr) : MetaM α := do
if i < minorFVars.size then
forallTelescopeReducing (← inferType minorFVars[i]) fun xs _ => do
forallBoundedTelescope (← inferType minorFVars'[i]) xs.size fun xs' _ => do
let mut minor ← mkNumeral (mkConst ``Nat) 1
for x in xs, x' in xs' do
unless (← isInductiveHypothesis motiveFVars x) do
unless (← whnf (← inferType x)).isForall do -- we suppress higher-order fields
match (← isRecField? motiveFVars xs x) with
| some idx => minor ← mkAdd minor xs'[idx]
| none => minor ← mkAdd minor (← mkAppM ``SizeOf.sizeOf #[x'])
minor ← mkLambdaFVars xs' minor
trace[Meta.sizeOf] "minor: {minor}"
loop (i+1) (minors.push minor)
else
k minors
/--
Create a "sizeOf" function with name `declName` using the recursor `recName`.
-/
partial def mkSizeOfFn (recName : Name) (declName : Name): MetaM Unit := do
trace[Meta.sizeOf] "recName: {recName}"
let recInfo : RecursorVal ← getConstInfoRec recName
forallTelescopeReducing recInfo.type fun xs type =>
let levelParams := recInfo.levelParams.tail! -- universe parameters for declaration being defined
let params := xs[:recInfo.numParams]
let motiveFVars := xs[recInfo.numParams : recInfo.numParams + recInfo.numMotives]
let minorFVars := xs[recInfo.getFirstMinorIdx : recInfo.getFirstMinorIdx + recInfo.numMinors]
let indices := xs[recInfo.getFirstIndexIdx : recInfo.getFirstIndexIdx + recInfo.numIndices]
let major := xs[recInfo.getMajorIdx]
let nat := mkConst ``Nat
mkLocalInstances params fun localInsts =>
mkSizeOfMotives motiveFVars fun motives => do
let us := levelOne :: levelParams.map mkLevelParam -- universe level parameters for `rec`-application
let recFn := mkConst recName us
let val := mkAppN recFn (params ++ motives)
forallBoundedTelescope (← inferType val) recInfo.numMinors fun minorFVars' _ =>
mkSizeOfMinors motiveFVars minorFVars minorFVars' fun minors => do
let sizeOfParams := params ++ localInsts ++ indices ++ #[major]
let sizeOfType ← mkForallFVars sizeOfParams nat
let val := mkAppN val (minors ++ indices ++ #[major])
trace[Meta.sizeOf] "val: {val}"
let sizeOfValue ← mkLambdaFVars sizeOfParams val
addDecl <| Declaration.defnDecl {
name := declName
levelParams := levelParams
type := sizeOfType
value := sizeOfValue
safety := DefinitionSafety.safe
hints := ReducibilityHints.abbrev
}
/--
Create `sizeOf` functions for all inductive datatypes in the mutual inductive declaration containing `typeName`
The resulting array contains the generated functions names. The `NameMap` maps recursor names into the generated function names.
There is a function for each element of the mutual inductive declaration, and for auxiliary recursors for nested inductive types.
-/
def mkSizeOfFns (typeName : Name) : MetaM (Array Name × NameMap Name) := do
let indInfo ← getConstInfoInduct typeName
let recInfo ← getConstInfoRec (mkRecName typeName)
let numExtra := recInfo.numMotives - indInfo.all.length -- numExtra > 0 for nested inductive types
let mut result := #[]
let baseName := indInfo.all.head! ++ `_sizeOf -- we use the first inductive type as the base name for `sizeOf` functions
let mut i := 1
let mut recMap : NameMap Name := {}
for indTypeName in indInfo.all do
let sizeOfName := baseName.appendIndexAfter i
let recName := mkRecName indTypeName
mkSizeOfFn recName sizeOfName
recMap := recMap.insert recName sizeOfName
result := result.push sizeOfName
i := i + 1
for j in [:numExtra] do
let recName := (mkRecName indInfo.all.head!).appendIndexAfter (j+1)
let sizeOfName := baseName.appendIndexAfter i
mkSizeOfFn recName sizeOfName
recMap := recMap.insert recName sizeOfName
result := result.push sizeOfName
i := i + 1
return (result, recMap)
def mkSizeOfSpecLemmaName (ctorName : Name) : Name :=
ctorName ++ `sizeOf_spec
def mkSizeOfSpecLemmaInstance (ctorApp : Expr) : MetaM Expr :=
matchConstCtor ctorApp.getAppFn (fun _ => throwError "failed to apply 'sizeOf' spec, constructor expected{indentExpr ctorApp}") fun ctorInfo ctorLevels => do
let ctorArgs := ctorApp.getAppArgs
let ctorFields := ctorArgs[ctorArgs.size - ctorInfo.numFields:]
let lemmaName := mkSizeOfSpecLemmaName ctorInfo.name
let lemmaInfo ← getConstInfo lemmaName
let lemmaArity ← forallTelescopeReducing lemmaInfo.type fun xs _ => return xs.size
let lemmaArgMask := mkArray (lemmaArity - ctorInfo.numFields) (none (α := Expr))
let lemmaArgMask := lemmaArgMask ++ ctorFields.toArray.map some
mkAppOptM lemmaName lemmaArgMask
/- SizeOf spec theorem for nested inductive types -/
namespace SizeOfSpecNested
structure Context where
indInfo : InductiveVal
sizeOfFns : Array Name
ctorName : Name
params : Array Expr
localInsts : Array Expr
recMap : NameMap Name -- mapping from recursor name into `_sizeOf_<idx>` function name (see `mkSizeOfFns`)
abbrev M := ReaderT Context MetaM
def throwUnexpected {α} (msg : MessageData) : M α := do
throwError "failed to generate sizeOf theorem for {(← read).ctorName} (use `set_option genSizeOfSpec false` to disable theorem generation), {msg}"
def throwFailed {α} : M α := do
throwError "failed to generate sizeOf theorem for {(← read).ctorName}, (use `set_option genSizeOfSpec false` to disable theorem generation)"
/-- Convert a recursor application into a `_sizeOf_<idx>` application. -/
private def recToSizeOf (e : Expr) : M Expr := do
matchConstRec e.getAppFn (fun _ => throwFailed) fun info us => do
match (← read).recMap.find? info.name with
| none => throwUnexpected m!"expected recursor application {indentExpr e}"
| some sizeOfName =>
let args := e.getAppArgs
let indices := args[info.getFirstIndexIdx : info.getFirstIndexIdx + info.numIndices]
let major := args[info.getMajorIdx]
return mkAppN (mkConst sizeOfName us.tail!) ((← read).params ++ (← read).localInsts ++ indices ++ #[major])
mutual
/-- Construct minor premise proof for `mkSizeOfAuxLemmaProof`. `ys` contains fields and inductive hypotheses for the minor premise. -/
private partial def mkMinorProof (ys : Array Expr) (lhs rhs : Expr) : M Expr := do
trace[Meta.sizeOf.minor] "{lhs} =?= {rhs}"
if (← isDefEq lhs rhs) then
mkEqRefl rhs
else
match (← whnfI lhs).natAdd?, (← whnfI rhs).natAdd? with
| some (a₁, b₁), some (a₂, b₂) =>
let p₁ ← mkMinorProof ys a₁ a₂
let p₂ ← mkMinorProofStep ys b₁ b₂
mkCongr (← mkCongrArg (mkConst ``Nat.add) p₁) p₂
| _, _ =>
throwUnexpected m!"expected 'Nat.add' application, lhs is {indentExpr lhs}\nrhs is{indentExpr rhs}"
/--
Helper method for `mkMinorProof`. The proof step is one of the following
- Reflexivity
- Assumption (i.e., using an inductive hypotheses from `ys`)
- `mkSizeOfAuxLemma` application. This case happens when we have multiple levels of nesting
-/
private partial def mkMinorProofStep (ys : Array Expr) (lhs rhs : Expr) : M Expr := do
if (← isDefEq lhs rhs) then
mkEqRefl rhs
else
let lhs ← recToSizeOf lhs
trace[Meta.sizeOf.minor.step] "{lhs} =?= {rhs}"
let target ← mkEq lhs rhs
for y in ys do
if (← isDefEq (← inferType y) target) then
return y
mkSizeOfAuxLemma lhs rhs
/-- Construct proof of auxiliary lemma. See `mkSizeOfAuxLemma` -/
private partial def mkSizeOfAuxLemmaProof (info : InductiveVal) (lhs rhs : Expr) : M Expr := do
let lhsArgs := lhs.getAppArgs
let sizeOfBaseArgs := lhsArgs[:lhsArgs.size - info.numIndices - 1]
let indicesMajor := lhsArgs[lhsArgs.size - info.numIndices - 1:]
let sizeOfLevels := lhs.getAppFn.constLevels!
/- Auxiliary function for constructing an `_sizeOf_<idx>` for `ys`,
where `ys` are the indices + major.
Recall that if `info.name` is part of a mutually inductive declaration, then the resulting application
is not necessarily a `lhs.getAppFn` application.
The result is an application of one of the `(← read),sizeOfFns` functions.
We use this auxiliary function to builtin the motive of the recursor. -/
let rec mkSizeOf (ys : Array Expr) : M Expr := do
for sizeOfFn in (← read).sizeOfFns do
let candidate := mkAppN (mkAppN (mkConst sizeOfFn sizeOfLevels) sizeOfBaseArgs) ys
if (← isTypeCorrect candidate) then
return candidate
throwFailed
let major := lhs.appArg!
let majorType ← whnf (← inferType major)
let majorTypeArgs := majorType.getAppArgs
match majorType.getAppFn.const? with
| none => throwFailed
| some (_, us) =>
let recName := mkRecName info.name
let recInfo ← getConstInfoRec recName
let r := mkConst recName (levelZero :: us)
let r := mkAppN r majorTypeArgs[:info.numParams]
forallBoundedTelescope (← inferType r) recInfo.numMotives fun motiveFVars _ => do
let mut r := r
-- Add motives
for motiveFVar in motiveFVars do
let motive ← forallTelescopeReducing (← inferType motiveFVar) fun ys _ => do
let lhs ← mkSizeOf ys
let rhs ← mkAppM ``SizeOf.sizeOf #[ys.back]
mkLambdaFVars ys (← mkEq lhs rhs)
r := mkApp r motive
forallBoundedTelescope (← inferType r) recInfo.numMinors fun minorFVars _ => do
let mut r := r
-- Add minors
for minorFVar in minorFVars do
let minor ← forallTelescopeReducing (← inferType minorFVar) fun ys target => do
let target ← whnf target
match target.eq? with
| none => throwFailed
| some (_, lhs, rhs) =>
if (← isDefEq lhs rhs) then
mkLambdaFVars ys (← mkEqRefl rhs)
else
let lhs ← unfoldDefinition lhs -- Unfold `_sizeOf_<idx>`
-- rhs is of the form `sizeOf (ctor ...)`
let ctorApp := rhs.appArg!
let specLemma ← mkSizeOfSpecLemmaInstance ctorApp
let specEq ← whnf (← inferType specLemma)
match specEq.eq? with
| none => throwFailed
| some (_, rhs, rhsExpanded) =>
let lhs_eq_rhsExpanded ← mkMinorProof ys lhs rhsExpanded
let rhsExpanded_eq_rhs ← mkEqSymm specLemma
mkLambdaFVars ys (← mkEqTrans lhs_eq_rhsExpanded rhsExpanded_eq_rhs)
r := mkApp r minor
-- Add indices and major
return mkAppN r indicesMajor
/--
Generate proof for `C._sizeOf_<idx> t = sizeOf t` where `C._sizeOf_<idx>` is a auxiliary function
generated for a nested inductive type in `C`.
For example, given
```lean
inductive Expr where
| app (f : String) (args : List Expr)
```
We generate the auxiliary function `Expr._sizeOf_1 : List Expr → Nat`.
To generate the `sizeOf` spec lemma
```
sizeOf (Expr.app f args) = 1 + sizeOf f + sizeOf args
```
we need an auxiliary lemma for showing `Expr._sizeOf_1 args = sizeOf args`.
Recall that `sizeOf (Expr.app f args)` is definitionally equal to `1 + sizeOf f + Expr._sizeOf_1 args`, but
`Expr._sizeOf_1 args` is **not** definitionally equal to `sizeOf args`. We need a proof by induction.
-/
private partial def mkSizeOfAuxLemma (lhs rhs : Expr) : M Expr := do
trace[Meta.sizeOf.aux] "{lhs} =?= {rhs}"
match lhs.getAppFn.const? with
| none => throwFailed
| some (fName, us) =>
let thmLevelParams ← us.mapM fun
| Level.param n _ => return n
| _ => throwFailed
let thmName := fName.appendAfter "_eq"
if (← getEnv).contains thmName then
-- Auxiliary lemma has already been defined
return mkAppN (mkConst thmName us) lhs.getAppArgs
else
-- Define auxiliary lemma
-- First, generalize indices
let x := lhs.appArg!
let xType ← whnf (← inferType x)
matchConstInduct xType.getAppFn (fun _ => throwFailed) fun info _ => do
let params := xType.getAppArgs[:info.numParams]
forallTelescopeReducing (← inferType (mkAppN xType.getAppFn params)) fun indices _ => do
let majorType := mkAppN (mkAppN xType.getAppFn params) indices
withLocalDeclD `x majorType fun major => do
let lhsArgs := lhs.getAppArgs
let lhsArgsNew := lhsArgs[:lhsArgs.size - 1 - indices.size] ++ indices ++ #[major]
let lhsNew := mkAppN lhs.getAppFn lhsArgsNew
let rhsNew ← mkAppM ``SizeOf.sizeOf #[major]
let eq ← mkEq lhsNew rhsNew
let thmParams := lhsArgsNew
let thmType ← mkForallFVars thmParams eq
let thmValue ← mkSizeOfAuxLemmaProof info lhsNew rhsNew
let thmValue ← mkLambdaFVars thmParams thmValue
trace[Meta.sizeOf] "thmValue: {thmValue}"
addDecl <| Declaration.thmDecl {
name := thmName
levelParams := thmLevelParams
type := thmType
value := thmValue
}
return mkAppN (mkConst thmName us) lhs.getAppArgs
end
/- Prove SizeOf spec lemma of the form `sizeOf <ctor-application> = 1 + sizeOf <field_1> + ... + sizeOf <field_n> -/
partial def main (lhs rhs : Expr) : M Expr := do
if (← isDefEq lhs rhs) then
mkEqRefl rhs
else
/- Expand lhs and rhs to obtain `Nat.add` applications -/
let lhs ← whnfI lhs -- Expand `sizeOf (ctor ...)` into `_sizeOf_<idx>` application
let lhs ← unfoldDefinition lhs -- Unfold `_sizeOf_<idx>` application into `HAdd.hAdd` application
loop lhs rhs
where
loop (lhs rhs : Expr) : M Expr := do
trace[Meta.sizeOf.loop] "{lhs} =?= {rhs}"
if (← isDefEq lhs rhs) then
mkEqRefl rhs
else
match (← whnfI lhs).natAdd?, (← whnfI rhs).natAdd? with
| some (a₁, b₁), some (a₂, b₂) =>
let p₁ ← loop a₁ a₂
let p₂ ← step b₁ b₂
mkCongr (← mkCongrArg (mkConst ``Nat.add) p₁) p₂
| _, _ =>
throwUnexpected m!"expected 'Nat.add' application, lhs is {indentExpr lhs}\nrhs is{indentExpr rhs}"
step (lhs rhs : Expr) : M Expr := do
if (← isDefEq lhs rhs) then
mkEqRefl rhs
else
let lhs ← recToSizeOf lhs
mkSizeOfAuxLemma lhs rhs
end SizeOfSpecNested
private def mkSizeOfSpecTheorem (indInfo : InductiveVal) (sizeOfFns : Array Name) (recMap : NameMap Name) (ctorName : Name) : MetaM Unit := do
let ctorInfo ← getConstInfoCtor ctorName
let us := ctorInfo.levelParams.map mkLevelParam
forallTelescopeReducing ctorInfo.type fun xs _ => do
let params := xs[:ctorInfo.numParams]
let fields := xs[ctorInfo.numParams:]
let ctorApp := mkAppN (mkConst ctorName us) xs
mkLocalInstances params fun localInsts => do
let lhs ← mkAppM ``SizeOf.sizeOf #[ctorApp]
let mut rhs ← mkNumeral (mkConst ``Nat) 1
for field in fields do
unless (← whnf (← inferType field)).isForall do
rhs ← mkAdd rhs (← mkAppM ``SizeOf.sizeOf #[field])
let target ← mkEq lhs rhs
let thmName := mkSizeOfSpecLemmaName ctorName
let thmParams := params ++ localInsts ++ fields
let thmType ← mkForallFVars thmParams target
let thmValue ←
if indInfo.isNested then
SizeOfSpecNested.main lhs rhs |>.run {
indInfo := indInfo, sizeOfFns := sizeOfFns, ctorName := ctorName, params := params, localInsts := localInsts, recMap := recMap
}
else
mkEqRefl rhs
let thmValue ← mkLambdaFVars thmParams thmValue
addDecl <| Declaration.thmDecl {
name := thmName
levelParams := ctorInfo.levelParams
type := thmType
value := thmValue
}
private def mkSizeOfSpecTheorems (indTypeNames : Array Name) (sizeOfFns : Array Name) (recMap : NameMap Name) : MetaM Unit := do
for indTypeName in indTypeNames do
let indInfo ← getConstInfoInduct indTypeName
for ctorName in indInfo.ctors do
mkSizeOfSpecTheorem indInfo sizeOfFns recMap ctorName
return ()
register_builtin_option genSizeOf : Bool := {
defValue := true
descr := "generate `SizeOf` instance for inductive types and structures"
}
register_builtin_option genSizeOfSpec : Bool := {
defValue := true
descr := "generate `SizeOf` specificiation theorems for automatically generated instances"
}
def mkSizeOfInstances (typeName : Name) : MetaM Unit := do
if (← getEnv).contains ``SizeOf && genSizeOf.get (← getOptions) && !(← isInductivePredicate typeName) then
let indInfo ← getConstInfoInduct typeName
unless indInfo.isUnsafe do
let (fns, recMap) ← mkSizeOfFns typeName
for indTypeName in indInfo.all, fn in fns do
let indInfo ← getConstInfoInduct indTypeName
forallTelescopeReducing indInfo.type fun xs _ =>
let params := xs[:indInfo.numParams]
let indices := xs[indInfo.numParams:]
mkLocalInstances params fun localInsts => do
let us := indInfo.levelParams.map mkLevelParam
let indType := mkAppN (mkConst indTypeName us) xs
let sizeOfIndType ← mkAppM ``SizeOf #[indType]
withLocalDeclD `m indType fun m => do
let v ← mkLambdaFVars #[m] <| mkAppN (mkConst fn us) (params ++ localInsts ++ indices ++ #[m])
let sizeOfMk ← mkAppM ``SizeOf.mk #[v]
let instDeclName := indTypeName ++ `_sizeOf_inst
let instDeclType ← mkForallFVars (xs ++ localInsts) sizeOfIndType
let instDeclValue ← mkLambdaFVars (xs ++ localInsts) sizeOfMk
addDecl <| Declaration.defnDecl {
name := instDeclName
levelParams := indInfo.levelParams
type := instDeclType
value := instDeclValue
safety := DefinitionSafety.safe
hints := ReducibilityHints.abbrev
}
addInstance instDeclName AttributeKind.global (eval_prio default)
if genSizeOfSpec.get (← getOptions) then
mkSizeOfSpecTheorems indInfo.all.toArray fns recMap
builtin_initialize
registerTraceClass `Meta.sizeOf
end Lean.Meta
|
1b33b07d68cf34721c86caed3242d2df854fb2f0 | 88fb7558b0636ec6b181f2a548ac11ad3919f8a5 | /tests/lean/run/super_tests.lean | af9d2f9d41564fc54c386ca46dafacfaac1aabcc | [
"Apache-2.0"
] | permissive | moritayasuaki/lean | 9f666c323cb6fa1f31ac597d777914aed41e3b7a | ae96ebf6ee953088c235ff7ae0e8c95066ba8001 | refs/heads/master | 1,611,135,440,814 | 1,493,852,869,000 | 1,493,852,869,000 | 90,269,903 | 0 | 0 | null | 1,493,906,291,000 | 1,493,906,291,000 | null | UTF-8 | Lean | false | false | 2,985 | lean | import tools.super
section
open super tactic
example (i : Type) (a b : i) (p : i → Prop) (H : a = b) (Hpa : p a) : true := by do
H ← get_local `H >>= clause.of_classical_proof,
Hpa ← get_local `Hpa >>= clause.of_classical_proof,
a ← get_local `a,
try_sup (λx y, ff) H Hpa 0 0 [0] tt ff ``super.sup_ltr >>= clause.validate,
to_expr `(trivial) >>= apply
example (i : Type) (a b : i) (p : i → Prop) (H : a = b) (Hpa : p a → false) (Hpb : p b → false) : true := by do
H ← get_local `H >>= clause.of_classical_proof,
Hpa ← get_local `Hpa >>= clause.of_classical_proof,
Hpb ← get_local `Hpb >>= clause.of_classical_proof,
try_sup (λx y, ff) H Hpa 0 0 [0] tt ff ``super.sup_ltr >>= clause.validate,
try_sup (λx y, ff) H Hpb 0 0 [0] ff ff ``super.sup_rtl >>= clause.validate,
to_expr `(trivial) >>= apply
example (i : Type) (p q : i → Prop) (H : ∀x y, p x → q y → false) : true := by do
h ← get_local `H >>= clause.of_classical_proof,
(op, lcs) ← h^.open_constn h^.num_binders,
guard $ (get_components lcs)^.length = 2,
triv
example (i : Type) (p : i → i → Prop) (H : ∀x y z, p x y → p y z → false) : true := by do
h ← get_local `H >>= clause.of_classical_proof,
(op, lcs) ← h^.open_constn h^.num_binders,
guard $ (get_components lcs)^.length = 1,
triv
example (i : Type) (p : i → i → Type) (c : i) (h : ∀ (x : i), p x c → p x c) : true := by do
h ← get_local `h, hcls ← clause.of_classical_proof h,
taut ← is_taut hcls,
when (¬taut) failed,
to_expr `(trivial) >>= apply
open tactic
example (m n : ℕ) : true := by do
e₁ ← to_expr `((0 + (m : ℕ)) + 0),
e₂ ← to_expr `(0 + (0 + (m : ℕ))),
e₃ ← to_expr `(0 + (m : ℕ)),
prec ← return (contained_funsyms e₁)^.keys,
prec_gt ← return $ prec_gt_of_name_list prec,
guard $ lpo prec_gt e₁ e₃,
guard $ lpo prec_gt e₂ e₃,
to_expr `(trivial) >>= apply
/-
open tactic
example (i : Type) (f : i → i) (c d x : i) : true := by do
ef ← get_local `f, ec ← get_local `c, ed ← get_local `d,
syms ← return [ef,ec,ed],
prec_gt ← return $ prec_gt_of_name_list (list.map local_uniq_name [ef, ec, ed]),
sequence' (do s1 ← syms, s2 ← syms, return (do
s1_fmt ← pp s1, s2_fmt ← pp s2,
trace (s1_fmt ++ to_fmt " > " ++ s2_fmt ++ to_fmt ": " ++ to_fmt (prec_gt s1 s2))
)),
exprs ← @mapM tactic _ _ _ to_expr [`(f c), `(f (f c)), `(f d), `(f x), `(f (f x))],
sequence' (do e1 ← exprs, e2 ← exprs, return (do
e1_fmt ← pp e1, e2_fmt ← pp e2,
trace (e1_fmt ++ to_fmt" > " ++ e2_fmt ++ to_fmt": " ++ to_fmt (lpo prec_gt e1 e2))
)),
mk_const ``true.intro >>= apply
-/
open monad
example (x y : ℕ) (h : nat.zero = nat.succ nat.zero) (h2 : nat.succ x = nat.succ y) : true := by do
h ← get_local `h >>= clause.of_classical_proof,
h2 ← get_local `h2 >>= clause.of_classical_proof,
cs ← try_no_confusion_eq_r h 0,
for' cs clause.validate,
cs ← try_no_confusion_eq_r h2 0,
for' cs clause.validate,
to_expr `(trivial) >>= exact
end
|
20781f45cb15421ba29d359db1f1077408bb5aa1 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/sets/compacts.lean | 28b0a6f2f6df4e78d57f7e508c6996ee03380650 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 14,809 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Yaël Dillies
-/
import topology.sets.closeds
import topology.quasi_separated
/-!
# Compact sets
We define a few types of compact sets in a topological space.
## Main Definitions
For a topological space `α`,
* `compacts α`: The type of compact sets.
* `nonempty_compacts α`: The type of non-empty compact sets.
* `positive_compacts α`: The type of compact sets with non-empty interior.
* `compact_opens α`: The type of compact open sets. This is a central object in the study of
spectral spaces.
-/
open set
variables {α β : Type*} [topological_space α] [topological_space β]
namespace topological_space
/-! ### Compact sets -/
/-- The type of compact sets of a topological space. -/
structure compacts (α : Type*) [topological_space α] :=
(carrier : set α)
(is_compact' : is_compact carrier)
namespace compacts
variables {α}
instance : set_like (compacts α) α :=
{ coe := compacts.carrier,
coe_injective' := λ s t h, by { cases s, cases t, congr' } }
protected lemma is_compact (s : compacts α) : is_compact (s : set α) := s.is_compact'
instance (K : compacts α) : compact_space K := is_compact_iff_compact_space.1 K.is_compact
instance : can_lift (set α) (compacts α) coe is_compact :=
{ prf := λ K hK, ⟨⟨K, hK⟩, rfl⟩ }
@[ext] protected lemma ext {s t : compacts α} (h : (s : set α) = t) : s = t := set_like.ext' h
@[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl
@[simp] lemma carrier_eq_coe (s : compacts α) : s.carrier = s := rfl
instance : has_sup (compacts α) := ⟨λ s t, ⟨s ∪ t, s.is_compact.union t.is_compact⟩⟩
instance [t2_space α] : has_inf (compacts α) := ⟨λ s t, ⟨s ∩ t, s.is_compact.inter t.is_compact⟩⟩
instance [compact_space α] : has_top (compacts α) := ⟨⟨univ, is_compact_univ⟩⟩
instance : has_bot (compacts α) := ⟨⟨∅, is_compact_empty⟩⟩
instance : semilattice_sup (compacts α) := set_like.coe_injective.semilattice_sup _ (λ _ _, rfl)
instance [t2_space α] : distrib_lattice (compacts α) :=
set_like.coe_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl)
instance : order_bot (compacts α) := order_bot.lift (coe : _ → set α) (λ _ _, id) rfl
instance [compact_space α] : bounded_order (compacts α) :=
bounded_order.lift (coe : _ → set α) (λ _ _, id) rfl rfl
/-- The type of compact sets is inhabited, with default element the empty set. -/
instance : inhabited (compacts α) := ⟨⊥⟩
@[simp] lemma coe_sup (s t : compacts α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_inf [t2_space α] (s t : compacts α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl
@[simp] lemma coe_top [compact_space α] : (↑(⊤ : compacts α) : set α) = univ := rfl
@[simp] lemma coe_bot : (↑(⊥ : compacts α) : set α) = ∅ := rfl
@[simp] lemma coe_finset_sup {ι : Type*} {s : finset ι} {f : ι → compacts α} :
(↑(s.sup f) : set α) = s.sup (λ i, f i) :=
begin
classical,
refine finset.induction_on s rfl (λ a s _ h, _),
simp_rw [finset.sup_insert, coe_sup, sup_eq_union],
congr',
end
/-- The image of a compact set under a continuous function. -/
protected def map (f : α → β) (hf : continuous f) (K : compacts α) : compacts β :=
⟨f '' K.1, K.2.image hf⟩
@[simp] lemma coe_map {f : α → β} (hf : continuous f) (s : compacts α) :
(s.map f hf : set β) = f '' s := rfl
/-- A homeomorphism induces an equivalence on compact sets, by taking the image. -/
@[simp] protected def equiv (f : α ≃ₜ β) : compacts α ≃ compacts β :=
{ to_fun := compacts.map f f.continuous,
inv_fun := compacts.map _ f.symm.continuous,
left_inv := λ s, by { ext1, simp only [coe_map, ← image_comp, f.symm_comp_self, image_id] },
right_inv := λ s, by { ext1, simp only [coe_map, ← image_comp, f.self_comp_symm, image_id] } }
/-- The image of a compact set under a homeomorphism can also be expressed as a preimage. -/
lemma equiv_to_fun_val (f : α ≃ₜ β) (K : compacts α) :
(compacts.equiv f K).1 = f.symm ⁻¹' K.1 :=
congr_fun (image_eq_preimage_of_inverse f.left_inv f.right_inv) K.1
/-- The product of two `compacts`, as a `compacts` in the product space. -/
protected def prod (K : compacts α) (L : compacts β) : compacts (α × β) :=
{ carrier := K ×ˢ L,
is_compact' := is_compact.prod K.2 L.2 }
@[simp] lemma coe_prod (K : compacts α) (L : compacts β) : (K.prod L : set (α × β)) = K ×ˢ L := rfl
end compacts
/-! ### Nonempty compact sets -/
/-- The type of nonempty compact sets of a topological space. -/
structure nonempty_compacts (α : Type*) [topological_space α] extends compacts α :=
(nonempty' : carrier.nonempty)
namespace nonempty_compacts
instance : set_like (nonempty_compacts α) α :=
{ coe := λ s, s.carrier,
coe_injective' := λ s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } }
protected lemma is_compact (s : nonempty_compacts α) : is_compact (s : set α) := s.is_compact'
protected lemma nonempty (s : nonempty_compacts α) : (s : set α).nonempty := s.nonempty'
/-- Reinterpret a nonempty compact as a closed set. -/
def to_closeds [t2_space α] (s : nonempty_compacts α) : closeds α := ⟨s, s.is_compact.is_closed⟩
@[ext] protected lemma ext {s t : nonempty_compacts α} (h : (s : set α) = t) : s = t :=
set_like.ext' h
@[simp] lemma coe_mk (s : compacts α) (h) : (mk s h : set α) = s := rfl
@[simp] lemma carrier_eq_coe (s : nonempty_compacts α) : s.carrier = s := rfl
instance : has_sup (nonempty_compacts α) :=
⟨λ s t, ⟨s.to_compacts ⊔ t.to_compacts, s.nonempty.mono $ subset_union_left _ _⟩⟩
instance [compact_space α] [nonempty α] : has_top (nonempty_compacts α) := ⟨⟨⊤, univ_nonempty⟩⟩
instance : semilattice_sup (nonempty_compacts α) :=
set_like.coe_injective.semilattice_sup _ (λ _ _, rfl)
instance [compact_space α] [nonempty α] : order_top (nonempty_compacts α) :=
order_top.lift (coe : _ → set α) (λ _ _, id) rfl
@[simp] lemma coe_sup (s t : nonempty_compacts α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_top [compact_space α] [nonempty α] :
(↑(⊤ : nonempty_compacts α) : set α) = univ := rfl
/-- In an inhabited space, the type of nonempty compact subsets is also inhabited, with
default element the singleton set containing the default element. -/
instance [inhabited α] : inhabited (nonempty_compacts α) :=
⟨{ carrier := {default}, is_compact' := is_compact_singleton, nonempty' := singleton_nonempty _ }⟩
instance to_compact_space {s : nonempty_compacts α} : compact_space s :=
is_compact_iff_compact_space.1 s.is_compact
instance to_nonempty {s : nonempty_compacts α} : nonempty s := s.nonempty.to_subtype
/-- The product of two `nonempty_compacts`, as a `nonempty_compacts` in the product space. -/
protected def prod (K : nonempty_compacts α) (L : nonempty_compacts β) :
nonempty_compacts (α × β) :=
{ nonempty' := K.nonempty.prod L.nonempty,
.. K.to_compacts.prod L.to_compacts }
@[simp] lemma coe_prod (K : nonempty_compacts α) (L : nonempty_compacts β) :
(K.prod L : set (α × β)) = K ×ˢ L := rfl
end nonempty_compacts
/-! ### Positive compact sets -/
/-- The type of compact sets with nonempty interior of a topological space.
See also `compacts` and `nonempty_compacts`. -/
structure positive_compacts (α : Type*) [topological_space α] extends compacts α :=
(interior_nonempty' : (interior carrier).nonempty)
namespace positive_compacts
instance : set_like (positive_compacts α) α :=
{ coe := λ s, s.carrier,
coe_injective' := λ s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } }
protected lemma is_compact (s : positive_compacts α) : is_compact (s : set α) := s.is_compact'
lemma interior_nonempty (s : positive_compacts α) : (interior (s : set α)).nonempty :=
s.interior_nonempty'
protected lemma nonempty (s : positive_compacts α) : (s : set α).nonempty :=
s.interior_nonempty.mono interior_subset
/-- Reinterpret a positive compact as a nonempty compact. -/
def to_nonempty_compacts (s : positive_compacts α) : nonempty_compacts α :=
⟨s.to_compacts, s.nonempty⟩
@[ext] protected lemma ext {s t : positive_compacts α} (h : (s : set α) = t) : s = t :=
set_like.ext' h
@[simp] lemma coe_mk (s : compacts α) (h) : (mk s h : set α) = s := rfl
@[simp] lemma carrier_eq_coe (s : positive_compacts α) : s.carrier = s := rfl
instance : has_sup (positive_compacts α) :=
⟨λ s t, ⟨s.to_compacts ⊔ t.to_compacts,
s.interior_nonempty.mono $ interior_mono $ subset_union_left _ _⟩⟩
instance [compact_space α] [nonempty α] : has_top (positive_compacts α) :=
⟨⟨⊤, interior_univ.symm.subst univ_nonempty⟩⟩
instance : semilattice_sup (positive_compacts α) :=
set_like.coe_injective.semilattice_sup _ (λ _ _, rfl)
instance [compact_space α] [nonempty α] : order_top (positive_compacts α) :=
order_top.lift (coe : _ → set α) (λ _ _, id) rfl
@[simp] lemma coe_sup (s t : positive_compacts α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_top [compact_space α] [nonempty α] :
(↑(⊤ : positive_compacts α) : set α) = univ := rfl
lemma _root_.exists_positive_compacts_subset [locally_compact_space α] {U : set α} (ho : is_open U)
(hn : U.nonempty) : ∃ K : positive_compacts α, ↑K ⊆ U :=
let ⟨x, hx⟩ := hn, ⟨K, hKc, hxK, hKU⟩ := exists_compact_subset ho hx in ⟨⟨⟨K, hKc⟩, ⟨x, hxK⟩⟩, hKU⟩
instance [compact_space α] [nonempty α] : inhabited (positive_compacts α) := ⟨⊤⟩
/-- In a nonempty locally compact space, there exists a compact set with nonempty interior. -/
instance nonempty' [locally_compact_space α] [nonempty α] : nonempty (positive_compacts α) :=
nonempty_of_exists $ exists_positive_compacts_subset is_open_univ univ_nonempty
/-- The product of two `positive_compacts`, as a `positive_compacts` in the product space. -/
protected def prod (K : positive_compacts α) (L : positive_compacts β) :
positive_compacts (α × β) :=
{ interior_nonempty' :=
begin
simp only [compacts.carrier_eq_coe, compacts.coe_prod, interior_prod_eq],
exact K.interior_nonempty.prod L.interior_nonempty,
end,
.. K.to_compacts.prod L.to_compacts }
@[simp] lemma coe_prod (K : positive_compacts α) (L : positive_compacts β) :
(K.prod L : set (α × β)) = K ×ˢ L := rfl
end positive_compacts
/-! ### Compact open sets -/
/-- The type of compact open sets of a topological space. This is useful in non Hausdorff contexts,
in particular spectral spaces. -/
structure compact_opens (α : Type*) [topological_space α] extends compacts α :=
(is_open' : is_open carrier)
namespace compact_opens
instance : set_like (compact_opens α) α :=
{ coe := λ s, s.carrier,
coe_injective' := λ s t h, by { obtain ⟨⟨_, _⟩, _⟩ := s, obtain ⟨⟨_, _⟩, _⟩ := t, congr' } }
protected lemma is_compact (s : compact_opens α) : is_compact (s : set α) := s.is_compact'
protected lemma is_open (s : compact_opens α) : is_open (s : set α) := s.is_open'
/-- Reinterpret a compact open as an open. -/
@[simps] def to_opens (s : compact_opens α) : opens α := ⟨s, s.is_open⟩
/-- Reinterpret a compact open as a clopen. -/
@[simps] def to_clopens [t2_space α] (s : compact_opens α) : clopens α :=
⟨s, s.is_open, s.is_compact.is_closed⟩
@[ext] protected lemma ext {s t : compact_opens α} (h : (s : set α) = t) : s = t := set_like.ext' h
@[simp] lemma coe_mk (s : compacts α) (h) : (mk s h : set α) = s := rfl
instance : has_sup (compact_opens α) :=
⟨λ s t, ⟨s.to_compacts ⊔ t.to_compacts, s.is_open.union t.is_open⟩⟩
instance [quasi_separated_space α] : has_inf (compact_opens α) :=
⟨λ U V, ⟨⟨(U : set α) ∩ (V : set α),
quasi_separated_space.inter_is_compact U.1.1 V.1.1 U.2 U.1.2 V.2 V.1.2⟩, U.2.inter V.2⟩⟩
instance [quasi_separated_space α] : semilattice_inf (compact_opens α) :=
set_like.coe_injective.semilattice_inf _ (λ _ _, rfl)
instance [compact_space α] : has_top (compact_opens α) := ⟨⟨⊤, is_open_univ⟩⟩
instance : has_bot (compact_opens α) := ⟨⟨⊥, is_open_empty⟩⟩
instance [t2_space α] : has_sdiff (compact_opens α) :=
⟨λ s t, ⟨⟨s \ t, s.is_compact.diff t.is_open⟩, s.is_open.sdiff t.is_compact.is_closed⟩⟩
instance [t2_space α] [compact_space α] : has_compl (compact_opens α) :=
⟨λ s, ⟨⟨sᶜ, s.is_open.is_closed_compl.is_compact⟩, s.is_compact.is_closed.is_open_compl⟩⟩
instance : semilattice_sup (compact_opens α) :=
set_like.coe_injective.semilattice_sup _ (λ _ _, rfl)
instance : order_bot (compact_opens α) := order_bot.lift (coe : _ → set α) (λ _ _, id) rfl
instance [t2_space α] : generalized_boolean_algebra (compact_opens α) :=
set_like.coe_injective.generalized_boolean_algebra _ (λ _ _, rfl) (λ _ _, rfl) rfl (λ _ _, rfl)
instance [compact_space α] : bounded_order (compact_opens α) :=
bounded_order.lift (coe : _ → set α) (λ _ _, id) rfl rfl
instance [t2_space α] [compact_space α] : boolean_algebra (compact_opens α) :=
set_like.coe_injective.boolean_algebra _ (λ _ _, rfl) (λ _ _, rfl) rfl rfl (λ _, rfl) (λ _ _, rfl)
@[simp] lemma coe_sup (s t : compact_opens α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_inf [t2_space α] (s t : compact_opens α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl
@[simp] lemma coe_top [compact_space α] : (↑(⊤ : compact_opens α) : set α) = univ := rfl
@[simp] lemma coe_bot : (↑(⊥ : compact_opens α) : set α) = ∅ := rfl
@[simp] lemma coe_sdiff [t2_space α] (s t : compact_opens α) : (↑(s \ t) : set α) = s \ t := rfl
@[simp] lemma coe_compl [t2_space α] [compact_space α] (s : compact_opens α) : (↑sᶜ : set α) = sᶜ :=
rfl
instance : inhabited (compact_opens α) := ⟨⊥⟩
/-- The image of a compact open under a continuous open map. -/
@[simps] def map (f : α → β) (hf : continuous f) (hf' : is_open_map f) (s : compact_opens α) :
compact_opens β :=
⟨s.to_compacts.map f hf, hf' _ s.is_open⟩
@[simp] lemma coe_map {f : α → β} (hf : continuous f) (hf' : is_open_map f) (s : compact_opens α) :
(s.map f hf hf' : set β) = f '' s := rfl
/-- The product of two `compact_opens`, as a `compact_opens` in the product space. -/
protected def prod (K : compact_opens α) (L : compact_opens β) :
compact_opens (α × β) :=
{ is_open' := K.is_open.prod L.is_open,
.. K.to_compacts.prod L.to_compacts }
@[simp] lemma coe_prod (K : compact_opens α) (L : compact_opens β) :
(K.prod L : set (α × β)) = K ×ˢ L := rfl
end compact_opens
end topological_space
|
c9cd728b7eacba464fc5b87b26e19cc728db2d9f | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /stage0/src/Init/Data/AssocList.lean | 445da38140bff91493739ce20b4a7625f19bade6 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 1,685 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Control.Id
universes u v w
/- List-like type to avoid extra level of indirection -/
inductive AssocList (α : Type u) (β : Type v)
| nil {} : AssocList
| cons (key : α) (value : β) (tail : AssocList) : AssocList
namespace AssocList
variables {α : Type u} {β : Type v} {δ : Type w} {m : Type w → Type w} [Monad m]
def empty : AssocList α β :=
nil
@[specialize] def foldlM (f : δ → α → β → m δ) : δ → AssocList α β → m δ
| d, nil => pure d
| d, cons a b es => do d ← f d a b; foldlM d es
@[inline] def foldl (f : δ → α → β → δ) (d : δ) (as : AssocList α β) : δ :=
Id.run (foldlM f d as)
def findEntry? [HasBeq α] (a : α) : AssocList α β → Option (α × β)
| nil => none
| cons k v es => match k == a with
| true => some (k, v)
| false => findEntry? es
def find? [HasBeq α] (a : α) : AssocList α β → Option β
| nil => none
| cons k v es => match k == a with
| true => some v
| false => find? es
def contains [HasBeq α] (a : α) : AssocList α β → Bool
| nil => false
| cons k v es => k == a || contains es
def replace [HasBeq α] (a : α) (b : β) : AssocList α β → AssocList α β
| nil => nil
| cons k v es => match k == a with
| true => cons a b es
| false => cons k v (replace es)
def erase [HasBeq α] (a : α) : AssocList α β → AssocList α β
| nil => nil
| cons k v es => match k == a with
| true => es
| false => cons k v (erase es)
end AssocList
|
7a22bde6ffd14de1c73315856f44d470111106be | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/module/bimodule.lean | 259311e22dd0c77e65547870349a8ba571f2dc99 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,439 | lean | /-
Copyright (c) 2022 Oliver Nash. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Oliver Nash
-/
import ring_theory.tensor_product
/-!
# Bimodules
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
One frequently encounters situations in which several sets of scalars act on a single space, subject
to compatibility condition(s). A distinguished instance of this is the theory of bimodules: one has
two rings `R`, `S` acting on an additive group `M`, with `R` acting covariantly ("on the left")
and `S` acting contravariantly ("on the right"). The compatibility condition is just:
`(r • m) • s = r • (m • s)` for all `r : R`, `s : S`, `m : M`.
This situation can be set up in Mathlib as:
```lean
variables (R S M : Type*) [ring R] [ring S]
variables [add_comm_group M] [module R M] [module Sᵐᵒᵖ M] [smul_comm_class R Sᵐᵒᵖ M]
```
The key fact is:
```lean
example : module (R ⊗[ℕ] Sᵐᵒᵖ) M := tensor_product.algebra.module
```
Note that the corresponding result holds for the canonically isomorphic ring `R ⊗[ℤ] Sᵐᵒᵖ` but it is
preferable to use the `R ⊗[ℕ] Sᵐᵒᵖ` instance since it works without additive inverses.
Bimodules are thus just a special case of `module`s and most of their properties follow from the
theory of `module`s`. In particular a two-sided submodule of a bimodule is simply a term of type
`submodule (R ⊗[ℕ] Sᵐᵒᵖ) M`.
This file is a place to collect results which are specific to bimodules.
## Main definitions
* `subbimodule.mk`
* `subbimodule.smul_mem`
* `subbimodule.smul_mem'`
* `subbimodule.to_submodule`
* `subbimodule.to_submodule'`
## Implementation details
For many definitions and lemmas it is preferable to set things up without opposites, i.e., as:
`[module S M] [smul_comm_class R S M]` rather than `[module Sᵐᵒᵖ M] [smul_comm_class R Sᵐᵒᵖ M]`.
The corresponding results for opposites then follow automatically and do not require taking
advantage of the fact that `(Sᵐᵒᵖ)ᵐᵒᵖ` is defeq to `S`.
## TODO
Develop the theory of two-sided ideals, which have type `submodule (R ⊗[ℕ] Rᵐᵒᵖ) R`.
-/
open_locale tensor_product
local attribute [instance] tensor_product.algebra.module
namespace subbimodule
section algebra
variables {R A B M : Type*}
variables [comm_semiring R] [add_comm_monoid M] [module R M]
variables [semiring A] [semiring B] [module A M] [module B M]
variables [algebra R A] [algebra R B]
variables [is_scalar_tower R A M] [is_scalar_tower R B M]
variables [smul_comm_class A B M]
/-- A constructor for a subbimodule which demands closure under the two sets of scalars
individually, rather than jointly via their tensor product.
Note that `R` plays no role but it is convenient to make this generalisation to support the cases
`R = ℕ` and `R = ℤ` which both show up naturally. See also `base_change`. -/
@[simps] def mk (p : add_submonoid M)
(hA : ∀ (a : A) {m : M}, m ∈ p → a • m ∈ p)
(hB : ∀ (b : B) {m : M}, m ∈ p → b • m ∈ p) : submodule (A ⊗[R] B) M :=
{ carrier := p,
smul_mem' := λ ab m, tensor_product.induction_on ab
(λ hm, by simpa only [zero_smul] using p.zero_mem)
(λ a b hm, by simpa only [tensor_product.algebra.smul_def] using hA a (hB b hm))
(λ z w hz hw hm, by simpa only [add_smul] using p.add_mem (hz hm) (hw hm)),
.. p }
lemma smul_mem (p : submodule (A ⊗[R] B) M) (a : A) {m : M} (hm : m ∈ p) : a • m ∈ p :=
begin
suffices : a • m = a ⊗ₜ[R] (1 : B) • m, { exact this.symm ▸ p.smul_mem _ hm, },
simp [tensor_product.algebra.smul_def],
end
lemma smul_mem' (p : submodule (A ⊗[R] B) M) (b : B) {m : M} (hm : m ∈ p) : b • m ∈ p :=
begin
suffices : b • m = (1 : A) ⊗ₜ[R] b • m, { exact this.symm ▸ p.smul_mem _ hm, },
simp [tensor_product.algebra.smul_def],
end
/-- If `A` and `B` are also `algebra`s over yet another set of scalars `S` then we may "base change"
from `R` to `S`. -/
@[simps] def base_change (S : Type*) [comm_semiring S] [module S M] [algebra S A] [algebra S B]
[is_scalar_tower S A M] [is_scalar_tower S B M] (p : submodule (A ⊗[R] B) M) :
submodule (A ⊗[S] B) M :=
mk p.to_add_submonoid (smul_mem p) (smul_mem' p)
/-- Forgetting the `B` action, a `submodule` over `A ⊗[R] B` is just a `submodule` over `A`. -/
@[simps] def to_submodule (p : submodule (A ⊗[R] B) M) : submodule A M :=
{ carrier := p,
smul_mem' := smul_mem p,
.. p }
/-- Forgetting the `A` action, a `submodule` over `A ⊗[R] B` is just a `submodule` over `B`. -/
@[simps] def to_submodule' (p : submodule (A ⊗[R] B) M) : submodule B M :=
{ carrier := p,
smul_mem' := smul_mem' p,
.. p }
end algebra
section ring
variables (R S M : Type*) [ring R] [ring S]
variables [add_comm_group M] [module R M] [module S M] [smul_comm_class R S M]
/-- A `submodule` over `R ⊗[ℕ] S` is naturally also a `submodule` over the canonically-isomorphic
ring `R ⊗[ℤ] S`. -/
@[simps] def to_subbimodule_int (p : submodule (R ⊗[ℕ] S) M) : submodule (R ⊗[ℤ] S) M :=
base_change ℤ p
/-- A `submodule` over `R ⊗[ℤ] S` is naturally also a `submodule` over the canonically-isomorphic
ring `R ⊗[ℕ] S`. -/
@[simps] def to_subbimodule_nat (p : submodule (R ⊗[ℤ] S) M) : submodule (R ⊗[ℕ] S) M :=
base_change ℕ p
end ring
end subbimodule
|
df5ab694a604ab62a1446c8417abc738cdaf5f1f | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/topology/sheaves/functors.lean | 28a320de365952473ab0a6272a9b6e5df4a1a8c3 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 2,445 | lean | /-
Copyright (c) 2021 Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu
-/
import topology.sheaves.sheaf_condition.pairwise_intersections
/-!
# functors between categories of sheaves
Show that the pushforward of a sheaf is a sheaf, and define
the pushforward functor from the category of C-valued sheaves
on X to that of sheaves on Y, given a continuous map between
topological spaces X and Y.
TODO: pullback for presheaves and sheaves
-/
noncomputable theory
universes v u u₁
open category_theory
open category_theory.limits
open topological_space
variables {C : Type u₁} [category.{v} C]
variables {X Y : Top.{v}} (f : X ⟶ Y)
variables ⦃ι : Type v⦄ {U : ι → opens Y}
namespace Top
namespace presheaf.sheaf_condition_pairwise_intersections
lemma map_diagram :
pairwise.diagram U ⋙ opens.map f = pairwise.diagram ((opens.map f).obj ∘ U) :=
begin
apply functor.hext,
abstract obj_eq {intro i, cases i; refl},
intros i j g, apply subsingleton.helim,
iterate 2 {rw map_diagram.obj_eq},
end
lemma map_cocone : (opens.map f).map_cocone (pairwise.cocone U)
== pairwise.cocone ((opens.map f).obj ∘ U) :=
begin
unfold functor.map_cocone cocones.functoriality, dsimp, congr,
iterate 2 {rw map_diagram, rw opens.map_supr},
apply subsingleton.helim, rw [map_diagram, opens.map_supr],
apply proof_irrel_heq,
end
theorem pushforward_sheaf_of_sheaf {F : presheaf C X}
(h : F.is_sheaf_pairwise_intersections) :
(f _* F).is_sheaf_pairwise_intersections :=
λ ι U, begin
convert h ((opens.map f).obj ∘ U) using 2,
rw ← map_diagram, refl,
change F.map_cone ((opens.map f).map_cocone _).op == _,
congr, iterate 2 {rw map_diagram}, apply map_cocone,
end
end presheaf.sheaf_condition_pairwise_intersections
namespace sheaf
open presheaf
variables [has_products.{v} C]
/--
The pushforward of a sheaf (by a continuous map) is a sheaf.
-/
theorem pushforward_sheaf_of_sheaf
{F : X.presheaf C} (h : F.is_sheaf) : (f _* F).is_sheaf :=
by rw is_sheaf_iff_is_sheaf_pairwise_intersections at h ⊢;
exact sheaf_condition_pairwise_intersections.pushforward_sheaf_of_sheaf f h
/--
The pushforward functor.
-/
def pushforward (f : X ⟶ Y) : X.sheaf C ⥤ Y.sheaf C :=
{ obj := λ ℱ, ⟨f _* ℱ.1, pushforward_sheaf_of_sheaf f ℱ.2⟩,
map := λ _ _ g, ⟨pushforward_map f g.1⟩ }
end sheaf
end Top
|
771c7ae5c4a2c34fad42dbecd7c041aad47925ff | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/geometry/euclidean/triangle.lean | c97326e4b4241f45ce468204913a4c7cc9b7d120 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 18,081 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import geometry.euclidean.angle.oriented.affine
import geometry.euclidean.angle.unoriented.affine
import tactic.interval_cases
/-!
# Triangles
This file proves basic geometrical results about distances and angles
in (possibly degenerate) triangles in real inner product spaces and
Euclidean affine spaces. More specialized results, and results
developed for simplices in general rather than just for triangles, are
in separate files. Definitions and results that make sense in more
general affine spaces rather than just in the Euclidean case go under
`linear_algebra.affine_space`.
## Implementation notes
Results in this file are generally given in a form with only those
non-degeneracy conditions needed for the particular result, rather
than requiring affine independence of the points of a triangle
unnecessarily.
## References
* https://en.wikipedia.org/wiki/Law_of_cosines
* https://en.wikipedia.org/wiki/Pons_asinorum
* https://en.wikipedia.org/wiki/Sum_of_angles_of_a_triangle
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
namespace inner_product_geometry
/-!
### Geometrical results on triangles in real inner product spaces
This section develops some results on (possibly degenerate) triangles
in real inner product spaces, where those definitions and results can
most conveniently be developed in terms of vectors and then used to
deduce corresponding results for Euclidean affine spaces.
-/
variables {V : Type*} [inner_product_space ℝ V]
/-- Law of cosines (cosine rule), vector angle form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle
(x y : V) :
‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ - 2 * ‖x‖ * ‖y‖ * real.cos (angle x y) :=
by rw [(show 2 * ‖x‖ * ‖y‖ * real.cos (angle x y) =
2 * (real.cos (angle x y) * (‖x‖ * ‖y‖)), by ring),
cos_angle_mul_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm,
←real_inner_self_eq_norm_mul_norm, ←real_inner_self_eq_norm_mul_norm,
real_inner_sub_sub_self, sub_add_eq_add_sub]
/-- Pons asinorum, vector angle form. -/
lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : ‖x‖ = ‖y‖) :
angle x (x - y) = angle y (y - x) :=
begin
refine real.inj_on_cos ⟨angle_nonneg _ _, angle_le_pi _ _⟩ ⟨angle_nonneg _ _, angle_le_pi _ _⟩ _,
rw [cos_angle, cos_angle, h, ←neg_sub, norm_neg, neg_sub,
inner_sub_right, inner_sub_right, real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm, h, real_inner_comm x y]
end
/-- Converse of pons asinorum, vector angle form. -/
lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V}
(h : angle x (x - y) = angle y (y - x)) (hpi : angle x y ≠ π) : ‖x‖ = ‖y‖ :=
begin
replace h := real.arccos_inj_on
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x (x - y)))
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one y (y - x))) h,
by_cases hxy : x = y,
{ rw hxy },
{ rw [←norm_neg (y - x), neg_sub, mul_comm, mul_comm ‖y‖, div_eq_mul_inv, div_eq_mul_inv,
mul_inv_rev, mul_inv_rev, ←mul_assoc, ←mul_assoc] at h,
replace h :=
mul_right_cancel₀ (inv_ne_zero (λ hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h,
rw [inner_sub_right, inner_sub_right, real_inner_comm x y, real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm, mul_sub_right_distrib, mul_sub_right_distrib,
mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub,
←mul_sub_left_distrib] at h,
by_cases hx0 : x = 0,
{ rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h,
rw [hx0, norm_zero, h] },
{ by_cases hy0 : y = 0,
{ rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h,
rw [hy0, norm_zero, h] },
{ rw [inv_sub_inv (λ hz, hx0 (norm_eq_zero.1 hz)) (λ hz, hy0 (norm_eq_zero.1 hz)),
←neg_sub, ←mul_div_assoc, mul_comm, mul_div_assoc, ←mul_neg_one] at h,
symmetry,
by_contradiction hyx,
replace h := (mul_left_cancel₀ (sub_ne_zero_of_ne hyx) h).symm,
rw [real_inner_div_norm_mul_norm_eq_neg_one_iff, ←angle_eq_pi_iff] at h,
exact hpi h } } }
end
/-- The cosine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.cos (angle x (x - y) + angle y (y - x)) = -real.cos (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.cos_add, cos_angle, cos_angle, cos_angle],
have hxn : ‖x‖ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)),
have hyn : ‖y‖ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)),
have hxyn : ‖x - y‖ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel₀ hxn,
apply mul_right_cancel₀ hyn,
apply mul_right_cancel₀ hxyn,
apply mul_right_cancel₀ hxyn,
have H1 : real.sin (angle x (x - y)) * real.sin (angle y (y - x)) *
‖x‖ * ‖y‖ * ‖x - y‖ * ‖x - y‖ =
(real.sin (angle x (x - y)) * (‖x‖ * ‖x - y‖)) *
(real.sin (angle y (y - x)) * (‖y‖ * ‖x - y‖)), { ring },
have H2 : ⟪x, x⟫ * (⟪x, x⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪y, y⟫)) -
(⟪x, x⟫ - ⟪x, y⟫) * (⟪x, x⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
have H3 : ⟪y, y⟫ * (⟪y, y⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪x, x⟫)) -
(⟪y, y⟫ - ⟪x, y⟫) * (⟪y, y⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
rw [mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib,
mul_sub_right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y,
sin_angle_mul_norm_mul_norm, norm_sub_rev y x, inner_sub_left, inner_sub_left,
inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H2,
H3, real.mul_self_sqrt (sub_nonneg_of_le (real_inner_mul_inner_self_le x y)),
real_inner_self_eq_norm_mul_norm, real_inner_self_eq_norm_mul_norm,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The sine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_sub_add_angle_sub_rev_eq_sin_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.sin (angle x (x - y) + angle y (y - x)) = real.sin (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.sin_add, cos_angle, cos_angle],
have hxn : ‖x‖ ≠ 0 := (λ h, hx (norm_eq_zero.1 h)),
have hyn : ‖y‖ ≠ 0 := (λ h, hy (norm_eq_zero.1 h)),
have hxyn : ‖x - y‖ ≠ 0 := (λ h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel₀ hxn,
apply mul_right_cancel₀ hyn,
apply mul_right_cancel₀ hxyn,
apply mul_right_cancel₀ hxyn,
have H1 : real.sin (angle x (x - y)) * (⟪y, y - x⟫ / (‖y‖ * ‖y - x‖)) * ‖x‖ * ‖y‖ * ‖x - y‖ =
real.sin (angle x (x - y)) * (‖x‖ * ‖x - y‖) *
(⟪y, y - x⟫ / (‖y‖ * ‖y - x‖)) * ‖y‖, { ring },
have H2 : ⟪x, x - y⟫ / (‖x‖ * ‖y - x‖) * real.sin (angle y (y - x)) * ‖x‖ * ‖y‖ * ‖y - x‖ =
⟪x, x - y⟫ / (‖x‖ * ‖y - x‖) *
(real.sin (angle y (y - x)) * (‖y‖ * ‖y - x‖)) * ‖x‖, { ring },
have H3 : ⟪x, x⟫ * (⟪x, x⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪y, y⟫)) -
(⟪x, x⟫ - ⟪x, y⟫) * (⟪x, x⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
have H4 : ⟪y, y⟫ * (⟪y, y⟫ - ⟪x, y⟫ - (⟪x, y⟫ - ⟪x, x⟫)) -
(⟪y, y⟫ - ⟪x, y⟫) * (⟪y, y⟫ - ⟪x, y⟫) =
⟪x, x⟫ * ⟪y, y⟫ - ⟪x, y⟫ * ⟪x, y⟫, { ring },
rw [right_distrib, right_distrib, right_distrib, right_distrib, H1,
sin_angle_mul_norm_mul_norm, norm_sub_rev x y, H2, sin_angle_mul_norm_mul_norm,
norm_sub_rev y x, mul_assoc (real.sin (angle x y)), sin_angle_mul_norm_mul_norm,
inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right,
inner_sub_right, real_inner_comm x y, H3, H4, real_inner_self_eq_norm_mul_norm,
real_inner_self_eq_norm_mul_norm,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The cosine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_add_angle_sub_add_angle_sub_eq_neg_one {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.cos (angle x y + angle x (x - y) + angle y (y - x)) = -1 :=
by rw [add_assoc, real.cos_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy, mul_neg, ←neg_add',
add_comm, ←sq, ←sq, real.sin_sq_add_cos_sq]
/-- The sine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_add_angle_sub_add_angle_sub_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.sin (angle x y + angle x (x - y) + angle y (y - x)) = 0 :=
begin
rw [add_assoc, real.sin_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy],
ring
end
/-- The sum of the angles of a possibly degenerate triangle (where the
two given sides are nonzero), vector angle form. -/
lemma angle_add_angle_sub_add_angle_sub_eq_pi {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
angle x y + angle x (x - y) + angle y (y - x) = π :=
begin
have hcos := cos_angle_add_angle_sub_add_angle_sub_eq_neg_one hx hy,
have hsin := sin_angle_add_angle_sub_add_angle_sub_eq_zero hx hy,
rw real.sin_eq_zero_iff at hsin,
cases hsin with n hn,
symmetry' at hn,
have h0 : 0 ≤ angle x y + angle x (x - y) + angle y (y - x) :=
add_nonneg (add_nonneg (angle_nonneg _ _) (angle_nonneg _ _)) (angle_nonneg _ _),
have h3 : angle x y + angle x (x - y) + angle y (y - x) ≤ π + π + π :=
add_le_add (add_le_add (angle_le_pi _ _) (angle_le_pi _ _)) (angle_le_pi _ _),
have h3lt : angle x y + angle x (x - y) + angle y (y - x) < π + π + π,
{ by_contradiction hnlt,
have hxy : angle x y = π,
{ by_contradiction hxy,
exact hnlt (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le
(lt_of_le_of_ne (angle_le_pi _ _) hxy)
(angle_le_pi _ _)) (angle_le_pi _ _)) },
rw hxy at hnlt,
rw angle_eq_pi_iff at hxy,
rcases hxy with ⟨hx, ⟨r, ⟨hr, hxr⟩⟩⟩,
rw [hxr, ←one_smul ℝ x, ←mul_smul, mul_one, ←sub_smul, one_smul, sub_eq_add_neg,
angle_smul_right_of_pos _ _ (add_pos zero_lt_one (neg_pos_of_neg hr)), angle_self hx,
add_zero] at hnlt,
apply hnlt,
rw add_assoc,
exact add_lt_add_left (lt_of_le_of_lt (angle_le_pi _ _)
(lt_add_of_pos_right π real.pi_pos)) _ },
have hn0 : 0 ≤ n,
{ rw [hn, mul_nonneg_iff_left_nonneg_of_pos real.pi_pos] at h0,
norm_cast at h0,
exact h0 },
have hn3 : n < 3,
{ rw [hn, (show π + π + π = 3 * π, by ring)] at h3lt,
replace h3lt := lt_of_mul_lt_mul_right h3lt (le_of_lt real.pi_pos),
norm_cast at h3lt,
exact h3lt },
interval_cases n,
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
{ rw hn,
norm_num },
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on triangles in Euclidean affine spaces
This section develops some geometrical definitions and results on
(possible degenerate) triangles in Euclidean affine spaces.
-/
open inner_product_geometry
open_locale euclidean_geometry
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- **Law of cosines** (cosine rule), angle-at-point form. -/
lemma dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle
(p1 p2 p3 : P) :
dist p1 p3 * dist p1 p3 =
dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 -
2 * dist p1 p2 * dist p3 p2 * real.cos (∠ p1 p2 p3) :=
begin
rw [dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p3 p2],
unfold angle,
convert norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle
(p1 -ᵥ p2 : V) (p3 -ᵥ p2 : V),
{ exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm },
{ exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm }
end
alias dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle ← law_cos
/-- **Isosceles Triangle Theorem**: Pons asinorum, angle-at-point form. -/
lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) :
∠ p1 p2 p3 = ∠ p1 p3 p2 :=
begin
rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3] at h,
unfold angle,
convert angle_sub_eq_angle_sub_rev_of_norm_eq h,
{ exact (vsub_sub_vsub_cancel_left p3 p2 p1).symm },
{ exact (vsub_sub_vsub_cancel_left p2 p3 p1).symm }
end
/-- Converse of pons asinorum, angle-at-point form. -/
lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = ∠ p1 p3 p2)
(hpi : ∠ p2 p1 p3 ≠ π) : dist p1 p2 = dist p1 p3 :=
begin
unfold angle at h hpi,
rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3],
rw [←angle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi,
rw [←vsub_sub_vsub_cancel_left p3 p2 p1, ←vsub_sub_vsub_cancel_left p2 p3 p1] at h,
exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi
end
/-- The **sum of the angles of a triangle** (possibly degenerate, where the
given vertex is distinct from the others), angle-at-point. -/
lemma angle_add_angle_add_angle_eq_pi {p1 p2 p3 : P} (h2 : p2 ≠ p1) (h3 : p3 ≠ p1) :
∠ p1 p2 p3 + ∠ p2 p3 p1 + ∠ p3 p1 p2 = π :=
begin
rw [add_assoc, add_comm, add_comm (∠ p2 p3 p1), angle_comm p2 p3 p1],
unfold angle,
rw [←angle_neg_neg (p1 -ᵥ p3), ←angle_neg_neg (p1 -ᵥ p2), neg_vsub_eq_vsub_rev,
neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev,
←vsub_sub_vsub_cancel_right p3 p2 p1, ←vsub_sub_vsub_cancel_right p2 p3 p1],
exact angle_add_angle_sub_add_angle_sub_eq_pi (λ he, h3 (vsub_eq_zero_iff_eq.1 he))
(λ he, h2 (vsub_eq_zero_iff_eq.1 he))
end
/-- The **sum of the angles of a triangle** (possibly degenerate, where the triangle is a line),
oriented angles at point. -/
lemma oangle_add_oangle_add_oangle_eq_pi
[module.oriented ℝ V (fin 2)] [fact (finite_dimensional.finrank ℝ V = 2)] {p1 p2 p3 : P}
(h21 : p2 ≠ p1) (h32 : p3 ≠ p2) (h13 : p1 ≠ p3) : ∡ p1 p2 p3 + ∡ p2 p3 p1 + ∡ p3 p1 p2 = π :=
by simpa only [neg_vsub_eq_vsub_rev] using
positive_orientation.oangle_add_cyc3_neg_left
(vsub_ne_zero.mpr h21) (vsub_ne_zero.mpr h32) (vsub_ne_zero.mpr h13)
/-- **Stewart's Theorem**. -/
theorem dist_sq_mul_dist_add_dist_sq_mul_dist (a b c p : P) (h : ∠ b p c = π) :
dist a b ^ 2 * dist c p + dist a c ^ 2 * dist b p =
dist b c * (dist a p ^ 2 + dist b p * dist c p) :=
begin
rw [pow_two, pow_two, law_cos a p b, law_cos a p c,
eq_sub_of_add_eq (angle_add_angle_eq_pi_of_angle_eq_pi a h), real.cos_pi_sub,
dist_eq_add_dist_of_angle_eq_pi h],
ring,
end
/-- **Apollonius's Theorem**. -/
theorem dist_sq_add_dist_sq_eq_two_mul_dist_midpoint_sq_add_half_dist_sq (a b c : P) :
dist a b ^ 2 + dist a c ^ 2 = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) :=
begin
by_cases hbc : b = c,
{ simp [hbc, midpoint_self, dist_self, two_mul] },
{ let m := midpoint ℝ b c,
have : dist b c ≠ 0 := (dist_pos.mpr hbc).ne',
have hm := dist_sq_mul_dist_add_dist_sq_mul_dist a b c m (angle_midpoint_eq_pi b c hbc),
simp only [dist_left_midpoint, dist_right_midpoint, real.norm_two] at hm,
calc dist a b ^ 2 + dist a c ^ 2
= 2 / dist b c * (dist a b ^ 2 * (2⁻¹ * dist b c) + dist a c ^ 2 * (2⁻¹ * dist b c)) :
by { field_simp, ring }
... = 2 * (dist a (midpoint ℝ b c) ^ 2 + (dist b c / 2) ^ 2) :
by { rw hm, field_simp, ring } },
end
lemma dist_mul_of_eq_angle_of_dist_mul (a b c a' b' c' : P) (r : ℝ) (h : ∠ a' b' c' = ∠ a b c)
(hab : dist a' b' = r * dist a b) (hcb : dist c' b' = r * dist c b) :
dist a' c' = r * dist a c :=
begin
have h' : dist a' c' ^ 2 = (r * dist a c) ^ 2,
calc dist a' c' ^ 2
= dist a' b' ^ 2 + dist c' b' ^ 2 - 2 * dist a' b' * dist c' b' * real.cos (∠ a' b' c') :
by { simp [pow_two, law_cos a' b' c'] }
... = r ^ 2 * (dist a b ^ 2 + dist c b ^ 2 - 2 * dist a b * dist c b * real.cos (∠ a b c)) :
by { rw [h, hab, hcb], ring }
... = (r * dist a c) ^ 2 : by simp [pow_two, ← law_cos a b c, mul_pow],
by_cases hab₁ : a = b,
{ have hab'₁ : a' = b', { rw [← dist_eq_zero, hab, dist_eq_zero.mpr hab₁, mul_zero r] },
rw [hab₁, hab'₁, dist_comm b' c', dist_comm b c, hcb] },
{ have h1 : 0 ≤ r * dist a b, { rw ← hab, exact dist_nonneg },
have h2 : 0 ≤ r := nonneg_of_mul_nonneg_left h1 (dist_pos.mpr hab₁),
exact (sq_eq_sq dist_nonneg (mul_nonneg h2 dist_nonneg)).mp h' },
end
end euclidean_geometry
|
85ae4c67114f34869e2bdff0080ebf94d5a488ff | faaa51985b30efc1857652fa0d5ba10007544221 | /Lean/1. Lists/Ex1_2.lean | a760e16f3ca9dc74943c3ca8012c3acbde370b4d | [] | no_license | SvenWille/ExerciseSolutions_New | 0d63f7b9a4e3f32236c19852a2fba744dc64be21 | b8243e7a669846c64e2f5520dae88ff41265d233 | refs/heads/master | 1,629,114,358,797 | 1,511,126,985,000 | 1,511,126,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,102 | lean | open decidable
open list
def replace {a : Type}[decidable_eq a]: a → a → list a → list a
| _ _ [] := []
| old new (x::xs) := (if eq old x then new else x) :: replace old new xs
lemma helper1 {A : Type}[c: decidable_eq A] (old new : A) (xs ys : list A): replace old new (xs ++ ys) = replace old new xs ++ replace old new ys :=
list.rec_on xs
(
show replace old new ([] ++ ys) = replace old new [] ++ replace old new ys, from calc
replace old new ([] ++ ys) = replace old new ys : by simp
... = [] ++ replace old new ys : by simp
... = replace old new [] ++ replace old new ys : by simp[replace]
)
(
assume aa: A,
assume xs: list A,
assume hyp:replace old new (xs ++ ys) = replace old new xs ++ replace old new ys,
show replace old new ((aa :: xs) ++ ys) = replace old new (aa::xs) ++ replace old new ys, from by_cases
(
assume ct : old = aa,
show replace old new ((aa :: xs) ++ ys) = replace old new (aa::xs) ++ replace old new ys , from calc
replace old new ((aa :: xs) ++ ys) = replace old new (aa :: (xs ++ ys)) : by simp
... = new :: replace old new (xs ++ ys) : by simp[ct,replace]
... = new :: (replace old new xs ++ replace old new ys) : by simp[hyp]
... = replace old new (aa ::xs) ++ replace old new ys : by simp[ct,replace]
)
(
assume cf : ¬(old = aa),
show replace old new ((aa :: xs) ++ ys) = replace old new (aa::xs) ++ replace old new ys, from calc
replace old new ((aa :: xs) ++ ys) = aa :: replace old new (xs ++ ys) : by simp[cf,replace]
... = aa :: replace old new xs ++ replace old new ys : by simp[hyp]
... = replace old new (aa :: xs) ++ replace old new ys : by simp[cf,replace]
)
)
lemma helper2{A:Type} : ∀ (xs ys : list A), reverse_core xs ys = reverse_core xs [] ++ ys
| [] ys := rfl
| (a::xs) ys :=
show reverse_core (a::xs) ys = reverse_core (a::xs) [] ++ ys , from calc
reverse_core (a::xs) ys = reverse_core xs [] ++ (a::ys) : by simp[ reverse_core , helper2 xs (a::ys)]
... = reverse_core xs [] ++ [a] ++ ys : by simp
... = reverse_core xs [a] ++ ys : by simp[helper2 xs ([a])]
... = reverse_core (a::xs) [] ++ ys : by simp[reverse_core]
lemma helper3 {A : Type} (xs ys : list A): reverse (xs ++ ys) = reverse ys ++ reverse xs :=
list.rec_on xs
(
show (reverse ([] ++ ys)) = (reverse ys ++ reverse []) , from calc
reverse ([] ++ ys) = reverse ys : by simp
... = reverse ys ++ reverse [] : by simp[reverse, reverse_core]
)
(
assume aa: A,
assume xs : list A ,
assume hyp: reverse (xs ++ ys) = reverse ys ++ reverse xs ,
show reverse ((aa :: xs ) ++ ys) = reverse ys ++ reverse (aa:: xs) , from calc
reverse ((aa:: xs) ++ys) = reverse_core (xs ++ ys) [] ++ [aa] : by simp[reverse, reverse_core , helper2 (xs ++ ys) ([aa])]
... = reverse (xs ++ ys) ++ [aa] : by simp[reverse]
... = reverse ys ++ reverse xs ++ [aa] : by simp[hyp]
... = reverse ys ++ reverse (aa::xs) : by simp[reverse, reverse_core , helper2 xs ([aa])]
)
lemma rev_1 {a : Type}[decidable_eq a] (x y : a)(ls : list a): reverse (replace x y ls) = replace x y(reverse ls) :=
list.rec_on ls
(
show reverse (replace x y []) = replace x y (reverse []), from rfl
)
(
assume aa : a,
assume ls : list a,
let tmp := (if eq x aa then y else aa) in
assume hyp:reverse (replace x y ls) = replace x y(reverse ls),
show reverse (replace x y (aa :: ls)) = replace x y(reverse (aa :: ls)), from calc
reverse (replace x y (aa :: ls)) = reverse (tmp :: replace x y ls) : by simp[replace]
... = reverse (replace x y ls) ++ [tmp] : by simp[reverse, reverse_core , helper2 (replace x y ls) ([tmp])]
... = replace x y (reverse ls) ++ [tmp] :by simp[hyp]
... = replace x y (reverse ls) ++ replace x y [aa] : by simp[replace]
... = replace x y (reverse ls ++ [aa]) :by simp[helper1 x y (reverse ls) ([aa])]
... = replace x y (reverse (aa::ls)) : by simp[reverse, reverse_core , helper2 ls ([aa])]
)
|
efa0b31f16c0ded3a627d822295044be45b8ed5d | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/list/nat_antidiagonal.lean | c33f04c354aba5028165b271d08bb2193dba8455 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,325 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.list.nodup
import data.list.range
/-!
# Antidiagonals in ℕ × ℕ as lists
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the antidiagonals of ℕ × ℕ as lists: the `n`-th antidiagonal is the list of
pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more
generally for sums going from `0` to `n`.
## Notes
Files `data.multiset.nat_antidiagonal` and `data.finset.nat_antidiagonal` successively turn the
`list` definition we have here into `multiset` and `finset`.
-/
open list function nat
namespace list
namespace nat
/-- The antidiagonal of a natural number `n` is the list of pairs `(i, j)` such that `i + j = n`. -/
def antidiagonal (n : ℕ) : list (ℕ × ℕ) :=
(range (n+1)).map (λ i, (i, n - i))
/-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/
@[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} :
x ∈ antidiagonal n ↔ x.1 + x.2 = n :=
begin
rw [antidiagonal, mem_map], split,
{ rintros ⟨i, hi, rfl⟩, rw [mem_range, lt_succ_iff] at hi, exact add_tsub_cancel_of_le hi },
{ rintro rfl, refine ⟨x.fst, _, _⟩,
{ rw [mem_range, add_assoc, lt_add_iff_pos_right], exact zero_lt_succ _ },
{ exact prod.ext rfl (add_tsub_cancel_left _ _) } }
end
/-- The length of the antidiagonal of `n` is `n + 1`. -/
@[simp] lemma length_antidiagonal (n : ℕ) : (antidiagonal n).length = n+1 :=
by rw [antidiagonal, length_map, length_range]
/-- The antidiagonal of `0` is the list `[(0, 0)]` -/
@[simp] lemma antidiagonal_zero : antidiagonal 0 = [(0, 0)] :=
rfl
/-- The antidiagonal of `n` does not contain duplicate entries. -/
lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) :=
(nodup_range _).map (@left_inverse.injective ℕ (ℕ × ℕ) prod.fst (λ i, (i, n-i)) $ λ i, rfl)
@[simp] lemma antidiagonal_succ {n : ℕ} :
antidiagonal (n + 1) = (0, n + 1) :: ((antidiagonal n).map (prod.map nat.succ id)) :=
begin
simp only [antidiagonal, range_succ_eq_map, map_cons, true_and, nat.add_succ_sub_one, add_zero,
id.def, eq_self_iff_true, tsub_zero, map_map, prod.map_mk],
apply congr (congr rfl _) rfl,
ext; simp,
end
lemma antidiagonal_succ' {n : ℕ} :
antidiagonal (n + 1) = ((antidiagonal n).map (prod.map id nat.succ)) ++ [(n + 1, 0)] :=
begin
simp only [antidiagonal, range_succ, add_tsub_cancel_left, map_append,
append_assoc, tsub_self, singleton_append, map_map, map],
congr' 1,
apply map_congr,
simp [le_of_lt, nat.succ_eq_add_one, nat.sub_add_comm] { contextual := tt },
end
lemma antidiagonal_succ_succ' {n : ℕ} :
antidiagonal (n + 2) =
(0, n + 2) :: ((antidiagonal n).map (prod.map nat.succ nat.succ)) ++ [(n + 2, 0)] :=
by { rw antidiagonal_succ', simpa }
lemma map_swap_antidiagonal {n : ℕ} :
(antidiagonal n).map prod.swap = (antidiagonal n).reverse :=
begin
rw [antidiagonal, map_map, prod.swap, ← list.map_reverse,
range_eq_range', reverse_range', ← range_eq_range', map_map],
apply map_congr,
simp [nat.sub_sub_self, lt_succ_iff] { contextual := tt },
end
end nat
end list
|
c8fe2ee618c1999e98c6e35e07a54d74d5b258ec | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Lean/Meta/Tactic/Clear.lean | 64fc706db37908806449eb10a5ded32b6e9f7ab9 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 1,625 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Tactic.Util
namespace Lean.Meta
def clear (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId :=
withMVarContext mvarId do
checkNotAssigned mvarId `clear
let lctx ← getLCtx
unless lctx.contains fvarId do
throwTacticEx `clear mvarId m!"unknown variable '{mkFVar fvarId}'"
let tag ← getMVarTag mvarId
let mctx ← getMCtx
lctx.forM fun localDecl => do
unless localDecl.fvarId == fvarId do
if mctx.localDeclDependsOn localDecl fvarId then
throwTacticEx `clear mvarId m!"variable '{localDecl.toExpr}' depends on '{mkFVar fvarId}'"
let mvarDecl ← getMVarDecl mvarId
if mctx.exprDependsOn mvarDecl.type fvarId then
throwTacticEx `clear mvarId m!"taget depends on '{mkFVar fvarId}'"
let lctx := lctx.erase fvarId
let localInsts ← getLocalInstances
let localInsts := match localInsts.findIdx? $ fun localInst => localInst.fvar.fvarId! == fvarId with
| none => localInsts
| some idx => localInsts.eraseIdx idx
let newMVar ← mkFreshExprMVarAt lctx localInsts mvarDecl.type MetavarKind.syntheticOpaque tag
assignExprMVar mvarId newMVar
pure newMVar.mvarId!
def tryClear (mvarId : MVarId) (fvarId : FVarId) : MetaM MVarId :=
clear mvarId fvarId <|> pure mvarId
def tryClearMany (mvarId : MVarId) (fvarIds : Array FVarId) : MetaM MVarId := do
fvarIds.foldrM (init := mvarId) fun fvarId mvarId => tryClear mvarId fvarId
end Lean.Meta
|
756757001c5796a8f7e921e120a54ce205a98e49 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/category_theory/limits/types.lean | c00d3b0150027da38b3682692c49b81ac39b7b08 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 3,761 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison, Reid Barton
import category_theory.limits.limits
universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation
open category_theory
open category_theory.limits
namespace category_theory.limits.types
variables {J : Type u} [small_category J]
def limit (F : J ⥤ Type u) : cone F :=
{ X := {u : Π j, F.obj j // ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'},
π := { app := λ j u, u.val j } }
local attribute [elab_simple] congr_fun
def limit_is_limit (F : J ⥤ Type u) : is_limit (limit F) :=
{ lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩,
uniq' :=
begin
intros, ext x, apply subtype.eq, ext j,
exact congr_fun (w j) x
end }
instance : has_limits.{u} (Type u) :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } }
@[simp] lemma types_limit (F : J ⥤ Type u) :
limits.limit F = {u : Π j, F.obj j // ∀ {j j'} f, F.map f (u j) = u j'} := rfl
@[simp] lemma types_limit_π (F : J ⥤ Type u) (j : J) (g : (limit F).X) :
limit.π F j g = g.val j := rfl
@[simp] lemma types_limit_pre
(F : J ⥤ Type u) {K : Type u} [𝒦 : small_category K] (E : K ⥤ J) (g : (limit F).X) :
limit.pre F E g = (⟨λ k, g.val (E.obj k), by obviously⟩ : (limit (E ⋙ F)).X) := rfl
@[simp] lemma types_limit_map {F G : J ⥤ Type u} (α : F ⟶ G) (g : (limit F).X) :
(lim.map α : (limit F).X → (limit G).X) g =
(⟨λ j, (α.app j) (g.val j), λ j j' f,
by rw [←functor_to_types.naturality, ←(g.property f)]⟩ : (limit G).X) := rfl
@[simp] lemma types_limit_lift (F : J ⥤ Type u) (c : cone F) (x : c.X):
limit.lift F c x = (⟨λ j, c.π.app j x, λ j j' f, congr_fun (cone.w c f) x⟩ : (limit F).X) :=
rfl
def colimit (F : J ⥤ Type u) : cocone F :=
{ X := @quot (Σ j, F.obj j) (λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2),
ι :=
{ app := λ j x, quot.mk _ ⟨j, x⟩,
naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } }
local attribute [elab_with_expected_type] quot.lift
def colimit_is_colimit (F : J ⥤ Type u) : is_colimit (colimit F) :=
{ desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2)
(assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) }
instance : has_colimits.{u} (Type u) :=
{ has_colimits_of_shape := λ J 𝒥,
{ has_colimit := λ F, by exactI { cocone := colimit F, is_colimit := colimit_is_colimit F } } }
@[simp] lemma types_colimit (F : J ⥤ Type u) :
limits.colimit F = @quot (Σ j, F.obj j) (λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2) := rfl
@[simp] lemma types_colimit_ι (F : J ⥤ Type u) (j : J) :
colimit.ι F j = λ x, quot.mk _ ⟨j, x⟩ := rfl
@[simp] lemma types_colimit_pre
(F : J ⥤ Type u) {K : Type u} [𝒦 : small_category K] (E : K ⥤ J) (g : (colimit (E ⋙ F)).X) :
colimit.pre F E =
quot.lift (λ p, quot.mk _ ⟨E.obj p.1, p.2⟩) (λ p p' ⟨f, h⟩, quot.sound ⟨E.map f, h⟩) := rfl
@[simp] lemma types_colimit_map {F G : J ⥤ Type u} (α : F ⟶ G) :
(colim.map α : (colimit F).X → (colimit G).X) =
quot.lift
(λ p, quot.mk _ ⟨p.1, (α.app p.1) p.2⟩)
(λ p p' ⟨f, h⟩, quot.sound ⟨f, by rw h; exact functor_to_types.naturality _ _ α f _⟩) := rfl
@[simp] lemma types_colimit_desc (F : J ⥤ Type u) (c : cocone F) :
colimit.desc F c =
quot.lift
(λ p, c.ι.app p.1 p.2)
(λ p p' ⟨f, h⟩, by rw h; exact (functor_to_types.naturality _ _ c.ι f _).symm) := rfl
end category_theory.limits.types
|
f8621e675a2db139a20b47da0bd5dc91904ded18 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/linear_algebra/free_module/finite/matrix.lean | 90590c37e3353ca4d883c61e66167eb9ebb15c50 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,160 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import linear_algebra.finrank
import linear_algebra.free_module.finite.basic
import linear_algebra.matrix.to_lin
/-!
# Finite and free modules using matrices
We provide some instances for finite and free modules involving matrices.
## Main results
* `module.free.linear_map` : if `M` and `N` are finite and free, then `M →ₗ[R] N` is free.
* `module.finite.of_basis` : A free module with a basis indexed by a `fintype` is finite.
* `module.finite.linear_map` : if `M` and `N` are finite and free, then `M →ₗ[R] N`
is finite.
-/
universes u v w
variables (R : Type u) (M : Type v) (N : Type w)
namespace module.free
section comm_ring
variables [comm_ring R] [add_comm_group M] [module R M] [module.free R M]
variables [add_comm_group N] [module R N] [module.free R N]
instance linear_map [module.finite R M] [module.finite R N] : module.free R (M →ₗ[R] N) :=
begin
casesI subsingleton_or_nontrivial R,
{ apply module.free.of_subsingleton' },
classical,
exact of_equiv
(linear_map.to_matrix (module.free.choose_basis R M) (module.free.choose_basis R N)).symm,
end
variables {R}
instance _root_.module.finite.linear_map [module.finite R M] [module.finite R N] :
module.finite R (M →ₗ[R] N) :=
begin
casesI subsingleton_or_nontrivial R,
{ apply_instance },
classical,
have f := (linear_map.to_matrix (choose_basis R M) (choose_basis R N)).symm,
exact module.finite.of_surjective f.to_linear_map (linear_equiv.surjective f),
end
end comm_ring
section integer
variables [add_comm_group M] [module.finite ℤ M] [module.free ℤ M]
variables [add_comm_group N] [module.finite ℤ N] [module.free ℤ N]
instance _root_.module.finite.add_monoid_hom : module.finite ℤ (M →+ N) :=
module.finite.equiv (add_monoid_hom_lequiv_int ℤ).symm
instance add_monoid_hom : module.free ℤ (M →+ N) :=
begin
letI : module.free ℤ (M →ₗ[ℤ] N) := module.free.linear_map _ _ _,
exact module.free.of_equiv (add_monoid_hom_lequiv_int ℤ).symm
end
end integer
section comm_ring
open finite_dimensional
variables [comm_ring R] [strong_rank_condition R]
variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M]
variables [add_comm_group N] [module R N] [module.free R N] [module.finite R N]
/-- The finrank of `M →ₗ[R] N` is `(finrank R M) * (finrank R N)`. -/
--TODO: this should follow from `linear_equiv.finrank_eq`, that is over a field.
lemma finrank_linear_hom : finrank R (M →ₗ[R] N) = (finrank R M) * (finrank R N) :=
begin
classical,
letI := nontrivial_of_invariant_basis_number R,
have h := (linear_map.to_matrix (choose_basis R M) (choose_basis R N)),
let b := (matrix.std_basis _ _ _).map h.symm,
rw [finrank, dim_eq_card_basis b, ← cardinal.mk_fintype, cardinal.mk_to_nat_eq_card, finrank,
finrank, rank_eq_card_choose_basis_index, rank_eq_card_choose_basis_index,
cardinal.mk_to_nat_eq_card, cardinal.mk_to_nat_eq_card, fintype.card_prod, mul_comm]
end
end comm_ring
end module.free
|
5fb4dc67f927965d33e3702de08d53950960ea2e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/measure_theory/integral/vitali_caratheodory.lean | 6b3e57b92046604086b250ab766d130cdda78ccb | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 29,659 | lean | /-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import measure_theory.measure.regular
import topology.semicontinuous
import measure_theory.integral.bochner
import topology.instances.ereal
/-!
# Vitali-Carathéodory theorem
Vitali-Carathéodory theorem asserts the following. Consider an integrable function `f : α → ℝ` on
a space with a regular measure. Then there exists a function `g : α → ereal` such that `f x < g x`
everywhere, `g` is lower semicontinuous, and the integral of `g` is arbitrarily close to that of
`f`. This theorem is proved in this file, as `exists_lt_lower_semicontinuous_integral_lt`.
Symmetrically, there exists `g < f` which is upper semicontinuous, with integral arbitrarily close
to that of `f`. It follows from the previous statement applied to `-f`. It is formalized under
the name `exists_upper_semicontinuous_lt_integral_gt`.
The most classical version of Vitali-Carathéodory theorem only ensures a large inequality
`f x ≤ g x`. For applications to the fundamental theorem of calculus, though, the strict inequality
`f x < g x` is important. Therefore, we prove the stronger version with strict inequalities in this
file. There is a price to pay: we require that the measure is `σ`-finite, which is not necessary for
the classical Vitali-Carathéodory theorem. Since this is satisfied in all applications, this is
not a real problem.
## Sketch of proof
Decomposing `f` as the difference of its positive and negative parts, it suffices to show that a
positive function can be bounded from above by a lower semicontinuous function, and from below
by an upper semicontinuous function, with integrals close to that of `f`.
For the bound from above, write `f` as a series `∑' n, cₙ * indicator (sₙ)` of simple functions.
Then, approximate `sₙ` by a larger open set `uₙ` with measure very close to that of `sₙ` (this is
possible by regularity of the measure), and set `g = ∑' n, cₙ * indicator (uₙ)`. It is
lower semicontinuous as a series of lower semicontinuous functions, and its integral is arbitrarily
close to that of `f`.
For the bound from below, use finitely many terms in the series, and approximate `sₙ` from inside by
a closed set `Fₙ`. Then `∑ n < N, cₙ * indicator (Fₙ)` is bounded from above by `f`, it is
upper semicontinuous as a finite sum of upper semicontinuous functions, and its integral is
arbitrarily close to that of `f`.
The main pain point in the implementation is that one needs to jump between the spaces `ℝ`, `ℝ≥0`,
`ℝ≥0∞` and `ereal` (and be careful that addition is not well behaved on `ereal`), and between
`lintegral` and `integral`.
We first show the bound from above for simple functions and the nonnegative integral
(this is the main nontrivial mathematical point), then deduce it for general nonnegative functions,
first for the nonnegative integral and then for the Bochner integral.
Then we follow the same steps for the lower bound.
Finally, we glue them together to obtain the main statement
`exists_lt_lower_semicontinuous_integral_lt`.
## Related results
Are you looking for a result on approximation by continuous functions (not just semicontinuous)?
See result `measure_theory.Lp.continuous_map_dense`, in the file
`measure_theory.continuous_map_dense`.
## References
[Rudin, *Real and Complex Analysis* (Theorem 2.24)][rudin2006real]
-/
open_locale ennreal nnreal
open measure_theory measure_theory.measure
variables {α : Type*} [topological_space α] [measurable_space α] [borel_space α] (μ : measure α)
[weakly_regular μ]
namespace measure_theory
local infixr ` →ₛ `:25 := simple_func
/-! ### Lower semicontinuous upper bound for nonnegative functions -/
/-- Given a simple function `f` with values in `ℝ≥0`, there exists a lower semicontinuous
function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma simple_func.exists_le_lower_semicontinuous_lintegral_ge (f : α →ₛ ℝ≥0)
{ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, f x ≤ g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing ε,
{ let f := simple_func.piecewise s hs (simple_func.const α c) (simple_func.const α 0),
by_cases h : ∫⁻ x, f x ∂μ = ⊤,
{ refine ⟨λ x, c, λ x, _, lower_semicontinuous_const,
by simp only [ennreal.top_add, le_top, h]⟩,
simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise],
exact set.indicator_le_self _ _ _ },
by_cases hc : c = 0,
{ refine ⟨λ x, 0, _, lower_semicontinuous_const, _⟩,
{ simp only [hc, set.indicator_zero', pi.zero_apply, simple_func.const_zero, implies_true_iff,
eq_self_iff_true, simple_func.coe_zero, set.piecewise_eq_indicator,
simple_func.coe_piecewise, le_zero_iff] },
{ simp only [lintegral_const, zero_mul, zero_le, ennreal.coe_zero] } },
have : μ s < μ s + ε / c,
{ have : (0 : ℝ≥0∞) < ε / c := ennreal.div_pos_iff.2 ⟨ε0, ennreal.coe_ne_top⟩,
simpa using ennreal.add_lt_add_left _ this,
simpa only [hs, hc, lt_top_iff_ne_top, true_and, simple_func.coe_const, function.const_apply,
lintegral_const, ennreal.coe_indicator, set.univ_inter, ennreal.coe_ne_top,
measurable_set.univ, with_top.mul_eq_top_iff, simple_func.const_zero, or_false,
lintegral_indicator, ennreal.coe_eq_zero, ne.def, not_false_iff, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, false_and, restrict_apply] using h },
obtain ⟨u, su, u_open, μu⟩ : ∃ u ⊇ s, is_open u ∧ μ u < μ s + ε / c :=
s.exists_is_open_lt_of_lt _ this,
refine ⟨set.indicator u (λ x, c), λ x, _, u_open.lower_semicontinuous_indicator (zero_le _), _⟩,
{ simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise],
exact set.indicator_le_indicator_of_subset su (λ x, zero_le _) _ },
{ suffices : (c : ℝ≥0∞) * μ u ≤ c * μ s + ε, by
simpa only [hs, u_open.measurable_set, simple_func.coe_const, function.const_apply,
lintegral_const, ennreal.coe_indicator, set.univ_inter, measurable_set.univ,
simple_func.const_zero, lintegral_indicator, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, restrict_apply],
calc (c : ℝ≥0∞) * μ u ≤ c * (μ s + ε / c) : ennreal.mul_le_mul le_rfl μu.le
... = c * μ s + ε :
begin
simp_rw [mul_add],
rw ennreal.mul_div_cancel' _ ennreal.coe_ne_top,
simpa using hc,
end } },
{ rcases h₁ (ennreal.half_pos ε0).ne' with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩,
rcases h₂ (ennreal.half_pos ε0).ne' with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩,
refine ⟨λ x, g₁ x + g₂ x, λ x, add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, _⟩,
simp only [simple_func.coe_add, ennreal.coe_add, pi.add_apply],
rw [lintegral_add_left f₁.measurable.coe_nnreal_ennreal,
lintegral_add_left g₁cont.measurable.coe_nnreal_ennreal],
convert add_le_add g₁int g₂int using 1,
simp only [],
conv_lhs { rw ← ennreal.add_halves ε },
abel }
end
open simple_func (eapprox_diff tsum_eapprox_diff)
/-- Given a measurable function `f` with values in `ℝ≥0`, there exists a lower semicontinuous
function `g ≥ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_le_lower_semicontinuous_lintegral_ge
(f : α → ℝ≥0∞) (hf : measurable f) {ε : ℝ≥0∞} (εpos : ε ≠ 0) :
∃ g : α → ℝ≥0∞, (∀ x, f x ≤ g x) ∧ lower_semicontinuous g ∧ (∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
rcases ennreal.exists_pos_sum_of_countable' εpos ℕ with ⟨δ, δpos, hδ⟩,
have : ∀ n, ∃ g : α → ℝ≥0, (∀ x, simple_func.eapprox_diff f n x ≤ g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, simple_func.eapprox_diff f n x ∂μ + δ n) :=
λ n, simple_func.exists_le_lower_semicontinuous_lintegral_ge μ
(simple_func.eapprox_diff f n) (δpos n).ne',
choose g f_le_g gcont hg using this,
refine ⟨λ x, (∑' n, g n x), λ x, _, _, _⟩,
{ rw ← tsum_eapprox_diff f hf,
exact ennreal.tsum_le_tsum (λ n, ennreal.coe_le_coe.2 (f_le_g n x)) },
{ apply lower_semicontinuous_tsum (λ n, _),
exact ennreal.continuous_coe.comp_lower_semicontinuous (gcont n)
(λ x y hxy, ennreal.coe_le_coe.2 hxy) },
{ calc ∫⁻ x, ∑' (n : ℕ), g n x ∂μ
= ∑' n, ∫⁻ x, g n x ∂μ :
by rw lintegral_tsum (λ n, (gcont n).measurable.coe_nnreal_ennreal)
... ≤ ∑' n, (∫⁻ x, eapprox_diff f n x ∂μ + δ n) : ennreal.tsum_le_tsum hg
... = ∑' n, (∫⁻ x, eapprox_diff f n x ∂μ) + ∑' n, δ n : ennreal.tsum_add
... ≤ ∫⁻ (x : α), f x ∂μ + ε :
begin
refine add_le_add _ hδ.le,
rw [← lintegral_tsum],
{ simp_rw [tsum_eapprox_diff f hf, le_refl] },
{ assume n, exact (simple_func.measurable _).coe_nnreal_ennreal }
end }
end
/-- Given a measurable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a
lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`.
Formulation in terms of `lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_lt_lower_semicontinuous_lintegral_ge [sigma_finite μ]
(f : α → ℝ≥0) (fmeas : measurable f) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
have : ε / 2 ≠ 0 := (ennreal.half_pos ε0).ne',
rcases exists_pos_lintegral_lt_of_sigma_finite μ this with ⟨w, wpos, wmeas, wint⟩,
let f' := λ x, ((f x + w x : ℝ≥0) : ℝ≥0∞),
rcases exists_le_lower_semicontinuous_lintegral_ge μ f' (fmeas.add wmeas).coe_nnreal_ennreal this
with ⟨g, le_g, gcont, gint⟩,
refine ⟨g, λ x, _, gcont, _⟩,
{ calc (f x : ℝ≥0∞) < f' x : by simpa [← ennreal.coe_lt_coe] using add_lt_add_left (wpos x) (f x)
... ≤ g x : le_g x },
{ calc ∫⁻ (x : α), g x ∂μ
≤ ∫⁻ (x : α), f x + w x ∂μ + ε / 2 : gint
... = ∫⁻ (x : α), f x ∂ μ + ∫⁻ (x : α), w x ∂ μ + (ε / 2) :
by rw lintegral_add_right _ wmeas.coe_nnreal_ennreal
... ≤ ∫⁻ (x : α), f x ∂ μ + ε / 2 + ε / 2 :
add_le_add_right (add_le_add_left wint.le _) _
... = ∫⁻ (x : α), f x ∂μ + ε : by rw [add_assoc, ennreal.add_halves] },
end
/-- Given an almost everywhere measurable function `f` with values in `ℝ≥0` in a sigma-finite space,
there exists a lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`.
Formulation in terms of `lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_lt_lower_semicontinuous_lintegral_ge_of_ae_measurable [sigma_finite μ]
(f : α → ℝ≥0) (fmeas : ae_measurable f μ) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧
(∫⁻ x, g x ∂μ ≤ ∫⁻ x, f x ∂μ + ε) :=
begin
have : ε / 2 ≠ 0 := (ennreal.half_pos ε0).ne',
rcases exists_lt_lower_semicontinuous_lintegral_ge μ (fmeas.mk f) fmeas.measurable_mk this
with ⟨g0, f_lt_g0, g0_cont, g0_int⟩,
rcases exists_measurable_superset_of_null fmeas.ae_eq_mk with ⟨s, hs, smeas, μs⟩,
rcases exists_le_lower_semicontinuous_lintegral_ge μ (s.indicator (λ x, ∞))
(measurable_const.indicator smeas) this
with ⟨g1, le_g1, g1_cont, g1_int⟩,
refine ⟨λ x, g0 x + g1 x, λ x, _, g0_cont.add g1_cont, _⟩,
{ by_cases h : x ∈ s,
{ have := le_g1 x,
simp only [h, set.indicator_of_mem, top_le_iff] at this,
simp [this] },
{ have : f x = fmeas.mk f x,
by { rw set.compl_subset_comm at hs, exact hs h },
rw this,
exact (f_lt_g0 x).trans_le le_self_add } },
{ calc ∫⁻ x, g0 x + g1 x ∂μ = ∫⁻ x, g0 x ∂μ + ∫⁻ x, g1 x ∂μ :
lintegral_add_left g0_cont.measurable _
... ≤ (∫⁻ x, f x ∂μ + ε / 2) + (0 + ε / 2) :
begin
refine add_le_add _ _,
{ convert g0_int using 2,
exact lintegral_congr_ae (fmeas.ae_eq_mk.fun_comp _) },
{ convert g1_int,
simp only [smeas, μs, lintegral_const, set.univ_inter, measurable_set.univ,
lintegral_indicator, mul_zero, restrict_apply] }
end
... = ∫⁻ x, f x ∂μ + ε : by simp only [add_assoc, ennreal.add_halves, zero_add] }
end
variable {μ}
/-- Given an integrable function `f` with values in `ℝ≥0` in a sigma-finite space, there exists a
lower semicontinuous function `g > f` with integral arbitrarily close to that of `f`.
Formulation in terms of `integral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_lt_lower_semicontinuous_integral_gt_nnreal [sigma_finite μ] (f : α → ℝ≥0)
(fint : integrable (λ x, (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ℝ≥0∞, (∀ x, (f x : ℝ≥0∞) < g x) ∧ lower_semicontinuous g ∧ (∀ᵐ x ∂ μ, g x < ⊤)
∧ (integrable (λ x, (g x).to_real) μ) ∧ (∫ x, (g x).to_real ∂μ < ∫ x, f x ∂μ + ε) :=
begin
have fmeas : ae_measurable f μ,
by { convert fint.ae_strongly_measurable.real_to_nnreal.ae_measurable, ext1 x,
simp only [real.to_nnreal_coe] },
lift ε to ℝ≥0 using εpos.le,
obtain ⟨δ, δpos, hδε⟩ : ∃ δ : ℝ≥0, 0 < δ ∧ δ < ε, from exists_between εpos,
have int_f_ne_top : ∫⁻ (a : α), (f a) ∂μ ≠ ∞ :=
(has_finite_integral_iff_of_nnreal.1 fint.has_finite_integral).ne,
rcases exists_lt_lower_semicontinuous_lintegral_ge_of_ae_measurable μ f fmeas
(ennreal.coe_ne_zero.2 δpos.ne')
with ⟨g, f_lt_g, gcont, gint⟩,
have gint_ne : ∫⁻ (x : α), g x ∂μ ≠ ∞ := ne_top_of_le_ne_top (by simpa) gint,
have g_lt_top : ∀ᵐ (x : α) ∂μ, g x < ∞ := ae_lt_top gcont.measurable gint_ne,
have Ig : ∫⁻ (a : α), ennreal.of_real (g a).to_real ∂μ = ∫⁻ (a : α), g a ∂μ,
{ apply lintegral_congr_ae,
filter_upwards [g_lt_top] with _ hx,
simp only [hx.ne, ennreal.of_real_to_real, ne.def, not_false_iff], },
refine ⟨g, f_lt_g, gcont, g_lt_top, _, _⟩,
{ refine ⟨gcont.measurable.ennreal_to_real.ae_measurable.ae_strongly_measurable, _⟩,
simp only [has_finite_integral_iff_norm, real.norm_eq_abs,
abs_of_nonneg ennreal.to_real_nonneg],
convert gint_ne.lt_top using 1 },
{ rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae],
{ calc
ennreal.to_real (∫⁻ (a : α), ennreal.of_real (g a).to_real ∂μ)
= ennreal.to_real (∫⁻ (a : α), g a ∂μ) : by congr' 1
... ≤ ennreal.to_real (∫⁻ (a : α), f a ∂μ + δ) :
begin
apply ennreal.to_real_mono _ gint,
simpa using int_f_ne_top,
end
... = ennreal.to_real (∫⁻ (a : α), f a ∂μ) + δ :
by rw [ennreal.to_real_add int_f_ne_top ennreal.coe_ne_top, ennreal.coe_to_real]
... < ennreal.to_real (∫⁻ (a : α), f a ∂μ) + ε :
add_lt_add_left hδε _
... = (∫⁻ (a : α), ennreal.of_real ↑(f a) ∂μ).to_real + ε :
by simp },
{ apply filter.eventually_of_forall (λ x, _), simp },
{ exact fmeas.coe_nnreal_real.ae_strongly_measurable, },
{ apply filter.eventually_of_forall (λ x, _), simp },
{ apply gcont.measurable.ennreal_to_real.ae_measurable.ae_strongly_measurable } }
end
/-! ### Upper semicontinuous lower bound for nonnegative functions -/
/-- Given a simple function `f` with values in `ℝ≥0`, there exists an upper semicontinuous
function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma simple_func.exists_upper_semicontinuous_le_lintegral_le
(f : α →ₛ ℝ≥0) (int_f : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x ∂μ + ε) :=
begin
induction f using measure_theory.simple_func.induction with c s hs f₁ f₂ H h₁ h₂ generalizing ε,
{ let f := simple_func.piecewise s hs (simple_func.const α c) (simple_func.const α 0),
by_cases hc : c = 0,
{ refine ⟨λ x, 0, _, upper_semicontinuous_const, _⟩,
{ simp only [hc, set.indicator_zero', pi.zero_apply, simple_func.const_zero, implies_true_iff,
eq_self_iff_true, simple_func.coe_zero, set.piecewise_eq_indicator,
simple_func.coe_piecewise, le_zero_iff] },
{ simp only [hc, set.indicator_zero', lintegral_const, zero_mul, pi.zero_apply,
simple_func.const_zero, zero_add, zero_le', simple_func.coe_zero,
set.piecewise_eq_indicator, ennreal.coe_zero, simple_func.coe_piecewise, zero_le] } },
have μs_lt_top : μ s < ∞,
by simpa only [hs, hc, lt_top_iff_ne_top, true_and, simple_func.coe_const, or_false,
lintegral_const, ennreal.coe_indicator, set.univ_inter, ennreal.coe_ne_top, restrict_apply
measurable_set.univ, with_top.mul_eq_top_iff, simple_func.const_zero, function.const_apply,
lintegral_indicator, ennreal.coe_eq_zero, ne.def, not_false_iff, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, false_and] using int_f,
have : (0 : ℝ≥0∞) < ε / c := ennreal.div_pos_iff.2 ⟨ε0, ennreal.coe_ne_top⟩,
obtain ⟨F, Fs, F_closed, μF⟩ : ∃ F ⊆ s, is_closed F ∧ μ s < μ F + ε / c :=
hs.exists_is_closed_lt_add μs_lt_top.ne this.ne',
refine ⟨set.indicator F (λ x, c), λ x, _,
F_closed.upper_semicontinuous_indicator (zero_le _), _⟩,
{ simp only [simple_func.coe_const, simple_func.const_zero, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise],
exact set.indicator_le_indicator_of_subset Fs (λ x, zero_le _) _ },
{ suffices : (c : ℝ≥0∞) * μ s ≤ c * μ F + ε,
by simpa only [hs, F_closed.measurable_set, simple_func.coe_const, function.const_apply,
lintegral_const, ennreal.coe_indicator, set.univ_inter, measurable_set.univ,
simple_func.const_zero, lintegral_indicator, simple_func.coe_zero,
set.piecewise_eq_indicator, simple_func.coe_piecewise, restrict_apply],
calc (c : ℝ≥0∞) * μ s ≤ c * (μ F + ε / c) : ennreal.mul_le_mul le_rfl μF.le
... = c * μ F + ε :
begin
simp_rw [mul_add],
rw ennreal.mul_div_cancel' _ ennreal.coe_ne_top,
simpa using hc,
end } },
{ have A : ∫⁻ (x : α), f₁ x ∂μ + ∫⁻ (x : α), f₂ x ∂μ ≠ ⊤,
by rwa ← lintegral_add_left f₁.measurable.coe_nnreal_ennreal,
rcases h₁ (ennreal.add_ne_top.1 A).1 (ennreal.half_pos ε0).ne'
with ⟨g₁, f₁_le_g₁, g₁cont, g₁int⟩,
rcases h₂ (ennreal.add_ne_top.1 A).2 (ennreal.half_pos ε0).ne'
with ⟨g₂, f₂_le_g₂, g₂cont, g₂int⟩,
refine ⟨λ x, g₁ x + g₂ x, λ x, add_le_add (f₁_le_g₁ x) (f₂_le_g₂ x), g₁cont.add g₂cont, _⟩,
simp only [simple_func.coe_add, ennreal.coe_add, pi.add_apply],
rw [lintegral_add_left f₁.measurable.coe_nnreal_ennreal,
lintegral_add_left g₁cont.measurable.coe_nnreal_ennreal],
convert add_le_add g₁int g₂int using 1,
simp only [],
conv_lhs { rw ← ennreal.add_halves ε },
abel }
end
/-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous
function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`lintegral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_upper_semicontinuous_le_lintegral_le
(f : α → ℝ≥0) (int_f : ∫⁻ x, f x ∂μ ≠ ∞) {ε : ℝ≥0∞} (ε0 : ε ≠ 0) :
∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (∫⁻ x, f x ∂μ ≤ ∫⁻ x, g x ∂μ + ε) :=
begin
obtain ⟨fs, fs_le_f, int_fs⟩ : ∃ (fs : α →ₛ ℝ≥0), (∀ x, fs x ≤ f x) ∧
(∫⁻ x, f x ∂μ ≤ ∫⁻ x, fs x ∂μ + ε/2) :=
begin
have := ennreal.lt_add_right int_f (ennreal.half_pos ε0).ne',
conv_rhs at this { rw lintegral_eq_nnreal (λ x, (f x : ℝ≥0∞)) μ },
erw ennreal.bsupr_add at this; [skip, exact ⟨0, λ x, by simp⟩],
simp only [lt_supr_iff] at this,
rcases this with ⟨fs, fs_le_f, int_fs⟩,
refine ⟨fs, λ x, by simpa only [ennreal.coe_le_coe] using fs_le_f x, _⟩,
convert int_fs.le,
rw ← simple_func.lintegral_eq_lintegral,
refl
end,
have int_fs_lt_top : ∫⁻ x, fs x ∂μ ≠ ∞,
{ apply ne_top_of_le_ne_top int_f (lintegral_mono (λ x, _)),
simpa only [ennreal.coe_le_coe] using fs_le_f x },
obtain ⟨g, g_le_fs, gcont, gint⟩ : ∃ g : α → ℝ≥0,
(∀ x, g x ≤ fs x) ∧ upper_semicontinuous g ∧ (∫⁻ x, fs x ∂μ ≤ ∫⁻ x, g x ∂μ + ε/2) :=
fs.exists_upper_semicontinuous_le_lintegral_le int_fs_lt_top (ennreal.half_pos ε0).ne',
refine ⟨g, λ x, (g_le_fs x).trans (fs_le_f x), gcont, _⟩,
calc ∫⁻ x, f x ∂μ ≤ ∫⁻ x, fs x ∂μ + ε / 2 : int_fs
... ≤ (∫⁻ x, g x ∂μ + ε / 2) + ε / 2 : add_le_add gint le_rfl
... = ∫⁻ x, g x ∂μ + ε : by rw [add_assoc, ennreal.add_halves]
end
/-- Given an integrable function `f` with values in `ℝ≥0`, there exists an upper semicontinuous
function `g ≤ f` with integral arbitrarily close to that of `f`. Formulation in terms of
`integral`.
Auxiliary lemma for Vitali-Carathéodory theorem `exists_lt_lower_semicontinuous_integral_lt`. -/
lemma exists_upper_semicontinuous_le_integral_le (f : α → ℝ≥0)
(fint : integrable (λ x, (f x : ℝ)) μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ℝ≥0, (∀ x, g x ≤ f x) ∧ upper_semicontinuous g ∧ (integrable (λ x, (g x : ℝ)) μ)
∧ (∫ x, (f x : ℝ) ∂μ - ε ≤ ∫ x, g x ∂μ) :=
begin
lift ε to ℝ≥0 using εpos.le,
rw [nnreal.coe_pos, ← ennreal.coe_pos] at εpos,
have If : ∫⁻ x, f x ∂ μ < ∞ := has_finite_integral_iff_of_nnreal.1 fint.has_finite_integral,
rcases exists_upper_semicontinuous_le_lintegral_le f If.ne εpos.ne' with ⟨g, gf, gcont, gint⟩,
have Ig : ∫⁻ x, g x ∂ μ < ∞,
{ apply lt_of_le_of_lt (lintegral_mono (λ x, _)) If,
simpa using gf x },
refine ⟨g, gf, gcont, _, _⟩,
{ refine integrable.mono fint
gcont.measurable.coe_nnreal_real.ae_measurable.ae_strongly_measurable _,
exact filter.eventually_of_forall (λ x, by simp [gf x]) },
{ rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae],
{ rw sub_le_iff_le_add,
convert ennreal.to_real_mono _ gint,
{ simp, },
{ rw ennreal.to_real_add Ig.ne ennreal.coe_ne_top, simp },
{ simpa using Ig.ne } },
{ apply filter.eventually_of_forall, simp },
{ exact gcont.measurable.coe_nnreal_real.ae_measurable.ae_strongly_measurable },
{ apply filter.eventually_of_forall, simp },
{ exact fint.ae_strongly_measurable } }
end
/-! ### Vitali-Carathéodory theorem -/
/-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an
integrable function `g > f` which is lower semicontinuous, with integral arbitrarily close
to that of `f`. This function has to be `ereal`-valued in general. -/
lemma exists_lt_lower_semicontinuous_integral_lt [sigma_finite μ]
(f : α → ℝ) (hf : integrable f μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ereal, (∀ x, (f x : ereal) < g x) ∧ lower_semicontinuous g ∧
(integrable (λ x, ereal.to_real (g x)) μ) ∧ (∀ᵐ x ∂ μ, g x < ⊤) ∧
(∫ x, ereal.to_real (g x) ∂μ < ∫ x, f x ∂μ + ε) :=
begin
let δ : ℝ≥0 := ⟨ε/2, (half_pos εpos).le⟩,
have δpos : 0 < δ := half_pos εpos,
let fp : α → ℝ≥0 := λ x, real.to_nnreal (f x),
have int_fp : integrable (λ x, (fp x : ℝ)) μ := hf.real_to_nnreal,
rcases exists_lt_lower_semicontinuous_integral_gt_nnreal fp int_fp δpos
with ⟨gp, fp_lt_gp, gpcont, gp_lt_top, gp_integrable, gpint⟩,
let fm : α → ℝ≥0 := λ x, real.to_nnreal (-f x),
have int_fm : integrable (λ x, (fm x : ℝ)) μ := hf.neg.real_to_nnreal,
rcases exists_upper_semicontinuous_le_integral_le fm int_fm δpos
with ⟨gm, gm_le_fm, gmcont, gm_integrable, gmint⟩,
let g : α → ereal := λ x, (gp x : ereal) - (gm x),
have ae_g : ∀ᵐ x ∂ μ, (g x).to_real = (gp x : ereal).to_real - (gm x : ereal).to_real,
{ filter_upwards [gp_lt_top] with _ hx,
rw ereal.to_real_sub;
simp [hx.ne], },
refine ⟨g, _, _, _, _, _⟩,
show integrable (λ x, ereal.to_real (g x)) μ,
{ rw integrable_congr ae_g,
convert gp_integrable.sub gm_integrable,
ext x,
simp },
show ∫ (x : α), (g x).to_real ∂μ < ∫ (x : α), f x ∂μ + ε, from calc
∫ (x : α), (g x).to_real ∂μ = ∫ (x : α), ereal.to_real (gp x) - ereal.to_real (gm x) ∂μ :
integral_congr_ae ae_g
... = ∫ (x : α), ereal.to_real (gp x) ∂ μ - ∫ (x : α), gm x ∂μ :
begin
simp only [ereal.to_real_coe_ennreal, ennreal.coe_to_real, coe_coe],
exact integral_sub gp_integrable gm_integrable,
end
... < ∫ (x : α), ↑(fp x) ∂μ + ↑δ - ∫ (x : α), gm x ∂μ :
begin
apply sub_lt_sub_right,
convert gpint,
simp only [ereal.to_real_coe_ennreal],
end
... ≤ ∫ (x : α), ↑(fp x) ∂μ + ↑δ - (∫ (x : α), fm x ∂μ - δ) :
sub_le_sub_left gmint _
... = ∫ (x : α), f x ∂μ + 2 * δ :
by { simp_rw [integral_eq_integral_pos_part_sub_integral_neg_part hf, fp, fm], ring }
... = ∫ (x : α), f x ∂μ + ε :
by { congr' 1, field_simp [δ, mul_comm] },
show ∀ᵐ (x : α) ∂μ, g x < ⊤,
{ filter_upwards [gp_lt_top] with _ hx,
simp [g, ereal.sub_eq_add_neg, lt_top_iff_ne_top, lt_top_iff_ne_top.1 hx], },
show ∀ x, (f x : ereal) < g x,
{ assume x,
rw ereal.coe_real_ereal_eq_coe_to_nnreal_sub_coe_to_nnreal (f x),
refine ereal.sub_lt_sub_of_lt_of_le _ _ _ _,
{ simp only [ereal.coe_ennreal_lt_coe_ennreal_iff, coe_coe], exact (fp_lt_gp x) },
{ simp only [ennreal.coe_le_coe, ereal.coe_ennreal_le_coe_ennreal_iff, coe_coe],
exact (gm_le_fm x) },
{ simp only [ereal.coe_ennreal_ne_bot, ne.def, not_false_iff, coe_coe] },
{ simp only [ereal.coe_nnreal_ne_top, ne.def, not_false_iff, coe_coe] } },
show lower_semicontinuous g,
{ apply lower_semicontinuous.add',
{ exact continuous_coe_ennreal_ereal.comp_lower_semicontinuous gpcont
(λ x y hxy, ereal.coe_ennreal_le_coe_ennreal_iff.2 hxy) },
{ apply ereal.continuous_neg.comp_upper_semicontinuous_antitone _
(λ x y hxy, ereal.neg_le_neg_iff.2 hxy),
dsimp,
apply continuous_coe_ennreal_ereal.comp_upper_semicontinuous _
(λ x y hxy, ereal.coe_ennreal_le_coe_ennreal_iff.2 hxy),
exact ennreal.continuous_coe.comp_upper_semicontinuous gmcont
(λ x y hxy, ennreal.coe_le_coe.2 hxy) },
{ assume x,
exact ereal.continuous_at_add (by simp) (by simp) } }
end
/-- **Vitali-Carathéodory Theorem**: given an integrable real function `f`, there exists an
integrable function `g < f` which is upper semicontinuous, with integral arbitrarily close to that
of `f`. This function has to be `ereal`-valued in general. -/
lemma exists_upper_semicontinuous_lt_integral_gt [sigma_finite μ]
(f : α → ℝ) (hf : integrable f μ) {ε : ℝ} (εpos : 0 < ε) :
∃ g : α → ereal, (∀ x, (g x : ereal) < f x) ∧ upper_semicontinuous g ∧
(integrable (λ x, ereal.to_real (g x)) μ) ∧ (∀ᵐ x ∂μ, ⊥ < g x) ∧
(∫ x, f x ∂μ < ∫ x, ereal.to_real (g x) ∂μ + ε) :=
begin
rcases exists_lt_lower_semicontinuous_integral_lt (λ x, - f x) hf.neg εpos
with ⟨g, g_lt_f, gcont, g_integrable, g_lt_top, gint⟩,
refine ⟨λ x, - g x, _, _, _, _, _⟩,
{ exact λ x, ereal.neg_lt_iff_neg_lt.1 (by simpa only [ereal.coe_neg] using g_lt_f x) },
{ exact ereal.continuous_neg.comp_lower_semicontinuous_antitone gcont
(λ x y hxy, ereal.neg_le_neg_iff.2 hxy) },
{ convert g_integrable.neg,
ext x,
simp },
{ simpa [bot_lt_iff_ne_bot, lt_top_iff_ne_top] using g_lt_top },
{ simp_rw [integral_neg, lt_neg_add_iff_add_lt] at gint,
rw add_comm at gint,
simpa [integral_neg] using gint }
end
end measure_theory
|
377f131acf063a198b685a417fd558c7b60ff24e | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/analysis/seminorm.lean | 1609cd254ca01801e6a9268bd471ccdd04194e5e | [
"Apache-2.0"
] | permissive | jumpy4/mathlib | d3829e75173012833e9f15ac16e481e17596de0f | af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13 | refs/heads/master | 1,693,508,842,818 | 1,636,203,271,000 | 1,636,203,271,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,077 | lean | /-
Copyright (c) 2019 Jean Lo. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jean Lo, Bhavik Mehta, Yaël Dillies
-/
import analysis.convex.basic
import analysis.normed_space.ordered
import data.real.pointwise
import data.set.intervals
/-!
# Seminorms and Local Convexity
This file defines absorbent sets, balanced sets, seminorms and the Minkowski functional.
An absorbent set is one that "surrounds" the origin. The idea is made precise by requiring that any
point belongs to all large enough scalings of the set. This is the vector world analog of a
topological neighborhood of the origin.
A balanced set is one that is everywhere around the origin. This means that `a • s ⊆ s` for all `a`
of norm less than `1`.
A seminorm is a function to the reals which is positive-semidefinite, absolutely homogeneous, and
subadditive. They are closely related to convex sets and a topological vector space is locally
convex if and only if its topology is induced by a family of seminorms.
The Minkowski functional of a set `s` is the function which associates each point to how much you
need to scale `s` for `x` to be inside it. When `s` is symmetric, convex and absorbent, its gauge is
a seminorm. Reciprocally, any seminorm arises as the gauge of some set, namely its unit ball. This
induces the equivalence of seminorms and locally convex topological vector spaces.
## Main declarations
For a vector space over a normed field:
* `absorbent`: A set `s` is absorbent if every point eventually belongs to all large scalings of
`s`.
* `balanced`: A set `s` is balanced if `a • s ⊆ s` for all `a` of norm less than `1`.
* `seminorm`: A function to the reals that is positive-semidefinite, absolutely homogeneous, and
subadditive.
* `gauge`: Aka Minkowksi functional. `gauge s x` is the least (actually, an infimum) `r` such
that `x ∈ r • s`.
* `gauge_seminorm`: The Minkowski functional as a seminorm, when `s` is symmetric, convex and
absorbent.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
## TODO
Define and show equivalence of two notions of local convexity for a
topological vector space over ℝ or ℂ: that it has a local base of
balanced convex absorbent sets, and that it carries the initial
topology induced by a family of seminorms.
Prove the properties of balanced and absorbent sets of a real vector space.
## Tags
absorbent, balanced, seminorm, Minkowski functional, gauge, locally convex, LCTVS
-/
/-!
### Set Properties
Absorbent and balanced sets in a vector space over a normed field.
-/
open normed_field set
open_locale pointwise topological_space
variables {𝕜 E : Type*}
section normed_field
variables (𝕜) [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
/-- A set `A` absorbs another set `B` if `B` is contained in all scalings of
`A` by elements of sufficiently large norms. -/
def absorbs (A B : set E) := ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → B ⊆ a • A
/-- A set is absorbent if it absorbs every singleton. -/
def absorbent (A : set E) := ∀ x, ∃ r, 0 < r ∧ ∀ a : 𝕜, r ≤ ∥a∥ → x ∈ a • A
/-- A set `A` is balanced if `a • A` is contained in `A` whenever `a`
has norm less than or equal to one. -/
def balanced (A : set E) := ∀ a : 𝕜, ∥a∥ ≤ 1 → a • A ⊆ A
variables {𝕜} (a : 𝕜) {A B : set E}
/-- A balanced set absorbs itself. -/
lemma balanced.absorbs_self (hA : balanced 𝕜 A) : absorbs 𝕜 A A :=
begin
use [1, zero_lt_one],
intros a ha x hx,
rw mem_smul_set_iff_inv_smul_mem₀,
{ apply hA a⁻¹,
{ rw norm_inv, exact inv_le_one ha },
{ rw mem_smul_set, use [x, hx] }},
{ rw ←norm_pos_iff, calc 0 < 1 : zero_lt_one ... ≤ ∥a∥ : ha, }
end
lemma balanced.univ : balanced 𝕜 (univ : set E) :=
λ a ha, subset_univ _
lemma balanced.union {A₁ A₂ : set E} (hA₁ : balanced 𝕜 A₁) (hA₂ : balanced 𝕜 A₂) :
balanced 𝕜 (A₁ ∪ A₂) :=
begin
intros a ha t ht,
rw [smul_set_union] at ht,
exact ht.imp (λ x, hA₁ _ ha x) (λ x, hA₂ _ ha x),
end
lemma balanced.inter {A₁ A₂ : set E} (hA₁ : balanced 𝕜 A₁) (hA₂ : balanced 𝕜 A₂) :
balanced 𝕜 (A₁ ∩ A₂) :=
begin
rintro a ha _ ⟨x, ⟨hx₁, hx₂⟩, rfl⟩,
exact ⟨hA₁ _ ha ⟨_, hx₁, rfl⟩, hA₂ _ ha ⟨_, hx₂, rfl⟩⟩,
end
lemma balanced.add {A₁ A₂ : set E} (hA₁ : balanced 𝕜 A₁) (hA₂ : balanced 𝕜 A₂) :
balanced 𝕜 (A₁ + A₂) :=
begin
rintro a ha _ ⟨_, ⟨x, y, hx, hy, rfl⟩, rfl⟩,
rw smul_add,
exact ⟨_, _, hA₁ _ ha ⟨_, hx, rfl⟩, hA₂ _ ha ⟨_, hy, rfl⟩, rfl⟩,
end
lemma balanced.smul (hA : balanced 𝕜 A) : balanced 𝕜 (a • A) :=
begin
rintro b hb _ ⟨_, ⟨x, hx, rfl⟩, rfl⟩,
exact ⟨b • x, hA _ hb ⟨_, hx, rfl⟩, smul_comm _ _ _⟩,
end
lemma balanced.subset_smul (hA : balanced 𝕜 A) {a : 𝕜} (ha : 1 ≤ ∥a∥) : A ⊆ a • A :=
begin
refine (subset_set_smul_iff₀ _).2 (hA (a⁻¹) _),
{ rintro rfl,
rw norm_zero at ha,
exact zero_lt_one.not_le ha },
{ rw norm_inv,
exact inv_le_one ha }
end
lemma balanced.smul_eq (hA : balanced 𝕜 A) {a : 𝕜} (ha : ∥a∥ = 1) : a • A = A :=
(hA _ ha.le).antisymm $ hA.subset_smul ha.ge
lemma absorbent.subset (hA : absorbent 𝕜 A) (hAB : A ⊆ B) : absorbent 𝕜 B :=
begin
rintro x,
obtain ⟨r, hr, hx⟩ := hA x,
refine ⟨r, hr, λ a ha, (set_smul_subset_set_smul_iff₀ _).2 hAB $ hx a ha⟩,
rintro rfl,
rw norm_zero at ha,
exact hr.not_le ha,
end
lemma absorbent_iff_forall_absorbs_singleton : absorbent 𝕜 A ↔ ∀ x, absorbs 𝕜 A {x} :=
by simp [absorbs, absorbent]
lemma absorbent_iff_nonneg_lt : absorbent 𝕜 A ↔ ∀ x, ∃ r, 0 ≤ r ∧ ∀ a : 𝕜, r < ∥a∥ → x ∈ a • A :=
begin
split,
{ rintro hA x,
obtain ⟨r, hr, hx⟩ := hA x,
exact ⟨r, hr.le, λ a ha, hx a ha.le⟩ },
{ rintro hA x,
obtain ⟨r, hr, hx⟩ := hA x,
exact ⟨r + 1, add_pos_of_nonneg_of_pos hr zero_lt_one,
λ a ha, hx a ((lt_add_of_pos_right r zero_lt_one).trans_le ha)⟩ }
end
/-!
Properties of balanced and absorbent sets in a topological vector space:
-/
variables [topological_space E] [has_continuous_smul 𝕜 E]
/-- Every neighbourhood of the origin is absorbent. -/
lemma absorbent_nhds_zero (hA : A ∈ 𝓝 (0 : E)) : absorbent 𝕜 A :=
begin
intro x,
rcases mem_nhds_iff.mp hA with ⟨w, hw₁, hw₂, hw₃⟩,
have hc : continuous (λ t : 𝕜, t • x), from continuous_id.smul continuous_const,
rcases metric.is_open_iff.mp (hw₂.preimage hc) 0 (by rwa [mem_preimage, zero_smul])
with ⟨r, hr₁, hr₂⟩,
have hr₃, from inv_pos.mpr (half_pos hr₁),
use [(r/2)⁻¹, hr₃],
intros a ha₁,
have ha₂ : 0 < ∥a∥ := hr₃.trans_le ha₁,
have ha₃ : a ⁻¹ • x ∈ w,
{ apply hr₂,
rw [metric.mem_ball, dist_zero_right, norm_inv],
calc ∥a∥⁻¹ ≤ r/2 : (inv_le (half_pos hr₁) ha₂).mp ha₁
... < r : half_lt_self hr₁ },
rw [mem_smul_set_iff_inv_smul_mem₀ (norm_pos_iff.mp ha₂)],
exact hw₁ ha₃,
end
/-- The union of `{0}` with the interior of a balanced set
is balanced. -/
lemma balanced_zero_union_interior (hA : balanced 𝕜 A) :
balanced 𝕜 ({(0 : E)} ∪ interior A) :=
begin
intros a ha, by_cases a = 0,
{ rw [h, zero_smul_set],
exacts [subset_union_left _ _, ⟨0, or.inl rfl⟩] },
{ rw [←image_smul, image_union],
apply union_subset_union,
{ rw [image_singleton, smul_zero] },
{ calc a • interior A ⊆ interior (a • A) : (is_open_map_smul₀ h).image_interior_subset A
... ⊆ interior A : interior_mono (hA _ ha) } }
end
/-- The interior of a balanced set is balanced if it contains the origin. -/
lemma balanced.interior (hA : balanced 𝕜 A) (h : (0 : E) ∈ interior A) :
balanced 𝕜 (interior A) :=
begin
rw ←singleton_subset_iff at h,
rw [←union_eq_self_of_subset_left h],
exact balanced_zero_union_interior hA,
end
/-- The closure of a balanced set is balanced. -/
lemma balanced.closure (hA : balanced 𝕜 A) : balanced 𝕜 (closure A) :=
assume a ha,
calc _ ⊆ closure (a • A) : image_closure_subset_closure_image (continuous_id.const_smul _)
... ⊆ _ : closure_mono (hA _ ha)
end normed_field
/-!
### Seminorms
-/
/-- A seminorm on a vector space over a normed field is a function to
the reals that is positive semidefinite, positive homogeneous, and
subadditive. -/
structure seminorm (𝕜 : Type*) (E : Type*)
[normed_field 𝕜] [add_comm_group E] [module 𝕜 E] :=
(to_fun : E → ℝ)
(smul' : ∀ (a : 𝕜) (x : E), to_fun (a • x) = ∥a∥ * to_fun x)
(triangle' : ∀ x y : E, to_fun (x + y) ≤ to_fun x + to_fun y)
namespace seminorm
section normed_field
variables [normed_field 𝕜] [add_comm_group E] [module 𝕜 E]
instance : inhabited (seminorm 𝕜 E) :=
⟨{ to_fun := λ _, 0,
smul' := λ _ _, (mul_zero _).symm,
triangle' := λ x y, by rw add_zero }⟩
instance : has_coe_to_fun (seminorm 𝕜 E) (λ _, E → ℝ) := ⟨λ p, p.to_fun⟩
@[ext] lemma ext {p q : seminorm 𝕜 E} (h : (p : E → ℝ) = q) : p = q :=
begin
cases p,
cases q,
have : p_to_fun = q_to_fun := h,
simp_rw this,
end
variables (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
protected lemma smul : p (c • x) = ∥c∥ * p x := p.smul' _ _
protected lemma triangle : p (x + y) ≤ p x + p y := p.triangle' _ _
protected lemma sub_le : p (x - y) ≤ p x + p y :=
calc
p (x - y)
= p (x + -y) : by rw sub_eq_add_neg
... ≤ p x + p (-y) : p.triangle x (-y)
... = p x + p y : by rw [←neg_one_smul 𝕜 y, p.smul, norm_neg, norm_one, one_mul]
@[simp]
protected lemma zero : p 0 = 0 :=
calc p 0 = p ((0 : 𝕜) • 0) : by rw zero_smul
... = 0 : by rw [p.smul, norm_zero, zero_mul]
@[simp]
protected lemma neg : p (-x) = p x :=
calc p (-x) = p ((-1 : 𝕜) • x) : by rw neg_one_smul
... = p x : by rw [p.smul, norm_neg, norm_one, one_mul]
lemma nonneg : 0 ≤ p x :=
have h: 0 ≤ 2 * p x, from
calc 0 = p (x + (- x)) : by rw [add_neg_self, p.zero]
... ≤ p x + p (-x) : p.triangle _ _
... = 2 * p x : by rw [p.neg, two_mul],
nonneg_of_mul_nonneg_left h zero_lt_two
lemma sub_rev : p (x - y) = p (y - x) :=
by rw [←neg_sub, p.neg]
/-- The ball of radius `r` at `x` with respect to seminorm `p`
is the set of elements `y` with `p (y - x) < `r`. -/
def ball (p : seminorm 𝕜 E) (x : E) (r : ℝ) := { y : E | p (y - x) < r }
lemma mem_ball : y ∈ ball p x r ↔ p (y - x) < r :=
iff.rfl
lemma mem_ball_zero : y ∈ ball p 0 r ↔ p y < r :=
by rw [mem_ball, sub_zero]
lemma ball_zero_eq : ball p 0 r = { y : E | p y < r } :=
set.ext $ λ x,by { rw mem_ball_zero, exact iff.rfl }
/-- Seminorm-balls at the origin are balanced. -/
lemma balanced_ball_zero : balanced 𝕜 (ball p 0 r) :=
begin
rintro a ha x ⟨y, hy, hx⟩,
rw [mem_ball_zero, ←hx, p.smul],
calc _ ≤ p y : mul_le_of_le_one_left (p.nonneg _) ha
... < r : by rwa mem_ball_zero at hy,
end
/-- Seminorm-balls at the origin are absorbent. -/
lemma absorbent_ball_zero {r : ℝ} (hr : 0 < r) : absorbent 𝕜 (ball p (0 : E) r) :=
begin
rw absorbent_iff_nonneg_lt,
rintro x,
have hxr : 0 ≤ p x/r := div_nonneg (p.nonneg _) hr.le,
refine ⟨p x/r, hxr, λ a ha, _⟩,
have ha₀ : 0 < ∥a∥ := hxr.trans_lt ha,
refine ⟨a⁻¹ • x, _, smul_inv_smul₀ (norm_pos_iff.1 ha₀) x⟩,
rwa [mem_ball_zero, p.smul, norm_inv, inv_mul_lt_iff ha₀, ←div_lt_iff hr],
end
/-- Seminorm-balls containing the origin are absorbent. -/
lemma absorbent_ball (hpr : p x < r) : absorbent 𝕜 (ball p x r) :=
begin
refine (p.absorbent_ball_zero $ sub_pos.2 hpr).subset (λ y hy, _),
rw p.mem_ball_zero at hy,
exact (p.mem_ball _ _ _).2 ((p.sub_le _ _).trans_lt $ add_lt_of_lt_sub_right hy),
end
lemma symmetric_ball_zero {x : E} (hx : x ∈ ball p 0 r) : -x ∈ ball p 0 r :=
balanced_ball_zero p r (-1) (by rw [norm_neg, norm_one]) ⟨x, hx, by rw [neg_smul, one_smul]⟩
end normed_field
section normed_linear_ordered_field
variables [normed_linear_ordered_field 𝕜] [add_comm_group E] [module ℝ E] [semi_normed_space ℝ 𝕜]
[module 𝕜 E] [is_scalar_tower ℝ 𝕜 E] (p : seminorm 𝕜 E) (c : 𝕜) (x y : E) (r : ℝ)
/-- Seminorm-balls are convex. -/
lemma convex_ball : convex ℝ (ball p x r) :=
begin
rw convex_iff_forall_pos,
rintro y z hy hz a b ha hb hab,
rw mem_ball at ⊢ hy hz,
calc p (a • y + b • z - x)
= p (a • (y - x) + b • (z - x))
: by rw [smul_sub, smul_sub, sub_add_comm, convex.combo_self hab x]
... ≤ p (a • (y - x)) + p (b • (z - x)) : p.triangle _ _
... = ∥a • (1 : 𝕜)∥ * p (y - x) + ∥b • (1 : 𝕜)∥ * p (z - x)
: by rw [←p.smul, ←p.smul, smul_one_smul, smul_one_smul]
... = a * p (y - x) + b * p (z - x)
: by rw [norm_smul, norm_smul, norm_one, mul_one, mul_one, real.norm_eq_abs,
real.norm_eq_abs, abs_of_pos ha, abs_of_pos hb]
... < a * r + b * r
: add_lt_add (mul_lt_mul_of_pos_left hy ha) (mul_lt_mul_of_pos_left hz hb)
... = r
: by rw [←smul_eq_mul, ←smul_eq_mul, convex.combo_self hab _]
end
end normed_linear_ordered_field
-- TODO: convexity and absorbent/balanced sets in vector spaces over ℝ
end seminorm
section gauge
noncomputable theory
variables [add_comm_group E] [module ℝ E]
/--The Minkowski functional. Given a set `s` in a real vector space, `gauge s` is the functional
which sends `x : E` to the smallest `r : ℝ` such that `x` is in `s` scaled by `r`. -/
def gauge (s : set E) (x : E) : ℝ := Inf {r : ℝ | 0 < r ∧ x ∈ r • s}
variables {s : set E} {x : E}
lemma gauge_def : gauge s x = Inf {r ∈ set.Ioi 0 | x ∈ r • s} := rfl
/-- An alternative definition of the gauge using scalar multiplication on the element rather than on
the set. -/
lemma gauge_def' : gauge s x = Inf {r ∈ set.Ioi 0 | r⁻¹ • x ∈ s} :=
begin
unfold gauge,
congr' 1,
ext r,
exact and_congr_right (λ hr, mem_smul_set_iff_inv_smul_mem₀ hr.ne' _ _),
end
private lemma gauge_set_bdd_below : bdd_below {r : ℝ | 0 < r ∧ x ∈ r • s} := ⟨0, λ r hr, hr.1.le⟩
/-- If the given subset is `absorbent` then the set we take an infimum over in `gauge` is nonempty,
which is useful for proving many properties about the gauge. -/
lemma absorbent.gauge_set_nonempty (absorbs : absorbent ℝ s) :
{r : ℝ | 0 < r ∧ x ∈ r • s}.nonempty :=
let ⟨r, hr₁, hr₂⟩ := absorbs x in ⟨r, hr₁, hr₂ r (real.norm_of_nonneg hr₁.le).ge⟩
lemma exists_lt_of_gauge_lt (absorbs : absorbent ℝ s) {x : E} {a : ℝ} (h : gauge s x < a) :
∃ b, 0 < b ∧ b < a ∧ x ∈ b • s :=
begin
obtain ⟨b, ⟨hb, hx⟩, hba⟩ := exists_lt_of_cInf_lt absorbs.gauge_set_nonempty h,
exact ⟨b, hb, hba, hx⟩,
end
/-- The gauge evaluated at `0` is always zero (mathematically this requires `0` to be in the set `s`
but, the real infimum of the empty set in Lean being defined as `0`, it holds unconditionally). -/
@[simp] lemma gauge_zero : gauge s 0 = 0 :=
begin
rw gauge_def',
by_cases (0 : E) ∈ s,
{ simp only [smul_zero, sep_true, h, cInf_Ioi] },
{ simp only [smul_zero, sep_false, h, real.Inf_empty] }
end
/-- The gauge is always nonnegative. -/
lemma gauge_nonneg (x : E) : 0 ≤ gauge s x := real.Inf_nonneg _ $ λ x hx, hx.1.le
lemma gauge_neg (symmetric : ∀ x ∈ s, -x ∈ s) (x : E) : gauge s (-x) = gauge s x :=
begin
have : ∀ x, -x ∈ s ↔ x ∈ s := λ x, ⟨λ h, by simpa using symmetric _ h, symmetric x⟩,
rw [gauge_def', gauge_def'],
simp_rw [smul_neg, this],
end
lemma gauge_le_of_mem {r : ℝ} (hr : 0 ≤ r) {x : E} (hx : x ∈ r • s) : gauge s x ≤ r :=
begin
obtain rfl | hr' := hr.eq_or_lt,
{ rw [mem_singleton_iff.1 (zero_smul_subset _ hx), gauge_zero] },
{ exact cInf_le gauge_set_bdd_below ⟨hr', hx⟩ }
end
lemma gauge_le_one_eq' (hs : convex ℝ s) (zero_mem : (0 : E) ∈ s) (absorbs : absorbent ℝ s) :
{x | gauge s x ≤ 1} = ⋂ (r : ℝ) (H : 1 < r), r • s :=
begin
ext,
simp_rw [set.mem_Inter, set.mem_set_of_eq],
split,
{ intros h r hr,
have hr' := zero_lt_one.trans hr,
rw mem_smul_set_iff_inv_smul_mem₀ hr'.ne',
obtain ⟨δ, δ_pos, hδr, hδ⟩ := exists_lt_of_gauge_lt absorbs (h.trans_lt hr),
suffices : (r⁻¹ * δ) • δ⁻¹ • x ∈ s,
{ rwa [smul_smul, mul_inv_cancel_right₀ δ_pos.ne'] at this },
rw mem_smul_set_iff_inv_smul_mem₀ δ_pos.ne' at hδ,
refine hs.smul_mem_of_zero_mem zero_mem hδ
⟨mul_nonneg (inv_nonneg.2 hr'.le) δ_pos.le, _⟩,
rw [inv_mul_le_iff hr', mul_one],
exact hδr.le },
{ refine λ h, le_of_forall_pos_lt_add (λ ε hε, _),
have hε' := (lt_add_iff_pos_right 1).2 (half_pos hε),
exact (gauge_le_of_mem (zero_le_one.trans hε'.le) $ h _ hε').trans_lt
(add_lt_add_left (half_lt_self hε) _) }
end
lemma gauge_le_one_eq (hs : convex ℝ s) (zero_mem : (0 : E) ∈ s) (absorbs : absorbent ℝ s) :
{x | gauge s x ≤ 1} = ⋂ (r ∈ set.Ioi (1 : ℝ)), r • s :=
gauge_le_one_eq' hs zero_mem absorbs
lemma gauge_lt_one_eq' (absorbs : absorbent ℝ s) :
{x | gauge s x < 1} = ⋃ (r : ℝ) (H : 0 < r) (H : r < 1), r • s :=
begin
ext,
simp_rw [set.mem_set_of_eq, set.mem_Union],
split,
{ intro h,
obtain ⟨r, hr₀, hr₁, hx⟩ := exists_lt_of_gauge_lt absorbs h,
exact ⟨r, hr₀, hr₁, hx⟩ },
{ exact λ ⟨r, hr₀, hr₁, hx⟩, (gauge_le_of_mem hr₀.le hx).trans_lt hr₁ }
end
lemma gauge_lt_one_eq (absorbs : absorbent ℝ s) :
{x | gauge s x < 1} = ⋃ (r ∈ set.Ioo 0 (1 : ℝ)), r • s :=
begin
ext,
simp_rw [set.mem_set_of_eq, set.mem_Union],
split,
{ intro h,
obtain ⟨r, hr₀, hr₁, hx⟩ := exists_lt_of_gauge_lt absorbs h,
exact ⟨r, ⟨hr₀, hr₁⟩, hx⟩ },
{ exact λ ⟨r, ⟨hr₀, hr₁⟩, hx⟩, (gauge_le_of_mem hr₀.le hx).trans_lt hr₁ }
end
lemma gauge_lt_one_subset_self (hs : convex ℝ s) (h₀ : (0 : E) ∈ s) (absorbs : absorbent ℝ s) :
{x | gauge s x < 1} ⊆ s :=
begin
rw gauge_lt_one_eq absorbs,
apply set.bUnion_subset,
rintro r hr _ ⟨y, hy, rfl⟩,
exact hs.smul_mem_of_zero_mem h₀ hy (Ioo_subset_Icc_self hr),
end
lemma gauge_le_one_of_mem {x : E} (hx : x ∈ s) : gauge s x ≤ 1 :=
gauge_le_of_mem zero_le_one $ by rwa one_smul
lemma self_subset_gauge_le_one : s ⊆ {x | gauge s x ≤ 1} := λ x, gauge_le_one_of_mem
lemma convex.gauge_le_one (hs : convex ℝ s) (h₀ : (0 : E) ∈ s) (absorbs : absorbent ℝ s) :
convex ℝ {x | gauge s x ≤ 1} :=
begin
rw gauge_le_one_eq hs h₀ absorbs,
exact convex_Inter (λ i, convex_Inter (λ (hi : _ < _), hs.smul _)),
end
section topological_space
variables [topological_space E] [has_continuous_smul ℝ E]
lemma interior_subset_gauge_lt_one (s : set E) : interior s ⊆ {x | gauge s x < 1} :=
begin
intros x hx,
let f : ℝ → E := λ t, t • x,
have hf : continuous f,
{ continuity },
let s' := f ⁻¹' (interior s),
have hs' : is_open s' := hf.is_open_preimage _ is_open_interior,
have one_mem : (1 : ℝ) ∈ s',
{ simpa only [s', f, set.mem_preimage, one_smul] },
obtain ⟨ε, hε₀, hε⟩ := (metric.nhds_basis_closed_ball.1 _).1
(is_open_iff_mem_nhds.1 hs' 1 one_mem),
rw real.closed_ball_eq at hε,
have hε₁ : 0 < 1 + ε := hε₀.trans (lt_one_add ε),
have : (1 + ε)⁻¹ < 1,
{ rw inv_lt_one_iff,
right,
linarith },
refine (gauge_le_of_mem (inv_nonneg.2 hε₁.le) _).trans_lt this,
rw mem_inv_smul_set_iff₀ hε₁.ne',
exact interior_subset
(hε ⟨(sub_le_self _ hε₀.le).trans ((le_add_iff_nonneg_right _).2 hε₀.le), le_rfl⟩),
end
lemma gauge_lt_one_eq_self_of_open {s : set E} (hs : convex ℝ s) (zero_mem : (0 : E) ∈ s)
(hs₂ : is_open s) :
{x | gauge s x < 1} = s :=
begin
apply (gauge_lt_one_subset_self hs ‹_› $ absorbent_nhds_zero $ hs₂.mem_nhds zero_mem).antisymm,
convert interior_subset_gauge_lt_one s,
exact hs₂.interior_eq.symm,
end
lemma gauge_lt_one_of_mem_of_open {s : set E} (hs : convex ℝ s) (zero_mem : (0 : E) ∈ s)
(hs₂ : is_open s) (x : E) (hx : x ∈ s) :
gauge s x < 1 :=
by rwa ←gauge_lt_one_eq_self_of_open hs zero_mem hs₂ at hx
lemma one_le_gauge_of_not_mem {s : set E} (hs : convex ℝ s) (zero_mem : (0 : E) ∈ s)
(hs₂ : is_open s) {x : E} (hx : x ∉ s) :
1 ≤ gauge s x :=
begin
rw ←gauge_lt_one_eq_self_of_open hs zero_mem hs₂ at hx,
exact le_of_not_lt hx
end
end topological_space
variables {α : Type*} [linear_ordered_field α] [mul_action_with_zero α ℝ] [ordered_smul α ℝ]
lemma gauge_smul_of_nonneg [mul_action_with_zero α E] [is_scalar_tower α ℝ (set E)] {s : set E}
{r : α} (hr : 0 ≤ r) (x : E) :
gauge s (r • x) = r • gauge s x :=
begin
obtain rfl | hr' := hr.eq_or_lt,
{ rw [zero_smul, gauge_zero, zero_smul] },
rw [gauge_def', gauge_def', ←real.Inf_smul_of_nonneg hr],
congr' 1,
ext β,
simp_rw [set.mem_smul_set, set.mem_sep_eq],
split,
{ rintro ⟨hβ, hx⟩,
simp_rw [mem_Ioi] at ⊢ hβ,
have := smul_pos (inv_pos.2 hr') hβ,
refine ⟨r⁻¹ • β, ⟨this, _⟩, smul_inv_smul₀ hr'.ne' _⟩,
rw ←mem_smul_set_iff_inv_smul_mem₀ at ⊢ hx,
rwa [smul_assoc, mem_smul_set_iff_inv_smul_mem₀ (inv_ne_zero hr'.ne'), inv_inv₀],
{ exact this.ne' },
{ exact hβ.ne' } },
{ rintro ⟨β, ⟨hβ, hx⟩, rfl⟩,
rw mem_Ioi at ⊢ hβ,
have := smul_pos hr' hβ,
refine ⟨this, _⟩,
rw ←mem_smul_set_iff_inv_smul_mem₀ at ⊢ hx,
rw smul_assoc,
exact smul_mem_smul_set hx,
{ exact this.ne' },
{ exact hβ.ne'} }
end
/-- In textbooks, this is the homogeneity of the Minkowksi functional. -/
lemma gauge_smul [module α E] [is_scalar_tower α ℝ (set E)] {s : set E}
(symmetric : ∀ x ∈ s, -x ∈ s) (r : α) (x : E) :
gauge s (r • x) = abs r • gauge s x :=
begin
rw ←gauge_smul_of_nonneg (abs_nonneg r),
obtain h | h := abs_choice r,
{ rw h },
{ rw [h, neg_smul, gauge_neg symmetric] },
{ apply_instance }
end
lemma gauge_add_le (hs : convex ℝ s) (absorbs : absorbent ℝ s) (x y : E) :
gauge s (x + y) ≤ gauge s x + gauge s y :=
begin
refine le_of_forall_pos_lt_add (λ ε hε, _),
obtain ⟨a, ha, ha', hx⟩ := exists_lt_of_gauge_lt absorbs
(lt_add_of_pos_right (gauge s x) (half_pos hε)),
obtain ⟨b, hb, hb', hy⟩ := exists_lt_of_gauge_lt absorbs
(lt_add_of_pos_right (gauge s y) (half_pos hε)),
rw mem_smul_set_iff_inv_smul_mem₀ ha.ne' at hx,
rw mem_smul_set_iff_inv_smul_mem₀ hb.ne' at hy,
suffices : gauge s (x + y) ≤ a + b,
{ linarith },
have hab : 0 < a + b := add_pos ha hb,
apply gauge_le_of_mem hab.le,
have := convex_iff_div.1 hs hx hy ha.le hb.le hab,
rwa [smul_smul, smul_smul, mul_comm_div', mul_comm_div', ←mul_div_assoc, ←mul_div_assoc,
mul_inv_cancel ha.ne', mul_inv_cancel hb.ne', ←smul_add, one_div,
←mem_smul_set_iff_inv_smul_mem₀ hab.ne'] at this,
end
/-- `gauge s` as a seminorm when `s` is symmetric, convex and absorbent. -/
@[simps] def gauge_seminorm (symmetric : ∀ x ∈ s, -x ∈ s) (hs : convex ℝ s) (hs' : absorbent ℝ s) :
seminorm ℝ E :=
{ to_fun := gauge s,
smul' := λ r x, by rw [gauge_smul symmetric, real.norm_eq_abs, smul_eq_mul];
apply_instance,
triangle' := gauge_add_le hs hs' }
/-- Any seminorm arises a the gauge of its unit ball. -/
lemma seminorm.gauge_ball (p : seminorm ℝ E) : gauge (p.ball 0 1) = p :=
begin
ext,
obtain hp | hp := {r : ℝ | 0 < r ∧ x ∈ r • p.ball 0 1}.eq_empty_or_nonempty,
{ rw [gauge, hp, real.Inf_empty],
by_contra,
have hpx : 0 < p x := (p.nonneg x).lt_of_ne h,
have hpx₂ : 0 < 2 * p x := mul_pos zero_lt_two hpx,
refine hp.subset ⟨hpx₂, (2 * p x)⁻¹ • x, _, smul_inv_smul₀ hpx₂.ne' _⟩,
rw [p.mem_ball_zero, p.smul, real.norm_eq_abs, abs_of_pos (inv_pos.2 hpx₂), inv_mul_lt_iff hpx₂,
mul_one],
exact lt_mul_of_one_lt_left hpx one_lt_two },
refine is_glb.cInf_eq ⟨λ r, _, λ r hr, le_of_forall_pos_le_add $ λ ε hε, _⟩ hp,
{ rintro ⟨hr, y, hy, rfl⟩,
rw p.mem_ball_zero at hy,
rw [p.smul, real.norm_eq_abs, abs_of_pos hr],
exact mul_le_of_le_one_right hr.le hy.le },
{ have hpε : 0 < p x + ε := add_pos_of_nonneg_of_pos (p.nonneg _) hε,
refine hr ⟨hpε, (p x + ε)⁻¹ • x, _, smul_inv_smul₀ hpε.ne' _⟩,
rw [p.mem_ball_zero, p.smul, real.norm_eq_abs, abs_of_pos (inv_pos.2 hpε), inv_mul_lt_iff hpε,
mul_one],
exact lt_add_of_pos_right _ hε }
end
lemma seminorm.gauge_seminorm_ball (p : seminorm ℝ E) :
gauge_seminorm (λ x, p.symmetric_ball_zero 1) (p.convex_ball 0 1)
(p.absorbent_ball_zero zero_lt_one) = p :=
seminorm.ext p.gauge_ball
end gauge
-- TODO: topology induced by family of seminorms, local convexity.
|
440078e38db21945ba495ad4d5c99e71575b6895 | a4673261e60b025e2c8c825dfa4ab9108246c32e | /stage0/src/Lean/Data/Name.lean | 7ffd9fbf270dabd5c20860afb9066a3343bf5d3d | [
"Apache-2.0"
] | permissive | jcommelin/lean4 | c02dec0cc32c4bccab009285475f265f17d73228 | 2909313475588cc20ac0436e55548a4502050d0a | refs/heads/master | 1,674,129,550,893 | 1,606,415,348,000 | 1,606,415,348,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,502 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
import Std.Data.HashSet
import Std.Data.RBMap
import Std.Data.RBTree
namespace Lean
instance : Coe String Name := ⟨Name.mkSimple⟩
namespace Name
@[export lean_name_hash] def hashEx : Name → USize :=
Name.hash
def getPrefix : Name → Name
| anonymous => anonymous
| str p s _ => p
| num p s _ => p
def getRoot : Name → Name
| anonymous => anonymous
| n@(str anonymous _ _) => n
| n@(num anonymous _ _) => n
| str n _ _ => getRoot n
| num n _ _ => getRoot n
def getString! : Name → String
| str _ s _ => s
| _ => unreachable!
def getNumParts : Name → Nat
| anonymous => 0
| str p _ _ => getNumParts p + 1
| num p _ _ => getNumParts p + 1
def updatePrefix : Name → Name → Name
| anonymous, newP => anonymous
| str p s _, newP => Name.mkStr newP s
| num p s _, newP => Name.mkNum newP s
def components' : Name → List Name
| anonymous => []
| str n s _ => Name.mkStr anonymous s :: components' n
| num n v _ => Name.mkNum anonymous v :: components' n
def components (n : Name) : List Name :=
n.components'.reverse
def eqStr : Name → String → Bool
| str anonymous s _, s' => s == s'
| _, _ => false
def replacePrefix : Name → Name → Name → Name
| anonymous, anonymous, newP => newP
| anonymous, _, _ => anonymous
| n@(str p s _), queryP, newP => if n == queryP then newP else Name.mkStr (p.replacePrefix queryP newP) s
| n@(num p s _), queryP, newP => if n == queryP then newP else Name.mkNum (p.replacePrefix queryP newP) s
def isPrefixOf : Name → Name → Bool
| p, anonymous => p == anonymous
| p, n@(num p' _ _) => p == n || isPrefixOf p p'
| p, n@(str p' _ _) => p == n || isPrefixOf p p'
def isSuffixOf : Name → Name → Bool
| anonymous, _ => true
| str p₁ s₁ _, str p₂ s₂ _ => s₁ == s₂ && isSuffixOf p₁ p₂
| num p₁ n₁ _, num p₂ n₂ _ => n₁ == n₂ && isSuffixOf p₁ p₂
| _, _ => false
def lt : Name → Name → Bool
| anonymous, anonymous => false
| anonymous, _ => true
| num p₁ i₁ _, num p₂ i₂ _ => lt p₁ p₂ || (p₁ == p₂ && i₁ < i₂)
| num _ _ _, str _ _ _ => true
| str p₁ n₁ _, str p₂ n₂ _ => lt p₁ p₂ || (p₁ == p₂ && n₁ < n₂)
| _, _ => false
def quickLtAux : Name → Name → Bool
| anonymous, anonymous => false
| anonymous, _ => true
| num n v _, num n' v' _ => v < v' || (v = v' && n.quickLtAux n')
| num _ _ _, str _ _ _ => true
| str n s _, str n' s' _ => s < s' || (s = s' && n.quickLtAux n')
| _, _ => false
def quickLt (n₁ n₂ : Name) : Bool :=
if n₁.hash < n₂.hash then true
else if n₁.hash > n₂.hash then false
else quickLtAux n₁ n₂
/- Alternative HasLt instance. -/
@[inline] protected def hasLtQuick : HasLess Name :=
⟨fun a b => Name.quickLt a b = true⟩
@[inline] instance : DecidableRel (@Less Name Name.hasLtQuick) :=
inferInstanceAs (DecidableRel (fun a b => Name.quickLt a b = true))
/- The frontend does not allow user declarations to start with `_` in any of its parts.
We use name parts starting with `_` internally to create auxiliary names (e.g., `_private`). -/
def isInternal : Name → Bool
| str p s _ => s.get 0 == '_' || isInternal p
| num p _ _ => isInternal p
| _ => false
def isAtomic : Name → Bool
| anonymous => true
| str anonymous _ _ => true
| num anonymous _ _ => true
| _ => false
def isAnonymous : Name → Bool
| anonymous => true
| _ => false
def isStr : Name → Bool
| str .. => true
| _ => false
def isNum : Name → Bool
| num .. => true
| _ => false
end Name
open Std (RBMap RBTree mkRBMap mkRBTree)
def NameMap (α : Type) := Std.RBMap Name α Name.quickLt
@[inline] def mkNameMap (α : Type) : NameMap α := Std.mkRBMap Name α Name.quickLt
namespace NameMap
variable {α : Type}
instance (α : Type) : EmptyCollection (NameMap α) := ⟨mkNameMap α⟩
instance (α : Type) : Inhabited (NameMap α) := ⟨{}⟩
def insert (m : NameMap α) (n : Name) (a : α) := Std.RBMap.insert m n a
def contains (m : NameMap α) (n : Name) : Bool := Std.RBMap.contains m n
@[inline] def find? (m : NameMap α) (n : Name) : Option α := Std.RBMap.find? m n
end NameMap
def NameSet := RBTree Name Name.quickLt
namespace NameSet
def empty : NameSet := mkRBTree Name Name.quickLt
instance : EmptyCollection NameSet := ⟨empty⟩
instance : Inhabited NameSet := ⟨{}⟩
def insert (s : NameSet) (n : Name) : NameSet := Std.RBTree.insert s n
def contains (s : NameSet) (n : Name) : Bool := Std.RBMap.contains s n
end NameSet
def NameHashSet := Std.HashSet Name
namespace NameHashSet
@[inline] def empty : NameHashSet := Std.HashSet.empty
instance : EmptyCollection NameHashSet := ⟨empty⟩
instance : Inhabited NameHashSet := ⟨{}⟩
def insert (s : NameHashSet) (n : Name) := Std.HashSet.insert s n
def contains (s : NameHashSet) (n : Name) : Bool := Std.HashSet.contains s n
end NameHashSet
end Lean
open Lean
def String.toName (s : String) : Name :=
let ps := s.splitOn ".";
ps.foldl (fun n p => Name.mkStr n p.trim) Name.anonymous
|
6795b768ad054ea9989bcc123b9f0513ae8d5017 | 97f752b44fd85ec3f635078a2dd125ddae7a82b6 | /hott/hit/colimit.hlean | 9ab899dd69615191518f8615644b03fb945f8329 | [
"Apache-2.0"
] | permissive | tectronics/lean | ab977ba6be0fcd46047ddbb3c8e16e7c26710701 | f38af35e0616f89c6e9d7e3eb1d48e47ee666efe | refs/heads/master | 1,532,358,526,384 | 1,456,276,623,000 | 1,456,276,623,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,577 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Definition of general colimits and sequential colimits.
-/
/- definition of a general colimit -/
open eq nat quotient sigma equiv equiv.ops is_trunc
namespace colimit
section
parameters {I J : Type} (A : I → Type) (dom cod : J → I)
(f : Π(j : J), A (dom j) → A (cod j))
variables {i : I} (a : A i) (j : J) (b : A (dom j))
local abbreviation B := Σ(i : I), A i
inductive colim_rel : B → B → Type :=
| Rmk : Π{j : J} (a : A (dom j)), colim_rel ⟨cod j, f j a⟩ ⟨dom j, a⟩
open colim_rel
local abbreviation R := colim_rel
-- TODO: define this in root namespace
definition colimit : Type :=
quotient colim_rel
definition incl : colimit :=
class_of R ⟨i, a⟩
abbreviation ι := @incl
definition cglue : ι (f j b) = ι b :=
eq_of_rel colim_rel (Rmk f b)
protected definition rec {P : colimit → Type}
(Pincl : Π⦃i : I⦄ (x : A i), P (ι x))
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x)
(y : colimit) : P y :=
begin
fapply (quotient.rec_on y),
{ intro a, cases a, apply Pincl},
{ intro a a' H, cases H, apply Pglue}
end
protected definition rec_on [reducible] {P : colimit → Type} (y : colimit)
(Pincl : Π⦃i : I⦄ (x : A i), P (ι x))
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x) : P y :=
rec Pincl Pglue y
theorem rec_cglue {P : colimit → Type}
(Pincl : Π⦃i : I⦄ (x : A i), P (ι x))
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) =[cglue j x] Pincl x)
{j : J} (x : A (dom j)) : apdo (rec Pincl Pglue) (cglue j x) = Pglue j x :=
!rec_eq_of_rel
protected definition elim {P : Type} (Pincl : Π⦃i : I⦄ (x : A i), P)
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) (y : colimit) : P :=
rec Pincl (λj a, pathover_of_eq (Pglue j a)) y
protected definition elim_on [reducible] {P : Type} (y : colimit)
(Pincl : Π⦃i : I⦄ (x : A i), P)
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x) : P :=
elim Pincl Pglue y
theorem elim_cglue {P : Type}
(Pincl : Π⦃i : I⦄ (x : A i), P)
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) = Pincl x)
{j : J} (x : A (dom j)) : ap (elim Pincl Pglue) (cglue j x) = Pglue j x :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (cglue j x)),
rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim,rec_cglue],
end
protected definition elim_type (Pincl : Π⦃i : I⦄ (x : A i), Type)
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) (y : colimit) : Type :=
elim Pincl (λj a, ua (Pglue j a)) y
protected definition elim_type_on [reducible] (y : colimit)
(Pincl : Π⦃i : I⦄ (x : A i), Type)
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x) : Type :=
elim_type Pincl Pglue y
theorem elim_type_cglue (Pincl : Π⦃i : I⦄ (x : A i), Type)
(Pglue : Π(j : J) (x : A (dom j)), Pincl (f j x) ≃ Pincl x)
{j : J} (x : A (dom j)) : transport (elim_type Pincl Pglue) (cglue j x) = Pglue j x :=
by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_cglue];apply cast_ua_fn
protected definition rec_prop {P : colimit → Type} [H : Πx, is_prop (P x)]
(Pincl : Π⦃i : I⦄ (x : A i), P (ι x)) (y : colimit) : P y :=
rec Pincl (λa b, !is_prop.elimo) y
protected definition elim_prop {P : Type} [H : is_prop P] (Pincl : Π⦃i : I⦄ (x : A i), P)
(y : colimit) : P :=
elim Pincl (λa b, !is_prop.elim) y
end
end colimit
/- definition of a sequential colimit -/
namespace seq_colim
section
/-
we define it directly in terms of quotients. An alternative definition could be
definition seq_colim := colimit.colimit A id succ f
-/
parameters {A : ℕ → Type} (f : Π⦃n⦄, A n → A (succ n))
variables {n : ℕ} (a : A n)
local abbreviation B := Σ(n : ℕ), A n
inductive seq_rel : B → B → Type :=
| Rmk : Π{n : ℕ} (a : A n), seq_rel ⟨succ n, f a⟩ ⟨n, a⟩
open seq_rel
local abbreviation R := seq_rel
-- TODO: define this in root namespace
definition seq_colim : Type :=
quotient seq_rel
definition inclusion : seq_colim :=
class_of R ⟨n, a⟩
abbreviation sι := @inclusion
definition glue : sι (f a) = sι a :=
eq_of_rel seq_rel (Rmk f a)
protected definition rec {P : seq_colim → Type}
(Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a))
(Pglue : Π(n : ℕ) (a : A n), Pincl (f a) =[glue a] Pincl a) (aa : seq_colim) : P aa :=
begin
fapply (quotient.rec_on aa),
{ intro a, cases a, apply Pincl},
{ intro a a' H, cases H, apply Pglue}
end
protected definition rec_on [reducible] {P : seq_colim → Type} (aa : seq_colim)
(Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a))
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a)
: P aa :=
rec Pincl Pglue aa
theorem rec_glue {P : seq_colim → Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a))
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) =[glue a] Pincl a) {n : ℕ} (a : A n)
: apdo (rec Pincl Pglue) (glue a) = Pglue a :=
!rec_eq_of_rel
protected definition elim {P : Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P)
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : seq_colim → P :=
rec Pincl (λn a, pathover_of_eq (Pglue a))
protected definition elim_on [reducible] {P : Type} (aa : seq_colim)
(Pincl : Π⦃n : ℕ⦄ (a : A n), P)
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) : P :=
elim Pincl Pglue aa
theorem elim_glue {P : Type} (Pincl : Π⦃n : ℕ⦄ (a : A n), P)
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) = Pincl a) {n : ℕ} (a : A n)
: ap (elim Pincl Pglue) (glue a) = Pglue a :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (glue a)),
rewrite [▸*,-apdo_eq_pathover_of_eq_ap,↑elim,rec_glue],
end
protected definition elim_type (Pincl : Π⦃n : ℕ⦄ (a : A n), Type)
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : seq_colim → Type :=
elim Pincl (λn a, ua (Pglue a))
protected definition elim_type_on [reducible] (aa : seq_colim)
(Pincl : Π⦃n : ℕ⦄ (a : A n), Type)
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) : Type :=
elim_type Pincl Pglue aa
theorem elim_type_glue (Pincl : Π⦃n : ℕ⦄ (a : A n), Type)
(Pglue : Π⦃n : ℕ⦄ (a : A n), Pincl (f a) ≃ Pincl a) {n : ℕ} (a : A n)
: transport (elim_type Pincl Pglue) (glue a) = Pglue a :=
by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_glue];apply cast_ua_fn
protected definition rec_prop {P : seq_colim → Type} [H : Πx, is_prop (P x)]
(Pincl : Π⦃n : ℕ⦄ (a : A n), P (sι a)) (aa : seq_colim) : P aa :=
rec Pincl (λa b, !is_prop.elimo) aa
protected definition elim_prop {P : Type} [H : is_prop P] (Pincl : Π⦃n : ℕ⦄ (a : A n), P)
: seq_colim → P :=
elim Pincl (λa b, !is_prop.elim)
end
end seq_colim
attribute colimit.incl seq_colim.inclusion [constructor]
attribute colimit.rec colimit.elim [unfold 10] [recursor 10]
attribute colimit.elim_type [unfold 9]
attribute colimit.rec_on colimit.elim_on [unfold 8]
attribute colimit.elim_type_on [unfold 7]
attribute seq_colim.rec seq_colim.elim [unfold 6] [recursor 6]
attribute seq_colim.elim_type [unfold 5]
attribute seq_colim.rec_on seq_colim.elim_on [unfold 4]
attribute seq_colim.elim_type_on [unfold 3]
|
738d951624a1a7372e6d0f56e26dd72738d87a56 | d5ecf6c46a2f605470a4a7724909dc4b9e7350e0 | /analysis/measure_theory/outer_measure.lean | dd1e0f9235897284fefc431ab64d689defdc5282 | [
"Apache-2.0"
] | permissive | MonoidMusician/mathlib | 41f79df478987a636b735c338396813d2e8e44c4 | 72234ef1a050eea3a2197c23aeb345fc13c08ff3 | refs/heads/master | 1,583,672,205,771 | 1,522,892,143,000 | 1,522,892,143,000 | 128,144,032 | 0 | 0 | Apache-2.0 | 1,522,892,144,000 | 1,522,890,892,000 | Lean | UTF-8 | Lean | false | false | 17,994 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Outer measures -- overapproximations of measures
-/
import data.set order.galois_connection algebra.big_operators
analysis.ennreal analysis.limits
analysis.measure_theory.measurable_space
noncomputable theory
open set lattice finset function filter
open ennreal (of_real)
local attribute [instance] classical.prop_decidable
namespace measure_theory
structure outer_measure (α : Type*) :=
(measure_of : set α → ennreal)
(empty : measure_of ∅ = 0)
(mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂)
(Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i)))
namespace outer_measure
section basic
variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α}
lemma subadditive (m : outer_measure α) {s₁ s₂ : set α} :
m.measure_of (s₁ ∪ s₂) ≤ m.measure_of s₁ + m.measure_of s₂ :=
let s := λi, ([s₁, s₂].nth i).get_or_else ∅ in
calc m.measure_of (s₁ ∪ s₂) ≤ m.measure_of (⋃i, s i) :
m.mono $ union_subset (subset_Union s 0) (subset_Union s 1)
... ≤ (∑i, m.measure_of (s i)) : m.Union_nat s
... = (insert 0 {1} : finset ℕ).sum (m.measure_of ∘ s) : tsum_eq_sum $ assume n h,
match n, h with
| 0, h := by simp at h; contradiction
| 1, h := by simp at h; contradiction
| nat.succ (nat.succ n), h := m.empty
end
... = m.measure_of s₁ + m.measure_of s₂ : by simp [-add_comm]; refl
lemma outer_measure_eq : ∀{μ₁ μ₂ : outer_measure α},
(∀s, μ₁.measure_of s = μ₂.measure_of s) → μ₁ = μ₂
| ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h :=
have m₁ = m₂, from funext $ assume s, h s,
by simp [this]
instance : has_zero (outer_measure α) :=
⟨{ measure_of := λ_, 0,
empty := rfl,
mono := assume _ _ _, le_refl 0,
Union_nat := assume s, ennreal.zero_le }⟩
instance : inhabited (outer_measure α) := ⟨0⟩
instance : has_add (outer_measure α) :=
⟨λm₁ m₂,
{ measure_of := λs, m₁.measure_of s + m₂.measure_of s,
empty := show m₁.measure_of ∅ + m₂.measure_of ∅ = 0, by simp [outer_measure.empty],
mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h),
Union_nat := assume s,
calc m₁.measure_of (⋃i, s i) + m₂.measure_of (⋃i, s i) ≤
(∑i, m₁.measure_of (s i)) + (∑i, m₂.measure_of (s i)) :
add_le_add' (m₁.Union_nat s) (m₂.Union_nat s)
... = _ : (tsum_add ennreal.has_sum ennreal.has_sum).symm}⟩
instance : add_comm_monoid (outer_measure α) :=
{ zero := 0,
add := (+),
add_comm := assume a b, outer_measure_eq $ assume s, add_comm _ _,
add_assoc := assume a b c, outer_measure_eq $ assume s, add_assoc _ _ _,
add_zero := assume a, outer_measure_eq $ assume s, add_zero _,
zero_add := assume a, outer_measure_eq $ assume s, zero_add _ }
instance : has_bot (outer_measure α) := ⟨0⟩
instance outer_measure.order_bot : order_bot (outer_measure α) :=
{ le := λm₁ m₂, ∀s, m₁.measure_of s ≤ m₂.measure_of s,
bot := 0,
le_refl := assume a s, le_refl _,
le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s),
le_antisymm := assume a b hab hba, outer_measure_eq $ assume s, le_antisymm (hab s) (hba s),
bot_le := assume a s, ennreal.zero_le }
section supremum
private def sup (ms : set (outer_measure α)) (h : ms ≠ ∅) :=
{ outer_measure .
measure_of := λs, ⨆m:ms, m.val.measure_of s,
empty :=
let ⟨m, hm⟩ := set.exists_mem_of_ne_empty h in
have ms := ⟨m, hm⟩,
by simp [outer_measure.empty]; exact @supr_const _ _ _ _ ⟨this⟩,
mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs,
Union_nat := assume f, supr_le $ assume m,
calc m.val.measure_of (⋃i, f i) ≤ (∑ (i : ℕ), m.val.measure_of (f i)) : m.val.Union_nat _
... ≤ (∑i, ⨆m:ms, m.val.measure_of (f i)) :
ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val.measure_of (f i)) m }
instance : has_Sup (outer_measure α) := ⟨λs, if h : s = ∅ then ⊥ else sup s h⟩
private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms :=
show m ≤ (if h : ms = ∅ then ⊥ else sup ms h),
by rw [dif_neg (set.ne_empty_of_mem hm)];
exact assume s, le_supr (λm:ms, m.val.measure_of s) ⟨m, hm⟩
private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m :=
show (if h : ms = ∅ then ⊥ else sup ms h) ≤ m,
begin
by_cases ms = ∅,
{ rw [dif_pos h], exact bot_le },
{ rw [dif_neg h], exact assume s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) }
end
instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩
private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm
private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm
instance : complete_lattice (outer_measure α) :=
{ top := Sup univ,
le_top := assume a, le_Sup (mem_univ a),
Sup := Sup,
Sup_le := assume s m, Sup_le,
le_Sup := assume s m, le_Sup,
Inf := Inf,
Inf_le := assume s m, Inf_le,
le_Inf := assume s m, le_Inf,
sup := λa b, Sup {a, b},
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
inf := λa b, Inf {a, b},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
.. outer_measure.order_bot }
end supremum
end basic
section of_function
set_option eqn_compiler.zeta true
-- TODO: if we move this proof into the definition of inf it does not terminate anymore
private lemma aux {ε : ℝ} (hε : 0 < ε) : (∑i, of_real ((ε / 2) * 2⁻¹ ^ i)) = of_real ε :=
let ε' := λi, (ε / 2) * 2⁻¹ ^ i in
have hε' : ∀i, 0 < ε' i,
from assume i, mul_pos (div_pos_of_pos_of_pos hε two_pos) $ pow_pos (inv_pos two_pos) _,
have is_sum (λi, 2⁻¹ ^ i : ℕ → ℝ) (1 / (1 - 2⁻¹)),
from is_sum_geometric (le_of_lt $ inv_pos two_pos) $ inv_lt_one one_lt_two,
have is_sum (λi, ε' i) ((ε / 2) * (1 / (1 - 2⁻¹))),
from is_sum_mul_left this,
have eq : ((ε / 2) * (1 / (1 - 2⁻¹))) = ε,
begin
have ne_two : (2:ℝ) ≠ 0, from (ne_of_lt two_pos).symm,
rw [inv_eq_one_div, sub_eq_add_neg, ←neg_div, add_div_eq_mul_add_div _ _ ne_two],
simp [bit0, bit1] at ne_two,
simp [bit0, bit1, mul_div_cancel' _ ne_two, mul_comm]
end,
have is_sum (λi, ε' i) ε, begin rw [eq] at this, exact this end,
ennreal.tsum_of_real this (assume i, le_of_lt $ hε' i)
/-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is
a unique minimal outer measure `μ` satisfying `μ s ≥ m s` for all `s : set α`. -/
protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) :
outer_measure α :=
let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in
{ measure_of := μ,
empty := le_antisymm
(infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty])
(zero_le _),
mono := assume s₁ s₂ hs, infi_le_infi $ assume f,
infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩,
Union_nat := assume s, ennreal.le_of_forall_epsilon_le $
assume ε hε (hb : (∑i, μ (s i)) < ⊤),
let ε' := λi, (ε / 2) * 2⁻¹ ^ i in
have hε' : ∀i, 0 < ε' i,
from assume i, mul_pos (div_pos_of_pos_of_pos hε two_pos) $ pow_pos (inv_pos two_pos) _,
have ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + of_real (ε' i),
from assume i,
have μ (s i) < μ (s i) + of_real (ε' i),
from ennreal.lt_add_right
(calc μ (s i) ≤ (∑i, μ (s i)) : ennreal.le_tsum
... < ⊤ : hb)
(by simp; exact hε' _),
by simpa [μ, infi_lt_iff] using this,
let ⟨f, hf⟩ := classical.axiom_of_choice this in
let f' := λi, f (nat.unpair i).1 (nat.unpair i).2 in
have hf' : (⋃ (i : ℕ), s i) ⊆ (⋃i, f' i),
from Union_subset $ assume i, subset.trans (hf i).left $ Union_subset_Union2 $ assume j,
⟨nat.mkpair i j, begin simp [f'], simp [nat.unpair_mkpair], exact subset.refl _ end⟩,
have (∑i, of_real (ε' i)) = of_real ε, from aux hε,
have (∑i, m (f' i)) ≤ (∑i, μ (s i)) + of_real ε,
from calc (∑i, m (f' i)) = (∑p:ℕ×ℕ, m (f' (nat.mkpair p.1 p.2))) :
(tsum_eq_tsum_of_iso (λp:ℕ×ℕ, nat.mkpair p.1 p.2) nat.unpair
(assume ⟨a, b⟩, nat.unpair_mkpair a b) nat.mkpair_unpair).symm
... = (∑i, ∑j, m (f i j)) :
by dsimp [f']; rw [←ennreal.tsum_prod]; simp [nat.unpair_mkpair]
... ≤ (∑i, μ (s i) + of_real (ε' i)) :
ennreal.tsum_le_tsum $ assume i, le_of_lt $ (hf i).right
... ≤ (∑i, μ (s i)) + (∑i, of_real (ε' i)) : by rw [tsum_add]; exact ennreal.has_sum
... = (∑i, μ (s i)) + of_real ε : by rw [this],
show μ (⋃ (i : ℕ), s i) ≤ (∑ (i : ℕ), μ (s i)) + of_real ε,
from infi_le_of_le f' $ infi_le_of_le hf' $ this }
end of_function
section caratheodory_measurable
universe u
parameters {α : Type u} (m : outer_measure α)
include m
local notation `μ` := m.measure_of
local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc
variables {s s₁ s₂ : set α}
private def C (s : set α) := ∀t, μ t = μ (t ∩ s) + μ (t \ s)
@[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, sdiff_empty]
private lemma C_compl : C s₁ → C (- s₁) := by simp [C, sdiff_eq]
@[simp] private lemma C_compl_iff : C (- s) ↔ C s :=
⟨assume h, let h' := C_compl h in by simp at h'; assumption, C_compl⟩
private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) :=
assume t,
have e₁ : (s₁ ∪ s₂) ∩ s₁ ∩ s₂ = s₁ ∩ s₂,
from set.ext $ assume x, by simp [iff_def] {contextual := tt},
have e₂ : (s₁ ∪ s₂) ∩ s₁ ∩ -s₂ = s₁ ∩ -s₂,
from set.ext $ assume x, by simp [iff_def] {contextual := tt},
calc μ t = μ (t ∩ s₁ ∩ s₂) + μ (t ∩ s₁ ∩ -s₂) + μ (t ∩ -s₁ ∩ s₂) + μ (t ∩ -s₁ ∩ -s₂) :
by rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁)]; simp [sdiff_eq]
... = μ (t ∩ ((s₁ ∪ s₂) ∩ s₁ ∩ s₂)) + μ (t ∩ ((s₁ ∪ s₂) ∩ s₁ ∩ -s₂)) +
μ (t ∩ s₂ ∩ -s₁) + μ (t ∩ -s₁ ∩ -s₂) :
by rw [e₁, e₂]; simp
... = ((μ (t ∩ (s₁ ∪ s₂) ∩ s₁ ∩ s₂) + μ ((t ∩ (s₁ ∪ s₂) ∩ s₁) \ s₂)) +
μ (t ∩ ((s₁ ∪ s₂) \ s₁))) + μ (t \ (s₁ ∪ s₂)) :
by rw [union_sdiff_right]; simp [sdiff_eq]
... = μ (t ∩ (s₁ ∪ s₂)) + μ (t \ (s₁ ∪ s₂)) :
by rw [h₁ (t ∩ (s₁ ∪ s₂)), h₂ ((t ∩ (s₁ ∪ s₂)) ∩ s₁)]; simp [sdiff_eq]
private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i)
| 0 h := by simp [nat.not_lt_zero]
| (n + 1) h := show C (⨆i < nat.succ n, s i),
begin
simp [nat.lt_succ_iff_lt_or_eq, supr_or, supr_sup_eq, sup_comm],
exact C_union m (h n (le_refl (n + 1)))
(C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _)
end
private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) :=
by rw [←C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂)
private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {n} {t : set α} :
(finset.range n).sum (λi, μ (t ∩ s i)) = μ (t ∩ ⋃i<n, s i) :=
begin
induction n,
case nat.zero { simp [nat.not_lt_zero, m.empty] },
case nat.succ : n ih {
have disj : ∀x i, x ∈ s n → i < n → x ∉ s i,
from assume x i hn h hi,
have hx : x ∈ s i ∩ s n, from ⟨hi, hn⟩,
have s i ∩ s n = ∅, from hd _ _ (ne_of_lt h),
by rwa [this] at hx,
have : (⋃i<n+1, s i) \ (⋃i<n, s i) = s n,
{ apply set.ext, intro x, simp,
constructor,
from assume ⟨⟨i, hin, hi⟩, hx⟩, (nat.lt_succ_iff_lt_or_eq.mp hin).elim
(assume h, (hx i h hi).elim)
(assume h, h ▸ hi),
from assume hx, ⟨⟨n, nat.lt_succ_self _, hx⟩, assume i, disj x i hx⟩ },
have e₁ : t ∩ s n = (t ∩ ⋃i<n+1, s i) \ ⋃i<n, s i,
from calc t ∩ s n = t ∩ ((⋃i<n+1, s i) \ (⋃i<n, s i)) : by rw [this]
... = (t ∩ ⋃i<n+1, s i) \ ⋃i<n, s i : by simp [sdiff_eq],
have : (⋃i<n+1, s i) ∩ (⋃i<n, s i) = (⋃i<n, s i),
from (inf_of_le_right $ supr_le_supr $ assume i, supr_le_supr_const $
assume hin, lt_trans hin (nat.lt_succ_self n)),
have e₂ : t ∩ (⋃i<n, s i) = (t ∩ ⋃i<n+1, s i) ∩ ⋃i<n, s i,
from calc t ∩ (⋃i<n, s i) = t ∩ ((⋃i<n+1, s i) ∩ (⋃i<n, s i)) : by rw [this]
... = _ : by simp,
have : C _ (⋃i<n, s i),
from C_Union_lt m (assume i _, h i),
from calc (range (nat.succ n)).sum (λi, μ (t ∩ s i)) = μ (t ∩ s n) + μ (t ∩ ⋃i < n, s i) :
by simp [range_succ, sum_insert, lt_irrefl, ih]
... = μ ((t ∩ ⋃i<n+1, s i) ∩ ⋃i<n, s i) + μ ((t ∩ ⋃i<n+1, s i) \ ⋃i<n, s i) :
by rw [e₁, e₂]; simp
... = μ (t ∩ ⋃i<n+1, s i) : (this $ t ∩ ⋃i<n+1, s i).symm }
end
private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) :
C (⋃i, s i) :=
assume t,
suffices μ t ≥ μ (t ∩ (⋃i, s i)) + μ (t \ (⋃i, s i)),
from le_antisymm
(calc μ t ≤ μ (t ∩ (⋃i, s i) ∪ t \ (⋃i, s i)) :
m.mono $ assume x ht, by by_cases x ∈ (⋃i, s i); simp [*] at *
... ≤ μ (t ∩ (⋃i, s i)) + μ (t \ (⋃i, s i)) : m.subadditive)
this,
have hp : μ (t ∩ ⋃i, s i) ≤ (⨆n, μ (t ∩ ⋃i<n, s i)),
from calc μ (t ∩ ⋃i, s i) = μ (⋃i, t ∩ s i) : by rw [inter_distrib_Union_left]
... ≤ ∑i, μ (t ∩ s i) : m.Union_nat _
... = ⨆n, (finset.range n).sum (λi, μ (t ∩ s i)) : ennreal.tsum_eq_supr_nat
... = ⨆n, μ (t ∩ ⋃i<n, s i) : congr_arg _ $ funext $ assume n, C_sum h hd,
have hn : ∀n, μ (t \ (⋃i<n, s i)) ≥ μ (t \ (⋃i, s i)),
from assume n,
m.mono $ sdiff_subset_sdiff (subset.refl t) $ bUnion_subset $ assume i _, le_supr s i,
calc μ (t ∩ (⋃i, s i)) + μ (t \ (⋃i, s i)) ≤ (⨆n, μ (t ∩ ⋃i<n, s i)) + μ (t \ (⋃i, s i)) :
add_le_add' hp (le_refl _)
... = (⨆n, μ (t ∩ ⋃i<n, s i) + μ (t \ (⋃i, s i))) :
ennreal.supr_add
... ≤ (⨆n, μ (t ∩ ⋃i<n, s i) + μ (t \ (⋃i<n, s i))) :
supr_le_supr $ assume i, add_le_add' (le_refl _) (hn _)
... ≤ μ t : supr_le $ assume n, le_of_eq (C_Union_lt (assume i _, h i) t).symm
private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) :
μ (⋃i, s i) = ∑i, μ (s i) :=
have ∀n, (finset.range n).sum (λ (i : ℕ), μ (s i)) ≤ μ (⋃ (i : ℕ), s i),
from assume n,
calc (finset.range n).sum (λi, μ (s i)) = (finset.range n).sum (λi, μ (univ ∩ s i)) :
by simp [univ_inter]
... = μ (⋃i<n, s i) :
by rw [C_sum _ h hd, univ_inter]
... ≤ μ (⋃ (i : ℕ), s i) : m.mono $ bUnion_subset $ assume i _, le_supr s i,
suffices μ (⋃i, s i) ≥ ∑i, μ (s i),
from le_antisymm (m.Union_nat s) this,
calc (∑i, μ (s i)) = (⨆n, (finset.range n).sum (λi, μ (s i))) : ennreal.tsum_eq_supr_nat
... ≤ _ : supr_le this
private def caratheodory_dynkin : measurable_space.dynkin_system α :=
{ has := C,
has_empty := C_empty,
has_compl := assume s, C_compl,
has_Union := assume f hf hn, C_Union_nat hn hf }
/-- Given an outer measure `μ`, the Caratheodory measurable space is
defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/
protected def caratheodory : measurable_space α :=
caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter
lemma caratheodory_is_measurable_eq {s : set α} :
caratheodory.is_measurable s = ∀t, μ t = μ (t ∩ s) + μ (t \ s) :=
rfl
protected lemma Union_eq_of_caratheodory {s : ℕ → set α}
(h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) :
μ (⋃i, s i) = ∑i, μ (s i) :=
f_Union h hd
lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α}
{h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) :
(outer_measure.of_function m h₀).caratheodory.is_measurable s :=
let o := (outer_measure.of_function m h₀), om := o.measure_of in
assume t,
le_antisymm
(calc om t = om ((t ∩ s) ∪ (t \ s)) :
congr_arg om (set.ext $ assume x, by by_cases x ∈ s; simp [iff_def, *])
... ≤ om (t ∩ s) + om (t \ s) :
o.subadditive)
(le_infi $ assume f, le_infi $ assume hf,
have h₁ : t ∩ s ⊆ ⋃i, f i ∩ s,
by rw [←inter_distrib_Union_right]; from inter_subset_inter hf (subset.refl s),
have h₂ : t \ s ⊆ ⋃i, f i \ s,
from subset.trans (sdiff_subset_sdiff hf (subset.refl s)) $
by simp [set.subset_def] {contextual := tt},
calc om (t ∩ s) + om (t \ s) ≤ (∑i, m (f i ∩ s)) + (∑i, m (f i \ s)) :
add_le_add'
(infi_le_of_le (λi, f i ∩ s) $ infi_le_of_le h₁ $ le_refl _)
(infi_le_of_le (λi, f i \ s) $ infi_le_of_le h₂ $ le_refl _)
... = (∑i, m (f i ∩ s) + m (f i \ s)) :
by rw [tsum_add]; exact ennreal.has_sum
... ≤ (∑i, m (f i)) :
ennreal.tsum_le_tsum $ assume i, hs _)
end caratheodory_measurable
end outer_measure
end measure_theory
|
3f64729920395233a536bf26c7877d2ed3b7b000 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/data/fin/ops.lean | d7e086eee0b54ccfc373e44bc1359c8269ceb5d1 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 3,854 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.nat init.data.fin.basic
namespace fin
open nat
variable {n : nat}
protected def succ : fin n → fin (succ n)
| ⟨a, h⟩ := ⟨nat.succ a, succ_lt_succ h⟩
def of_nat {n : nat} (a : nat) : fin (succ n) :=
⟨a % succ n, nat.mod_lt _ (nat.zero_lt_succ _)⟩
private lemma mlt {n b : nat} : ∀ {a}, n > a → b % n < n
| 0 h := nat.mod_lt _ h
| (a+1) h :=
have n > 0, from lt.trans (nat.zero_lt_succ _) h,
nat.mod_lt _ this
protected def add : fin n → fin n → fin n
| ⟨a, h⟩ ⟨b, _⟩ := ⟨(a + b) % n, mlt h⟩
protected def mul : fin n → fin n → fin n
| ⟨a, h⟩ ⟨b, _⟩ := ⟨(a * b) % n, mlt h⟩
private lemma sublt {a b n : nat} (h : a < n) : a - b < n :=
lt_of_le_of_lt (nat.sub_le a b) h
protected def sub : fin n → fin n → fin n
| ⟨a, h⟩ ⟨b, _⟩ := ⟨a - b, sublt h⟩
private lemma modlt {a b n : nat} (h₁ : a < n) (h₂ : b < n) : a % b < n :=
begin
cases b with b,
{simp [mod_zero], assumption},
{have h : a % (succ b) < succ b,
apply nat.mod_lt _ (nat.zero_lt_succ _),
exact lt.trans h h₂}
end
protected def mod : fin n → fin n → fin n
| ⟨a, h₁⟩ ⟨b, h₂⟩ := ⟨a % b, modlt h₁ h₂⟩
private lemma divlt {a b n : nat} (h : a < n) : a / b < n :=
lt_of_le_of_lt (nat.div_le_self a b) h
protected def div : fin n → fin n → fin n
| ⟨a, h⟩ ⟨b, _⟩ := ⟨a / b, divlt h⟩
protected def lt : fin n → fin n → Prop
| ⟨a, _⟩ ⟨b, _⟩ := a < b
protected def le : fin n → fin n → Prop
| ⟨a, _⟩ ⟨b, _⟩ := a ≤ b
instance : has_zero (fin (succ n)) := ⟨⟨0, succ_pos n⟩⟩
instance : has_one (fin (succ n)) := ⟨of_nat 1⟩
instance : has_add (fin n) := ⟨fin.add⟩
instance : has_sub (fin n) := ⟨fin.sub⟩
instance : has_mul (fin n) := ⟨fin.mul⟩
instance : has_mod (fin n) := ⟨fin.mod⟩
instance : has_div (fin n) := ⟨fin.div⟩
instance : has_lt (fin n) := ⟨fin.lt⟩
instance : has_le (fin n) := ⟨fin.le⟩
instance decidable_lt : ∀ (a b : fin n), decidable (a < b)
| ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_lt
instance decidable_le : ∀ (a b : fin n), decidable (a ≤ b)
| ⟨a, _⟩ ⟨b, _⟩ := by apply nat.decidable_le
lemma of_nat_zero : @of_nat n 0 = 0 := rfl
lemma add_def (a b : fin n) : (a + b).val = (a.val + b.val) % n :=
show (fin.add a b).val = (a.val + b.val) % n, from
by cases a; cases b; simp [fin.add]
lemma mul_def (a b : fin n) : (a * b).val = (a.val * b.val) % n :=
show (fin.mul a b).val = (a.val * b.val) % n, from
by cases a; cases b; simp [fin.mul]
lemma sub_def (a b : fin n) : (a - b).val = a.val - b.val :=
show (fin.sub a b).val = a.val - b.val, from
by cases a; cases b; simp [fin.sub]
lemma mod_def (a b : fin n) : (a % b).val = a.val % b.val :=
show (fin.mod a b).val = a.val % b.val, from
by cases a; cases b; simp [fin.mod]
lemma div_def (a b : fin n) : (a / b).val = a.val / b.val :=
show (fin.div a b).val = a.val / b.val, from
by cases a; cases b; simp [fin.div]
lemma lt_def (a b : fin n) : (a < b) = (a.val < b.val) :=
show (fin.lt a b) = (a.val < b.val), from
by cases a; cases b; simp [fin.lt]
lemma le_def (a b : fin n) : (a ≤ b) = (a.val ≤ b.val) :=
show (fin.le a b) = (a.val ≤ b.val), from
by cases a; cases b; simp [fin.le]
lemma val_zero : (0 : fin (succ n)).val = 0 := rfl
def pred {n : nat} : ∀ i : fin (succ n), i ≠ 0 → fin n
| ⟨a, h₁⟩ h₂ := ⟨a.pred,
begin
have this : a ≠ 0,
{ have aux₁ := vne_of_ne h₂,
dsimp at aux₁, rw val_zero at aux₁, exact aux₁ },
exact nat.pred_lt_pred this (nat.succ_ne_zero n) h₁
end⟩
end fin
|
bf9a3cf3570ef75eabf4ac94672ae8c558f64176 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/reflect_type_defeq.lean | d54c97ce1afd8b1f58eb0a32a7c355f0a3ed38a3 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 82 | lean | meta def foo (x : reflected (3 : ℕ)) : reflected ([10] : list ℕ) :=
x -- ERROR |
8687abda2a9b7f927a3f88def897d509d51c0074 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/group_theory/order_of_element.lean | 2f1b459829c875c73026bb3fc7cf3995102232a6 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 24,620 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.big_operators.order
import group_theory.coset
import data.nat.totient
import data.set.finite
open function
open_locale big_operators
variables {α : Type*} {s : set α} {a a₁ a₂ b c: α}
-- TODO mem_range_iff_mem_finset_range_of_mod_eq should be moved elsewhere.
namespace finset
open finset
lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ}
(hn : 0 < n) (h : ∀i, f (i % n) = f i) :
a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) :=
suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h],
have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn,
iff.intro
(assume ⟨i, hi⟩,
have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'),
⟨int.to_nat (i % n),
by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩)
(assume ⟨i, hi, ha⟩,
⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩)
end finset
lemma conj_injective [group α] {x : α} : function.injective (λ (g : α), x * g * x⁻¹) :=
λ a b h, by simpa [mul_left_inj, mul_right_inj] using h
lemma mem_normalizer_fintype [group α] {s : set α} [fintype s] {x : α}
(h : ∀ n, n ∈ s → x * n * x⁻¹ ∈ s) : x ∈ subgroup.set_normalizer s :=
by haveI := classical.prop_decidable;
haveI := set.fintype_image s (λ n, x * n * x⁻¹); exact
λ n, ⟨h n, λ h₁,
have heq : (λ n, x * n * x⁻¹) '' s = s := set.eq_of_subset_of_card_le
(λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective s conj_injective),
have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' s := heq.symm ▸ h₁,
let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩
section order_of
variable [group α]
open quotient_group set
instance fintype_bot : fintype (⊥ : subgroup α) := ⟨{1},
by {rintro ⟨x, ⟨hx⟩⟩, exact finset.mem_singleton_self _}⟩
@[simp] lemma card_trivial :
fintype.card (⊥ : subgroup α) = 1 :=
fintype.card_eq_one_iff.2
⟨⟨(1 : α), set.mem_singleton 1⟩, λ ⟨y, hy⟩, subtype.eq $ subgroup.mem_bot.1 hy⟩
variables [fintype α] [dec : decidable_eq α]
instance quotient_group.fintype (s : subgroup α) [d : decidable_pred (λ a, a ∈ s)] :
fintype (quotient s) :=
@quotient.fintype _ _ (left_rel s) (λ _ _, d _)
lemma card_eq_card_quotient_mul_card_subgroup (s : subgroup α) [fintype s]
[decidable_pred (λ a, a ∈ s)] : fintype.card α = fintype.card (quotient s) * fintype.card s :=
by rw ← fintype.card_prod;
exact fintype.card_congr (subgroup.group_equiv_quotient_times_subgroup)
lemma card_subgroup_dvd_card (s : subgroup α) [fintype s] :
fintype.card s ∣ fintype.card α :=
by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s]
lemma card_quotient_dvd_card (s : subgroup α) [decidable_pred (λ a, a ∈ s)] [fintype s] :
fintype.card (quotient s) ∣ fintype.card α :=
by simp [card_eq_card_quotient_mul_card_subgroup s]
lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 :=
have ¬ injective (λi:ℤ, a ^ i),
from not_injective_infinite_fintype _,
let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j,
by rw [injective] at this; simpa [not_forall] in
have a ^ (i - j) = 1,
by simp [sub_eq_add_neg, gpow_add, gpow_neg, a_eq],
⟨i - j, sub_ne_zero.mpr ne, this⟩
lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 :=
let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in
begin
cases i,
{ exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ },
{ exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ }
end
include dec
/-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/
def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a)
lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 :=
let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂
lemma order_of_pos (a : α) : 0 < order_of a :=
let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁
private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m)
(hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m :=
decidable.by_contradiction $ assume ne : n ≠ m,
have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]),
have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq],
have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩,
have lt : m - n < order_of a,
from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm,
lt_irrefl _ (lt_of_le_of_lt le lt)
lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α)
(hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m :=
(le_total n m).elim
(assume h, pow_injective_aux a h hn hm eq)
(assume h, (pow_injective_aux a h hm hn eq.symm).symm)
lemma order_of_le_card_univ : order_of a ≤ fintype.card α :=
finset.card_le_of_inj_on ((^) a)
(assume n _, fintype.complete _)
(assume i j, pow_injective_of_lt_order_of a)
lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) :=
calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) :
by rw [nat.mod_add_div]
... = a ^ (n % order_of a) :
by simp [pow_add, pow_mul, pow_order_of_eq_one]
lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) :=
calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) :
by rw [int.mod_add_div]
... = a ^ (i % order_of a) :
by simp [gpow_add, gpow_mul, pow_order_of_eq_one]
lemma mem_gpowers_iff_mem_range_order_of {a a' : α} :
a' ∈ subgroup.gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) :=
finset.mem_range_iff_mem_finset_range_of_mod_eq
(order_of_pos a)
(assume i, gpow_eq_mod_order_of.symm)
instance decidable_gpowers : decidable_pred (subgroup.gpowers a : set α) :=
assume a', decidable_of_iff'
(a' ∈ (finset.range (order_of a)).image ((^) a))
mem_gpowers_iff_mem_range_order_of
lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n :=
by_contradiction
(λ h₁, nat.find_min _ (show n % order_of a < order_of a,
from nat.mod_lt _ (order_of_pos _))
⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩)
lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of a ∣ n ↔ a ^ n = 1 :=
⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩
lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n :=
nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩
lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) :
∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ a : α, order_of a = m)).card
= (finset.univ.filter (λ a : α, a ^ n = 1)).card :=
calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ a : α, order_of a = m)).card
= _ : (finset.card_bind (by { intros, apply finset.disjoint_filter.2, cc })).symm
... = _ : congr_arg finset.card (finset.ext (begin
assume a,
suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1,
{ simpa [nat.lt_succ_iff], },
exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow],
λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩
end))
section
local attribute [instance] set_fintype
lemma order_eq_card_gpowers : order_of a = fintype.card (subgroup.gpowers a : set α) :=
begin
refine (finset.card_eq_of_bijective _ _ _ _).symm,
{ exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ },
{ exact assume ⟨_, i, rfl⟩ _,
have pos: (0:int) < order_of a,
from int.coe_nat_lt.mpr $ order_of_pos a,
have 0 ≤ i % (order_of a),
from int.mod_nonneg _ $ ne_of_gt pos,
⟨int.to_nat (i % order_of a),
by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this];
exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ },
{ intros, exact finset.mem_univ _ },
{ exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq }
end
@[simp] lemma order_of_one : order_of (1 : α) = 1 :=
by rw [order_eq_card_gpowers, fintype.card_eq_one_iff];
exact ⟨⟨1, 0, rfl⟩, λ ⟨a, i, ha⟩, by simp [ha.symm]⟩
@[simp] lemma order_of_eq_one_iff : order_of a = 1 ↔ a = 1 :=
⟨λ h, by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] }, λ h, by simp [h]⟩
lemma order_of_eq_prime {p : ℕ} [hp : fact p.prime]
(hg : a^p = 1) (hg1 : a ≠ 1) : order_of a = p :=
(hp.2 _ (order_of_dvd_of_pow_eq_one hg)).resolve_left (mt order_of_eq_one_iff.1 hg1)
section classical
open_locale classical
open quotient_group subgroup
/- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/
lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α :=
have ft_prod : fintype (quotient (gpowers a) × (gpowers a)),
from fintype.of_equiv α group_equiv_quotient_times_subgroup,
have ft_s : fintype (gpowers a),
from @fintype.fintype_prod_right _ _ _ ft_prod _,
have ft_cosets : fintype (quotient (gpowers a)),
from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, (gpowers a).one_mem⟩⟩,
have ft : fintype (quotient (gpowers a) × (gpowers a)),
from @prod.fintype _ _ ft_cosets ft_s,
have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s,
from calc fintype.card α = @fintype.card _ ft_prod :
@fintype.card_congr _ _ _ ft_prod group_equiv_quotient_times_subgroup
... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) :
congr_arg (@fintype.card _) $ subsingleton.elim _ _
... = @fintype.card _ ft_cosets * @fintype.card _ ft_s :
@fintype.card_prod _ _ ft_cosets ft_s,
have eq₂ : order_of a = @fintype.card _ ft_s,
from calc order_of a = _ : order_eq_card_gpowers
... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _,
dvd.intro (@fintype.card (quotient (subgroup.gpowers a)) ft_cosets) $
by rw [eq₁, eq₂, mul_comm]
omit dec
@[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 :=
let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in
by simp [hm, pow_mul, pow_order_of_eq_one]
lemma mem_powers_iff_mem_gpowers {a x : α} : x ∈ submonoid.powers a ↔ x ∈ gpowers a :=
⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩,
λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs,
by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩
lemma powers_eq_gpowers (a : α) : (submonoid.powers a : set α) = gpowers a :=
set.ext $ λ x, mem_powers_iff_mem_gpowers
end classical
open nat subgroup
lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n :=
dvd_antisymm
(order_of_dvd_of_pow_eq_one
(by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow]))
(have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a),
have hdvd : order_of a ∣ n * order_of (a ^ n),
from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]),
coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos)
(dvd_of_mul_dvd_mul_right gcd_pos
(by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc,
nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm])))
lemma image_range_order_of (a : α) :
finset.image (λ i, a ^ i) (finset.range (order_of a)) = (gpowers a : set α).to_finset :=
by { ext x, rw [set.mem_to_finset, mem_coe, mem_gpowers_iff_mem_range_order_of] }
omit dec
open_locale classical
lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} :
a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 :=
⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $
by_contradiction (λ ha, by rw pow_eq_mod_order_of at h;
exact (not_le_of_gt (nat.mod_lt n (order_of_pos a)))
(order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)),
let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in
by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow],
λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in
by rw [hm, pow_mul, h, _root_.one_pow]⟩
end
end order_of
section cyclic
local attribute [instance] set_fintype
open subgroup
/-- A group is called *cyclic* if it is generated by a single element. -/
class is_cyclic (α : Type*) [group α] : Prop :=
(exists_generator [] : ∃ g : α, ∀ x, x ∈ gpowers g)
/-- A cyclic group is always commutative. This is not an `instance` because often we have a better
proof of `comm_group`. -/
def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α :=
{ mul_comm := λ x y, show x * y = y * x,
from let ⟨g, hg⟩ := is_cyclic.exists_generator α in
let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in
hm ▸ hn ▸ gpow_mul_comm _ _ _,
..hg }
lemma is_cyclic_of_order_of_eq_card [group α] [decidable_eq α] [fintype α]
(x : α) (hx : order_of x = fintype.card α) : is_cyclic α :=
⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le
(set.subset_univ _)
(by {rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers], refl})⟩⟩
lemma order_of_eq_card_of_forall_mem_gpowers [group α] [decidable_eq α] [fintype α]
{g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α :=
by {rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers],
simp [hx], apply fintype.card_of_finset', simp, intro x, exact hx x}
instance bot.is_cyclic [group α] : is_cyclic (⊥ : subgroup α) :=
⟨⟨1, λ x, ⟨0, subtype.eq $ eq.symm (subgroup.mem_bot.1 x.2)⟩⟩⟩
instance subgroup.is_cyclic [group α] [is_cyclic α] (H : subgroup α) : is_cyclic H :=
by haveI := classical.prop_decidable; exact
let ⟨g, hg⟩ := is_cyclic.exists_generator α in
if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then
let ⟨x, hx₁, hx₂⟩ := hx in
let ⟨k, hk⟩ := hg x in
have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H,
from ⟨k.nat_abs, nat.pos_of_ne_zero
(λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]),
match k, hk with
| (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁
| -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat,
← subgroup.inv_mem_iff H]; simp * at *
end⟩,
⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩,
λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in
have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex),
from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩,
have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H,
by rw gpow_mul; exact H.gpow_mem (nat.find_spec hex).2 _,
have hk₃ : g ^ (k % nat.find hex) ∈ H,
from (subgroup.mul_mem_cancel_right H hk₂).1 $
by rw [← gpow_add, int.mod_add_div, hk]; exact hx,
have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs,
by rw int.nat_abs_of_nonneg (int.mod_nonneg _
(int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)),
have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H,
by rwa [← gpow_coe_nat, ← hk₄],
have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0,
from by_contradiction (λ h,
nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄];
exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1))
⟨nat.pos_of_ne_zero h, hk₅⟩),
⟨k / (nat.find hex : ℤ), subtype.ext_iff_val.2 begin
suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x,
{ simpa [gpow_mul] },
rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk]
end⟩⟩⟩
else
have H = (⊥ : subgroup α), from subgroup.ext $ λ x, ⟨λ h, by simp at *; tauto,
λ h, by rw [subgroup.mem_bot.1 h]; exact H.one_mem⟩,
by clear _let_match; substI this; apply_instance
open finset nat
lemma is_cyclic.card_pow_eq_one_le [group α] [decidable_eq α] [fintype α] [is_cyclic α] {n : ℕ}
(hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n :=
let ⟨g, hg⟩ := is_cyclic.exists_generator α in
calc (univ.filter (λ a : α, a ^ n = 1)).card
≤ ((gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))) : set α).to_finset.card :
card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ submonoid.powers g,
from mem_powers_iff_mem_gpowers.2 $ hg x in
set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ),
have hgmn : g ^ (m * gcd n (fintype.card α)) = 1,
by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2,
begin
rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm],
refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _,
conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]},
exact order_of_dvd_of_pow_eq_one hgmn
end⟩)
... ≤ n :
let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in
have hm0 : 0 < m, from nat.pos_of_ne_zero
(λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)),
begin
rw [← fintype.card_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers,
order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg],
rw [hm] {occs := occurrences.pos [2,3]},
rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left,
hm, nat.mul_div_cancel _ hm0],
exact le_of_dvd hn0 (gcd_dvd_left _ _)
end
lemma is_cyclic.exists_monoid_generator (α : Type*) [group α] [fintype α] [is_cyclic α] :
∃ x : α, ∀ y : α, y ∈ submonoid.powers x :=
by { simp only [mem_powers_iff_mem_gpowers], exact is_cyclic.exists_generator α }
section
variables [group α] [decidable_eq α] [fintype α]
lemma is_cyclic.image_range_order_of (ha : ∀ x : α, x ∈ gpowers a) :
finset.image (λ i, a ^ i) (range (order_of a)) = univ :=
begin
simp_rw [←subgroup.mem_coe] at ha,
simp only [image_range_order_of, set.eq_univ_iff_forall.mpr ha],
convert set.to_finset_univ
end
lemma is_cyclic.image_range_card (ha : ∀ x : α, x ∈ gpowers a) :
finset.image (λ i, a ^ i) (range (fintype.card α)) = univ :=
by rw [← order_of_eq_card_of_forall_mem_gpowers ha, is_cyclic.image_range_order_of ha]
end
section totient
variables [group α] [decidable_eq α] [fintype α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n)
include hn
lemma card_pow_eq_one_eq_order_of_aux (a : α) :
(finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a :=
le_antisymm
(hn _ (order_of_pos _))
(calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers
... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α)
(fintype.of_finset _ (λ _, iff.rfl)) :
@fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α)
(id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _,
let ⟨i, hi⟩ := b.2 in
by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat,
pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h))
... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : fintype.card_of_finset _ _)
open_locale nat -- use φ for nat.totient
private lemma card_order_of_eq_totient_aux₁ :
∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card →
(univ.filter (λ a : α, order_of a = d)).card = φ d
| 0 := λ hd hd0,
let ⟨a, ha⟩ := card_pos.1 hd0 in absurd (mem_filter.1 ha).2 $ ne_of_gt $ order_of_pos a
| (d+1) := λ hd hd0,
let ⟨a, ha⟩ := card_pos.1 hd0 in
have ha : order_of a = d.succ, from (mem_filter.1 ha).2,
have h : ∑ m in (range d.succ).filter (∣ d.succ),
(univ.filter (λ a : α, order_of a = m)).card =
∑ m in (range d.succ).filter (∣ d.succ), φ m, from
finset.sum_congr rfl
(λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1,
have hm : m ∣ d.succ, from (mem_filter.1 hm).2,
card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2
⟨a ^ (d.succ / m), mem_filter.2 ⟨mem_univ _,
by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm),
nat.div_div_self hm (succ_pos _)]⟩⟩)),
have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ))
= (range d.succ.succ).filter (∣ d.succ),
from (finset.ext $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h, range_succ])
(by clear _let_match; simp [range_succ]; tauto), by clear _let_match; simp [range_succ] {contextual := tt}; tauto⟩),
have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ),
by simp [mem_range, zero_le_one, le_succ],
(add_left_inj (∑ m in (range d.succ).filter (∣ d.succ),
(univ.filter (λ a : α, order_of a = m)).card)).1
(calc _ = ∑ m in insert d.succ (filter (∣ d.succ) (range d.succ)),
(univ.filter (λ a : α, order_of a = m)).card :
eq.symm (finset.sum_insert (by simp [mem_range, zero_le_one, le_succ]))
... = ∑ m in (range d.succ.succ).filter (∣ d.succ),
(univ.filter (λ a : α, order_of a = m)).card :
sum_congr hinsert (λ _ _, rfl)
... = (univ.filter (λ a : α, a ^ d.succ = 1)).card :
sum_card_order_of_eq_card_pow_eq_one (succ_pos d)
... = ∑ m in (range d.succ.succ).filter (∣ d.succ), φ m :
ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm
... = _ : by rw [h, ← sum_insert hinsert₁];
exact finset.sum_congr hinsert.symm (λ _ _, rfl))
lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) :
(univ.filter (λ a : α, order_of a = d)).card = φ d :=
by_contradiction $ λ h,
have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 :=
not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)),
let c := fintype.card α in
have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩,
lt_irrefl c $
calc c = (univ.filter (λ a : α, a ^ c = 1)).card :
congr_arg card $ by simp [finset.ext_iff, c]
... = ∑ m in (range c.succ).filter (∣ c),
(univ.filter (λ a : α, order_of a = m)).card :
(sum_card_order_of_eq_card_pow_eq_one hc0).symm
... = ∑ m in ((range c.succ).filter (∣ c)).erase d,
(univ.filter (λ a : α, order_of a = m)).card :
eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂,
have m = d, by simp at *; cc,
by simp [*, finset.ext_iff] at *; exact h0))
... ≤ ∑ m in ((range c.succ).filter (∣ c)).erase d, φ m :
sum_le_sum (λ m hm,
have hmc : m ∣ c, by simp at hm; tauto,
(imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim
(λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le])
(λ h, by rw h))
... < φ d + ∑ m in ((range c.succ).filter (∣ c)).erase d, φ m :
lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero
(λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd))))
... = ∑ m in insert d (((range c.succ).filter (∣ c)).erase d), φ m : eq.symm (sum_insert (by simp))
... = ∑ m in (range c.succ).filter (∣ c), φ m : finset.sum_congr
(finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl)
... = c : sum_totient _
lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α :=
have (univ.filter (λ a : α, order_of a = fintype.card α)).nonempty,
from (card_pos.1 $
by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)];
exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)),
let ⟨x, hx⟩ := this in
is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2
end totient
lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [decidable_eq α] [fintype α]
{d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d :=
card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd
end cyclic
|
e1ad454580bce448bb70560b62fbce2709f56e66 | 5c7fe6c4a9d4079b5457ffa5f061797d42a1cd65 | /src/exercises/src_27_cartesian_product.lean | 4b10ef76be4ade9cdb83b32bf8e7ff4131ba1b69 | [] | no_license | gihanmarasingha/mth1001_tutorial | 8e0817feeb96e7c1bb3bac49b63e3c9a3a329061 | bb277eebd5013766e1418365b91416b406275130 | refs/heads/master | 1,675,008,746,310 | 1,607,993,443,000 | 1,607,993,443,000 | 321,511,270 | 3 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,644 | lean | import data.set
import logic.basic
open set
namespace mth1001
section cartesian_product
-- In this file, we'll deal with two types, `U` and `V`.
variables (U : Type*) (V : Type*)
variables (S T : set U) (A B : set V)
/-
`U × V` is the (Cartesian) product type of `U` and `V`. It is the type of all pairs `(u,v)`, where
`u : U` and `v : V`.
-/
#check U × V
/-
WARNING: In Lean, the `×` symbol denotes the Cartesian product of types, not sets. However, we
can use the following special command to make Lean temporarily treat `×` as a set product.
-/
local notation a `×` b := set.prod a b
-- In addition to the results `mem_inter_iff`, `mem_union_eq`, `mem_diff` introduced in
-- the previous files, we'll use `mem_prod` to rewrite a product of two sets.
example (x : prod U V) : x ∈ (S × A) ↔ x.fst ∈ S ∧ x.snd ∈ A := by rw mem_prod
example : (S × (A ∪ B)) = (S × A) ∪ (S × B) :=
begin
ext, -- Assume `x : U × V`. It suffices to prove `x ∈ (S × (A ∪ B)) ↔ x ∈ (S × A) ∪ (S × B)`.
rw [mem_prod, mem_union_eq, mem_union_eq, mem_prod, mem_prod],
rw and_or_distrib_left, -- Complete using left distributivity of `∧` over `∨`.
end
-- Exercise 139:
-- In this example, feel free to use the `tauto` tactic to finish the 'logic' part of the proof.
example : (S × (A ∩ B)) = (S × A) ∩ (S × B) :=
begin
sorry
end
-- Exercise 140:
-- For this example, you'll either need De Morgan's law or the `tauto!` tactic which,
-- unlike `tauto`, is permitted to use classical reasoning.
example : (S × (A \ B)) = (S × A) \ (S × B) :=
begin
sorry
end
end cartesian_product
end mth1001
|
2fe57eb179115a2f50bd88b385018c311fedd31f | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/field_theory/separable.lean | 486eadb1d8959b078f1f41704590e572382de28e | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 29,166 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.polynomial.big_operators
import field_theory.minpoly
import field_theory.splitting_field
import field_theory.tower
import algebra.squarefree
/-!
# Separable polynomials
We define a polynomial to be separable if it is coprime with its derivative. We prove basic
properties about separable polynomials here.
## Main definitions
* `polynomial.separable f`: a polynomial `f` is separable iff it is coprime with its derivative.
* `polynomial.expand R p f`: expand the polynomial `f` with coefficients in a
commutative semiring `R` by a factor of p, so `expand R p (∑ aₙ xⁿ)` is `∑ aₙ xⁿᵖ`.
* `polynomial.contract p f`: the opposite of `expand`, so it sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`.
-/
universes u v w
open_locale classical big_operators
open finset
namespace polynomial
section comm_semiring
variables {R : Type u} [comm_semiring R] {S : Type v} [comm_semiring S]
/-- A polynomial is separable iff it is coprime with its derivative. -/
def separable (f : polynomial R) : Prop :=
is_coprime f f.derivative
lemma separable_def (f : polynomial R) :
f.separable ↔ is_coprime f f.derivative :=
iff.rfl
lemma separable_def' (f : polynomial R) :
f.separable ↔ ∃ a b : polynomial R, a * f + b * f.derivative = 1 :=
iff.rfl
lemma not_separable_zero [nontrivial R] : ¬ separable (0 : polynomial R) :=
begin
rintro ⟨x, y, h⟩,
simpa only [derivative_zero, mul_zero, add_zero, zero_ne_one] using h,
end
lemma separable_one : (1 : polynomial R).separable :=
is_coprime_one_left
lemma separable_X_add_C (a : R) : (X + C a).separable :=
by { rw [separable_def, derivative_add, derivative_X, derivative_C, add_zero],
exact is_coprime_one_right }
lemma separable_X : (X : polynomial R).separable :=
by { rw [separable_def, derivative_X], exact is_coprime_one_right }
lemma separable_C (r : R) : (C r).separable ↔ is_unit r :=
by rw [separable_def, derivative_C, is_coprime_zero_right, is_unit_C]
lemma separable.of_mul_left {f g : polynomial R} (h : (f * g).separable) : f.separable :=
begin
have := h.of_mul_left_left, rw derivative_mul at this,
exact is_coprime.of_mul_right_left (is_coprime.of_add_mul_left_right this)
end
lemma separable.of_mul_right {f g : polynomial R} (h : (f * g).separable) : g.separable :=
by { rw mul_comm at h, exact h.of_mul_left }
lemma separable.of_dvd {f g : polynomial R} (hf : f.separable) (hfg : g ∣ f) : g.separable :=
by { rcases hfg with ⟨f', rfl⟩, exact separable.of_mul_left hf }
lemma separable_gcd_left {F : Type*} [field F] {f : polynomial F}
(hf : f.separable) (g : polynomial F) : (euclidean_domain.gcd f g).separable :=
separable.of_dvd hf (euclidean_domain.gcd_dvd_left f g)
lemma separable_gcd_right {F : Type*} [field F] {g : polynomial F}
(f : polynomial F) (hg : g.separable) : (euclidean_domain.gcd f g).separable :=
separable.of_dvd hg (euclidean_domain.gcd_dvd_right f g)
lemma separable.is_coprime {f g : polynomial R} (h : (f * g).separable) : is_coprime f g :=
begin
have := h.of_mul_left_left, rw derivative_mul at this,
exact is_coprime.of_mul_right_right (is_coprime.of_add_mul_left_right this)
end
theorem separable.of_pow' {f : polynomial R} :
∀ {n : ℕ} (h : (f ^ n).separable), is_unit f ∨ (f.separable ∧ n = 1) ∨ n = 0
| 0 := λ h, or.inr $ or.inr rfl
| 1 := λ h, or.inr $ or.inl ⟨pow_one f ▸ h, rfl⟩
| (n+2) := λ h, by { rw [pow_succ, pow_succ] at h,
exact or.inl (is_coprime_self.1 h.is_coprime.of_mul_right_left) }
theorem separable.of_pow {f : polynomial R} (hf : ¬is_unit f) {n : ℕ} (hn : n ≠ 0)
(hfs : (f ^ n).separable) : f.separable ∧ n = 1 :=
(hfs.of_pow'.resolve_left hf).resolve_right hn
theorem separable.map {p : polynomial R} (h : p.separable) {f : R →+* S} : (p.map f).separable :=
let ⟨a, b, H⟩ := h in ⟨a.map f, b.map f,
by rw [derivative_map, ← map_mul, ← map_mul, ← map_add, H, map_one]⟩
variables (R) (p q : ℕ)
/-- Expand the polynomial by a factor of p, so `∑ aₙ xⁿ` becomes `∑ aₙ xⁿᵖ`. -/
noncomputable def expand : polynomial R →ₐ[R] polynomial R :=
{ commutes' := λ r, eval₂_C _ _,
.. (eval₂_ring_hom C (X ^ p) : polynomial R →+* polynomial R) }
lemma coe_expand : (expand R p : polynomial R → polynomial R) = eval₂ C (X ^ p) := rfl
variables {R}
lemma expand_eq_sum {f : polynomial R} :
expand R p f = f.sum (λ e a, C a * (X ^ p) ^ e) :=
by { dsimp [expand, eval₂], refl, }
@[simp] lemma expand_C (r : R) : expand R p (C r) = C r := eval₂_C _ _
@[simp] lemma expand_X : expand R p X = X ^ p := eval₂_X _ _
@[simp] lemma expand_monomial (r : R) : expand R p (monomial q r) = monomial (q * p) r :=
by simp_rw [monomial_eq_smul_X, alg_hom.map_smul, alg_hom.map_pow, expand_X, mul_comm, pow_mul]
theorem expand_expand (f : polynomial R) : expand R p (expand R q f) = expand R (p * q) f :=
polynomial.induction_on f (λ r, by simp_rw expand_C)
(λ f g ihf ihg, by simp_rw [alg_hom.map_add, ihf, ihg])
(λ n r ih, by simp_rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X,
alg_hom.map_pow, expand_X, pow_mul])
theorem expand_mul (f : polynomial R) : expand R (p * q) f = expand R p (expand R q f) :=
(expand_expand p q f).symm
@[simp] theorem expand_one (f : polynomial R) : expand R 1 f = f :=
polynomial.induction_on f
(λ r, by rw expand_C)
(λ f g ihf ihg, by rw [alg_hom.map_add, ihf, ihg])
(λ n r ih, by rw [alg_hom.map_mul, expand_C, alg_hom.map_pow, expand_X, pow_one])
theorem expand_pow (f : polynomial R) : expand R (p ^ q) f = (expand R p ^[q] f) :=
nat.rec_on q (by rw [pow_zero, expand_one, function.iterate_zero, id]) $ λ n ih,
by rw [function.iterate_succ_apply', pow_succ, expand_mul, ih]
theorem derivative_expand (f : polynomial R) :
(expand R p f).derivative = expand R p f.derivative * (p * X ^ (p - 1)) :=
by rw [coe_expand, derivative_eval₂_C, derivative_pow, derivative_X, mul_one]
theorem coeff_expand {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) :
(expand R p f).coeff n = if p ∣ n then f.coeff (n / p) else 0 :=
begin
simp only [expand_eq_sum],
simp_rw [coeff_sum, ← pow_mul, C_mul_X_pow_eq_monomial, coeff_monomial, sum],
split_ifs with h,
{ rw [finset.sum_eq_single (n/p), nat.mul_div_cancel' h, if_pos rfl],
{ intros b hb1 hb2, rw if_neg, intro hb3, apply hb2, rw [← hb3, nat.mul_div_cancel_left b hp] },
{ intro hn, rw not_mem_support_iff.1 hn, split_ifs; refl } },
{ rw finset.sum_eq_zero, intros k hk, rw if_neg, exact λ hkn, h ⟨k, hkn.symm⟩, },
end
@[simp] theorem coeff_expand_mul {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) :
(expand R p f).coeff (n * p) = f.coeff n :=
by rw [coeff_expand hp, if_pos (dvd_mul_left _ _), nat.mul_div_cancel _ hp]
@[simp] theorem coeff_expand_mul' {p : ℕ} (hp : 0 < p) (f : polynomial R) (n : ℕ) :
(expand R p f).coeff (p * n) = f.coeff n :=
by rw [mul_comm, coeff_expand_mul hp]
theorem expand_inj {p : ℕ} (hp : 0 < p) {f g : polynomial R} :
expand R p f = expand R p g ↔ f = g :=
⟨λ H, ext $ λ n, by rw [← coeff_expand_mul hp, H, coeff_expand_mul hp], congr_arg _⟩
theorem expand_eq_zero {p : ℕ} (hp : 0 < p) {f : polynomial R} : expand R p f = 0 ↔ f = 0 :=
by rw [← (expand R p).map_zero, expand_inj hp, alg_hom.map_zero]
theorem expand_eq_C {p : ℕ} (hp : 0 < p) {f : polynomial R} {r : R} :
expand R p f = C r ↔ f = C r :=
by rw [← expand_C, expand_inj hp, expand_C]
theorem nat_degree_expand (p : ℕ) (f : polynomial R) :
(expand R p f).nat_degree = f.nat_degree * p :=
begin
cases p.eq_zero_or_pos with hp hp,
{ rw [hp, coe_expand, pow_zero, mul_zero, ← C_1, eval₂_hom, nat_degree_C] },
by_cases hf : f = 0,
{ rw [hf, alg_hom.map_zero, nat_degree_zero, zero_mul] },
have hf1 : expand R p f ≠ 0 := mt (expand_eq_zero hp).1 hf,
rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree hf1],
refine le_antisymm ((degree_le_iff_coeff_zero _ _).2 $ λ n hn, _) _,
{ rw coeff_expand hp, split_ifs with hpn,
{ rw coeff_eq_zero_of_nat_degree_lt, contrapose! hn,
rw [with_bot.coe_le_coe, ← nat.div_mul_cancel hpn], exact nat.mul_le_mul_right p hn },
{ refl } },
{ refine le_degree_of_ne_zero _,
rw [coeff_expand_mul hp, ← leading_coeff], exact mt leading_coeff_eq_zero.1 hf }
end
theorem map_expand {p : ℕ} (hp : 0 < p) {f : R →+* S} {q : polynomial R} :
map f (expand R p q) = expand S p (map f q) :=
by { ext, rw [coeff_map, coeff_expand hp, coeff_expand hp], split_ifs; simp, }
/-- Expansion is injective. -/
lemma expand_injective {n : ℕ} (hn : 0 < n) :
function.injective (expand R n) :=
λ g g' h, begin
ext,
have h' : (expand R n g).coeff (n * n_1) = (expand R n g').coeff (n * n_1) :=
begin
apply polynomial.ext_iff.1,
exact h,
end,
rw [polynomial.coeff_expand hn g (n * n_1), polynomial.coeff_expand hn g' (n * n_1)] at h',
simp only [if_true, dvd_mul_right] at h',
rw (nat.mul_div_right n_1 hn) at h',
exact h',
end
end comm_semiring
section comm_ring
variables {R : Type u} [comm_ring R]
lemma separable_X_sub_C {x : R} : separable (X - C x) :=
by simpa only [sub_eq_add_neg, C_neg] using separable_X_add_C (-x)
lemma separable.mul {f g : polynomial R} (hf : f.separable) (hg : g.separable)
(h : is_coprime f g) : (f * g).separable :=
by { rw [separable_def, derivative_mul], exact ((hf.mul_right h).add_mul_left_right _).mul_left
((h.symm.mul_right hg).mul_add_right_right _) }
lemma separable_prod' {ι : Sort*} {f : ι → polynomial R} {s : finset ι} :
(∀x∈s, ∀y∈s, x ≠ y → is_coprime (f x) (f y)) → (∀x∈s, (f x).separable) →
(∏ x in s, f x).separable :=
finset.induction_on s (λ _ _, separable_one) $ λ a s has ih h1 h2, begin
simp_rw [finset.forall_mem_insert, forall_and_distrib] at h1 h2, rw prod_insert has,
exact h2.1.mul (ih h1.2.2 h2.2) (is_coprime.prod_right $ λ i his, h1.1.2 i his $
ne.symm $ ne_of_mem_of_not_mem his has)
end
lemma separable_prod {ι : Sort*} [fintype ι] {f : ι → polynomial R}
(h1 : pairwise (is_coprime on f)) (h2 : ∀ x, (f x).separable) : (∏ x, f x).separable :=
separable_prod' (λ x hx y hy hxy, h1 x y hxy) (λ x hx, h2 x)
lemma separable.inj_of_prod_X_sub_C [nontrivial R] {ι : Sort*} {f : ι → R} {s : finset ι}
(hfs : (∏ i in s, (X - C (f i))).separable)
{x y : ι} (hx : x ∈ s) (hy : y ∈ s) (hfxy : f x = f y) : x = y :=
begin
by_contra hxy,
rw [← insert_erase hx, prod_insert (not_mem_erase _ _),
← insert_erase (mem_erase_of_ne_of_mem (ne.symm hxy) hy),
prod_insert (not_mem_erase _ _), ← mul_assoc, hfxy, ← sq] at hfs,
cases (hfs.of_mul_left.of_pow (by exact not_is_unit_X_sub_C) two_ne_zero).2
end
lemma separable.injective_of_prod_X_sub_C [nontrivial R] {ι : Sort*} [fintype ι] {f : ι → R}
(hfs : (∏ i, (X - C (f i))).separable) : function.injective f :=
λ x y hfxy, hfs.inj_of_prod_X_sub_C (mem_univ _) (mem_univ _) hfxy
lemma is_unit_of_self_mul_dvd_separable {p q : polynomial R}
(hp : p.separable) (hq : q * q ∣ p) : is_unit q :=
begin
obtain ⟨p, rfl⟩ := hq,
apply is_coprime_self.mp,
have : is_coprime (q * (q * p)) (q * (q.derivative * p + q.derivative * p + q * p.derivative)),
{ simp only [← mul_assoc, mul_add],
convert hp,
rw [derivative_mul, derivative_mul],
ring },
exact is_coprime.of_mul_right_left (is_coprime.of_mul_left_left this)
end
end comm_ring
section is_domain
variables (R : Type u) [comm_ring R] [is_domain R]
theorem is_local_ring_hom_expand {p : ℕ} (hp : 0 < p) :
is_local_ring_hom (↑(expand R p) : polynomial R →+* polynomial R) :=
begin
refine ⟨λ f hf1, _⟩, rw ← coe_fn_coe_base at hf1,
have hf2 := eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf1),
rw [coeff_expand hp, if_pos (dvd_zero _), p.zero_div] at hf2,
rw [hf2, is_unit_C] at hf1, rw expand_eq_C hp at hf2, rwa [hf2, is_unit_C]
end
end is_domain
section field
variables {F : Type u} [field F] {K : Type v} [field K]
theorem separable_iff_derivative_ne_zero {f : polynomial F} (hf : irreducible f) :
f.separable ↔ f.derivative ≠ 0 :=
⟨λ h1 h2, hf.not_unit $ is_coprime_zero_right.1 $ h2 ▸ h1,
λ h, is_coprime_of_dvd (mt and.right h) $ λ g hg1 hg2 ⟨p, hg3⟩ hg4,
let ⟨u, hu⟩ := (hf.is_unit_or_is_unit hg3).resolve_left hg1 in
have f ∣ f.derivative, by { conv_lhs { rw [hg3, ← hu] }, rwa units.mul_right_dvd },
not_lt_of_le (nat_degree_le_of_dvd this h) $ nat_degree_derivative_lt h⟩
theorem separable_map (f : F →+* K) {p : polynomial F} : (p.map f).separable ↔ p.separable :=
by simp_rw [separable_def, derivative_map, is_coprime_map]
section char_p
/-- The opposite of `expand`: sends `∑ aₙ xⁿᵖ` to `∑ aₙ xⁿ`. -/
noncomputable def contract (p : ℕ) (f : polynomial F) : polynomial F :=
∑ n in range (f.nat_degree + 1), monomial n (f.coeff (n * p))
variables (p : ℕ) [hp : fact p.prime]
include hp
theorem coeff_contract (f : polynomial F) (n : ℕ) : (contract p f).coeff n = f.coeff (n * p) :=
begin
simp only [contract, coeff_monomial, sum_ite_eq', finset_sum_coeff, mem_range, not_lt,
ite_eq_left_iff],
assume hn,
apply (coeff_eq_zero_of_nat_degree_lt _).symm,
calc f.nat_degree < f.nat_degree + 1 : nat.lt_succ_self _
... ≤ n * 1 : by simpa only [mul_one] using hn
... ≤ n * p : mul_le_mul_of_nonneg_left (@nat.prime.one_lt p (fact.out _)).le (zero_le n)
end
theorem of_irreducible_expand {f : polynomial F} (hf : irreducible (expand F p f)) :
irreducible f :=
@@of_irreducible_map _ _ _ (is_local_ring_hom_expand F hp.1.pos) hf
theorem of_irreducible_expand_pow {f : polynomial F} {n : ℕ} :
irreducible (expand F (p ^ n) f) → irreducible f :=
nat.rec_on n (λ hf, by rwa [pow_zero, expand_one] at hf) $ λ n ih hf,
ih $ of_irreducible_expand p $ by { rw pow_succ at hf, rwa [expand_expand] }
variables [HF : char_p F p]
include HF
theorem expand_char (f : polynomial F) :
map (frobenius F p) (expand F p f) = f ^ p :=
begin
refine f.induction_on' (λ a b ha hb, _) (λ n a, _),
{ rw [alg_hom.map_add, map_add, ha, hb, add_pow_char], },
{ rw [expand_monomial, map_monomial, monomial_eq_C_mul_X, monomial_eq_C_mul_X,
mul_pow, ← C.map_pow, frobenius_def],
ring_exp }
end
theorem map_expand_pow_char (f : polynomial F) (n : ℕ) :
map ((frobenius F p) ^ n) (expand F (p ^ n) f) = f ^ (p ^ n) :=
begin
induction n, { simp [ring_hom.one_def] },
symmetry,
rw [pow_succ', pow_mul, ← n_ih, ← expand_char, pow_succ, ring_hom.mul_def, ← map_map, mul_comm,
expand_mul, ← map_expand (nat.prime.pos hp.1)],
end
theorem expand_contract {f : polynomial F} (hf : f.derivative = 0) :
expand F p (contract p f) = f :=
begin
ext n, rw [coeff_expand hp.1.pos, coeff_contract], split_ifs with h,
{ rw nat.div_mul_cancel h },
{ cases n, { exact absurd (dvd_zero p) h },
have := coeff_derivative f n, rw [hf, coeff_zero, zero_eq_mul] at this, cases this, { rw this },
rw [← nat.cast_succ, char_p.cast_eq_zero_iff F p] at this,
exact absurd this h }
end
theorem separable_or {f : polynomial F} (hf : irreducible f) : f.separable ∨
¬f.separable ∧ ∃ g : polynomial F, irreducible g ∧ expand F p g = f :=
if H : f.derivative = 0 then or.inr
⟨by rw [separable_iff_derivative_ne_zero hf, not_not, H],
contract p f,
by haveI := is_local_ring_hom_expand F hp.1.pos; exact
of_irreducible_map ↑(expand F p) (by rwa ← expand_contract p H at hf),
expand_contract p H⟩
else or.inl $ (separable_iff_derivative_ne_zero hf).2 H
theorem exists_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0) :
∃ (n : ℕ) (g : polynomial F), g.separable ∧ expand F (p ^ n) g = f :=
begin
unfreezingI {
induction hn : f.nat_degree using nat.strong_induction_on with N ih generalizing f },
rcases separable_or p hf with h | ⟨h1, g, hg, hgf⟩,
{ refine ⟨0, f, h, _⟩, rw [pow_zero, expand_one] },
{ cases N with N,
{ rw [nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff] at hn,
rw [hn, separable_C, is_unit_iff_ne_zero, not_not] at h1,
rw [h1, C_0] at hn, exact absurd hn hf0 },
have hg1 : g.nat_degree * p = N.succ,
{ rwa [← nat_degree_expand, hgf] },
have hg2 : g.nat_degree ≠ 0,
{ intro this, rw [this, zero_mul] at hg1, cases hg1 },
have hg3 : g.nat_degree < N.succ,
{ rw [← mul_one g.nat_degree, ← hg1],
exact nat.mul_lt_mul_of_pos_left hp.1.one_lt (nat.pos_of_ne_zero hg2) },
have hg4 : g ≠ 0,
{ rintro rfl, exact hg2 nat_degree_zero },
rcases ih _ hg3 hg hg4 rfl with ⟨n, g, hg5, rfl⟩, refine ⟨n+1, g, hg5, _⟩,
rw [← hgf, expand_expand, pow_succ] }
end
theorem is_unit_or_eq_zero_of_separable_expand {f : polynomial F} (n : ℕ)
(hf : (expand F (p ^ n) f).separable) : is_unit f ∨ n = 0 :=
begin
rw or_iff_not_imp_right, intro hn,
have hf2 : (expand F (p ^ n) f).derivative = 0,
{ by rw [derivative_expand, nat.cast_pow, char_p.cast_eq_zero,
zero_pow (nat.pos_of_ne_zero hn), zero_mul, mul_zero] },
rw [separable_def, hf2, is_coprime_zero_right, is_unit_iff] at hf, rcases hf with ⟨r, hr, hrf⟩,
rw [eq_comm, expand_eq_C (pow_pos hp.1.pos _)] at hrf,
rwa [hrf, is_unit_C]
end
theorem unique_separable_of_irreducible {f : polynomial F} (hf : irreducible f) (hf0 : f ≠ 0)
(n₁ : ℕ) (g₁ : polynomial F) (hg₁ : g₁.separable) (hgf₁ : expand F (p ^ n₁) g₁ = f)
(n₂ : ℕ) (g₂ : polynomial F) (hg₂ : g₂.separable) (hgf₂ : expand F (p ^ n₂) g₂ = f) :
n₁ = n₂ ∧ g₁ = g₂ :=
begin
revert g₁ g₂, wlog hn : n₁ ≤ n₂ := le_total n₁ n₂ using [n₁ n₂, n₂ n₁] tactic.skip,
unfreezingI { intros, rw le_iff_exists_add at hn, rcases hn with ⟨k, rfl⟩,
rw [← hgf₁, pow_add, expand_mul, expand_inj (pow_pos hp.1.pos n₁)] at hgf₂, subst hgf₂,
subst hgf₁,
rcases is_unit_or_eq_zero_of_separable_expand p k hg₁ with h | rfl,
{ rw is_unit_iff at h, rcases h with ⟨r, hr, rfl⟩,
simp_rw expand_C at hf, exact absurd (is_unit_C.2 hr) hf.1 },
{ rw [add_zero, pow_zero, expand_one], split; refl } },
exact λ g₁ g₂ hg₁ hgf₁ hg₂ hgf₂, let ⟨hn, hg⟩ :=
this g₂ g₁ hg₂ hgf₂ hg₁ hgf₁ in ⟨hn.symm, hg.symm⟩
end
end char_p
lemma separable_prod_X_sub_C_iff' {ι : Sort*} {f : ι → F} {s : finset ι} :
(∏ i in s, (X - C (f i))).separable ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) :=
⟨λ hfs x hx y hy hfxy, hfs.inj_of_prod_X_sub_C hx hy hfxy,
λ H, by { rw ← prod_attach, exact separable_prod' (λ x hx y hy hxy,
@pairwise_coprime_X_sub _ _ { x // x ∈ s } (λ x, f x)
(λ x y hxy, subtype.eq $ H x.1 x.2 y.1 y.2 hxy) _ _ hxy)
(λ _ _, separable_X_sub_C) }⟩
lemma separable_prod_X_sub_C_iff {ι : Sort*} [fintype ι] {f : ι → F} :
(∏ i, (X - C (f i))).separable ↔ function.injective f :=
separable_prod_X_sub_C_iff'.trans $ by simp_rw [mem_univ, true_implies_iff, function.injective]
section splits
open_locale big_operators
variables {i : F →+* K}
lemma not_unit_X_sub_C (a : F) : ¬ is_unit (X - C a) :=
λ h, have one_eq_zero : (1 : with_bot ℕ) = 0, by simpa using degree_eq_zero_of_is_unit h,
one_ne_zero (option.some_injective _ one_eq_zero)
lemma nodup_of_separable_prod {s : multiset F}
(hs : separable (multiset.map (λ a, X - C a) s).prod) : s.nodup :=
begin
rw multiset.nodup_iff_ne_cons_cons,
rintros a t rfl,
refine not_unit_X_sub_C a (is_unit_of_self_mul_dvd_separable hs _),
simpa only [multiset.map_cons, multiset.prod_cons] using mul_dvd_mul_left _ (dvd_mul_right _ _)
end
lemma multiplicity_le_one_of_separable {p q : polynomial F} (hq : ¬ is_unit q)
(hsep : separable p) : multiplicity q p ≤ 1 :=
begin
contrapose! hq,
apply is_unit_of_self_mul_dvd_separable hsep,
rw ← sq,
apply multiplicity.pow_dvd_of_le_multiplicity,
simpa only [nat.cast_one, nat.cast_bit0] using enat.add_one_le_of_lt hq
end
lemma separable.squarefree {p : polynomial F} (hsep : separable p) : squarefree p :=
begin
rw multiplicity.squarefree_iff_multiplicity_le_one p,
intro f,
by_cases hunit : is_unit f,
{ exact or.inr hunit },
exact or.inl (multiplicity_le_one_of_separable hunit hsep)
end
/--If `is_unit n` in a nontrivial `comm_ring R`, then `X ^ n - u` is separable for any unit `u`. -/
lemma separable_X_pow_sub_C_unit {R : Type*} [comm_ring R] [nontrivial R] {n : ℕ}
(u : units R) (hn : is_unit (n : R)) : separable (X ^ n - C (u : R)) :=
begin
rcases n.eq_zero_or_pos with rfl | hpos,
{ simpa using hn },
apply (separable_def' (X ^ n - C (u : R))).2,
obtain ⟨n', hn'⟩ := hn.exists_left_inv,
refine ⟨-C ↑u⁻¹, C ↑u⁻¹ * C n' * X, _⟩,
rw [derivative_sub, derivative_C, sub_zero, derivative_pow X n, derivative_X, mul_one],
calc - C ↑u⁻¹ * (X ^ n - C ↑u) + C ↑u⁻¹ * C n' * X * (↑n * X ^ (n - 1))
= C (↑u⁻¹ * ↑ u) - C ↑u⁻¹ * X^n + C ↑ u ⁻¹ * C (n' * ↑n) * (X * X ^ (n - 1)) :
by { simp only [C.map_mul, C_eq_nat_cast], ring }
... = 1 : by simp only [units.inv_mul, hn', C.map_one, mul_one, ← pow_succ,
nat.sub_add_cancel (show 1 ≤ n, from hpos), sub_add_cancel]
end
/--If `n ≠ 0` in `F`, then ` X ^ n - a` is separable for any `a ≠ 0`. -/
lemma separable_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) :
separable (X ^ n - C a) :=
separable_X_pow_sub_C_unit (units.mk0 a ha) (is_unit.mk0 n hn)
-- this can possibly be strengthened to making `separable_X_pow_sub_C_unit` a
-- bi-implication, but it is nontrivial!
/-- In a field `F`, `X ^ n - ↑n` is separable iff `↑n ≠ 0`. -/
lemma X_pow_sub_one_separable_iff {n : ℕ} :
(X ^ n - 1 : polynomial F).separable ↔ (n : F) ≠ 0 :=
begin
refine ⟨_, λ h, separable_X_pow_sub_C_unit 1 (is_unit.mk0 ↑n h)⟩,
rw [separable_def', derivative_sub, derivative_X_pow, derivative_one, sub_zero],
-- Suppose `(n : F) = 0`, then the derivative is `0`, so `X ^ n - 1` is a unit, contradiction.
rintro (h : is_coprime _ _) hn',
rw [← C_eq_nat_cast, hn', C.map_zero, zero_mul, is_coprime_zero_right] at h,
have := not_is_unit_X_pow_sub_one F n,
contradiction
end
/--If `n ≠ 0` in `F`, then ` X ^ n - a` is squarefree for any `a ≠ 0`. -/
lemma squarefree_X_pow_sub_C {n : ℕ} (a : F) (hn : (n : F) ≠ 0) (ha : a ≠ 0) :
squarefree (X ^ n - C a) :=
(separable_X_pow_sub_C a hn ha).squarefree
lemma root_multiplicity_le_one_of_separable {p : polynomial F} (hp : p ≠ 0)
(hsep : separable p) (x : F) : root_multiplicity x p ≤ 1 :=
begin
rw [root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_le_coe, enat.coe_get, nat.cast_one],
exact multiplicity_le_one_of_separable (not_unit_X_sub_C _) hsep
end
lemma count_roots_le_one {p : polynomial F} (hsep : separable p) (x : F) :
p.roots.count x ≤ 1 :=
begin
by_cases hp : p = 0,
{ simp [hp] },
rw count_roots hp,
exact root_multiplicity_le_one_of_separable hp hsep x
end
lemma nodup_roots {p : polynomial F} (hsep : separable p) :
p.roots.nodup :=
multiset.nodup_iff_count_le_one.mpr (count_roots_le_one hsep)
lemma card_root_set_eq_nat_degree [algebra F K] {p : polynomial F} (hsep : p.separable)
(hsplit : splits (algebra_map F K) p) : fintype.card (p.root_set K) = p.nat_degree :=
begin
simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe],
rw [multiset.to_finset_card_of_nodup, ←nat_degree_eq_card_roots hsplit],
exact nodup_roots hsep.map,
end
lemma eq_X_sub_C_of_separable_of_root_eq {x : F} {h : polynomial F} (h_ne_zero : h ≠ 0)
(h_sep : h.separable) (h_root : h.eval x = 0) (h_splits : splits i h)
(h_roots : ∀ y ∈ (h.map i).roots, y = i x) : h = (C (leading_coeff h)) * (X - C x) :=
begin
apply polynomial.eq_X_sub_C_of_splits_of_single_root i h_splits,
apply finset.mk.inj,
{ change _ = {i x},
rw finset.eq_singleton_iff_unique_mem,
split,
{ apply finset.mem_mk.mpr,
rw mem_roots (show h.map i ≠ 0, by exact map_ne_zero h_ne_zero),
rw [is_root.def,←eval₂_eq_eval_map,eval₂_hom,h_root],
exact ring_hom.map_zero i },
{ exact h_roots } },
{ exact nodup_roots (separable.map h_sep) },
end
lemma exists_finset_of_splits
(i : F →+* K) {f : polynomial F} (sep : separable f) (sp : splits i f) :
∃ (s : finset K), f.map i =
C (i f.leading_coeff) * (s.prod (λ a : K, (X : polynomial K) - C a)) :=
begin
classical,
obtain ⟨s, h⟩ := exists_multiset_of_splits i sp,
use s.to_finset,
rw [h, finset.prod_eq_multiset_prod, ←multiset.to_finset_eq],
apply nodup_of_separable_prod,
apply separable.of_mul_right,
rw ←h,
exact sep.map,
end
end splits
end field
end polynomial
open polynomial
theorem irreducible.separable {F : Type u} [field F] [char_zero F] {f : polynomial F}
(hf : irreducible f) : f.separable :=
begin
rw [separable_iff_derivative_ne_zero hf, ne, ← degree_eq_bot, degree_derivative_eq], rintro ⟨⟩,
rw [pos_iff_ne_zero, ne, nat_degree_eq_zero_iff_degree_le_zero, degree_le_zero_iff],
refine λ hf1, hf.not_unit _, rw [hf1, is_unit_C, is_unit_iff_ne_zero],
intro hf2, rw [hf2, C_0] at hf1, exact absurd hf1 hf.ne_zero
end
section comm_ring
variables (F K : Type*) [comm_ring F] [ring K] [algebra F K]
-- TODO: refactor to allow transcendental extensions?
-- See: https://en.wikipedia.org/wiki/Separable_extension#Separability_of_transcendental_extensions
/-- Typeclass for separable field extension: `K` is a separable field extension of `F` iff
the minimal polynomial of every `x : K` is separable.
We define this for general (commutative) rings and only assume `F` and `K` are fields if this
is needed for a proof.
-/
class is_separable : Prop :=
(is_integral' (x : K) : is_integral F x)
(separable' (x : K) : (minpoly F x).separable)
variables (F) {K}
theorem is_separable.is_integral [is_separable F K] :
∀ x : K, is_integral F x := is_separable.is_integral'
theorem is_separable.separable [is_separable F K] :
∀ x : K, (minpoly F x).separable := is_separable.separable'
variables {F K}
theorem is_separable_iff : is_separable F K ↔ ∀ x : K, is_integral F x ∧ (minpoly F x).separable :=
⟨λ h x, ⟨@@is_separable.is_integral F _ _ _ h x, @@is_separable.separable F _ _ _ h x⟩,
λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩
end comm_ring
instance is_separable_self (F : Type*) [field F] : is_separable F F :=
⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact separable_X_sub_C }⟩
/-- A finite field extension in characteristic 0 is separable. -/
@[priority 100] -- See note [lower instance priority]
instance is_separable.of_finite (F K : Type*) [field F] [field K] [algebra F K]
[finite_dimensional F K] [char_zero F] : is_separable F K :=
have ∀ (x : K), is_integral F x,
from λ x, (is_algebraic_iff_is_integral _).mp (algebra.is_algebraic_of_finite _),
⟨this, λ x, (minpoly.irreducible (this x)).separable⟩
section is_separable_tower
variables (F K E : Type*) [field F] [field K] [field E] [algebra F K] [algebra F E]
[algebra K E] [is_scalar_tower F K E]
lemma is_separable_tower_top_of_is_separable [is_separable F E] : is_separable K E :=
⟨λ x, is_integral_of_is_scalar_tower x (is_separable.is_integral F x),
λ x, (is_separable.separable F x).map.of_dvd (minpoly.dvd_map_of_is_scalar_tower _ _ _)⟩
lemma is_separable_tower_bot_of_is_separable [h : is_separable F E] : is_separable F K :=
is_separable_iff.2 $ λ x, begin
refine (is_separable_iff.1 h (algebra_map K E x)).imp
is_integral_tower_bot_of_is_integral_field (λ hs, _),
obtain ⟨q, hq⟩ := minpoly.dvd F x
(is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero_field
(minpoly.aeval F ((algebra_map K E) x))),
rw hq at hs,
exact hs.of_mul_left
end
variables {E}
lemma is_separable.of_alg_hom (E' : Type*) [field E'] [algebra F E']
(f : E →ₐ[F] E') [is_separable F E'] : is_separable F E :=
begin
letI : algebra E E' := ring_hom.to_algebra f.to_ring_hom,
haveI : is_scalar_tower F E E' := is_scalar_tower.of_algebra_map_eq (λ x, (f.commutes x).symm),
exact is_separable_tower_bot_of_is_separable F E E',
end
end is_separable_tower
section card_alg_hom
variables {R S T : Type*} [comm_ring S]
variables {K L F : Type*} [field K] [field L] [field F]
variables [algebra K S] [algebra K L]
lemma alg_hom.card_of_power_basis (pb : power_basis K S) (h_sep : (minpoly K pb.gen).separable)
(h_splits : (minpoly K pb.gen).splits (algebra_map K L)) :
@fintype.card (S →ₐ[K] L) (power_basis.alg_hom.fintype pb) = pb.dim :=
begin
let s := ((minpoly K pb.gen).map (algebra_map K L)).roots.to_finset,
have H := λ x, multiset.mem_to_finset,
rw [fintype.card_congr pb.lift_equiv', fintype.card_of_subtype s H,
← pb.nat_degree_minpoly, nat_degree_eq_card_roots h_splits, multiset.to_finset_card_of_nodup],
exact nodup_roots ((separable_map (algebra_map K L)).mpr h_sep)
end
end card_alg_hom
|
7fd8fda447deb6e4ae255214fccea9269fd7e4c3 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/matrix/transvection.lean | a50b2eb4ab470d621aea842889fc46e57d260b51 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 32,952 | lean | /-
Copyright (c) 2021 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.matrix.basis
import data.matrix.dmatrix
import linear_algebra.matrix.determinant
import linear_algebra.matrix.trace
import linear_algebra.matrix.reindex
import tactic.field_simp
/-!
# Transvections
Transvections are matrices of the form `1 + std_basis_matrix i j c`, where `std_basis_matrix i j c`
is the basic matrix with a `c` at position `(i, j)`. Multiplying by such a transvection on the left
(resp. on the right) amounts to adding `c` times the `j`-th row to to the `i`-th row
(resp `c` times the `i`-th column to the `j`-th column). Therefore, they are useful to present
algorithms operating on rows and columns.
Transvections are a special case of *elementary matrices* (according to most references, these also
contain the matrices exchanging rows, and the matrices multiplying a row by a constant).
We show that, over a field, any matrix can be written as `L ⬝ D ⬝ L'`, where `L` and `L'` are
products of transvections and `D` is diagonal. In other words, one can reduce a matrix to diagonal
form by operations on its rows and columns, a variant of Gauss' pivot algorithm.
## Main definitions and results
* `transvection i j c` is the matrix equal to `1 + std_basis_matrix i j c`.
* `transvection_struct n R` is a structure containing the data of `i, j, c` and a proof that
`i ≠ j`. These are often easier to manipulate than straight matrices, especially in inductive
arguments.
* `exists_list_transvec_mul_diagonal_mul_list_transvec` states that any matrix `M` over a field can
be written in the form `t_1 ⬝ ... ⬝ t_k ⬝ D ⬝ t'_1 ⬝ ... ⬝ t'_l`, where `D` is diagonal and
the `t_i`, `t'_j` are transvections.
* `diagonal_transvection_induction` shows that a property which is true for diagonal matrices and
transvections, and invariant under product, is true for all matrices.
* `diagonal_transvection_induction_of_det_ne_zero` is the same statement over invertible matrices.
## Implementation details
The proof of the reduction results is done inductively on the size of the matrices, reducing an
`(r + 1) × (r + 1)` matrix to a matrix whose last row and column are zeroes, except possibly for
the last diagonal entry. This step is done as follows.
If all the coefficients on the last row and column are zero, there is nothing to do. Otherwise,
one can put a nonzero coefficient in the last diagonal entry by a row or column operation, and then
subtract this last diagonal entry from the other entries in the last row and column to make them
vanish.
This step is done in the type `fin r ⊕ unit`, where `fin r` is useful to choose arbitrarily some
order in which we cancel the coefficients, and the sum structure is useful to use the formalism of
block matrices.
To proceed with the induction, we reindex our matrices to reduce to the above situation.
-/
universes u₁ u₂
namespace matrix
open_locale matrix
variables (n p : Type*) (R : Type u₂) {𝕜 : Type*} [field 𝕜]
variables [decidable_eq n] [decidable_eq p]
variables [comm_ring R]
section transvection
variables {R n} (i j : n)
/-- The transvection matrix `transvection i j c` is equal to the identity plus `c` at position
`(i, j)`. Multiplying by it on the left (as in `transvection i j c ⬝ M`) corresponds to adding
`c` times the `j`-th line of `M` to its `i`-th line. Multiplying by it on the right corresponds
to adding `c` times the `i`-th column to the `j`-th column. -/
def transvection (c : R) : matrix n n R := 1 + matrix.std_basis_matrix i j c
@[simp] lemma transvection_zero : transvection i j (0 : R) = 1 :=
by simp [transvection]
section
/-- A transvection matrix is obtained from the identity by adding `c` times the `j`-th row to
the `i`-th row. -/
lemma update_row_eq_transvection [finite n] (c : R) :
update_row (1 : matrix n n R) i (((1 : matrix n n R)) i + c • (1 : matrix n n R) j) =
transvection i j c :=
begin
casesI nonempty_fintype n,
ext a b,
by_cases ha : i = a, by_cases hb : j = b,
{ simp only [update_row, transvection, ha, hb, function.update_same, std_basis_matrix.apply_same,
pi.add_apply, one_apply_eq, pi.smul_apply, mul_one, algebra.id.smul_eq_mul], },
{ simp only [update_row, transvection, ha, hb, std_basis_matrix.apply_of_ne, function.update_same,
pi.add_apply, ne.def, not_false_iff, pi.smul_apply, and_false, one_apply_ne,
algebra.id.smul_eq_mul, mul_zero] },
{ simp only [update_row, transvection, ha, ne.symm ha, std_basis_matrix.apply_of_ne, add_zero,
algebra.id.smul_eq_mul, function.update_noteq, ne.def, not_false_iff, dmatrix.add_apply,
pi.smul_apply, mul_zero, false_and] },
end
variables [fintype n]
lemma transvection_mul_transvection_same (h : i ≠ j) (c d : R) :
transvection i j c ⬝ transvection i j d = transvection i j (c + d) :=
by simp [transvection, matrix.add_mul, matrix.mul_add, h, h.symm, add_smul, add_assoc,
std_basis_matrix_add]
@[simp] lemma transvection_mul_apply_same (b : n) (c : R) (M : matrix n n R) :
(transvection i j c ⬝ M) i b = M i b + c * M j b :=
by simp [transvection, matrix.add_mul]
@[simp] lemma mul_transvection_apply_same (a : n) (c : R) (M : matrix n n R) :
(M ⬝ transvection i j c) a j = M a j + c * M a i :=
by simp [transvection, matrix.mul_add, mul_comm]
@[simp] lemma transvection_mul_apply_of_ne (a b : n) (ha : a ≠ i) (c : R) (M : matrix n n R) :
(transvection i j c ⬝ M) a b = M a b :=
by simp [transvection, matrix.add_mul, ha]
@[simp] lemma mul_transvection_apply_of_ne (a b : n) (hb : b ≠ j) (c : R) (M : matrix n n R) :
(M ⬝ transvection i j c) a b = M a b :=
by simp [transvection, matrix.mul_add, hb]
@[simp] lemma det_transvection_of_ne (h : i ≠ j) (c : R) : det (transvection i j c) = 1 :=
by rw [← update_row_eq_transvection i j, det_update_row_add_smul_self _ h, det_one]
end
variables (R n)
/-- A structure containing all the information from which one can build a nontrivial transvection.
This structure is easier to manipulate than transvections as one has a direct access to all the
relevant fields. -/
@[nolint has_nonempty_instance]
structure transvection_struct :=
(i j : n)
(hij : i ≠ j)
(c : R)
instance [nontrivial n] : nonempty (transvection_struct n R) :=
by { choose x y hxy using exists_pair_ne n, exact ⟨⟨x, y, hxy, 0⟩⟩ }
namespace transvection_struct
variables {R n}
/-- Associating to a `transvection_struct` the corresponding transvection matrix. -/
def to_matrix (t : transvection_struct n R) : matrix n n R :=
transvection t.i t.j t.c
@[simp] lemma to_matrix_mk (i j : n) (hij : i ≠ j) (c : R) :
transvection_struct.to_matrix ⟨i, j, hij, c⟩ = transvection i j c := rfl
@[simp] protected lemma det [fintype n] (t : transvection_struct n R) : det t.to_matrix = 1 :=
det_transvection_of_ne _ _ t.hij _
@[simp] lemma det_to_matrix_prod [fintype n] (L : list (transvection_struct n 𝕜)) :
det ((L.map to_matrix).prod) = 1 :=
begin
induction L with t L IH,
{ simp },
{ simp [IH], }
end
/-- The inverse of a `transvection_struct`, designed so that `t.inv.to_matrix` is the inverse of
`t.to_matrix`. -/
@[simps] protected def inv (t : transvection_struct n R) : transvection_struct n R :=
{ i := t.i,
j := t.j,
hij := t.hij,
c := - t.c }
section
variable [fintype n]
lemma inv_mul (t : transvection_struct n R) :
t.inv.to_matrix ⬝ t.to_matrix = 1 :=
by { rcases t, simp [to_matrix, transvection_mul_transvection_same, t_hij] }
lemma mul_inv (t : transvection_struct n R) :
t.to_matrix ⬝ t.inv.to_matrix = 1 :=
by { rcases t, simp [to_matrix, transvection_mul_transvection_same, t_hij] }
lemma reverse_inv_prod_mul_prod (L : list (transvection_struct n R)) :
(L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (L.map to_matrix).prod = 1 :=
begin
induction L with t L IH,
{ simp },
{ suffices : (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝
(t.inv.to_matrix ⬝ t.to_matrix) ⬝ (L.map to_matrix).prod = 1, by simpa [matrix.mul_assoc],
simpa [inv_mul] using IH, }
end
lemma prod_mul_reverse_inv_prod (L : list (transvection_struct n R)) :
(L.map to_matrix).prod ⬝ (L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod = 1 :=
begin
induction L with t L IH,
{ simp },
{ suffices : t.to_matrix ⬝ ((L.map to_matrix).prod ⬝
(L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod) ⬝ t.inv.to_matrix = 1,
by simpa [matrix.mul_assoc],
simp_rw [IH, matrix.mul_one, t.mul_inv], }
end
end
variables (p)
open sum
/-- Given a `transvection_struct` on `n`, define the corresponding `transvection_struct` on `n ⊕ p`
using the identity on `p`. -/
def sum_inl (t : transvection_struct n R) : transvection_struct (n ⊕ p) R :=
{ i := inl t.i,
j := inl t.j,
hij := by simp [t.hij],
c := t.c }
lemma to_matrix_sum_inl (t : transvection_struct n R) :
(t.sum_inl p).to_matrix = from_blocks t.to_matrix 0 0 1 :=
begin
cases t,
ext a b,
cases a; cases b,
{ by_cases h : a = b;
simp [transvection_struct.sum_inl, transvection, h, std_basis_matrix], },
{ simp [transvection_struct.sum_inl, transvection] },
{ simp [transvection_struct.sum_inl, transvection] },
{ by_cases h : a = b;
simp [transvection_struct.sum_inl, transvection, h] },
end
@[simp] lemma sum_inl_to_matrix_prod_mul [fintype n] [fintype p]
(M : matrix n n R) (L : list (transvection_struct n R)) (N : matrix p p R) :
(L.map (to_matrix ∘ sum_inl p)).prod ⬝ from_blocks M 0 0 N
= from_blocks ((L.map to_matrix).prod ⬝ M) 0 0 N :=
begin
induction L with t L IH,
{ simp },
{ simp [matrix.mul_assoc, IH, to_matrix_sum_inl, from_blocks_multiply], },
end
@[simp] lemma mul_sum_inl_to_matrix_prod [fintype n] [fintype p]
(M : matrix n n R) (L : list (transvection_struct n R)) (N : matrix p p R) :
(from_blocks M 0 0 N) ⬝ (L.map (to_matrix ∘ sum_inl p)).prod
= from_blocks (M ⬝ (L.map to_matrix).prod) 0 0 N :=
begin
induction L with t L IH generalizing M N,
{ simp },
{ simp [IH, to_matrix_sum_inl, from_blocks_multiply], },
end
variable {p}
/-- Given a `transvection_struct` on `n` and an equivalence between `n` and `p`, define the
corresponding `transvection_struct` on `p`. -/
def reindex_equiv (e : n ≃ p) (t : transvection_struct n R) : transvection_struct p R :=
{ i := e t.i,
j := e t.j,
hij := by simp [t.hij],
c := t.c }
variables [fintype n] [fintype p]
lemma to_matrix_reindex_equiv (e : n ≃ p) (t : transvection_struct n R) :
(t.reindex_equiv e).to_matrix = reindex_alg_equiv R e t.to_matrix :=
begin
cases t,
ext a b,
simp only [reindex_equiv, transvection, mul_boole, algebra.id.smul_eq_mul, to_matrix_mk,
submatrix_apply, reindex_apply, dmatrix.add_apply, pi.smul_apply, reindex_alg_equiv_apply],
by_cases ha : e t_i = a; by_cases hb : e t_j = b; by_cases hab : a = b;
simp [ha, hb, hab, ← e.apply_eq_iff_eq_symm_apply, std_basis_matrix]
end
lemma to_matrix_reindex_equiv_prod (e : n ≃ p) (L : list (transvection_struct n R)) :
(L.map (to_matrix ∘ (reindex_equiv e))).prod = reindex_alg_equiv R e (L.map to_matrix).prod :=
begin
induction L with t L IH,
{ simp },
{ simp only [to_matrix_reindex_equiv, IH, function.comp_app, list.prod_cons, mul_eq_mul,
reindex_alg_equiv_apply, list.map],
exact (reindex_alg_equiv_mul _ _ _ _).symm }
end
end transvection_struct
end transvection
/-!
# Reducing matrices by left and right multiplication by transvections
In this section, we show that any matrix can be reduced to diagonal form by left and right
multiplication by transvections (or, equivalently, by elementary operations on lines and columns).
The main step is to kill the last row and column of a matrix in `fin r ⊕ unit` with nonzero last
coefficient, by subtracting this coefficient from the other ones. The list of these operations is
recorded in `list_transvec_col M` and `list_transvec_row M`. We have to analyze inductively how
these operations affect the coefficients in the last row and the last column to conclude that they
have the desired effect.
Once this is done, one concludes the reduction by induction on the size
of the matrices, through a suitable reindexing to identify any fintype with `fin r ⊕ unit`.
-/
namespace pivot
variables {R} {r : ℕ} (M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜)
open sum unit fin transvection_struct
/-- A list of transvections such that multiplying on the left with these transvections will replace
the last column with zeroes. -/
def list_transvec_col : list (matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :=
list.of_fn $ λ i : fin r, transvection (inl i) (inr star) $
-M (inl i) (inr star) / M (inr star) (inr star)
/-- A list of transvections such that multiplying on the right with these transvections will replace
the last row with zeroes. -/
def list_transvec_row : list (matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :=
list.of_fn $ λ i : fin r, transvection (inr star) (inl i) $
-M (inr star) (inl i) / M (inr star) (inr star)
/-- Multiplying by some of the matrices in `list_transvec_col M` does not change the last row. -/
lemma list_transvec_col_mul_last_row_drop (i : fin r ⊕ unit) {k : ℕ} (hk : k ≤ r) :
(((list_transvec_col M).drop k).prod ⬝ M) (inr star) i = M (inr star) i :=
begin
apply nat.decreasing_induction' _ hk,
{ simp only [list_transvec_col, list.length_of_fn, matrix.one_mul, list.drop_eq_nil_of_le,
list.prod_nil], },
{ assume n hn hk IH,
have hn' : n < (list_transvec_col M).length, by simpa [list_transvec_col] using hn,
rw ← list.cons_nth_le_drop_succ hn',
simpa [list_transvec_col, matrix.mul_assoc] }
end
/-- Multiplying by all the matrices in `list_transvec_col M` does not change the last row. -/
lemma list_transvec_col_mul_last_row (i : fin r ⊕ unit) :
((list_transvec_col M).prod ⬝ M) (inr star) i = M (inr star) i :=
by simpa using list_transvec_col_mul_last_row_drop M i (zero_le _)
/-- Multiplying by all the matrices in `list_transvec_col M` kills all the coefficients in the
last column but the last one. -/
lemma list_transvec_col_mul_last_col (hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
((list_transvec_col M).prod ⬝ M) (inl i) (inr star) = 0 :=
begin
suffices H : ∀ (k : ℕ), k ≤ r → (((list_transvec_col M).drop k).prod ⬝ M) (inl i) (inr star) =
if k ≤ i then 0 else M (inl i) (inr star),
by simpa only [if_true, list.drop.equations._eqn_1] using H 0 (zero_le _),
assume k hk,
apply nat.decreasing_induction' _ hk,
{ simp only [list_transvec_col, list.length_of_fn, matrix.one_mul, list.drop_eq_nil_of_le,
list.prod_nil],
rw if_neg,
simpa only [not_le] using i.2 },
{ assume n hn hk IH,
have hn' : n < (list_transvec_col M).length, by simpa [list_transvec_col] using hn,
let n' : fin r := ⟨n, hn⟩,
rw ← list.cons_nth_le_drop_succ hn',
have A : (list_transvec_col M).nth_le n hn' = transvection (inl n') (inr star)
(-M (inl n') (inr star) / M (inr star) (inr star)), by simp [list_transvec_col],
simp only [matrix.mul_assoc, A, matrix.mul_eq_mul, list.prod_cons],
by_cases h : n' = i,
{ have hni : n = i,
{ cases i, simp only [fin.mk_eq_mk] at h, simp [h] },
rw [h, transvection_mul_apply_same, IH, list_transvec_col_mul_last_row_drop _ _ hn, ← hni],
field_simp [hM] },
{ have hni : n ≠ i,
{ rintros rfl, cases i, simpa using h },
simp only [transvection_mul_apply_of_ne, ne.def, not_false_iff, ne.symm h],
rw IH,
rcases le_or_lt (n+1) i with hi|hi,
{ simp only [hi, n.le_succ.trans hi, if_true] },
{ rw [if_neg, if_neg],
{ simpa only [hni.symm, not_le, or_false] using nat.lt_succ_iff_lt_or_eq.1 hi },
{ simpa only [not_le] using hi } } } }
end
/-- Multiplying by some of the matrices in `list_transvec_row M` does not change the last column. -/
lemma mul_list_transvec_row_last_col_take (i : fin r ⊕ unit) {k : ℕ} (hk : k ≤ r) :
(M ⬝ ((list_transvec_row M).take k).prod) i (inr star) = M i (inr star) :=
begin
induction k with k IH,
{ simp only [matrix.mul_one, list.take_zero, list.prod_nil], },
{ have hkr : k < r := hk,
let k' : fin r := ⟨k, hkr⟩,
have : (list_transvec_row M).nth k = ↑(transvection (inr unit.star) (inl k')
(-M (inr unit.star) (inl k') / M (inr unit.star) (inr unit.star))),
{ simp only [list_transvec_row, list.of_fn_nth_val, hkr, dif_pos, list.nth_of_fn], refl },
simp only [list.take_succ, ← matrix.mul_assoc, this, list.prod_append, matrix.mul_one,
matrix.mul_eq_mul, list.prod_cons, list.prod_nil, option.to_list_some],
rw [mul_transvection_apply_of_ne, IH hkr.le],
simp only [ne.def, not_false_iff], }
end
/-- Multiplying by all the matrices in `list_transvec_row M` does not change the last column. -/
lemma mul_list_transvec_row_last_col (i : fin r ⊕ unit) :
(M ⬝ (list_transvec_row M).prod) i (inr star) = M i (inr star) :=
begin
have A : (list_transvec_row M).length = r, by simp [list_transvec_row],
rw [← list.take_length (list_transvec_row M), A],
simpa using mul_list_transvec_row_last_col_take M i le_rfl,
end
/-- Multiplying by all the matrices in `list_transvec_row M` kills all the coefficients in the
last row but the last one. -/
lemma mul_list_transvec_row_last_row (hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
(M ⬝ (list_transvec_row M).prod) (inr star) (inl i) = 0 :=
begin
suffices H : ∀ (k : ℕ), k ≤ r → (M ⬝ ((list_transvec_row M).take k).prod) (inr star) (inl i) =
if k ≤ i then M (inr star) (inl i) else 0,
{ have A : (list_transvec_row M).length = r, by simp [list_transvec_row],
rw [← list.take_length (list_transvec_row M), A],
have : ¬ (r ≤ i), by simp,
simpa only [this, ite_eq_right_iff] using H r le_rfl },
assume k hk,
induction k with n IH,
{ simp only [if_true, matrix.mul_one, list.take_zero, zero_le', list.prod_nil] },
{ have hnr : n < r := hk,
let n' : fin r := ⟨n, hnr⟩,
have A : (list_transvec_row M).nth n = ↑(transvection (inr unit.star) (inl n')
(-M (inr unit.star) (inl n') / M (inr unit.star) (inr unit.star))),
{ simp only [list_transvec_row, list.of_fn_nth_val, hnr, dif_pos, list.nth_of_fn], refl },
simp only [list.take_succ, A, ← matrix.mul_assoc, list.prod_append, matrix.mul_one,
matrix.mul_eq_mul, list.prod_cons, list.prod_nil, option.to_list_some],
by_cases h : n' = i,
{ have hni : n = i,
{ cases i, simp only [fin.mk_eq_mk] at h, simp only [h, coe_mk] },
have : ¬ (n.succ ≤ i), by simp only [← hni, n.lt_succ_self, not_le],
simp only [h, mul_transvection_apply_same, list.take, if_false,
mul_list_transvec_row_last_col_take _ _ hnr.le, hni.le, this, if_true, IH hnr.le],
field_simp [hM] },
{ have hni : n ≠ i,
{ rintros rfl, cases i, simpa using h },
simp only [IH hnr.le, ne.def, mul_transvection_apply_of_ne, not_false_iff, ne.symm h],
rcases le_or_lt (n+1) i with hi|hi,
{ simp [hi, n.le_succ.trans hi, if_true], },
{ rw [if_neg, if_neg],
{ simpa only [not_le] using hi },
{ simpa only [hni.symm, not_le, or_false] using nat.lt_succ_iff_lt_or_eq.1 hi } } } }
end
/-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` kills
all the coefficients in the last row but the last one. -/
lemma list_transvec_col_mul_mul_list_transvec_row_last_col
(hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) (inr star) (inl i) = 0 :=
begin
have : list_transvec_row M = list_transvec_row ((list_transvec_col M).prod ⬝ M),
by simp [list_transvec_row, list_transvec_col_mul_last_row],
rw this,
apply mul_list_transvec_row_last_row,
simpa [list_transvec_col_mul_last_row] using hM
end
/-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` kills
all the coefficients in the last column but the last one. -/
lemma list_transvec_col_mul_mul_list_transvec_row_last_row
(hM : M (inr star) (inr star) ≠ 0) (i : fin r) :
((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) (inl i) (inr star) = 0 :=
begin
have : list_transvec_col M = list_transvec_col (M ⬝ (list_transvec_row M).prod),
by simp [list_transvec_col, mul_list_transvec_row_last_col],
rw [this, matrix.mul_assoc],
apply list_transvec_col_mul_last_col,
simpa [mul_list_transvec_row_last_col] using hM
end
/-- Multiplying by all the matrices either in `list_transvec_col M` and `list_transvec_row M` turns
the matrix in block-diagonal form. -/
lemma is_two_block_diagonal_list_transvec_col_mul_mul_list_transvec_row
(hM : M (inr star) (inr star) ≠ 0) :
is_two_block_diagonal ((list_transvec_col M).prod ⬝ M ⬝ (list_transvec_row M).prod) :=
begin
split,
{ ext i j,
have : j = star, by simp only [eq_iff_true_of_subsingleton],
simp [to_blocks₁₂, this, list_transvec_col_mul_mul_list_transvec_row_last_row M hM] },
{ ext i j,
have : i = star, by simp only [eq_iff_true_of_subsingleton],
simp [to_blocks₂₁, this, list_transvec_col_mul_mul_list_transvec_row_last_col M hM] },
end
/-- There exist two lists of `transvection_struct` such that multiplying by them on the left and
on the right makes a matrix block-diagonal, when the last coefficient is nonzero. -/
lemma exists_is_two_block_diagonal_of_ne_zero (hM : M (inr star) (inr star) ≠ 0) :
∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)),
is_two_block_diagonal ((L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod) :=
begin
let L : list (transvection_struct (fin r ⊕ unit) 𝕜) :=
list.of_fn (λ i : fin r, ⟨inl i, inr star, by simp,
-M (inl i) (inr star) / M (inr star) (inr star)⟩),
let L' : list (transvection_struct (fin r ⊕ unit) 𝕜) :=
list.of_fn (λ i : fin r, ⟨inr star, inl i, by simp,
-M (inr star) (inl i) / M (inr star) (inr star)⟩),
refine ⟨L, L', _⟩,
have A : L.map to_matrix = list_transvec_col M, by simp [L, list_transvec_col, (∘)],
have B : L'.map to_matrix = list_transvec_row M, by simp [L, list_transvec_row, (∘)],
rw [A, B],
exact is_two_block_diagonal_list_transvec_col_mul_mul_list_transvec_row M hM
end
/-- There exist two lists of `transvection_struct` such that multiplying by them on the left and
on the right makes a matrix block-diagonal. -/
lemma exists_is_two_block_diagonal_list_transvec_mul_mul_list_transvec
(M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :
∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)),
is_two_block_diagonal ((L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod) :=
begin
by_cases H : is_two_block_diagonal M, { refine ⟨list.nil, list.nil, by simpa using H⟩ },
-- we have already proved this when the last coefficient is nonzero
by_cases hM : M (inr star) (inr star) ≠ 0,
{ exact exists_is_two_block_diagonal_of_ne_zero M hM },
-- when the last coefficient is zero but there is a nonzero coefficient on the last row or the
-- last column, we will first put this nonzero coefficient in last position, and then argue as
-- above.
push_neg at hM,
simp [not_and_distrib, is_two_block_diagonal, to_blocks₁₂, to_blocks₂₁, ←matrix.ext_iff] at H,
have : ∃ (i : fin r), M (inl i) (inr star) ≠ 0 ∨ M (inr star) (inl i) ≠ 0,
{ cases H,
{ contrapose! H,
rintros i ⟨⟩,
exact (H i).1 },
{ contrapose! H,
rintros ⟨⟩ j,
exact (H j).2, } },
rcases this with ⟨i, h|h⟩,
{ let M' := transvection (inr unit.star) (inl i) 1 ⬝ M,
have hM' : M' (inr star) (inr star) ≠ 0, by simpa [M', hM],
rcases exists_is_two_block_diagonal_of_ne_zero M' hM' with ⟨L, L', hLL'⟩,
rw matrix.mul_assoc at hLL',
refine ⟨L ++ [⟨inr star, inl i, by simp, 1⟩], L', _⟩,
simp only [list.map_append, list.prod_append, matrix.mul_one, to_matrix_mk, list.prod_cons,
list.prod_nil, mul_eq_mul, list.map, matrix.mul_assoc (L.map to_matrix).prod],
exact hLL' },
{ let M' := M ⬝ transvection (inl i) (inr star) 1,
have hM' : M' (inr star) (inr star) ≠ 0, by simpa [M', hM],
rcases exists_is_two_block_diagonal_of_ne_zero M' hM' with ⟨L, L', hLL'⟩,
refine ⟨L, ⟨inl i, inr star, by simp, 1⟩ :: L', _⟩,
simp only [←matrix.mul_assoc, to_matrix_mk, list.prod_cons, mul_eq_mul, list.map],
rw [matrix.mul_assoc (L.map to_matrix).prod],
exact hLL' }
end
/-- Inductive step for the reduction: if one knows that any size `r` matrix can be reduced to
diagonal form by elementary operations, then one deduces it for matrices over `fin r ⊕ unit`. -/
lemma exists_list_transvec_mul_mul_list_transvec_eq_diagonal_induction
(IH : ∀ (M : matrix (fin r) (fin r) 𝕜),
∃ (L₀ L₀' : list (transvection_struct (fin r) 𝕜)) (D₀ : (fin r) → 𝕜),
(L₀.map to_matrix).prod ⬝ M ⬝ (L₀'.map to_matrix).prod = diagonal D₀)
(M : matrix (fin r ⊕ unit) (fin r ⊕ unit) 𝕜) :
∃ (L L' : list (transvection_struct (fin r ⊕ unit) 𝕜)) (D : fin r ⊕ unit → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
rcases exists_is_two_block_diagonal_list_transvec_mul_mul_list_transvec M with ⟨L₁, L₁', hM⟩,
let M' := (L₁.map to_matrix).prod ⬝ M ⬝ (L₁'.map to_matrix).prod,
let M'' := to_blocks₁₁ M',
rcases IH M'' with ⟨L₀, L₀', D₀, h₀⟩,
set c := M' (inr star) (inr star) with hc,
refine ⟨L₀.map (sum_inl unit) ++ L₁, L₁' ++ L₀'.map (sum_inl unit),
sum.elim D₀ (λ _, M' (inr star) (inr star)), _⟩,
suffices :
(L₀.map (to_matrix ∘ sum_inl unit)).prod ⬝ M' ⬝ (L₀'.map (to_matrix ∘ sum_inl unit)).prod =
diagonal (sum.elim D₀ (λ _, c)), by simpa [M', matrix.mul_assoc, c],
have : M' = from_blocks M'' 0 0 (diagonal (λ _, c)),
{ rw ← from_blocks_to_blocks M',
congr,
{ exact hM.1 },
{ exact hM.2 },
{ ext ⟨⟩ ⟨⟩, rw [hc, to_blocks₂₂, of_apply], refl, } },
rw this,
simp [h₀],
end
variables {n p} [fintype n] [fintype p]
/-- Reduction to diagonal form by elementary operations is invariant under reindexing. -/
lemma reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal (M : matrix p p 𝕜) (e : p ≃ n)
(H : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
(L.map to_matrix).prod ⬝ (matrix.reindex_alg_equiv 𝕜 e M) ⬝ (L'.map to_matrix).prod
= diagonal D) :
∃ (L L' : list (transvection_struct p 𝕜)) (D : p → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
rcases H with ⟨L₀, L₀', D₀, h₀⟩,
refine ⟨L₀.map (reindex_equiv e.symm), L₀'.map (reindex_equiv e.symm), D₀ ∘ e, _⟩,
have : M = reindex_alg_equiv 𝕜 e.symm (reindex_alg_equiv 𝕜 e M),
by simp only [equiv.symm_symm, submatrix_submatrix, reindex_apply, submatrix_id_id,
equiv.symm_comp_self, reindex_alg_equiv_apply],
rw this,
simp only [to_matrix_reindex_equiv_prod, list.map_map, reindex_alg_equiv_apply],
simp only [← reindex_alg_equiv_apply, ← reindex_alg_equiv_mul, h₀],
simp only [equiv.symm_symm, reindex_apply, submatrix_diagonal_equiv, reindex_alg_equiv_apply],
end
/-- Any matrix can be reduced to diagonal form by elementary operations. Formulated here on `Type 0`
because we will make an induction using `fin r`.
See `exists_list_transvec_mul_mul_list_transvec_eq_diagonal` for the general version (which follows
from this one and reindexing). -/
lemma exists_list_transvec_mul_mul_list_transvec_eq_diagonal_aux
(n : Type) [fintype n] [decidable_eq n]
(M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
unfreezingI { induction hn : fintype.card n with r IH generalizing n M },
{ refine ⟨list.nil, list.nil, λ _, 1, _⟩,
ext i j,
rw fintype.card_eq_zero_iff at hn,
exact hn.elim' i },
{ have e : n ≃ fin r ⊕ unit,
{ refine fintype.equiv_of_card_eq _,
rw hn,
convert (@fintype.card_sum (fin r) unit _ _).symm,
simp },
apply reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal M e,
apply exists_list_transvec_mul_mul_list_transvec_eq_diagonal_induction
(λ N, IH (fin r) N (by simp)) }
end
/-- Any matrix can be reduced to diagonal form by elementary operations. -/
theorem exists_list_transvec_mul_mul_list_transvec_eq_diagonal
(M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
(L.map to_matrix).prod ⬝ M ⬝ (L'.map to_matrix).prod = diagonal D :=
begin
have e : n ≃ fin (fintype.card n) := fintype.equiv_of_card_eq (by simp),
apply reindex_exists_list_transvec_mul_mul_list_transvec_eq_diagonal M e,
apply exists_list_transvec_mul_mul_list_transvec_eq_diagonal_aux
end
/-- Any matrix can be written as the product of transvections, a diagonal matrix, and
transvections.-/
theorem exists_list_transvec_mul_diagonal_mul_list_transvec
(M : matrix n n 𝕜) : ∃ (L L' : list (transvection_struct n 𝕜)) (D : n → 𝕜),
M = (L.map to_matrix).prod ⬝ diagonal D ⬝ (L'.map to_matrix).prod :=
begin
rcases exists_list_transvec_mul_mul_list_transvec_eq_diagonal M with ⟨L, L', D, h⟩,
refine ⟨L.reverse.map transvection_struct.inv, L'.reverse.map transvection_struct.inv, D, _⟩,
suffices : M =
((L.reverse.map (to_matrix ∘ transvection_struct.inv)).prod ⬝ (L.map to_matrix).prod) ⬝ M ⬝
((L'.map to_matrix).prod ⬝ (L'.reverse.map (to_matrix ∘ transvection_struct.inv)).prod),
by simpa [← h, matrix.mul_assoc],
rw [reverse_inv_prod_mul_prod, prod_mul_reverse_inv_prod, matrix.one_mul, matrix.mul_one],
end
end pivot
open pivot transvection_struct
variables {n} [fintype n]
/-- Induction principle for matrices based on transvections: if a property is true for all diagonal
matrices, all transvections, and is stable under product, then it is true for all matrices. This is
the useful way to say that matrices are generated by diagonal matrices and transvections.
We state a slightly more general version: to prove a property for a matrix `M`, it suffices to
assume that the diagonal matrices we consider have the same determinant as `M`. This is useful to
obtain similar principles for `SLₙ` or `GLₙ`. -/
lemma diagonal_transvection_induction (P : matrix n n 𝕜 → Prop) (M : matrix n n 𝕜)
(hdiag : ∀ D : n → 𝕜, det (diagonal D) = det M → P (diagonal D))
(htransvec : ∀ (t : transvection_struct n 𝕜), P t.to_matrix)
(hmul : ∀ A B, P A → P B → P (A ⬝ B)) :
P M :=
begin
rcases exists_list_transvec_mul_diagonal_mul_list_transvec M with ⟨L, L', D, h⟩,
have PD : P (diagonal D) := hdiag D (by simp [h]),
suffices H : ∀ (L₁ L₂ : list (transvection_struct n 𝕜)) (E : matrix n n 𝕜),
P E → P ((L₁.map to_matrix).prod ⬝ E ⬝ (L₂.map to_matrix).prod),
by { rw h, apply H L L', exact PD },
assume L₁ L₂ E PE,
induction L₁ with t L₁ IH,
{ simp only [matrix.one_mul, list.prod_nil, list.map],
induction L₂ with t L₂ IH generalizing E,
{ simpa },
{ simp only [←matrix.mul_assoc, list.prod_cons, mul_eq_mul, list.map],
apply IH,
exact hmul _ _ PE (htransvec _) } },
{ simp only [matrix.mul_assoc, list.prod_cons, mul_eq_mul, list.map] at ⊢ IH,
exact hmul _ _ (htransvec _) IH }
end
/-- Induction principle for invertible matrices based on transvections: if a property is true for
all invertible diagonal matrices, all transvections, and is stable under product of invertible
matrices, then it is true for all invertible matrices. This is the useful way to say that
invertible matrices are generated by invertible diagonal matrices and transvections. -/
lemma diagonal_transvection_induction_of_det_ne_zero (P : matrix n n 𝕜 → Prop)
(M : matrix n n 𝕜) (hMdet : det M ≠ 0)
(hdiag : ∀ D : n → 𝕜, det (diagonal D) ≠ 0 → P (diagonal D))
(htransvec : ∀ (t : transvection_struct n 𝕜), P t.to_matrix)
(hmul : ∀ A B, det A ≠ 0 → det B ≠ 0 → P A → P B → P (A ⬝ B)) :
P M :=
begin
let Q : matrix n n 𝕜 → Prop := λ N, det N ≠ 0 ∧ P N,
have : Q M,
{ apply diagonal_transvection_induction Q M,
{ assume D hD,
have detD : det (diagonal D) ≠ 0, by { rw hD, exact hMdet },
exact ⟨detD, hdiag _ detD⟩ },
{ assume t,
exact ⟨by simp, htransvec t⟩ },
{ assume A B QA QB,
exact ⟨by simp [QA.1, QB.1], hmul A B QA.1 QB.1 QA.2 QB.2⟩ } },
exact this.2
end
end matrix
|
8661ad0ba7c7f061d2aeb731c9cd511b6df1c9a6 | ea4aee6b11f86433e69bb5e50d0259e056d0ae61 | /src/tidy/automatic_induction.lean | 9cde037eb4206787b0d32e4e204936440f5cb839 | [] | no_license | timjb/lean-tidy | e18feff0b7f0aad08c614fb4d34aaf527bf21e20 | e767e259bf76c69edfd4ab8af1b76e6f1ed67f48 | refs/heads/master | 1,624,861,693,182 | 1,504,411,006,000 | 1,504,411,006,000 | 103,740,824 | 0 | 0 | null | 1,505,553,968,000 | 1,505,553,968,000 | null | UTF-8 | Lean | false | false | 1,284 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import .at_least_one
open tactic
meta def new_names ( e : expr ) : tactic (list name) :=
do
n1 ← get_unused_name e.local_pp_name (some 1),
n2 ← get_unused_name e.local_pp_name (some 2),
pure [ n1, n2 ]
-- TODO better automatic naming of introduced hypotheses
meta def automatic_induction_at (h : expr) : tactic unit :=
do t ← infer_type h,
match t with
| `(unit) := induction h >> skip
| `(punit) := induction h >> skip
| `(false) := induction h >> skip
| `(empty) := induction h >> skip
| `(fin nat.zero) := induction h >> `[cases is_lt]
| `(ulift _) := induction h >> skip
| `(plift _) := induction h >> skip
| `(eq _ _) := induction h >> skip
| `(prod _ _) := do names ← new_names h,
induction h >> skip
| `(sigma _) := do names ← new_names h,
induction h >> skip
| `(subtype _) := do names ← new_names h,
induction h names >> skip
| _ := failed
end
meta def automatic_induction : tactic unit :=
do l ← local_context,
at_least_one (l.reverse.map(λ h, automatic_induction_at h)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.