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
8a0dc8b68d80f1a19fa366d52db98dd846d488c6
46125763b4dbf50619e8846a1371029346f4c3db
/src/order/bounded_lattice.lean
0812118cd38f6d71fd17d531c37e51727bc3b9fe
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
29,854
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 Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import order.lattice data.option.basic tactic.pi_instances set_option old_structure_cmd true universes u v namespace lattice variable {α : Type u} /-- Typeclass for the `⊤` (`\top`) notation -/ class has_top (α : Type u) := (top : α) /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_bot (α : Type u) := (bot : α) notation `⊤` := has_top.top _ notation `⊥` := has_bot.bot _ attribute [pattern] lattice.has_bot.bot lattice.has_top.top section prio set_option default_priority 100 -- see Note [default priority] /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α := (le_top : ∀ a : α, a ≤ ⊤) end prio section order_top variables [order_top α] {a b : α} @[simp] theorem le_top : a ≤ ⊤ := order_top.le_top a theorem top_unique (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a := ⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩ @[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ := ⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩ @[simp] theorem not_top_lt : ¬ ⊤ < a := assume h, lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := top_le_iff.1 $ h₂ ▸ h lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ := begin haveI := classical.dec_eq α, haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff, by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)] end lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ := lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := assume ha, hb $ top_unique $ ha ▸ hab end order_top theorem order_top.ext_top {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊤ : α) = ⊤ := top_unique $ by rw ← H; apply le_top theorem order_top.ext {α} {A B : order_top α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have tt := order_top.ext_top H, cases A; cases B; injection this; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α := (bot_le : ∀ a : α, ⊥ ≤ a) end prio section order_bot variables [order_bot α] {a b : α} @[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ := ⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩ @[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ := ⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩ @[simp] theorem not_lt_bot : ¬ a < ⊥ := assume h, lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := assume ha, hb $ bot_unique $ ha ▸ hab theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := le_bot_iff.1 $ h₂ ▸ h lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ := begin haveI := classical.dec_eq α, haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff, simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)] end lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ := bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h end order_bot theorem order_bot.ext_bot {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : (by haveI := A; exact ⊥ : α) = ⊥ := bot_unique $ by rw ← H; apply bot_le theorem order_bot.ext {α} {A B : order_bot α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI this := partial_order.ext H, have tt := order_bot.ext_bot H, cases A; cases B; injection this; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α end prio section semilattice_sup_top variables [semilattice_sup_top α] {a : α} @[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top end semilattice_sup_top section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α end prio section semilattice_sup_bot variables [semilattice_sup_bot α] {a b : α} @[simp] theorem bot_sup_eq : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) := by rw [eq_bot_iff, sup_le_iff]; simp end semilattice_sup_bot instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := { bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice } private def bot_aux (s : set ℕ) [decidable_pred s] [h : nonempty s] : s := have ∃ x, x ∈ s, from nonempty.elim h (λ x, ⟨x.1, x.2⟩), ⟨nat.find this, nat.find_spec this⟩ instance nat.subtype.semilattice_sup_bot (s : set ℕ) [decidable_pred s] [h : nonempty s] : semilattice_sup_bot s := { bot := bot_aux s, bot_le := λ x, nat.find_min' _ x.2, ..subtype.linear_order s, ..lattice.lattice_of_decidable_linear_order } section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α end prio section semilattice_inf_top variables [semilattice_inf_top α] {a b : α} @[simp] theorem top_inf_eq : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) := by rw [eq_top_iff, le_inf_iff]; simp end semilattice_inf_top section prio set_option default_priority 100 -- see Note [default priority] /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α end prio section semilattice_inf_bot variables [semilattice_inf_bot α] {a : α} @[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le end semilattice_inf_bot /- Bounded lattices -/ section prio set_option default_priority 100 -- see Note [default priority] /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α end prio @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := { le_top := assume x, @le_top α _ x, ..bl } @[priority 100] -- see Note [lower instance priority] instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := { bot_le := assume x, @bot_le α _ x, ..bl } theorem bounded_lattice.ext {α} {A B : bounded_lattice α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin haveI H1 : @bounded_lattice.to_lattice α A = @bounded_lattice.to_lattice α B := lattice.ext H, haveI H2 := order_bot.ext H, haveI H3 : @bounded_lattice.to_order_top α A = @bounded_lattice.to_order_top α B := order_top.ext H, have tt := order_bot.ext_bot H, cases A; cases B; injection H1; injection H2; injection H3; congr' end section prio set_option default_priority 100 -- see Note [default priority] /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α end prio lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := ⟨assume : a ⊓ b = ⊥, calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁] ... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left] ... ≤ c : by simp [this, inf_le_right], assume : a ≤ c, bot_unique $ calc a ⊓ b ≤ b ⊓ c : by rw [inf_comm]; exact inf_le_inf (le_refl _) this ... = ⊥ : h₂⟩ /- Prop instance -/ instance bounded_lattice_Prop : bounded_lattice Prop := { lattice.bounded_lattice . le := λa b, a → b, le_refl := assume _, id, le_trans := assume a b c f g, g ∘ f, le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩, sup := or, le_sup_left := @or.inl, le_sup_right := @or.inr, sup_le := assume a b c, or.rec, inf := and, inf_le_left := @and.left, inf_le_right := @and.right, le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha), top := true, le_top := assume a Ha, true.intro, bot := false, bot_le := @false.elim } section logic variable [preorder α] theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∧ q x) := assume a b h, and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone (λx, p x ∨ q x) := assume a b h, or.imp (m_p h) (m_q h) end logic /- Function lattices -/ /- TODO: * build up the lattice hierarchy for `fun`-functor piecewise. semilattic_*, bounded_lattice, lattice ... * can this be generalized to the dependent function space? -/ instance pi.bounded_lattice {α : Type u} {β : Type v} [bounded_lattice β] : bounded_lattice (α → β) := by pi_instance end lattice def with_bot (α : Type*) := option α namespace with_bot variable {α : Type u} open lattice meta instance {α} [has_to_format α] : has_to_format (with_bot α) := { to_format := λ x, match x with | none := "⊥" | (some x) := to_fmt x end } instance : has_coe_t α (with_bot α) := ⟨some⟩ instance has_bot : has_bot (with_bot α) := ⟨none⟩ instance : inhabited (with_bot α) := ⟨⊥⟩ lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[priority 10] instance has_lt [has_lt α] : has_lt (with_bot α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b := by simp [(<)] instance [preorder α] : preorder (with_bot α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b, lt := (<), lt_iff_le_not_le := by intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<)]; split; refl, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha, let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in ⟨c, hc, le_trans ab bc⟩ } instance partial_order [partial_order α] : partial_order (with_bot α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₁ with a, { cases o₂ with b, {refl}, rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩, rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_bot.preorder } instance order_bot [partial_order α] : order_bot (with_bot α) := { bot_le := λ a a' h, option.no_confusion h, ..with_bot.partial_order, ..with_bot.has_bot } @[simp] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_bot α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩ @[simp] theorem some_le_some [partial_order α] {a b : α} : @has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe theorem coe_le [partial_order α] {a b : α} : ∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b) | _ rfl := coe_le_coe lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some lemma bot_lt_some [partial_order α] (a : α) : (⊥ : with_bot α) < some a := lt_of_le_of_ne bot_le (λ h, option.no_confusion h) lemma bot_lt_coe [partial_order α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a instance linear_order [linear_order α] : linear_order (with_bot α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inl bot_le}, cases o₂ with b, {exact or.inr bot_le}, simp [le_total] end, ..with_bot.partial_order } instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<) | none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩ | (some x) (some y) := if h : x < y then is_true $ by simp * else is_false $ by simp * | x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩ instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_bot α) := { decidable_le := λ a b, begin cases a with a, { exact is_true bot_le }, cases b with b, { exact is_false (mt (le_antisymm bot_le) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_bot.linear_order } instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) := { sup := option.lift_or_get (⊔), le_sup_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], le_sup_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₁ with b; cases o₂ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, sup_le h₁' h₂⟩ } end, ..with_bot.order_bot } instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) := { inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)), inf_le_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_left⟩ end, inf_le_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, inf_le_right⟩ end, le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, le_inf ab ac⟩ end, ..with_bot.order_bot } instance lattice [lattice α] : lattice (with_bot α) := { ..with_bot.semilattice_sup, ..with_bot.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice.lattice_of_decidable_linear_order = @with_bot.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_bot α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_bot α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_top [order_top α] : order_top (with_bot α) := { top := some ⊤, le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩, ..with_bot.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) := { ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot } lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_bot α → with_bot α → Prop) := have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ := acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim), ⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot) (λ b, well_founded.induction h b (show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a → acc ((<) : with_bot α → with_bot α → Prop) b, from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot) (λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := ⟨ assume a b, match a, b with | a, none := assume h : a < ⊥, (not_lt_bot h).elim | none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ end with_bot --TODO(Mario): Construct using order dual on with_bot def with_top (α : Type*) := option α namespace with_top variable {α : Type u} open lattice meta instance {α} [has_to_format α] : has_to_format (with_top α) := { to_format := λ x, match x with | none := "⊤" | (some x) := to_fmt x end } instance : has_coe_t α (with_top α) := ⟨some⟩ instance has_top : has_top (with_top α) := ⟨none⟩ instance : inhabited (with_top α) := ⟨⊤⟩ lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b := by rw [← option.some.inj_eq a b]; refl @[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) . @[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ . @[priority 10] instance has_lt [has_lt α] : has_lt (with_top α) := { lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a } @[priority 10] instance has_le [has_le α] : has_le (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a } @[simp] theorem some_lt_some [has_lt α] {a b : α} : @has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b := by simp [(<)] @[simp] theorem some_le_some [has_le α] {a b : α} : @has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b := by simp [(≤)] @[simp] theorem none_le [has_le α] {a : with_top α} : @has_le.le (with_top α) _ a none := by simp [(≤)] @[simp] theorem none_lt_some [has_lt α] {a : α} : @has_lt.lt (with_top α) _ (some a) none := by simp [(<)]; existsi a; refl instance [preorder α] : preorder (with_top α) := { le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a, lt := (<), lt_iff_le_not_le := by { intros; cases a; cases b; simp [lt_iff_le_not_le]; simp [(<),(≤)] }, le_refl := λ o a ha, ⟨a, ha, le_refl _⟩, le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc, let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in ⟨a, ha, le_trans ab bc⟩, } instance partial_order [partial_order α] : partial_order (with_top α) := { le_antisymm := λ o₁ o₂ h₁ h₂, begin cases o₂ with b, { cases o₁ with a, {refl}, rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ }, { rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩, rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩, rw le_antisymm h₁' h₂' } end, .. with_top.preorder } instance order_top [partial_order α] : order_top (with_top α) := { le_top := λ a a' h, option.no_confusion h, ..with_top.partial_order, .. with_top.has_top } @[simp] theorem coe_le_coe [partial_order α] {a b : α} : (a : with_top α) ≤ b ↔ a ≤ b := ⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h, λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩ theorem le_coe [partial_order α] {a b : α} : ∀ {o : option α}, a ∈ o → (@has_le.le (with_top α) _ o b ↔ a ≤ b) | _ rfl := coe_le_coe theorem le_coe_iff [partial_order α] (b : α) : ∀(x : with_top α), x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b) | (some a) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem coe_le_iff [partial_order α] (a : α) : ∀(x : with_top α), ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b) | (some b) := by simp [some_eq_coe, coe_eq_coe] | none := by simp [none_eq_top] theorem lt_iff_exists_coe [partial_order α] : ∀(a b : with_top α), a < b ↔ (∃p:α, a = p ∧ ↑p < b) | (some a) b := by simp [some_eq_coe, coe_eq_coe] | none b := by simp [none_eq_top] lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := lt_of_le_of_ne le_top (λ h, option.no_confusion h) lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a := assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim instance linear_order [linear_order α] : linear_order (with_top α) := { le_total := λ o₁ o₂, begin cases o₁ with a, {exact or.inr le_top}, cases o₂ with b, {exact or.inl le_top}, simp [le_total] end, ..with_top.partial_order } instance decidable_linear_order [decidable_linear_order α] : decidable_linear_order (with_top α) := { decidable_le := λ a b, begin cases b with b, { exact is_true le_top }, cases a with a, { exact is_false (mt (le_antisymm le_top) (by simp)) }, { exact decidable_of_iff _ some_le_some } end, ..with_top.linear_order } instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) := { inf := option.lift_or_get (⊓), inf_le_left := λ o₁ o₂ a ha, by cases ha; cases o₂; simp [option.lift_or_get], inf_le_right := λ o₁ o₂ a ha, by cases ha; cases o₁; simp [option.lift_or_get], le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases o₂ with b; cases o₃ with c; cases ha, { exact h₂ a rfl }, { exact h₁ a rfl }, { rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩, simp at h₂, exact ⟨d, rfl, le_inf h₁' h₂⟩ } end, ..with_top.order_top } lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) := { sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)), le_sup_left := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_left⟩ end, le_sup_right := λ o₁ o₂ a ha, begin simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩, exact ⟨_, rfl, le_sup_right⟩ end, sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin cases ha, rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩, rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩, exact ⟨_, rfl, sup_le ab ac⟩ end, ..with_top.order_top } lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl instance lattice [lattice α] : lattice (with_top α) := { ..with_top.semilattice_sup, ..with_top.semilattice_inf } theorem lattice_eq_DLO [decidable_linear_order α] : lattice.lattice_of_decidable_linear_order = @with_top.lattice α _ := lattice.ext $ λ x y, iff.rfl theorem sup_eq_max [decidable_linear_order α] (x y : with_top α) : x ⊔ y = max x y := by rw [← sup_eq_max, lattice_eq_DLO] theorem inf_eq_min [decidable_linear_order α] (x y : with_top α) : x ⊓ y = min x y := by rw [← inf_eq_min, lattice_eq_DLO] instance order_bot [order_bot α] : order_bot (with_top α) := { bot := some ⊥, bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩, ..with_top.partial_order } instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) := { ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot } lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) : well_founded ((<) : with_top α → with_top α → Prop) := have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) := λ a, acc.intro _ (well_founded.induction h a (show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) → ∀ y : with_top α, y < some b → acc (<) y, from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge lattice.le_top hc).elim) (λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))), ⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim) (λ _ _, acc_some _))) acc_some⟩ instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := ⟨ assume a b, match a, b with | none, a := assume h : ⊤ < a, (not_top_lt h).elim | some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩ | some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := dense (coe_lt_coe.1 h) in ⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩ end⟩ lemma dense_coe [partial_order α] [densely_ordered α] [no_top_order α] {a b : with_top α} (h : a < b) : ∃ x : α, a < ↑x ∧ ↑x < b := let ⟨y, hy⟩ := dense h, ⟨x, hx⟩ := (lt_iff_exists_coe _ _).1 hy.2 in ⟨x, hx.1 ▸ hy⟩ end with_top namespace order_dual open lattice variable (α : Type*) instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩ instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩ instance [order_bot α] : order_top (order_dual α) := { le_top := @bot_le α _, .. order_dual.partial_order α, .. order_dual.lattice.has_top α } instance [order_top α] : order_bot (order_dual α) := { bot_le := @le_top α _, .. order_dual.partial_order α, .. order_dual.lattice.has_bot α } instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := { .. order_dual.lattice.semilattice_sup α, .. order_dual.lattice.order_top α } instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := { .. order_dual.lattice.semilattice_sup α, .. order_dual.lattice.order_bot α } instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := { .. order_dual.lattice.semilattice_inf α, .. order_dual.lattice.order_top α } instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := { .. order_dual.lattice.semilattice_inf α, .. order_dual.lattice.order_bot α } instance [bounded_lattice α] : bounded_lattice (order_dual α) := { .. order_dual.lattice.lattice α, .. order_dual.lattice.order_top α, .. order_dual.lattice.order_bot α } instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := { .. order_dual.lattice.bounded_lattice α, .. order_dual.lattice.distrib_lattice α } end order_dual namespace prod open lattice variables (α : Type u) (β : Type v) instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩ instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩ instance [order_top α] [order_top β] : order_top (α × β) := { le_top := assume a, ⟨le_top, le_top⟩, .. prod.partial_order α β, .. prod.lattice.has_top α β } instance [order_bot α] [order_bot β] : order_bot (α × β) := { bot_le := assume a, ⟨bot_le, bot_le⟩, .. prod.partial_order α β, .. prod.lattice.has_bot α β } instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := { .. prod.lattice.semilattice_sup α β, .. prod.lattice.order_top α β } instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := { .. prod.lattice.semilattice_inf α β, .. prod.lattice.order_top α β } instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := { .. prod.lattice.semilattice_sup α β, .. prod.lattice.order_bot α β } instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := { .. prod.lattice.semilattice_inf α β, .. prod.lattice.order_bot α β } instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := { .. prod.lattice.lattice α β, .. prod.lattice.order_top α β, .. prod.lattice.order_bot α β } instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := { .. prod.lattice.bounded_lattice α β, .. prod.lattice.distrib_lattice α β } end prod
c71692df661a8b0a69cb114dc55bb6bbb5ed318f
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/funext.lean
1b1aad7dd933b8aabdd69720b4471fcfc59054b5
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,126
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Extensional equality for functions, and a proof of function extensionality from quotients. -/ prelude import init.data.quot init.logic universes u v namespace function variables {α : Sort u} {β : α → Sort v} protected def equiv (f₁ f₂ : Π x : α, β x) : Prop := ∀ x, f₁ x = f₂ x local infix `~` := function.equiv protected theorem equiv.refl (f : Π x : α, β x) : f ~ f := take x, rfl protected theorem equiv.symm {f₁ f₂ : Π x: α, β x} : f₁ ~ f₂ → f₂ ~ f₁ := λ h x, eq.symm (h x) protected theorem equiv.trans {f₁ f₂ f₃ : Π x: α, β x} : f₁ ~ f₂ → f₂ ~ f₃ → f₁ ~ f₃ := λ h₁ h₂ x, eq.trans (h₁ x) (h₂ x) protected theorem equiv.is_equivalence (α : Sort u) (β : α → Sort v) : equivalence (@function.equiv α β) := mk_equivalence (@function.equiv α β) (@equiv.refl α β) (@equiv.symm α β) (@equiv.trans α β) end function section open quotient variables {α : Sort u} {β : α → Sort v} @[instance] private def fun_setoid (α : Sort u) (β : α → Sort v) : setoid (Π x : α, β x) := setoid.mk (@function.equiv α β) (function.equiv.is_equivalence α β) private def extfun (α : Sort u) (β : α → Sort v) : Sort (imax u v) := quotient (fun_setoid α β) private def fun_to_extfun (f : Π x : α, β x) : extfun α β := ⟦f⟧ private def extfun_app (f : extfun α β) : Π x : α, β x := take x, quot.lift_on f (λ f : Π x : α, β x, f x) (λ f₁ f₂ h, h x) theorem funext {f₁ f₂ : Π x : α, β x} : (∀ x, f₁ x = f₂ x) → f₁ = f₂ := assume h, calc f₁ = extfun_app ⟦f₁⟧ : rfl ... = extfun_app ⟦f₂⟧ : @sound _ _ f₁ f₂ h ▸ rfl ... = f₂ : rfl end attribute [intro!] funext local infix `~` := function.equiv instance pi.subsingleton {α : Sort u} {β : α → Sort v} [∀ a, subsingleton (β a)] : subsingleton (Π a, β a) := ⟨λ f₁ f₂, funext (λ a, subsingleton.elim (f₁ a) (f₂ a))⟩
48978020237305e5d70dddc48d3590e29d504d1f
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/preadditive/additive_functor.lean
e517370f1cd34016ddffa918ead5cf5fbdb1d9ac
[ "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
6,171
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz, Scott Morrison -/ import category_theory.limits.preserves.shapes.biproducts import category_theory.preadditive.functor_category /-! # Additive Functors A functor between two preadditive categories is called *additive* provided that the induced map on hom types is a morphism of abelian groups. An additive functor between preadditive categories creates and preserves biproducts. Conversely, if `F : C ⥤ D` is a functor between preadditive categories, where `C` has binary biproducts, and if `F` preserves binary biproducts, then `F` is additive. We also define the category of bundled additive functors. # Implementation details `functor.additive` is a `Prop`-valued class, defined by saying that for every two objects `X` and `Y`, the map `F.map : (X ⟶ Y) → (F.obj X ⟶ F.obj Y)` is a morphism of abelian groups. -/ namespace category_theory /-- A functor `F` is additive provided `F.map` is an additive homomorphism. -/ class functor.additive {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) : Prop := (map_add' : Π {X Y : C} {f g : X ⟶ Y}, F.map (f + g) = F.map f + F.map g . obviously) section preadditive namespace functor section variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] (F : C ⥤ D) [functor.additive F] @[simp] lemma map_add {X Y : C} {f g : X ⟶ Y} : F.map (f + g) = F.map f + F.map g := functor.additive.map_add' /-- `F.map_add_hom` is an additive homomorphism whose underlying function is `F.map`. -/ @[simps {fully_applied := ff}] def map_add_hom {X Y : C} : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y) := add_monoid_hom.mk' (λ f, F.map f) (λ f g, F.map_add) lemma coe_map_add_hom {X Y : C} : ⇑(F.map_add_hom : (X ⟶ Y) →+ _) = @map C _ D _ F X Y := rfl @[priority 100] instance preserves_zero_morphisms_of_additive : preserves_zero_morphisms F := { map_zero' := λ X Y, F.map_add_hom.map_zero } instance : additive (𝟭 C) := {} instance {E : Type*} [category E] [preadditive E] (G : D ⥤ E) [functor.additive G] : additive (F ⋙ G) := {} @[simp] lemma map_neg {X Y : C} {f : X ⟶ Y} : F.map (-f) = - F.map f := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_neg _ @[simp] lemma map_sub {X Y : C} {f g : X ⟶ Y} : F.map (f - g) = F.map f - F.map g := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_sub _ _ -- You can alternatively just use `functor.map_smul` here, with an explicit `(r : ℤ)` argument. lemma map_zsmul {X Y : C} {f : X ⟶ Y} {r : ℤ} : F.map (r • f) = r • F.map f := (F.map_add_hom : (X ⟶ Y) →+ (F.obj X ⟶ F.obj Y)).map_zsmul _ _ open_locale big_operators @[simp] lemma map_sum {X Y : C} {α : Type*} (f : α → (X ⟶ Y)) (s : finset α) : F.map (∑ a in s, f a) = ∑ a in s, F.map (f a) := (F.map_add_hom : (X ⟶ Y) →+ _).map_sum f s end section induced_category variables {C : Type*} {D : Type*} [category D] [preadditive D] (F : C → D) instance induced_functor_additive : functor.additive (induced_functor F) := {} end induced_category section -- To talk about preservation of biproducts we need to specify universes explicitly. noncomputable theory universes v₁ v₂ u₁ u₂ variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₂} D] [preadditive C] [preadditive D] (F : C ⥤ D) open category_theory.limits open category_theory.preadditive @[priority 100] instance preserves_finite_biproducts_of_additive [additive F] : preserves_finite_biproducts F := { preserves := λ J _, { preserves := λ f, { preserves := λ b hb, by exactI is_bilimit_of_total _ begin simp_rw [F.map_bicone_π, F.map_bicone_ι, ← F.map_comp, ← F.map_sum], dsimp only [map_bicone_X], simp_rw [← F.map_id], refine congr_arg _ (hb.is_limit.hom_ext (λ j, hb.is_colimit.hom_ext (λ j', _))), cases j, cases j', simp [sum_comp, comp_sum, bicone.ι_π, comp_dite, dite_comp], end } } } lemma additive_of_preserves_binary_biproducts [has_binary_biproducts C] [preserves_zero_morphisms F] [preserves_binary_biproducts F] : additive F := { map_add' := λ X Y f g, by rw [biprod.add_eq_lift_id_desc, F.map_comp, ← biprod.lift_map_biprod, ← biprod.map_biprod_hom_desc, category.assoc, iso.inv_hom_id_assoc, F.map_id, biprod.add_eq_lift_id_desc] } end end functor namespace equivalence variables {C D : Type*} [category C] [category D] [preadditive C] [preadditive D] instance inverse_additive (e : C ≌ D) [e.functor.additive] : e.inverse.additive := { map_add' := λ X Y f g, by { apply e.functor.map_injective, simp, }, } end equivalence section variables (C D : Type*) [category C] [category D] [preadditive C] [preadditive D] /-- Bundled additive functors. -/ @[derive category, nolint has_inhabited_instance] def AdditiveFunctor := { F : C ⥤ D // functor.additive F } infixr ` ⥤+ `:26 := AdditiveFunctor instance : preadditive (C ⥤+ D) := preadditive.induced_category.category _ /-- An additive functor is in particular a functor. -/ @[derive full, derive faithful] def AdditiveFunctor.forget : (C ⥤+ D) ⥤ (C ⥤ D) := full_subcategory_inclusion _ variables {C D} /-- Turn an additive functor into an object of the category `AdditiveFunctor C D`. -/ def AdditiveFunctor.of (F : C ⥤ D) [F.additive] : C ⥤+ D := ⟨F, infer_instance⟩ @[simp] lemma AdditiveFunctor.of_fst (F : C ⥤ D) [F.additive] : (AdditiveFunctor.of F).1 = F := rfl @[simp] lemma AdditiveFunctor.forget_obj (F : C ⥤+ D) : (AdditiveFunctor.forget C D).obj F = F.1 := rfl lemma AdditiveFunctor.forget_obj_of (F : C ⥤ D) [F.additive] : (AdditiveFunctor.forget C D).obj (AdditiveFunctor.of F) = F := rfl @[simp] lemma AdditiveFunctor.forget_map (F G : C ⥤+ D) (α : F ⟶ G) : (AdditiveFunctor.forget C D).map α = α := rfl instance : functor.additive (AdditiveFunctor.forget C D) := { map_add' := λ F G α β, rfl } instance (F : C ⥤+ D) : functor.additive F.1 := F.2 end end preadditive end category_theory
5398198a31ff3f8f6b1a47a73e365589233ad4da
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/461b.lean
cd35443892ded5ab4900df49444b43fec4ba53b0
[ "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
215
lean
structure FooS where x : Nat y : Nat h : x = y structure BarS extends FooS where h' : x = y h := h' def f (x : Nat) : BarS := { x, y := x, h' := rfl } def f1 (x : Nat) : BarS := { x, h' := rfl }
88e33c39e8bf73902ccdec4881d34d920d1aacd6
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Data/Nat/Basic.lean
84dce91155c6fcb2cd7eb2b29e287c4e9b04edc9
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,171
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import Init.Core universes u namespace Nat @[extern "lean_nat_dec_eq"] def beq : Nat → Nat → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem eqOfBeqEqTt : ∀ {n m : Nat}, beq n m = true → n = m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have beq n m = true from h; have n = m from eqOfBeqEqTt this; congrArg succ this theorem neOfBeqEqFf : ∀ {n m : Nat}, beq n m = false → n ≠ m | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have beq n m = false from h₁; have n ≠ m from neOfBeqEqFf this; Nat.noConfusion h₂ (fun h₂ => absurd h₂ this) @[extern "lean_nat_dec_eq"] protected def decEq (n m : @& Nat) : Decidable (n = m) := if h : beq n m = true then isTrue (eqOfBeqEqTt h) else isFalse (neOfBeqEqFf (eqFalseOfNeTrue h)) @[inline] instance : DecidableEq Nat := Nat.decEq @[extern "lean_nat_dec_le"] def ble : Nat → Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def le (n m : Nat) : Prop := ble n m = true instance : HasLessEq Nat := ⟨Nat.le⟩ protected def lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat := ⟨Nat.lt⟩ @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def pred : Nat → Nat | 0 => 0 | a+1 => a @[extern "lean_nat_sub"] protected def sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, b+1 => pred (sub a b) @[extern "lean_nat_mul"] protected def mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, b+1 => (mul a b) + a instance : HasSub Nat := ⟨Nat.sub⟩ instance : HasMul Nat := ⟨Nat.mul⟩ @[specialize] def foldAux {α : Type u} (f : Nat → α → α) (s : Nat) : Nat → α → α | 0, a => a | succ n, a => foldAux n (f (s - (succ n)) a) @[inline] def fold {α : Type u} (f : Nat → α → α) (n : Nat) (a : α) : α := foldAux f n n a @[specialize] def foldRevAux {α : Type u} (f : Nat → α → α) : Nat → α → α | 0, a => a | succ n, a => foldRevAux n (f n a) @[inline] def foldRev {α : Type u} (f : Nat → α → α) (n : Nat) (a : α) : α := foldRevAux f n a @[specialize] def anyAux (f : Nat → Bool) (s : Nat) : Nat → Bool | 0 => false | succ n => f (s - (succ n)) || anyAux n /- `any f n = true` iff there is `i in [0, n-1]` s.t. `f i = true` -/ @[inline] def any (f : Nat → Bool) (n : Nat) : Bool := anyAux f n n @[inline] def all (f : Nat → Bool) (n : Nat) : Bool := !any (fun i => !f i) n @[specialize] def repeatAux {α : Type u} (f : α → α) : Nat → α → α | 0, a => a | succ n, a => repeatAux n (f a) @[inline] def repeat {α : Type u} (f : α → α) (n : Nat) (a : α) : α := repeatAux f n a protected def pow (m : Nat) : Nat → Nat | 0 => 1 | succ n => pow n * m instance : HasPow Nat Nat := ⟨Nat.pow⟩ /- Nat.add theorems -/ protected theorem zeroAdd : ∀ (n : Nat), 0 + n = n | 0 => rfl | n+1 => congrArg succ (zeroAdd n) theorem succAdd : ∀ (n m : Nat), (succ n) + m = succ (n + m) | n, 0 => rfl | n, m+1 => congrArg succ (succAdd n m) theorem addSucc (n m : Nat) : n + succ m = succ (n + m) := rfl protected theorem addZero (n : Nat) : n + 0 = n := rfl theorem addOne (n : Nat) : n + 1 = succ n := rfl theorem succEqAddOne (n : Nat) : succ n = n + 1 := rfl protected theorem addComm : ∀ (n m : Nat), n + m = m + n | n, 0 => Eq.symm (Nat.zeroAdd n) | n, m+1 => suffices succ (n + m) = succ (m + n) from Eq.symm (succAdd m n) ▸ this; congrArg succ (addComm n m) protected theorem addAssoc : ∀ (n m k : Nat), (n + m) + k = n + (m + k) | n, m, 0 => rfl | n, m, succ k => congrArg succ (addAssoc n m k) protected theorem addLeftComm : ∀ (n m k : Nat), n + (m + k) = m + (n + k) := leftComm Nat.add Nat.addComm Nat.addAssoc protected theorem addRightComm : ∀ (n m k : Nat), (n + m) + k = (n + k) + m := rightComm Nat.add Nat.addComm Nat.addAssoc protected theorem addLeftCancel : ∀ {n m k : Nat}, n + m = n + k → m = k | 0, m, k, h => Nat.zeroAdd m ▸ Nat.zeroAdd k ▸ h | succ n, m, k, h => have n+m = n+k from have succ (n + m) = succ (n + k) from succAdd n m ▸ succAdd n k ▸ h; Nat.noConfusion this id; addLeftCancel this protected theorem addRightCancel {n m k : Nat} (h : n + m = k + m) : n = k := have m + n = m + k from Nat.addComm n m ▸ Nat.addComm k m ▸ h; Nat.addLeftCancel this /- Nat.mul theorems -/ protected theorem mulZero (n : Nat) : n * 0 = 0 := rfl theorem mulSucc (n m : Nat) : n * succ m = n * m + n := rfl protected theorem zeroMul : ∀ (n : Nat), 0 * n = 0 | 0 => rfl | succ n => (mulSucc 0 n).symm ▸ (zeroMul n).symm ▸ rfl theorem succMul : ∀ (n m : Nat), (succ n) * m = (n * m) + m | n, 0 => rfl | n, succ m => have succ (n * m + m + n) = succ (n * m + n + m) from congrArg succ (Nat.addRightComm _ _ _); (mulSucc n m).symm ▸ (mulSucc (succ n) m).symm ▸ (succMul n m).symm ▸ this protected theorem mulComm : ∀ (n m : Nat), n * m = m * n | n, 0 => (Nat.zeroMul n).symm ▸ (Nat.mulZero n).symm ▸ rfl | n, succ m => (mulSucc n m).symm ▸ (succMul m n).symm ▸ (mulComm n m).symm ▸ rfl protected theorem mulOne : ∀ (n : Nat), n * 1 = n := Nat.zeroAdd protected theorem oneMul (n : Nat) : 1 * n = n := Nat.mulComm n 1 ▸ Nat.mulOne n protected theorem leftDistrib : ∀ (n m k : Nat), n * (m + k) = n * m + n * k | 0, m, k => (Nat.zeroMul (m + k)).symm ▸ (Nat.zeroMul m).symm ▸ (Nat.zeroMul k).symm ▸ rfl | succ n, m, k => have h₁ : succ n * (m + k) = n * (m + k) + (m + k) from succMul _ _; have h₂ : n * (m + k) + (m + k) = (n * m + n * k) + (m + k) from leftDistrib n m k ▸ rfl; have h₃ : (n * m + n * k) + (m + k) = n * m + (n * k + (m + k)) from Nat.addAssoc _ _ _; have h₄ : n * m + (n * k + (m + k)) = n * m + (m + (n * k + k)) from congrArg (fun x => n*m + x) (Nat.addLeftComm _ _ _); have h₅ : n * m + (m + (n * k + k)) = (n * m + m) + (n * k + k) from (Nat.addAssoc _ _ _).symm; have h₆ : (n * m + m) + (n * k + k) = (n * m + m) + succ n * k from succMul n k ▸ rfl; have h₇ : (n * m + m) + succ n * k = succ n * m + succ n * k from succMul n m ▸ rfl; (((((h₁.trans h₂).trans h₃).trans h₄).trans h₅).trans h₆).trans h₇ protected theorem rightDistrib (n m k : Nat) : (n + m) * k = n * k + m * k := have h₁ : (n + m) * k = k * (n + m) from Nat.mulComm _ _; have h₂ : k * (n + m) = k * n + k * m from Nat.leftDistrib _ _ _; have h₃ : k * n + k * m = n * k + k * m from Nat.mulComm n k ▸ rfl; have h₄ : n * k + k * m = n * k + m * k from Nat.mulComm m k ▸ rfl; ((h₁.trans h₂).trans h₃).trans h₄ protected theorem mulAssoc : ∀ (n m k : Nat), (n * m) * k = n * (m * k) | n, m, 0 => rfl | n, m, succ k => have h₁ : n * m * succ k = n * m * (k + 1) from rfl; have h₂ : n * m * (k + 1) = (n * m * k) + n * m * 1 from Nat.leftDistrib _ _ _; have h₃ : (n * m * k) + n * m * 1 = (n * m * k) + n * m from (Nat.mulOne (n*m)).symm ▸ rfl; have h₄ : (n * m * k) + n * m = (n * (m * k)) + n * m from (mulAssoc n m k).symm ▸ rfl; have h₅ : (n * (m * k)) + n * m = n * (m * k + m) from (Nat.leftDistrib n (m*k) m).symm; have h₆ : n * (m * k + m) = n * (m * succ k) from Nat.mulSucc m k ▸ rfl; ((((h₁.trans h₂).trans h₃).trans h₄).trans h₅).trans h₆ /- Inequalities -/ protected def leRefl : ∀ (n : Nat), n ≤ n | zero => rfl | succ n => leRefl n theorem leSucc : ∀ (n : Nat), n ≤ succ n | zero => rfl | succ n => leSucc n theorem succLeSucc {n m : Nat} (h : n ≤ m) : succ n ≤ succ m := h theorem succLtSucc {n m : Nat} : n < m → succ n < succ m := succLeSucc theorem leStep : ∀ {n m : Nat}, n ≤ m → n ≤ succ m | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have n ≤ m from h; have n ≤ succ m from leStep this; succLeSucc this theorem zeroLe : ∀ (n : Nat), 0 ≤ n | zero => rfl | succ n => rfl theorem zeroLtSucc (n : Nat) : 0 < succ n := succLeSucc (zeroLe n) def succPos := zeroLtSucc theorem notSuccLeZero : ∀ (n : Nat), succ n ≤ 0 → False | 0, h => nomatch h | n+1, h => nomatch h theorem notLtZero (n : Nat) : ¬ n < 0 := notSuccLeZero n theorem predLePred : ∀ {n m : Nat}, n ≤ m → pred n ≤ pred m | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem leOfSuccLeSucc {n m : Nat} : succ n ≤ succ m → n ≤ m := predLePred @[extern "lean_nat_dec_le"] instance decLe (n m : @& Nat) : Decidable (n ≤ m) := decEq (ble n m) true @[extern "lean_nat_dec_lt"] instance decLt (n m : @& Nat) : Decidable (n < m) := Nat.decLe (succ n) m protected theorem eqOrLtOfLe : ∀ {n m: Nat}, n ≤ m → n = m ∨ n < m | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr $ zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have n ≤ m from h; have n = m ∨ n < m from eqOrLtOfLe this; Or.elim this (fun h => Or.inl $ congrArg succ h) (fun h => Or.inr $ succLtSucc h) theorem ltSuccOfLe {n m : Nat} : n ≤ m → n < succ m := succLeSucc protected theorem subZero (n : Nat) : n - 0 = n := rfl theorem succSubSuccEqSub (n m : Nat) : succ n - succ m = n - m := Nat.recOn m (show succ n - succ zero = n - zero from (Eq.refl (succ n - succ zero))) (fun m => congrArg pred) theorem notSuccLeSelf : ∀ (n : Nat), ¬succ n ≤ n := fun n => Nat.rec (notSuccLeZero 0) (fun a b c => b (leOfSuccLeSucc c)) n protected theorem ltIrrefl (n : Nat) : ¬n < n := notSuccLeSelf n protected theorem leTrans : ∀ {n m k : Nat}, n ≤ m → m ≤ k → n ≤ k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : n ≤ m from h₁; have h₂' : m ≤ k from h₂; have n ≤ k from leTrans h₁' h₂'; succLeSucc this theorem predLe : ∀ (n : Nat), pred n ≤ n | zero => rfl | succ n => leSucc _ theorem predLt : ∀ {n : Nat}, n ≠ 0 → pred n < n | zero, h => absurd rfl h | succ n, h => ltSuccOfLe (Nat.leRefl _) theorem subLe (n m : Nat) : n - m ≤ n := Nat.recOn m (Nat.leRefl (n - 0)) (fun m => Nat.leTrans (predLe (n - m))) theorem subLt : ∀ {n m : Nat}, 0 < n → 0 < m → n - m < n | 0, m, h1, h2 => absurd h1 (Nat.ltIrrefl 0) | n+1, 0, h1, h2 => absurd h2 (Nat.ltIrrefl 0) | n+1, m+1, h1, h2 => Eq.symm (succSubSuccEqSub n m) ▸ show n - m < succ n from ltSuccOfLe (subLe n m) protected theorem ltOfLtOfLe {n m k : Nat} : n < m → m ≤ k → n < k := Nat.leTrans protected theorem leOfEq {n m : Nat} (p : n = m) : n ≤ m := p ▸ Nat.leRefl n theorem leSuccOfLe {n m : Nat} (h : n ≤ m) : n ≤ succ m := Nat.leTrans h (leSucc m) theorem leOfSuccLe {n m : Nat} (h : succ n ≤ m) : n ≤ m := Nat.leTrans (leSucc n) h protected theorem leOfLt {n m : Nat} (h : n < m) : n ≤ m := leOfSuccLe h def lt.step {n m : Nat} : n < m → n < succ m := leStep theorem eqZeroOrPos : ∀ (n : Nat), n = 0 ∨ n > 0 | 0 => Or.inl rfl | n+1 => Or.inr (succPos _) protected theorem ltTrans {n m k : Nat} (h₁ : n < m) : m < k → n < k := Nat.leTrans (leStep h₁) protected theorem ltOfLeOfLt {n m k : Nat} (h₁ : n ≤ m) : m < k → n < k := Nat.leTrans (succLeSucc h₁) def lt.base (n : Nat) : n < succ n := Nat.leRefl (succ n) theorem ltSuccSelf (n : Nat) : n < succ n := lt.base n protected theorem leAntisymm : ∀ {n m : Nat}, n ≤ m → m ≤ n → n = m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : n ≤ m from h₁; have h₂' : m ≤ n from h₂; have n = m from leAntisymm h₁' h₂'; congrArg succ this protected theorem ltOrGe : ∀ (n m : Nat), n < m ∨ n ≥ m | n, 0 => Or.inr (zeroLe n) | n, m+1 => match ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ ltSuccSelf m) | Or.inr h1 => Or.inr h1 protected theorem leTotal (m n : Nat) : m ≤ n ∨ n ≤ m := Or.elim (Nat.ltOrGe m n) (fun h => Or.inl (Nat.leOfLt h)) Or.inr protected theorem ltOfLeAndNe {m n : Nat} (h1 : m ≤ n) : m ≠ n → m < n := resolveRight (Or.swap (Nat.eqOrLtOfLe h1)) theorem eqZeroOfLeZero {n : Nat} (h : n ≤ 0) : n = 0 := Nat.leAntisymm h (zeroLe _) theorem ltOfSuccLt {n m : Nat} : succ n < m → n < m := leOfSuccLe theorem ltOfSuccLtSucc {n m : Nat} : succ n < succ m → n < m := leOfSuccLeSucc theorem ltOfSuccLe {n m : Nat} (h : succ n ≤ m) : n < m := h theorem succLeOfLt {n m : Nat} (h : n < m) : succ n ≤ m := h theorem ltOrEqOrLeSucc {m n : Nat} (h : m ≤ succ n) : m ≤ n ∨ m = succ n := Decidable.byCases (fun (h' : m = succ n) => Or.inr h') (fun (h' : m ≠ succ n) => have m < succ n from Nat.ltOfLeAndNe h h'; have succ m ≤ succ n from succLeOfLt this; Or.inl (leOfSuccLeSucc this)) theorem leAddRight : ∀ (n k : Nat), n ≤ n + k | n, 0 => Nat.leRefl n | n, k+1 => leSuccOfLe (leAddRight n k) theorem leAddLeft (n m : Nat): n ≤ m + n := Nat.addComm n m ▸ leAddRight n m theorem le.dest : ∀ {n m : Nat}, n ≤ m → Exists (fun k => n + k = m) | zero, zero, h => ⟨0, rfl⟩ | zero, succ n, h => ⟨succ n, show 0 + succ n = succ n from (Nat.addComm 0 (succ n)).symm ▸ rfl⟩ | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have n ≤ m from h; have Exists (fun k => n + k = m) from le.dest this; match this with | ⟨k, h⟩ => ⟨k, show succ n + k = succ m from ((succAdd n k).symm ▸ h ▸ rfl)⟩ theorem le.intro {n m k : Nat} (h : n + k = m) : n ≤ m := h ▸ leAddRight n k protected theorem notLeOfGt {n m : Nat} (h : n > m) : ¬ n ≤ m := fun h₁ => Or.elim (Nat.ltOrGe n m) (fun h₂ => absurd (Nat.ltTrans h h₂) (Nat.ltIrrefl _)) (fun h₂ => have Heq : n = m from Nat.leAntisymm h₁ h₂; absurd (@Eq.subst _ _ _ _ Heq h) (Nat.ltIrrefl m)) theorem gtOfNotLe {n m : Nat} (h : ¬ n ≤ m) : n > m := Or.elim (Nat.ltOrGe m n) (fun h₁ => h₁) (fun h₁ => absurd h₁ h) protected theorem ltOfLeOfNe {n m : Nat} (h₁ : n ≤ m) (h₂ : n ≠ m) : n < m := Or.elim (Nat.ltOrGe n m) (fun h₃ => h₃) (fun h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂) protected theorem addLeAddLeft {n m : Nat} (h : n ≤ m) (k : Nat) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ => have h₁ : k + n + w = k + (n + w) from Nat.addAssoc _ _ _; have h₂ : k + (n + w) = k + m from congrArg _ hw; le.intro $ h₁.trans h₂ protected theorem addLeAddRight {n m : Nat} (h : n ≤ m) (k : Nat) : n + k ≤ m + k := have h₁ : n + k = k + n from Nat.addComm _ _; have h₂ : k + n ≤ k + m from Nat.addLeAddLeft h k; have h₃ : k + m = m + k from Nat.addComm _ _; transRelLeft (fun a b => a ≤ b) (transRelRight (fun a b => a ≤ b) h₁ h₂) h₃ protected theorem addLtAddLeft {n m : Nat} (h : n < m) (k : Nat) : k + n < k + m := ltOfSuccLe (addSucc k n ▸ Nat.addLeAddLeft (succLeOfLt h) k) protected theorem addLtAddRight {n m : Nat} (h : n < m) (k : Nat) : n + k < m + k := Nat.addComm k m ▸ Nat.addComm k n ▸ Nat.addLtAddLeft h k protected theorem zeroLtOne : 0 < (1:Nat) := zeroLtSucc 0 theorem leOfLtSucc {m n : Nat} : m < succ n → m ≤ n := leOfSuccLeSucc theorem addLeAdd {a b c d : Nat} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := Nat.leTrans (Nat.addLeAddRight h₁ c) (Nat.addLeAddLeft h₂ b) theorem addLtAdd {a b c d : Nat} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := Nat.ltTrans (Nat.addLtAddRight h₁ c) (Nat.addLtAddLeft h₂ b) /- Basic theorems for comparing numerals -/ theorem natZeroEqZero : Nat.zero = 0 := rfl protected theorem oneNeZero : 1 ≠ (0 : Nat) := fun h => Nat.noConfusion h protected theorem zeroNeOne : 0 ≠ (1 : Nat) := fun h => Nat.noConfusion h theorem succNeZero (n : Nat) : succ n ≠ 0 := fun h => Nat.noConfusion h protected theorem bit0SuccEq (n : Nat) : bit0 (succ n) = succ (succ (bit0 n)) := show succ (succ n + n) = succ (succ (n + n)) from congrArg succ (succAdd n n) protected theorem zeroLtBit0 : ∀ {n : Nat}, n ≠ 0 → 0 < bit0 n | 0, h => absurd rfl h | succ n, h => have h₁ : 0 < succ (succ (bit0 n)) from zeroLtSucc _; have h₂ : succ (succ (bit0 n)) = bit0 (succ n) from (Nat.bit0SuccEq n).symm; transRelLeft (fun a b => a < b) h₁ h₂ protected theorem zeroLtBit1 (n : Nat) : 0 < bit1 n := zeroLtSucc _ protected theorem bit0NeZero : ∀ {n : Nat}, n ≠ 0 → bit0 n ≠ 0 | 0, h => absurd rfl h | n+1, h => suffices (n+1) + (n+1) ≠ 0 from this; suffices succ ((n+1) + n) ≠ 0 from this; fun h => Nat.noConfusion h protected theorem bit1NeZero (n : Nat) : bit1 n ≠ 0 := show succ (n + n) ≠ 0 from fun h => Nat.noConfusion h protected theorem bit1EqSuccBit0 (n : Nat) : bit1 n = succ (bit0 n) := rfl protected theorem bit1SuccEq (n : Nat) : bit1 (succ n) = succ (succ (bit1 n)) := Eq.trans (Nat.bit1EqSuccBit0 (succ n)) (congrArg succ (Nat.bit0SuccEq n)) protected theorem bit1NeOne : ∀ {n : Nat}, n ≠ 0 → bit1 n ≠ 1 | 0, h, h1 => absurd rfl h | n+1, h, h1 => Nat.noConfusion h1 (fun h2 => absurd h2 (succNeZero _)) protected theorem bit0NeOne : ∀ (n : Nat), bit0 n ≠ 1 | 0, h => absurd h (Ne.symm Nat.oneNeZero) | n+1, h => have h1 : succ (succ (n + n)) = 1 from succAdd n n ▸ h; Nat.noConfusion h1 (fun h2 => absurd h2 (succNeZero (n + n))) protected theorem addSelfNeOne : ∀ (n : Nat), n + n ≠ 1 | 0, h => Nat.noConfusion h | n+1, h => have h1 : succ (succ (n + n)) = 1 from succAdd n n ▸ h; Nat.noConfusion h1 (fun h2 => absurd h2 (Nat.succNeZero (n + n))) protected theorem bit1NeBit0 : ∀ (n m : Nat), bit1 n ≠ bit0 m | 0, m, h => absurd h (Ne.symm (Nat.addSelfNeOne m)) | n+1, 0, h => have h1 : succ (bit0 (succ n)) = 0 from h; absurd h1 (Nat.succNeZero _) | n+1, m+1, h => have h1 : succ (succ (bit1 n)) = succ (succ (bit0 m)) from Nat.bit0SuccEq m ▸ Nat.bit1SuccEq n ▸ h; have h2 : bit1 n = bit0 m from Nat.noConfusion h1 (fun h2' => Nat.noConfusion h2' (fun h2'' => h2'')); absurd h2 (bit1NeBit0 n m) protected theorem bit0NeBit1 : ∀ (n m : Nat), bit0 n ≠ bit1 m := fun n m => Ne.symm (Nat.bit1NeBit0 m n) protected theorem bit0Inj : ∀ {n m : Nat}, bit0 n = bit0 m → n = m | 0, 0, h => rfl | 0, m+1, h => absurd h.symm (succNeZero _) | n+1, 0, h => absurd h (succNeZero _) | n+1, m+1, h => have (n+1) + n = (m+1) + m from Nat.noConfusion h id; have n + (n+1) = m + (m+1) from Nat.addComm (m+1) m ▸ Nat.addComm (n+1) n ▸ this; have succ (n + n) = succ (m + m) from this; have n + n = m + m from Nat.noConfusion this id; have n = m from bit0Inj this; congrArg (fun a => a + 1) this protected theorem bit1Inj : ∀ {n m : Nat}, bit1 n = bit1 m → n = m := fun n m h => have succ (bit0 n) = succ (bit0 m) from Nat.bit1EqSuccBit0 n ▸ Nat.bit1EqSuccBit0 m ▸ h; have bit0 n = bit0 m from Nat.noConfusion this id; Nat.bit0Inj this protected theorem bit0Ne {n m : Nat} : n ≠ m → bit0 n ≠ bit0 m := fun h₁ h₂ => absurd (Nat.bit0Inj h₂) h₁ protected theorem bit1Ne {n m : Nat} : n ≠ m → bit1 n ≠ bit1 m := fun h₁ h₂ => absurd (Nat.bit1Inj h₂) h₁ protected theorem zeroNeBit0 {n : Nat} : n ≠ 0 → 0 ≠ bit0 n := fun h => Ne.symm (Nat.bit0NeZero h) protected theorem zeroNeBit1 (n : Nat) : 0 ≠ bit1 n := Ne.symm (Nat.bit1NeZero n) protected theorem oneNeBit0 (n : Nat) : 1 ≠ bit0 n := Ne.symm (Nat.bit0NeOne n) protected theorem oneNeBit1 {n : Nat} : n ≠ 0 → 1 ≠ bit1 n := fun h => Ne.symm (Nat.bit1NeOne h) protected theorem oneLtBit1 : ∀ {n : Nat}, n ≠ 0 → 1 < bit1 n | 0, h => absurd rfl h | succ n, h => suffices succ 0 < succ (succ (bit1 n)) from (Nat.bit1SuccEq n).symm ▸ this; succLtSucc (zeroLtSucc _) protected theorem oneLtBit0 : ∀ {n : Nat}, n ≠ 0 → 1 < bit0 n | 0, h => absurd rfl h | succ n, h => suffices succ 0 < succ (succ (bit0 n)) from (Nat.bit0SuccEq n).symm ▸ this; succLtSucc (zeroLtSucc _) protected theorem bit0Lt {n m : Nat} (h : n < m) : bit0 n < bit0 m := Nat.addLtAdd h h protected theorem bit1Lt {n m : Nat} (h : n < m) : bit1 n < bit1 m := succLtSucc (Nat.addLtAdd h h) protected theorem bit0LtBit1 {n m : Nat} (h : n ≤ m) : bit0 n < bit1 m := ltSuccOfLe (Nat.addLeAdd h h) protected theorem bit1LtBit0 : ∀ {n m : Nat}, n < m → bit1 n < bit0 m | n, 0, h => absurd h (notLtZero _) | n, succ m, h => have n ≤ m from leOfLtSucc h; have succ (n + n) ≤ succ (m + m) from succLeSucc (addLeAdd this this); have succ (n + n) ≤ succ m + m from (succAdd m m).symm ▸ this; show succ (n + n) < succ (succ m + m) from ltSuccOfLe this protected theorem oneLeBit1 (n : Nat) : 1 ≤ bit1 n := show 1 ≤ succ (bit0 n) from succLeSucc (zeroLe (bit0 n)) protected theorem oneLeBit0 : ∀ (n : Nat), n ≠ 0 → 1 ≤ bit0 n | 0, h => absurd rfl h | n+1, h => suffices 1 ≤ succ (succ (bit0 n)) from Eq.symm (Nat.bit0SuccEq n) ▸ this; succLeSucc (zeroLe (succ (bit0 n))) /- mul + order -/ theorem mulLeMulLeft {n m : Nat} (k : Nat) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ => have k * n + k * l = k * m from Nat.leftDistrib k n l ▸ hl.symm ▸ rfl; le.intro this theorem mulLeMulRight {n m : Nat} (k : Nat) (h : n ≤ m) : n * k ≤ m * k := Nat.mulComm k m ▸ Nat.mulComm k n ▸ mulLeMulLeft k h protected theorem mulLeMul {n₁ m₁ n₂ m₂ : Nat} (h₁ : n₁ ≤ n₂) (h₂ : m₁ ≤ m₂) : n₁ * m₁ ≤ n₂ * m₂ := Nat.leTrans (mulLeMulRight _ h₁) (mulLeMulLeft _ h₂) protected theorem mulLtMulOfPosLeft {n m k : Nat} (h : n < m) (hk : k > 0) : k * n < k * m := Nat.ltOfLtOfLe (Nat.addLtAddLeft hk _) (Nat.mulSucc k n ▸ Nat.mulLeMulLeft k (succLeOfLt h)) protected theorem mulLtMulOfPosRight {n m k : Nat} (h : n < m) (hk : k > 0) : n * k < m * k := Nat.mulComm k m ▸ Nat.mulComm k n ▸ Nat.mulLtMulOfPosLeft h hk protected theorem mulPos {n m : Nat} (ha : n > 0) (hb : m > 0) : n * m > 0 := have h : 0 * m < n * m from Nat.mulLtMulOfPosRight ha hb; Nat.zeroMul m ▸ h /- power -/ theorem powSucc (n m : Nat) : n^(succ m) = n^m * n := rfl theorem powZero (n : Nat) : n^0 = 1 := rfl theorem powLePowOfLeLeft {n m : Nat} (h : n ≤ m) : ∀ (i : Nat), n^i ≤ m^i | 0 => Nat.leRefl _ | succ i => Nat.mulLeMul (powLePowOfLeLeft i) h theorem powLePowOfLeRight {n : Nat} (hx : n > 0) {i : Nat} : ∀ {j}, i ≤ j → n^i ≤ n^j | 0, h => have i = 0 from eqZeroOfLeZero h; this.symm ▸ Nat.leRefl _ | succ j, h => Or.elim (ltOrEqOrLeSucc h) (fun h => show n^i ≤ n^j * n from suffices n^i * 1 ≤ n^j * n from Nat.mulOne (n^i) ▸ this; Nat.mulLeMul (powLePowOfLeRight h) hx) (fun h => h.symm ▸ Nat.leRefl _) theorem posPowOfPos {n : Nat} (m : Nat) (h : 0 < n) : 0 < n^m := powLePowOfLeRight h (Nat.zeroLe _) /- Max -/ protected def max (n m : Nat) : Nat := if n ≤ m then m else n end Nat namespace Prod @[inline] def foldI {α : Type u} (f : Nat → α → α) (i : Nat × Nat) (a : α) : α := Nat.foldAux f i.2 (i.2 - i.1) a @[inline] def anyI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux f i.2 (i.2 - i.1) @[inline] def allI (f : Nat → Bool) (i : Nat × Nat) : Bool := !Nat.anyAux (fun a => !f a) i.2 (i.2 - i.1) end Prod
e73ced8dcbb74e30611d0d70a125c9b555aec93f
00de0c30dd1b090ed139f65c82ea6deb48c3f4c2
/src/category_theory/limits/shapes/binary_products.lean
8e5350e9d2c67ea42c660c48873a6be79cb3d782
[ "Apache-2.0" ]
permissive
paulvanwamelen/mathlib
4b9c5c19eec71b475f3dd515cd8785f1c8515f26
79e296bdc9f83b9447dc1b81730d36f63a99f72d
refs/heads/master
1,667,766,172,625
1,590,239,595,000
1,590,239,595,000
266,392,625
0
0
Apache-2.0
1,590,257,277,000
1,590,257,277,000
null
UTF-8
Lean
false
false
21,547
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.limits.shapes.terminal /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. -/ universes v u open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq, derive inhabited] inductive walking_pair : Type v | left | right open walking_pair instance fintype_walking_pair : fintype walking_pair := { elems := {left, right}, complete := λ x, by { cases x; simp } } variables {C : Type u} [category.{v} C] /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := functor.of_function (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl section variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right) /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, match j with | left := f | right := g end } @[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G := { hom := map_pair f.hom g.hom, inv := map_pair f.inv g.inv, hom_inv_id' := begin ext j, cases j; { dsimp, simp, } end, inv_hom_id' := begin ext j, cases j; { dsimp, simp, } end } end section variables {D : Type u} [category.{v} D] /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) /-- A binary fan is just a cone on a diagram indexing a product. -/ abbreviation binary_fan (X Y : C) := cone (pair X Y) /-- The first projection of a binary fan. -/ abbreviation binary_fan.fst {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.left /-- The second projection of a binary fan. -/ abbreviation binary_fan.snd {X Y : C} (s : binary_fan X Y) := s.π.app walking_pair.right lemma binary_fan.is_limit.hom_ext {W X Y : C} {s : binary_fan X Y} (h : is_limit s) {f g : W ⟶ s.X} (h₁ : f ≫ s.fst = g ≫ s.fst) (h₂ : f ≫ s.snd = g ≫ s.snd) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ /-- A binary cofan is just a cocone on a diagram indexing a coproduct. -/ abbreviation binary_cofan (X Y : C) := cocone (pair X Y) /-- The first inclusion of a binary cofan. -/ abbreviation binary_cofan.inl {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.left /-- The second inclusion of a binary cofan. -/ abbreviation binary_cofan.inr {X Y : C} (s : binary_cofan X Y) := s.ι.app walking_pair.right lemma binary_cofan.is_colimit.hom_ext {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) {f g : s.X ⟶ W} (h₁ : s.inl ≫ f = s.inl ≫ g) (h₂ : s.inr ≫ f = s.inr ≫ g) : f = g := h.hom_ext $ λ j, walking_pair.cases_on j h₁ h₂ variables {X Y : C} /-- A binary fan with vertex `P` consists of the two projections `π₁ : P ⟶ X` and `π₂ : P ⟶ Y`. -/ def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} /-- A binary cofan with vertex `P` consists of the two inclusions `ι₁ : X ⟶ P` and `ι₂ : Y ⟶ P`. -/ def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl /-- If `s` is a limit binary fan over `X` and `Y`, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ s.X` satisfying `l ≫ s.fst = f` and `l ≫ s.snd = g`. -/ def binary_fan.is_limit.lift' {W X Y : C} {s : binary_fan X Y} (h : is_limit s) (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ s.X // l ≫ s.fst = f ∧ l ≫ s.snd = g} := ⟨h.lift $ binary_fan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If `s` is a colimit binary cofan over `X` and `Y`,, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : s.X ⟶ W` satisfying `s.inl ≫ l = f` and `s.inr ≫ l = g`. -/ def binary_cofan.is_colimit.desc' {W X Y : C} {s : binary_cofan X Y} (h : is_colimit s) (f : X ⟶ W) (g : Y ⟶ W) : {l : s.X ⟶ W // s.inl ≫ l = f ∧ s.inr ≫ l = g} := ⟨h.desc $ binary_cofan.mk f g, h.fac _ _, h.fac _ _⟩ /-- If we have chosen a product of `X` and `Y`, we can access it using `prod X Y` or `X ⨯ Y`. -/ abbreviation prod (X Y : C) [has_limit (pair X Y)] := limit (pair X Y) /-- If we have chosen a coproduct of `X` and `Y`, we can access it using `coprod X Y ` or `X ⨿ Y`. -/ abbreviation coprod (X Y : C) [has_colimit (pair X Y)] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y /-- The projection map to the first component of the product. -/ abbreviation prod.fst {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left /-- The projecton map to the second component of the product. -/ abbreviation prod.snd {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right /-- The inclusion map from the first component of the coproduct. -/ abbreviation coprod.inl {X Y : C} [has_colimit (pair X Y)] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left /-- The inclusion map from the second component of the coproduct. -/ abbreviation coprod.inr {X Y : C} [has_colimit (pair X Y)] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right @[ext] lemma prod.hom_ext {W X Y : C} [has_limit (pair X Y)] {f g : W ⟶ X ⨯ Y} (h₁ : f ≫ prod.fst = g ≫ prod.fst) (h₂ : f ≫ prod.snd = g ≫ prod.snd) : f = g := binary_fan.is_limit.hom_ext (limit.is_limit _) h₁ h₂ @[ext] lemma coprod.hom_ext {W X Y : C} [has_colimit (pair X Y)] {f g : X ⨿ Y ⟶ W} (h₁ : coprod.inl ≫ f = coprod.inl ≫ g) (h₂ : coprod.inr ≫ f = coprod.inr ≫ g) : f = g := binary_cofan.is_colimit.hom_ext (colimit.is_colimit _) h₁ h₂ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `prod.lift f g : W ⟶ X ⨯ Y`. -/ abbreviation prod.lift {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `coprod.desc f g : X ⨿ Y ⟶ W`. -/ abbreviation coprod.desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) @[simp, reassoc] lemma prod.lift_fst {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.fst = f := limit.lift_π _ _ @[simp, reassoc] lemma prod.lift_snd {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : prod.lift f g ≫ prod.snd = g := limit.lift_π _ _ @[simp, reassoc] lemma coprod.inl_desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inl ≫ coprod.desc f g = f := colimit.ι_desc _ _ @[simp, reassoc] lemma coprod.inr_desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : coprod.inr ≫ coprod.desc f g = g := colimit.ι_desc _ _ instance prod.mono_lift_of_mono_left {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_fst _ _ instance prod.mono_lift_of_mono_right {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ prod.lift_snd _ _ instance coprod.epi_desc_of_epi_left {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inl_desc _ _ instance coprod.epi_desc_of_epi_right {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ coprod.inr_desc _ _ /-- If the product of `X` and `Y` exists, then every pair of morphisms `f : W ⟶ X` and `g : W ⟶ Y` induces a morphism `l : W ⟶ X ⨯ Y` satisfying `l ≫ prod.fst = f` and `l ≫ prod.snd = g`. -/ def prod.lift' {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : {l : W ⟶ X ⨯ Y // l ≫ prod.fst = f ∧ l ≫ prod.snd = g} := ⟨prod.lift f g, prod.lift_fst _ _, prod.lift_snd _ _⟩ /-- If the coproduct of `X` and `Y` exists, then every pair of morphisms `f : X ⟶ W` and `g : Y ⟶ W` induces a morphism `l : X ⨿ Y ⟶ W` satisfying `coprod.inl ≫ l = f` and `coprod.inr ≫ l = g`. -/ def coprod.desc' {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : {l : X ⨿ Y ⟶ W // coprod.inl ≫ l = f ∧ coprod.inr ≫ l = g} := ⟨coprod.desc f g, coprod.inl_desc _ _, coprod.inr_desc _ _⟩ /-- If the products `W ⨯ X` and `Y ⨯ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : X ⟶ Z` induces a morphism `prod.map f g : W ⨯ X ⟶ Y ⨯ Z`. -/ abbreviation prod.map {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) /-- If the coproducts `W ⨿ X` and `Y ⨿ Z` exist, then every pair of morphisms `f : W ⟶ Y` and `g : W ⟶ Z` induces a morphism `coprod.map f g : W ⨿ X ⟶ Y ⨿ Z`. -/ abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) section prod_lemmas variable [has_limits_of_shape.{v} (discrete walking_pair) C] @[reassoc] lemma prod.map_fst {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.fst = prod.fst ≫ f := by simp @[reassoc] lemma prod.map_snd {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : prod.map f g ≫ prod.snd = prod.snd ≫ g := by simp @[simp] lemma prod_map_id_id {X Y : C} : prod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by tidy @[simp] lemma prod_lift_fst_snd {X Y : C} : prod.lift prod.fst prod.snd = 𝟙 (X ⨯ Y) := by tidy -- I don't think it's a good idea to make any of the following simp lemmas. @[reassoc] lemma prod_map_map {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : prod.map (𝟙 X) f ≫ prod.map g (𝟙 B) = prod.map g (𝟙 A) ≫ prod.map (𝟙 Y) f := by tidy @[reassoc] lemma prod_map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : prod.map (f ≫ g) (𝟙 W) = prod.map f (𝟙 W) ≫ prod.map g (𝟙 W) := by tidy @[reassoc] lemma prod_map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : prod.map (𝟙 W) (f ≫ g) = prod.map (𝟙 W) f ≫ prod.map (𝟙 W) g := by tidy @[reassoc] lemma prod.lift_map (V W X Y Z : C) (f : V ⟶ W) (g : V ⟶ X) (h : W ⟶ Y) (k : X ⟶ Z) : prod.lift f g ≫ prod.map h k = prod.lift (f ≫ h) (g ≫ k) := by tidy end prod_lemmas section coprod_lemmas variable [has_colimits_of_shape.{v} (discrete walking_pair) C] @[reassoc] lemma coprod.inl_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inl ≫ coprod.map f g = f ≫ coprod.inl := by simp @[reassoc] lemma coprod.inr_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) : coprod.inr ≫ coprod.map f g = g ≫ coprod.inr := by simp @[simp] lemma coprod_map_id_id {X Y : C} : coprod.map (𝟙 X) (𝟙 Y) = 𝟙 _ := by tidy @[simp] lemma coprod_desc_inl_inr {X Y : C} : coprod.desc coprod.inl coprod.inr = 𝟙 (X ⨿ Y) := by tidy -- I don't think it's a good idea to make any of the following simp lemmas. @[reassoc] lemma coprod_map_map {A B X Y : C} (f : A ⟶ B) (g : X ⟶ Y) : coprod.map (𝟙 X) f ≫ coprod.map g (𝟙 B) = coprod.map g (𝟙 A) ≫ coprod.map (𝟙 Y) f := by tidy @[reassoc] lemma coprod_map_comp_id {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : coprod.map (f ≫ g) (𝟙 W) = coprod.map f (𝟙 W) ≫ coprod.map g (𝟙 W) := by tidy @[reassoc] lemma coprod_map_id_comp {X Y Z W : C} (f : X ⟶ Y) (g : Y ⟶ Z) : coprod.map (𝟙 W) (f ≫ g) = coprod.map (𝟙 W) f ≫ coprod.map (𝟙 W) g := by tidy @[reassoc] lemma coprod.map_desc {S T U V W : C} (f : U ⟶ S) (g : W ⟶ S) (h : T ⟶ U) (k : V ⟶ W) : coprod.map h k ≫ coprod.desc f g = coprod.desc (h ≫ f) (k ≫ g) := by tidy end coprod_lemmas variables (C) /-- `has_binary_products` represents a choice of product for every pair of objects. -/ class has_binary_products := (has_limits_of_shape : has_limits_of_shape.{v} (discrete walking_pair) C) /-- `has_binary_coproducts` represents a choice of coproduct for every pair of objects. -/ class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape.{v} (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_finite_products.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 100] -- see Note [lower instance priority] instance [has_finite_coproducts.{v} C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ def has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ def has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } } section variables {C} [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash /-- The binary product functor. -/ @[simps] def prod_functor : C ⥤ C ⥤ C := { obj := λ X, { obj := λ Y, X ⨯ Y, map := λ Y Z, prod.map (𝟙 X) }, map := λ Y Z f, { app := λ T, prod.map f (𝟙 T) }} /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } /-- The braiding isomorphism can be passed through a map by swapping the order. -/ @[reassoc] lemma braid_natural {W X Y Z : C} (f : X ⟶ Y) (g : Z ⟶ W) : prod.map f g ≫ (prod.braiding _ _).hom = (prod.braiding _ _).hom ≫ prod.map g f := by tidy @[simp, reassoc] lemma prod.symmetry' (P Q : C) : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ @[reassoc] lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } /-- The product functor can be decomposed. -/ def prod_functor_left_comp (X Y : C) : prod_functor.obj (X ⨯ Y) ≅ prod_functor.obj Y ⋙ prod_functor.obj X := nat_iso.of_components (prod.associator _ _) (by tidy) @[reassoc] lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y⨯Z)).hom := by tidy @[reassoc] lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy variables [has_terminal.{v} C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } @[reassoc] lemma prod_left_unitor_hom_naturality (f : X ⟶ Y): prod.map (𝟙 _) f ≫ (prod.left_unitor Y).hom = (prod.left_unitor X).hom ≫ f := prod.map_snd _ _ @[reassoc] lemma prod_left_unitor_inv_naturality (f : X ⟶ Y): (prod.left_unitor X).inv ≫ prod.map (𝟙 _) f = f ≫ (prod.left_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod_left_unitor_hom_naturality] @[reassoc] lemma prod_right_unitor_hom_naturality (f : X ⟶ Y): prod.map f (𝟙 _) ≫ (prod.right_unitor Y).hom = (prod.right_unitor X).hom ≫ f := prod.map_fst _ _ @[reassoc] lemma prod_right_unitor_inv_naturality (f : X ⟶ Y): (prod.right_unitor X).inv ≫ prod.map f (𝟙 _) = f ≫ (prod.right_unitor Y).inv := by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, prod_right_unitor_hom_naturality] lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[simp] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X⨿Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W⨿X) Y Z).hom ≫ (coprod.associator W X (Y⨿Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial.{v} C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
29d447e826a46a92119f90f1ac258a9585dc8816
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/nat/part_enat.lean
b781908972ff08d0d0c04c992e6c244d77426a43
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
21,114
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.hom.equiv.basic import data.part import data.enat.lattice import tactic.norm_num /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. This implementation uses `part ℕ` as an implementation. Use `ℕ∞` instead unless you care about computability. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid part_enat` * `canonically_ordered_add_monoid part_enat` * `complete_linear_order part_enat` There is no additive analogue of `monoid_with_zero`; if there were then `part_enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `part_enat` to `ℕ∞`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : part_enat ≃+ ℕ∞` * `with_top_order_iso : part_enat ≃o ℕ∞` ## Implementation details `part_enat` is defined to be `part ℕ`. `+` and `≤` are defined on `part_enat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `part_enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags part_enat, ℕ∞ -/ open part (hiding some) /-- Type of natural numbers with infinity (`⊤`) -/ def part_enat : Type := part ℕ namespace part_enat /-- The computable embedding `ℕ → part_enat`. This coincides with the coercion `coe : ℕ → part_enat`, see `part_enat.some_eq_coe`. However, `coe` is noncomputable so `some` is preferable when computability is a concern. -/ def some : ℕ → part_enat := part.some instance : has_zero part_enat := ⟨some 0⟩ instance : inhabited part_enat := ⟨0⟩ instance : has_one part_enat := ⟨some 1⟩ instance : has_add part_enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance (n : ℕ) : decidable (some n).dom := is_true trivial @[simp] lemma dom_some (x : ℕ) : (some x).dom := trivial instance : add_comm_monoid part_enat := { add := (+), zero := (0), add_comm := λ x y, part.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, part.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, part.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, part.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : add_comm_monoid_with_one part_enat := { one := 1, nat_cast := some, nat_cast_zero := rfl, nat_cast_succ := λ _, part.ext' (true_and _).symm (λ _ _, rfl), .. part_enat.add_comm_monoid } lemma some_eq_coe (n : ℕ) : some n = n := rfl @[simp, norm_cast] lemma coe_inj {x y : ℕ} : (x : part_enat) = y ↔ x = y := part.some_inj @[simp] lemma dom_coe (x : ℕ) : (x : part_enat).dom := trivial instance : has_le part_enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top part_enat := ⟨none⟩ instance : has_bot part_enat := ⟨0⟩ instance : has_sup part_enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ lemma le_def (x y : part_enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy := iff.rfl @[elab_as_eliminator] protected lemma cases_on' {P : part_enat → Prop} : ∀ a : part_enat, P ⊤ → (∀ n : ℕ, P (some n)) → P a := part.induction_on @[elab_as_eliminator] protected lemma cases_on {P : part_enat → Prop} : ∀ a : part_enat, P ⊤ → (∀ n : ℕ, P n) → P a := by { simp only [← some_eq_coe], exact part_enat.cases_on' } @[simp] lemma top_add (x : part_enat) : ⊤ + x = ⊤ := part.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : part_enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] lemma coe_get {x : part_enat} (h : x.dom) : (x.get h : part_enat) = x := by { rw [← some_eq_coe], exact part.ext' (iff_of_true trivial h) (λ _ _, rfl) } @[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : part_enat).dom) : get (x : part_enat) h = x := by rw [← coe_inj, coe_get] lemma get_coe {x : ℕ} : get (x : part_enat) (dom_coe x) = x := get_coe' _ _ lemma coe_add_get {x : ℕ} {y : part_enat} (h : ((x : part_enat) + y).dom) : get ((x : part_enat) + y) h = x + get y h.2 := by { simp only [← some_eq_coe] at h ⊢, refl } @[simp] lemma get_add {x y : part_enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma get_zero (h : (0 : part_enat).dom) : (0 : part_enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : part_enat).dom) : (1 : part_enat).get h = 1 := rfl lemma get_eq_iff_eq_some {a : part_enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some lemma get_eq_iff_eq_coe {a : part_enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some, some_eq_coe] lemma dom_of_le_of_dom {x y : part_enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h lemma dom_of_le_some {x : part_enat} {y : ℕ} (h : x ≤ some y) : x.dom := dom_of_le_of_dom h trivial lemma dom_of_le_coe {x : part_enat} {y : ℕ} (h : x ≤ y) : x.dom := by { rw [← some_eq_coe] at h, exact dom_of_le_some h } instance decidable_le (x y : part_enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) := if hx : x.dom then decidable_of_decidable_of_iff (show decidable (∀ (hy : (y : part_enat).dom), x.get hx ≤ (y : part_enat).get hy), from forall_prop_decidable _) $ by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] } else if hy : y.dom then is_false $ λ h, hx $ dom_of_le_of_dom h hy else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩ /-- The coercion `ℕ → part_enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ part_enat := ⟨coe, nat.cast_zero, nat.cast_add⟩ @[simp] lemma coe_coe_hom : ⇑coe_hom = coe := rfl instance : partial_order part_enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_rfl⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, part.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } lemma lt_def (x y : part_enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy := begin rw [lt_iff_le_not_le, le_def, le_def, not_exists], split, { rintro ⟨⟨hyx, H⟩, h⟩, by_cases hx : x.dom, { use hx, intro hy, specialize H hy, specialize h (λ _, hy), rw not_forall at h, cases h with hx' h, rw not_le at h, exact h }, { specialize h (λ hx', (hx hx').elim), rw not_forall at h, cases h with hx' h, exact (hx hx').elim } }, { rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ } end @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : part_enat) ≤ y ↔ x ≤ y := by { rw [← some_eq_coe, ← some_eq_coe], exact ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ } @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : part_enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] @[simp] lemma get_le_get {x y : part_enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} lemma le_coe_iff (x : part_enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n := begin rw [← some_eq_coe], show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n, simp only [forall_prop_of_true, some_eq_coe, dom_coe, get_coe'] end lemma lt_coe_iff (x : part_enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe] lemma coe_le_iff (n : ℕ) (x : part_enat) : (n : part_enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h := begin rw [← some_eq_coe], simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end lemma coe_lt_iff (n : ℕ) (x : part_enat) : (n : part_enat) < x ↔ ∀ h : x.dom, n < x.get h := begin rw [← some_eq_coe], simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end instance ne_zero.one : ne_zero (1 : part_enat) := ⟨coe_inj.not.mpr dec_trivial⟩ instance semilattice_sup : semilattice_sup part_enat := { sup := (⊔), le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..part_enat.partial_order } instance order_bot : order_bot part_enat := { bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩ } instance order_top : order_top part_enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩ } lemma eq_zero_iff {x : part_enat} : x = 0 ↔ x ≤ 0 := eq_bot_iff lemma ne_zero_iff {x : part_enat} : x ≠ 0 ↔ ⊥ < x := bot_lt_iff_ne_bot.symm lemma dom_of_lt {x y : part_enat} : x < y → x.dom := part_enat.cases_on x not_top_lt $ λ _ _, dom_coe _ lemma top_eq_none : (⊤ : part_enat) = none := rfl @[simp] lemma coe_lt_top (x : ℕ) : (x : part_enat) < ⊤ := ne.lt_top (λ h, absurd (congr_arg dom h) $ by simpa only [dom_coe] using true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : part_enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma not_is_max_coe (x : ℕ) : ¬ is_max (x : part_enat) := not_is_max_of_lt (coe_lt_top x) lemma ne_top_iff {x : part_enat} : x ≠ ⊤ ↔ ∃ (n : ℕ), x = n := by simpa only [← some_eq_coe] using part.ne_none_iff lemma ne_top_iff_dom {x : part_enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 part.eq_none_iff'.symm lemma not_dom_iff_eq_top {x : part_enat} : ¬ x.dom ↔ x = ⊤ := iff.not_left ne_top_iff_dom.symm lemma ne_top_of_lt {x y : part_enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma eq_top_iff_forall_lt (x : part_enat) : x = ⊤ ↔ ∀ n : ℕ, (n : part_enat) < x := begin split, { rintro rfl n, exact coe_lt_top _ }, { contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ } end lemma eq_top_iff_forall_le (x : part_enat) : x = ⊤ ↔ ∀ n : ℕ, (n : part_enat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ lemma pos_iff_one_le {x : part_enat} : 0 < x ↔ 1 ≤ x := part_enat.cases_on x (by simp only [iff_true, le_top, coe_lt_top, ← @nat.cast_zero part_enat]) $ λ n, by { rw [← nat.cast_zero, ← nat.cast_one, part_enat.coe_lt_coe, part_enat.coe_le_coe], refl } instance : is_total part_enat (≤) := { total := λ x y, part_enat.cases_on x (or.inr le_top) (part_enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))) } noncomputable instance : linear_order part_enat := { le_total := is_total.total, decidable_le := classical.dec_rel _, max := (⊔), max_def := @sup_eq_max_default _ _ (id _) _, ..part_enat.partial_order } instance : bounded_order part_enat := { ..part_enat.order_top, ..part_enat.order_bot } noncomputable instance : lattice part_enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..part_enat.semilattice_sup } instance : ordered_add_comm_monoid part_enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, part_enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro (dom_coe _) (h₁ h.2), λ h, by simpa only [coe_add_get] using add_le_add_left (h₂ _) c⟩), ..part_enat.linear_order, ..part_enat.add_comm_monoid } instance : canonically_ordered_add_monoid part_enat := { le_self_add := λ a b, part_enat.cases_on b (le_top.trans_eq (add_top _).symm) $ λ b, part_enat.cases_on a (top_add _).ge $ λ a, (coe_le_coe.2 le_self_add).trans_eq (nat.cast_add _ _), exists_add_of_le := λ a b, part_enat.cases_on b (λ _, ⟨⊤, (add_top _).symm⟩) $ λ b, part_enat.cases_on a (λ h, ((coe_lt_top _).not_le h).elim) $ λ a h, ⟨(b - a : ℕ), by rw [←nat.cast_add, coe_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩, ..part_enat.semilattice_sup, ..part_enat.order_bot, ..part_enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : part_enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using part_enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : part_enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, part_enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : part_enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, part_enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : part_enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← part_enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : part_enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [part_enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : part_enat} (h : x < y + 1) : x ≤ y := begin induction y using part_enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : part_enat} (h : x < y) : x + 1 ≤ y := begin induction y using part_enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : part_enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using part_enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : part_enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using part_enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : part_enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply part_enat.cases_on a; apply part_enat.cases_on b; simp; simp only [(nat.cast_add _ _).symm, part_enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : part_enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply part_enat.cases_on a; apply part_enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : part_enat)]; simp only [(nat.cast_add _ _).symm, add_left_cancel_iff, part_enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : part_enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, part_enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `part_enat` to a `ℕ∞`. -/ def to_with_top (x : part_enat) [decidable x.dom] : ℕ∞ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : part_enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : part_enat).dom} : to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_some (n : ℕ) : to_with_top (some n) = n := rfl lemma to_with_top_coe (n : ℕ) {_ : decidable (n : part_enat).dom} : to_with_top n = n := by simp only [← some_eq_coe, ← to_with_top_some] @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : part_enat).dom} : to_with_top (n : part_enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : part_enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := part_enat.cases_on y (by simp) (part_enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : part_enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le end with_top section with_top_equiv open_locale classical @[simp] lemma to_with_top_add {x y : part_enat} : to_with_top (x + y) = to_with_top x + to_with_top y := by apply part_enat.cases_on y; apply part_enat.cases_on x; simp [← nat.cast_add, ← enat.coe_add] /-- `equiv` between `part_enat` and `ℕ∞` (for the order isomorphism see `with_top_order_iso`). -/ noncomputable def with_top_equiv : part_enat ≃ ℕ∞ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (option.some n) := coe n | none := ⊤ end, left_inv := λ x, by apply part_enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := by simpa only [nat.cast_zero] using with_top_equiv_coe 0 @[simp] lemma with_top_equiv_le {x y : part_enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : part_enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `part_enat` and `ℕ∞`. -/ noncomputable def with_top_order_iso : part_enat ≃o ℕ∞ := { map_rel_iff' := λ _ _, with_top_equiv_le, .. with_top_equiv} @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : ℕ∞} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : ℕ∞} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp /-- `to_with_top` induces an additive monoid isomorphism between `part_enat` and `ℕ∞`. -/ noncomputable def with_top_add_equiv : part_enat ≃+ ℕ∞ := { map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add, ..with_top_equiv} end with_top_equiv lemma lt_wf : @well_founded part_enat (<) := begin classical, change well_founded (λ a b : part_enat, a < b), simp_rw ←to_with_top_lt, exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) end instance : well_founded_lt part_enat := ⟨lt_wf⟩ instance : is_well_order part_enat (<) := { } instance : has_well_founded part_enat := ⟨(<), lt_wf⟩ section find variables (P : ℕ → Prop) [decidable_pred P] /-- The smallest `part_enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : part_enat := ⟨∃ n, P n, nat.find⟩ @[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl lemma find_dom (h : ∃ n, P n) : (find P).dom := h lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : part_enat) < find P := begin rw coe_lt_iff, intro h', rw find_get, have := @nat.find_spec P _ h', contrapose! this, exact h _ this end lemma lt_find_iff (n : ℕ) : (n : part_enat) < find P ↔ (∀ m ≤ n, ¬P m) := begin refine ⟨_, lt_find P n⟩, intros h m hm, by_cases H : (find P).dom, { apply nat.find_min H, rw coe_lt_iff at h, specialize h H, exact lt_of_le_of_lt hm h }, { exact not_exists.mp H m } end lemma find_le (n : ℕ) (h : P n) : find P ≤ n := by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ } lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩ end find noncomputable instance : linear_ordered_add_comm_monoid_with_top part_enat := { top_add' := top_add, .. part_enat.linear_order, .. part_enat.ordered_add_comm_monoid, .. part_enat.order_top } noncomputable instance : complete_linear_order part_enat := { inf := (⊓), sup := (⊔), top := ⊤, bot := ⊥, le := (≤), lt := (<), .. part_enat.lattice, .. with_top_order_iso.symm.to_galois_insertion.lift_complete_lattice, .. part_enat.linear_order, } end part_enat
164e09bad116e55b7af7843006ce824477ed6593
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/finsupp/to_dfinsupp.lean
a38c81d2d937bae78d3d2048358bb71d87f7b2cc
[ "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
10,874
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 data.dfinsupp import data.finsupp.basic import algebra.module.linear_map /-! # Conversion between `finsupp` and homogenous `dfinsupp` This module provides conversions between `finsupp` and `dfinsupp`. It is in its own file since neither `finsupp` or `dfinsupp` depend on each other. ## Main definitions * "identity" maps between `finsupp` and `dfinsupp`: * `finsupp.to_dfinsupp : (ι →₀ M) → (Π₀ i : ι, M)` * `dfinsupp.to_finsupp : (Π₀ i : ι, M) → (ι →₀ M)` * Bundled equiv versions of the above: * `finsupp_equiv_dfinsupp : (ι →₀ M) ≃ (Π₀ i : ι, M)` * `finsupp_add_equiv_dfinsupp : (ι →₀ M) ≃+ (Π₀ i : ι, M)` * `finsupp_lequiv_dfinsupp R : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M)` * stronger versions of `finsupp.split`: * `sigma_finsupp_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N))` * `sigma_finsupp_add_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N))` * `sigma_finsupp_lequiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N))` ## Theorems The defining features of these operations is that they preserve the function and support: * `finsupp.to_dfinsupp_coe` * `finsupp.to_dfinsupp_support` * `dfinsupp.to_finsupp_coe` * `dfinsupp.to_finsupp_support` and therefore map `finsupp.single` to `dfinsupp.single` and vice versa: * `finsupp.to_dfinsupp_single` * `dfinsupp.to_finsupp_single` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `finsupp.to_dfinsupp`: * `finsupp_add_equiv_dfinsupp_apply` * `finsupp_lequiv_dfinsupp_apply` * `finsupp_add_equiv_dfinsupp_symm_apply` * `finsupp_lequiv_dfinsupp_symm_apply` ## Implementation notes We provide `dfinsupp.to_finsupp` and `finsupp_equiv_dfinsupp` computably by adding `[decidable_eq ι]` and `[Π m : M, decidable (m ≠ 0)]` arguments. To aid with definitional unfolding, these arguments are also present on the `noncomputable` equivs. -/ variables {ι : Type*} {R : Type*} {M : Type*} /-! ### Basic definitions and lemmas -/ section defs /-- Interpret a `finsupp` as a homogenous `dfinsupp`. -/ def finsupp.to_dfinsupp [has_zero M] (f : ι →₀ M) : Π₀ i : ι, M := ⟦⟨f, f.support.1, λ i, (classical.em (f i = 0)).symm.imp_left (finsupp.mem_support_iff.mpr)⟩⟧ @[simp] lemma finsupp.to_dfinsupp_coe [has_zero M] (f : ι →₀ M) : ⇑f.to_dfinsupp = f := rfl section variables [decidable_eq ι] [has_zero M] @[simp] lemma finsupp.to_dfinsupp_single (i : ι) (m : M) : (finsupp.single i m).to_dfinsupp = dfinsupp.single i m := by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] } variables [Π m : M, decidable (m ≠ 0)] @[simp] lemma to_dfinsupp_support (f : ι →₀ M) : f.to_dfinsupp.support = f.support := by { ext, simp, } /-- Interpret a homogenous `dfinsupp` as a `finsupp`. Note that the elaborator has a lot of trouble with this definition - it is often necessary to write `(dfinsupp.to_finsupp f : ι →₀ M)` instead of `f.to_finsupp`, as for some unknown reason using dot notation or omitting the type ascription prevents the type being resolved correctly. -/ def dfinsupp.to_finsupp (f : Π₀ i : ι, M) : ι →₀ M := ⟨f.support, f, λ i, by simp only [dfinsupp.mem_support_iff]⟩ @[simp] lemma dfinsupp.to_finsupp_coe (f : Π₀ i : ι, M) : ⇑f.to_finsupp = f := rfl @[simp] lemma dfinsupp.to_finsupp_support (f : Π₀ i : ι, M) : f.to_finsupp.support = f.support := by { ext, simp, } @[simp] lemma dfinsupp.to_finsupp_single (i : ι) (m : M) : (dfinsupp.single i m : Π₀ i : ι, M).to_finsupp = finsupp.single i m := by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] } @[simp] lemma finsupp.to_dfinsupp_to_finsupp (f : ι →₀ M) : f.to_dfinsupp.to_finsupp = f := finsupp.coe_fn_injective rfl @[simp] lemma dfinsupp.to_finsupp_to_dfinsupp (f : Π₀ i : ι, M) : f.to_finsupp.to_dfinsupp = f := dfinsupp.coe_fn_injective rfl end end defs /-! ### Lemmas about arithmetic operations -/ section lemmas namespace finsupp @[simp] lemma to_dfinsupp_zero [has_zero M] : (0 : ι →₀ M).to_dfinsupp = 0 := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_add [add_zero_class M] (f g : ι →₀ M) : (f + g).to_dfinsupp = f.to_dfinsupp + g.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_neg [add_group M] (f : ι →₀ M) : (-f).to_dfinsupp = -f.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_sub [add_group M] (f g : ι →₀ M) : (f - g).to_dfinsupp = f.to_dfinsupp - g.to_dfinsupp := dfinsupp.coe_fn_injective (sub_eq_add_neg _ _) @[simp] lemma to_dfinsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M] (r : R) (f : ι →₀ M) : (r • f).to_dfinsupp = r • f.to_dfinsupp := dfinsupp.coe_fn_injective rfl end finsupp namespace dfinsupp variables [decidable_eq ι] @[simp] lemma to_finsupp_zero [has_zero M] [Π m : M, decidable (m ≠ 0)] : to_finsupp 0 = (0 : ι →₀ M) := finsupp.coe_fn_injective rfl @[simp] lemma to_finsupp_add [add_zero_class M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) : (to_finsupp (f + g) : ι →₀ M) = (to_finsupp f + to_finsupp g) := finsupp.coe_fn_injective $ dfinsupp.coe_add _ _ @[simp] lemma to_finsupp_neg [add_group M] [Π m : M, decidable (m ≠ 0)] (f : Π₀ i : ι, M) : (to_finsupp (-f) : ι →₀ M) = -to_finsupp f := finsupp.coe_fn_injective $ dfinsupp.coe_neg _ @[simp] lemma to_finsupp_sub [add_group M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) : (to_finsupp (f - g) : ι →₀ M) = to_finsupp f - to_finsupp g := finsupp.coe_fn_injective $ dfinsupp.coe_sub _ _ @[simp] lemma to_finsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M] [Π m : M, decidable (m ≠ 0)] (r : R) (f : Π₀ i : ι, M) : (to_finsupp (r • f) : ι →₀ M) = r • to_finsupp f := finsupp.coe_fn_injective $ dfinsupp.coe_smul _ _ end dfinsupp end lemmas /-! ### Bundled `equiv`s -/ section equivs /-- `finsupp.to_dfinsupp` and `dfinsupp.to_finsupp` together form an equiv. -/ @[simps {fully_applied := ff}] def finsupp_equiv_dfinsupp [decidable_eq ι] [has_zero M] [Π m : M, decidable (m ≠ 0)] : (ι →₀ M) ≃ (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, left_inv := finsupp.to_dfinsupp_to_finsupp, right_inv := dfinsupp.to_finsupp_to_dfinsupp } /-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because `finsupp.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] noncomputable def finsupp_add_equiv_dfinsupp [decidable_eq ι] [add_zero_class M] [Π m : M, decidable (m ≠ 0)] : (ι →₀ M) ≃+ (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, map_add' := finsupp.to_dfinsupp_add, .. finsupp_equiv_dfinsupp} variables (R) /-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because `finsupp.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] noncomputable def finsupp_lequiv_dfinsupp [decidable_eq ι] [semiring R] [add_comm_monoid M] [Π m : M, decidable (m ≠ 0)] [module R M] : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, map_smul' := finsupp.to_dfinsupp_smul, map_add' := finsupp.to_dfinsupp_add, .. finsupp_equiv_dfinsupp} section sigma /-- ### Stronger versions of `finsupp.split` -/ noncomputable theory open_locale classical variables {η : ι → Type*} {N : Type*} [semiring R] open finsupp /-- `finsupp.split` is an equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ def sigma_finsupp_equiv_dfinsupp [has_zero N] : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N)) := { to_fun := λ f, ⟦⟨split f, (split_support f : finset ι).val, λ i, begin rw [← finset.mem_def, mem_split_support_iff_nonzero], exact (decidable.em _).symm end⟩⟧, inv_fun := λ f, begin refine on_finset (finset.sigma f.support (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨_, mem_support_iff.mpr hg⟩), simp only [ne.def, dfinsupp.mem_support_to_fun], intro h, rw h at hg, simpa using hg end, left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_dfinsupp_apply [has_zero N] (f : (Σ i, η i) →₀ N) : (sigma_finsupp_equiv_dfinsupp f : Π i, (η i →₀ N)) = finsupp.split f := rfl @[simp] lemma sigma_finsupp_equiv_dfinsupp_symm_apply [has_zero N] (f : Π₀ i, (η i →₀ N)) (s : Σ i, η i) : (sigma_finsupp_equiv_dfinsupp.symm f : (Σ i, η i) →₀ N) s = f s.1 s.2 := rfl @[simp] lemma sigma_finsupp_equiv_dfinsupp_support [has_zero N] (f : (Σ i, η i) →₀ N) : (sigma_finsupp_equiv_dfinsupp f).support = finsupp.split_support f := begin ext, rw dfinsupp.mem_support_to_fun, exact (finsupp.mem_split_support_iff_nonzero _ _).symm, end -- Without this Lean fails to find the `add_zero_class` instance on `Π₀ i, (η i →₀ N)`. local attribute [-instance] finsupp.has_zero @[simp] lemma sigma_finsupp_equiv_dfinsupp_add [add_zero_class N] (f g : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (f + g) = (sigma_finsupp_equiv_dfinsupp f + (sigma_finsupp_equiv_dfinsupp g) : (Π₀ (i : ι), η i →₀ N)) := by {ext, refl} /-- `finsupp.split` is an additive equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigma_finsupp_add_equiv_dfinsupp [add_zero_class N] : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N)) := { to_fun := sigma_finsupp_equiv_dfinsupp, inv_fun := sigma_finsupp_equiv_dfinsupp.symm, map_add' := sigma_finsupp_equiv_dfinsupp_add, .. sigma_finsupp_equiv_dfinsupp } local attribute [-instance] finsupp.add_zero_class --tofix: r • (sigma_finsupp_equiv_dfinsupp f) doesn't work. @[simp] lemma sigma_finsupp_equiv_dfinsupp_smul {R} [monoid R] [add_monoid N] [distrib_mul_action R N] (r : R) (f : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (r • f) = @has_scalar.smul R (Π₀ i, η i →₀ N) mul_action.to_has_scalar r (sigma_finsupp_equiv_dfinsupp f) := by { ext, refl } local attribute [-instance] finsupp.add_monoid /-- `finsupp.split` is a linear equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigma_finsupp_lequiv_dfinsupp [add_comm_monoid N] [module R N] : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N)) := { map_smul' := sigma_finsupp_equiv_dfinsupp_smul, .. sigma_finsupp_add_equiv_dfinsupp } end sigma end equivs
145f43f7d1276984edfecd35ccb7be741936be22
492a7e27d49633a89f7ce6e1e28f676b062fcbc9
/src/monoidal_categories_reboot/tensor_product.lean
7c0d5e913d8e0b589ae971640ff5c0cc396fca6f
[ "Apache-2.0" ]
permissive
semorrison/monoidal-categories-reboot
9edba30277de48a234b63813cf85b171772ce36f
48b5f1d535daba4e591672042a298ac36be2e6dd
refs/heads/master
1,642,472,396,149
1,560,587,477,000
1,560,587,477,000
156,465,626
0
1
null
1,541,549,278,000
1,541,549,278,000
null
UTF-8
Lean
false
false
3,342
lean
-- -- Copyright (c) 2018 Michael Jendrusch. All rights reserved. -- -- Released under Apache 2.0 license as described in the file LICENSE. -- -- Authors: Michael Jendrusch, Scott Morrison -- import category_theory.products -- universes v u -- open category_theory -- namespace category_theory.monoidal -- @[reducible] def tensor_obj_type -- (C : Sort u) [category.{v} C] := -- C → C → C -- @[reducible] def tensor_hom_type -- {C : Sort u} [category.{v} C] (tensor_obj : tensor_obj_type C) : Sort (imax u u u u v) := -- Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((tensor_obj X₁ X₂) ⟶ (tensor_obj Y₁ Y₂)) -- def assoc_obj -- {C : Sort u} [category.{v} C] (tensor_obj : tensor_obj_type C) : Sort (max u v 1) := -- Π X Y Z : C, (tensor_obj (tensor_obj X Y) Z) ≅ (tensor_obj X (tensor_obj Y Z)) -- def assoc_natural -- {C : Sort u} [category.{v} C] -- (tensor_obj : tensor_obj_type C) -- (tensor_hom : tensor_hom_type tensor_obj) -- (assoc : assoc_obj tensor_obj) : Prop := -- ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), -- (tensor_hom (tensor_hom f₁ f₂) f₃) ≫ (assoc Y₁ Y₂ Y₃).hom = (assoc X₁ X₂ X₃).hom ≫ (tensor_hom f₁ (tensor_hom f₂ f₃)) -- def left_unitor_obj -- {C : Sort u} [category.{v} C] -- (tensor_obj : tensor_obj_type C) -- (tensor_unit : C) : Sort (max v 1 u) := -- Π X : C, (tensor_obj tensor_unit X) ≅ X -- def left_unitor_natural -- {C : Sort u} [category.{v} C] -- (tensor_obj : tensor_obj_type C) -- (tensor_hom : tensor_hom_type tensor_obj) -- (tensor_unit : C) -- (left_unitor : left_unitor_obj tensor_obj tensor_unit) : Prop := -- ∀ {X Y : C} (f : X ⟶ Y), -- (tensor_hom (𝟙 tensor_unit) f) ≫ (left_unitor Y).hom = (left_unitor X).hom ≫ f -- def right_unitor_obj -- {C : Sort u} [category.{v} C] -- (tensor_obj : tensor_obj_type C) -- (tensor_unit : C) : Sort (max v 1 u) := -- Π (X : C), (tensor_obj X tensor_unit) ≅ X -- def right_unitor_natural -- {C : Sort u} [category.{v} C] -- (tensor_obj : tensor_obj_type C) -- (tensor_hom : tensor_hom_type tensor_obj) -- (tensor_unit : C) -- (right_unitor : right_unitor_obj tensor_obj tensor_unit) : Prop := -- ∀ {X Y : C} (f : X ⟶ Y), -- (tensor_hom f (𝟙 tensor_unit)) ≫ (right_unitor Y).hom = (right_unitor X).hom ≫ f -- @[reducible] def pentagon -- {C : Sort u} [category.{v} C] -- {tensor_obj : tensor_obj_type C} -- (tensor_hom : tensor_hom_type tensor_obj) -- (assoc : assoc_obj tensor_obj) : Prop := -- ∀ W X Y Z : C, -- (tensor_hom (assoc W X Y).hom (𝟙 Z)) ≫ (assoc W (tensor_obj X Y) Z).hom ≫ (tensor_hom (𝟙 W) (assoc X Y Z).hom) -- = (assoc (tensor_obj W X) Y Z).hom ≫ (assoc W X (tensor_obj Y Z)).hom -- @[reducible] def triangle -- {C : Sort u} [category.{v} C] -- {tensor_obj : tensor_obj_type C} {tensor_unit : C} -- (tensor_hom : tensor_hom_type tensor_obj) -- (left_unitor : left_unitor_obj tensor_obj tensor_unit) -- (right_unitor : right_unitor_obj tensor_obj tensor_unit) -- (assoc : assoc_obj tensor_obj) : Prop := -- ∀ X Y : C, -- (assoc X tensor_unit Y).hom ≫ (tensor_hom (𝟙 X) (left_unitor Y).hom) -- = tensor_hom (right_unitor X).hom (𝟙 Y) -- end category_theory.monoidal
1dd4d55fc6b871c06c8d93edf78ff3131bcc62b9
de3bb37f178fdd10c6dc8c5de6cf51de10c1ba17
/two_adj.lean
99702153b901f2dcf6e87ab925faea26991b4281
[]
no_license
RyanSandford/HOTT-adjoint-equivalences
e58b2be0cb2ebba260f45f46ff4668b14442df98
331a4e6085bc35ab19a59ef28a60f299dee4dc6d
refs/heads/master
1,622,097,493,839
1,618,173,901,000
1,618,173,901,000
254,230,569
0
0
null
null
null
null
UTF-8
Lean
false
false
18,261
lean
/- Authors: Daniel Carranza, Jonathon Chang, Ryan Sandford Under the supervision of Chris Kapulkin Theorems about two half-adjoint equivalences, including a proof that two left half-adjoint and two right half-adjoint equivalences are propositions and that the two full-adjoint equivalence is equivalent to a non-propositional type Last updated: 2020-07-31 -/ import hott.init hott.types.sigma hott.types.prod hott.types.pi hott.types.fiber hott.types.equiv .adj .prelim universes u v hott_theory namespace hott open hott hott.eq hott.is_trunc hott.sigma -- This is used in the definition of the compatibilites for -- a two half-adjoint and two left half-adjoint equivalence @[hott] def nat_coh {A : Type u} {B : Type _} (g : B → A) (f : A → B) (H : g ∘ f ~ id) (x : A) : H (g (f x)) = ap g (ap f (H x)) := cancel_right (H x) (ap_con_eq_con H (H x))⁻¹ ⬝ ap_compose g f _ namespace equiv variables {A B: Type u} -- Right coherence for two half-adjoint equivalence @[hott] def r2coh (f : A → B) (h : adj f) (x : A) := nat_coh h.inv f h.η x ⬝ ap02 h.inv (h.τ x) = h.θ (f x) -- Left coherence for two half-adjoint equivalence @[hott] def l2coh (f : A → B) (h : adj f) (y : B) := h.τ (h.inv y) ⬝ (nat_coh f h.inv h.ε y) = ap02 f (h.θ y) -- Definition of a two (right) half-adjoint equivalence @[hott] def is_two_hae (f : A → B) := Σ(g : B → A) (η : g ∘ f ~ id) (ε: f ∘ g ~ id) (τ : Π(x : A), rcoh f ⟨g, (η, ε)⟩ x) (θ : Π(y : B), lcoh f ⟨g, (η, ε)⟩ y), Π(x : A), r2coh f ⟨g, ⟨η, ⟨ε, (τ, θ)⟩⟩⟩ x @[hott, reducible] def is_two_hae.inv {f : A → B} (h : is_two_hae f) := h.1 @[hott, reducible] def is_two_hae.η {f : A → B} (h : is_two_hae f) := h.2.1 @[hott, reducible] def is_two_hae.ε {f : A → B} (h : is_two_hae f) := h.2.2.1 @[hott, reducible] def is_two_hae.τ {f : A → B} (h : is_two_hae f) := h.2.2.2.1 @[hott, reducible] def is_two_hae.θ {f : A → B} (h : is_two_hae f) := h.2.2.2.2.1 @[hott, reducible] def is_two_hae.α {f : A → B} (h : is_two_hae f) := h.2.2.2.2.2 @[hott] def is_two_hae_to_is_equiv (f : A → B) : is_two_hae f → is_equiv f := λh, hott.is_equiv.mk f h.inv h.ε h.η h.τ⁻¹ʰᵗʸ -- Definition of a two left half-adjoint equivalence @[hott] def is_two_hae_l (f : A → B) := Σ(g : B → A) (η : g ∘ f ~ id) (ε: f ∘ g ~ id) (τ : Π(x : A), rcoh f ⟨g, (η, ε)⟩ x) (θ : Π(y : B), lcoh f ⟨g, (η, ε)⟩ y), Π(y : B), l2coh f ⟨g, ⟨η, ⟨ε, (τ, θ)⟩⟩⟩ y @[hott, reducible] def is_two_hae_l.inv {f : A → B} (h : is_two_hae_l f) := h.1 @[hott, reducible] def is_two_hae_l.η {f : A → B} (h : is_two_hae_l f) := h.2.1 @[hott, reducible] def is_two_hae_l.ε {f : A → B} (h : is_two_hae_l f) := h.2.2.1 @[hott, reducible] def is_two_hae_l.τ {f : A → B} (h : is_two_hae_l f) := h.2.2.2.1 @[hott, reducible] def is_two_hae_l.θ {f : A → B} (h : is_two_hae_l f) := h.2.2.2.2.1 @[hott, reducible] def is_two_hae_l.β {f : A → B} (h : is_two_hae_l f) := h.2.2.2.2.2 @[hott] def is_two_hae_l_to_is_equiv (f : A → B) : is_two_hae_l f → is_equiv f := λh, is_equiv.adjointify f h.inv h.ε h.η @[hott] def l2coh_equiv_fib_eq (f : A → B) (h : is_equiv f) : (Σ(l : Π(y : B), lcoh f ⟨h.inv, (h.left_inv, h.right_inv)⟩ y), Π(y : B), l2coh f ⟨h.inv, ⟨h.left_inv, ⟨h.right_inv, (h.adj⁻¹ʰᵗʸ, l)⟩⟩⟩ y) ≃ Π(y : B), fiber.mk ((is_equiv.left_inv f) ((is_equiv.inv f) y)) (h.adj⁻¹ʰᵗʸ ((is_equiv.inv f) y) ⬝ nat_coh f h.inv h.right_inv y) = fiber.mk (ap h.inv ((is_equiv.right_inv f) y)) rfl := sigma.sigma_pi_equiv_pi_sigma (λ(y : B) l : lcoh f ⟨h.inv, (h.left_inv, h.right_inv)⟩ y, h.adj⁻¹ʰᵗʸ (is_equiv.inv f y) ⬝ (nat_coh f h.inv h.right_inv y) = ap02 f l) ⬝e pi.pi_equiv_pi_right (λy : B, (fiber.fiber_eq_equiv (fiber.mk ((is_equiv.left_inv f) ((is_equiv.inv f) y)) (@concat _ _ _ _ ((is_equiv.adj f)⁻¹ʰᵗʸ ((is_equiv.inv f) y)) (nat_coh f h.inv h.right_inv y))) (fiber.mk (ap h.inv ((is_equiv.right_inv f) y)) rfl))⁻¹ᵉ) @[hott] def r2coh_equiv_fib_eq (f : A → B) (h : is_hadj_l f) : (Σ(r : Π(x : A), rcoh f ⟨h.inv, (h.η, h.ε)⟩ x), Π(x : A), nat_coh h.inv f h.η x ⬝ ap02 h.inv (r x) = h.θ (f x)) ≃ Π(x : A), fiber.mk (ap f (h.η x)) ((nat_coh h.inv f h.η x)⁻¹ ⬝ h.θ (f x)) = fiber.mk (h.ε (f x)) rfl := sigma.sigma_pi_equiv_pi_sigma (λ(x : A) r : rcoh f ⟨h.inv, (h.η, h.ε)⟩ x, nat_coh h.inv f h.η x ⬝ ap02 h.inv r = h.θ (f x)) ⬝e pi.pi_equiv_pi_right (λx : A, @sigma.sigma_equiv_sigma_right _ (λr, nat_coh h.inv f h.η x ⬝ ap02 h.inv r = h.θ (f x)) (λr, (nat_coh h.inv f h.η x)⁻¹ ⬝ h.θ (f x) = ap02 h.inv r) (λr : rcoh f ⟨h.inv, (h.η, h.ε)⟩ x, (@eq_inv_con_equiv_con_eq _ _ _ _ (ap02 h.inv r) (h.θ (f x)) (nat_coh h.inv f h.η x))⁻¹ᵉ ⬝e eq_equiv_eq_symm (ap02 h.inv r) ((nat_coh h.inv f h.η x)⁻¹ ⬝ h.θ (f x)))) ⬝e pi.pi_equiv_pi_right (λx : A, (fiber.fiber_eq_equiv (fiber.mk (ap f (h.η x)) ((nat_coh h.inv f h.η x)⁻¹ ⬝ h.θ (f x))) (fiber.mk (h.ε (f x)) rfl))⁻¹ᵉ ) @[hott, instance] def is_contr_r2coh (f : A → B) (h : is_hadj_l f) : is_contr (Σ(r : Π(x : A), rcoh f ⟨h.inv, (h.η, h.ε)⟩ x), Π(x : A), nat_coh h.inv f h.η x ⬝ ap02 h.inv (r x) = h.θ (f x)) := @is_trunc.is_contr_equiv_closed _ _ (r2coh_equiv_fib_eq f h)⁻¹ᵉ (@pi.is_trunc_pi _ _ -2 (λx : A, @is_trunc.is_contr_eq _ (@is_equiv.is_contr_fiber_of_is_equiv _ _ (ap h.inv) (@is_equiv.is_equiv_ap _ _ h.inv (@is_equiv.is_equiv_inv _ _ f (equiv.is_hadj_l_equiv_is_equiv f h)) _ _) _) (fiber.mk (ap f (h.η x)) ((nat_coh h.inv f h.η x)⁻¹ ⬝ h.θ (f x))) (fiber.mk (h.ε (f x)) rfl))) @[hott, instance] def is_contr_l2coh (f : A → B) (h : is_equiv f) : is_contr (Σ(l : Π(y : B), lcoh f ⟨h.inv, (h.left_inv, h.right_inv)⟩ y), Π(y : B), l2coh f ⟨h.inv, ⟨h.left_inv, ⟨h.right_inv, (h.adj⁻¹ʰᵗʸ, l)⟩⟩⟩ y) := @is_trunc.is_contr_equiv_closed _ _ (l2coh_equiv_fib_eq f h)⁻¹ᵉ (@pi.is_trunc_pi _ _ -2 (λy : B, @is_trunc.is_contr_eq _ (@is_equiv.is_contr_fiber_of_is_equiv _ _ (ap f) _ _) (fiber.mk ((is_equiv.left_inv f) ((is_equiv.inv f) y)) (@concat _ _ _ _ ((is_equiv.adj f)⁻¹ʰᵗʸ ((is_equiv.inv f) y)) (nat_coh f h.inv h.right_inv y))) (fiber.mk (ap h.inv ((is_equiv.right_inv f) y)) rfl))) @[hott] def is_two_hae_reorder (f : A → B) : is_two_hae f ≃ Σ(u : Σ(g : B → A), linv g f) (v : Σ(ε : rinv u.1 f), Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y) (τ : Π(x : A), rcoh f ⟨u.1, (u.2, v.1)⟩ x), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨v.1, (τ, v.2)⟩⟩⟩ x := begin apply sigma.sigma_assoc_equiv (λu : Σ(g : B → A), linv g f, Σ(ε : rinv u.1 f) (τ : Π(x : A), rcoh f ⟨u.1, (u.2, ε)⟩ x) (θ : Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨ε, (τ, θ)⟩⟩⟩ x) ⬝e _, apply sigma.sigma_equiv_sigma_right, intro u, apply (@sigma.sigma_equiv_sigma_right _ (λε : rinv u.1 f, Σ(τ : Π(x : A), rcoh f ⟨u.1, (u.2, ε)⟩ x) (θ : Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨ε, (τ, θ)⟩⟩⟩ x) (λε : rinv u.1 f, Σ(θ : Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y) (τ : Π(x : A), rcoh f ⟨u.1, (u.2, ε)⟩ x), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨ε, (τ, θ)⟩⟩⟩ x) (λε : rinv u.1 f, sigma.sigma_comm_equiv (λ(τ : Π(x : A), rcoh f ⟨u.1, (u.2, ε)⟩ x) (θ : Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨ε, (τ, θ)⟩⟩⟩ x))) ⬝e _, exact sigma.sigma_assoc_equiv (λv : Σ(ε : rinv u.1 f), Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y, Σ(τ : Π(x : A), rcoh f ⟨u.1, (u.2, v.1)⟩ x), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨v.1, (τ, v.2)⟩⟩⟩ x) end -- Proof that two half-adjoint equivalence is a mere proposition @[hott, instance] def is_prop_is_two_hae (f : A → B) : is_prop (is_two_hae f) := begin apply is_trunc.is_prop_of_imp_is_contr, intro h, apply is_trunc.is_trunc_equiv_closed_rev -2 (is_two_hae_reorder f), have H : is_equiv f := is_two_hae_to_is_equiv f h, apply is_trunc.is_trunc_equiv_closed_rev -2 (@sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(g : B → A), linv g f, Σ(v : Σ(ε : rinv u.1 f), Π(y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y), Σ(τ : Π(x : A), rcoh f ⟨u.1, (u.2, v.1)⟩ x), Π(x : A), r2coh f ⟨u.1, ⟨u.2, ⟨v.1, (τ, v.2)⟩⟩⟩ x) (@is_contr_linv _ _ f H)), dsimp, let u := (@is_trunc.center _ (@is_contr_linv _ _ f H)), apply is_trunc.is_trunc_equiv_closed_rev -2 (@sigma.sigma_equiv_of_is_contr_left _ (λv : Σ(ε : rinv u.1 f), Π (y : B), lcoh f ⟨u.1, (u.2, ε)⟩ y, _) (@is_contr_lcoh _ _ f H u)), dsimp, let v := @is_trunc.center _ (@is_contr_lcoh _ _ f H u), exact is_contr_r2coh f ⟨u.1, ⟨u.2, ⟨v.1, v.2⟩⟩⟩ end @[hott] def is_two_hae_l_reorder (f : A → B) : is_two_hae_l f ≃ Σ(u : Σ(g : B → A), rinv g f) (v : Σ(η : linv u.1 f), Π(x : A), rcoh f ⟨u.1, (η, u.2)⟩ x) (θ : Π(y : B), lcoh f ⟨u.1, (v.1, u.2)⟩ y), Π(y : B), l2coh f ⟨u.1, ⟨v.1, ⟨u.2, (v.2, θ)⟩⟩⟩ y := begin apply (@sigma.sigma_equiv_sigma_right _ (λg : B → A, Σ(l : linv g f) (r : rinv g f), _) (λg : B → A, Σ(r : rinv g f) (l : linv g f), _) (λg: B → A, sigma.sigma_comm_equiv (λ(l : linv g f) (r : rinv g f), _))) ⬝e _, dsimp, apply (sigma.sigma_assoc_equiv (λu : Σ(g : B → A), rinv g f, Σ(η : linv u.1 f) (τ : Π(x : A), rcoh f ⟨u.1, (η, u.2)⟩ x) (θ : Π(y : B), lcoh f ⟨u.1, (η, u.2)⟩ y), Π(y : B), l2coh f ⟨u.1, ⟨η, ⟨u.2, (τ, θ)⟩⟩⟩ y)) ⬝e _, apply sigma.sigma_equiv_sigma_right, intro u, exact sigma.sigma_assoc_equiv (λv : Σ(η : linv u.1 f), Π(x : A), rcoh f ⟨u.1, (η, u.2)⟩ x, Σ(θ : Π(y : B), lcoh f ⟨u.1, (v.1, u.2)⟩ y), Π(y : B), l2coh f ⟨u.1, ⟨v.1, ⟨u.2, (v.2, θ)⟩⟩⟩ y), end -- Proof that two left half-adjoint equivalence is a mere proposition @[hott, instance] def is_prop_is_two_hae_l (f : A → B) : is_prop (is_two_hae_l f) := begin apply is_trunc.is_prop_of_imp_is_contr, intro h, have H : is_equiv f := is_two_hae_l_to_is_equiv f h, apply is_trunc.is_trunc_equiv_closed_rev -2 (is_two_hae_l_reorder f), apply is_trunc.is_trunc_equiv_closed_rev -2 (@sigma.sigma_equiv_of_is_contr_left _ (λu: Σ(g : B → A), rinv g f, Σ(v : Σ(η : linv u.1 f), Π(x : A), rcoh f ⟨u.1, (η, u.2)⟩ x), Σ(θ : Π(y : B), lcoh f ⟨u.1, (v.1, u.2)⟩ y), Π(y : B), l2coh f ⟨u.1, ⟨v.1, ⟨u.2, (v.2, θ)⟩⟩⟩ y) (@is_equiv.is_contr_right_inverse _ _ f H)), dsimp, let u := @is_trunc.center _ (@is_equiv.is_contr_right_inverse _ _ f H), apply is_trunc.is_trunc_is_equiv_closed_rev -2 (@sigma.sigma_equiv_of_is_contr_left _ (λv : Σ(η : linv u.1 f), Π(x : A), rcoh f ⟨u.1, (η, u.2)⟩ x, Σ(θ : Π(y : B), lcoh f ⟨u.1, (v.1, u.2)⟩ y), Π(y : B), l2coh f ⟨u.1, ⟨v.1, ⟨u.2, (v.2, θ)⟩⟩⟩ y) (@is_contr_rcoh _ _ f H u)), dsimp, let v := @is_trunc.center _ (@is_contr_rcoh _ _ f H u), let H' := (hott.is_equiv.mk' u.1 u.2 v.1 v.2⁻¹ʰᵗʸ), exact transport (λH, is_contr (Σ(θ : Π(y : B), lcoh f ⟨u.1, (v.1, u.2)⟩ y), Π(y : B), l2coh f ⟨u.1, ⟨v.1, ⟨u.2, (H, θ)⟩⟩⟩ y)) (eq.inv_inv_htpy v.2) (is_contr_l2coh f H') end -- Promoting a left half-adjoint equivalence to a two half-adjoint equivalence @[hott] def two_adjointify (f : A → B) : is_hadj_l f → is_two_hae f := λh, have _, from @is_trunc.center _ (is_contr_r2coh f h), ⟨h.inv, ⟨h.η, ⟨h.ε, ⟨this.1, ⟨h.θ, this.2⟩⟩⟩⟩⟩ -- Promoting a half-adjoint equivalence to a two left half-adjoint equivalence @[hott] def two_adjointify_left (f : A → B) : is_equiv f → is_two_hae_l f := λh, have _, from @is_trunc.center _ (is_contr_l2coh f h), ⟨h.inv, ⟨h.left_inv, ⟨h.right_inv, ⟨h.adj⁻¹ʰᵗʸ, this⟩⟩⟩⟩ -- Two half-adjoint equivalences and two left half-adjoint equivalences are equivalent @[hott] def two_hae_equiv_two_hae_l (f : A → B) : is_two_hae f ≃ is_two_hae_l f := is_trunc.equiv_of_is_prop (λh : is_two_hae f, two_adjointify_left f (is_equiv.mk' h.inv h.ε h.η h.τ⁻¹ʰᵗʸ)) (λh : is_two_hae_l f, two_adjointify f ⟨h.inv, ⟨h.η, ⟨h.ε, h.θ⟩⟩⟩) -- Definition of a two full-adjoint equivalence @[hott] def two_adj (f : A → B) := Σ(g : B → A) (η : g ∘ f ~ id) (ε: f ∘ g ~ id) (τ : Π(x : A), rcoh f ⟨g, (η, ε)⟩ x) (θ : Π(y : B), lcoh f ⟨g, (η, ε)⟩ y), (Π(x : A), r2coh f ⟨g, ⟨η, ⟨ε, (τ, θ)⟩⟩⟩ x) × Π(y : B), l2coh f ⟨g, ⟨η, ⟨ε, (τ, θ)⟩⟩⟩ y @[hott, reducible] def two_adj.inv {f : A → B} (h : two_adj f) := h.1 @[hott, reducible] def two_adj.η {f : A → B} (h : two_adj f) := h.2.1 @[hott, reducible] def two_adj.ε {f : A → B} (h : two_adj f) := h.2.2.1 @[hott, reducible] def two_adj.τ {f : A → B} (h : two_adj f) := h.2.2.2.1 @[hott, reducible] def two_adj.θ {f : A → B} (h : two_adj f) := h.2.2.2.2.1 @[hott, reducible] def two_adj.α {f : A → B} (h : two_adj f) := h.2.2.2.2.2.1 @[hott, reducible] def two_adj.β {f : A → B} (h : two_adj f) := h.2.2.2.2.2.2 @[hott] def two_adj_id_equiv_no_linv : two_adj (@id A) ≃ Σ(ε : @id A ~ id) (τ : Π(x : A), rfl = ε x) (θ : Π(x : A), rfl = ap id (ε x)), (Π(x : A), nat_coh id id (@hott.eq.refl A) x ⬝ ap02 id (τ x) = θ x) × (Π(x : A), τ x ⬝ nat_coh id id ε x = ap02 id (θ x)) := sigma.sigma_assoc_equiv (λu : Σ(g : A → A), g ~ id, Σ(ε : u.1 ~ id) (τ : Π(x : A), ap id (u.2 x) = ε x) (θ : Π(x : A), u.2 (u.1 x) = ap u.1 (ε x)), (Π(x : A), nat_coh u.1 id u.2 x ⬝ ap02 u.1 (τ x) = θ x) × (Π(x : A), τ (u.1 x) ⬝ nat_coh id u.1 ε x = ap02 id (θ x))) ⬝e @sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(g : A → A), g ~ id, Σ(ε : u.1 ~ id) (τ : Π(x : A), ap id (u.2 x) = ε x) (θ : Π(x : A), u.2 (u.1 x) = ap u.1 (ε x)), (Π(x : A), nat_coh u.1 id u.2 x ⬝ ap02 u.1 (τ x) = θ x) × (Π(x : A), τ (u.1 x) ⬝ nat_coh id u.1 ε x = ap02 id (θ x))) (is_trunc.sigma_hty_is_contr_right (@id A)) @[hott] def two_adj_id_equiv_no_rcoh : (Σ(ε : @id A ~ id) (τ : Π(x : A), rfl = ε x) (θ : Π(x : A), rfl = ap id (ε x)), (Π(x : A), nat_coh id id (@hott.eq.refl A) x ⬝ ap02 id (τ x) = θ x) × (Π(x : A), τ x ⬝ nat_coh id id ε x = ap02 id (θ x))) ≃ Σ(θ : Π(x : A), rfl = ap id (hott.eq.refl x)), (Π(x : A), nat_coh id id (@hott.eq.refl A) x ⬝ ap02 id rfl = θ x) × (Π(x : A), rfl ⬝ nat_coh id id (@hott.eq.refl A) x = ap02 id (θ x)) := sigma.sigma_assoc_equiv (λu : Σ(ε : @id A ~ id), Π(x : A), rfl = ε x, Σ(θ : Π(x : A), rfl = ap id (u.1 x)), (Π(x : A), nat_coh id id (@hott.eq.refl A) x ⬝ ap02 id (u.2 x) = θ x) × (Π(x : A), u.2 x ⬝ nat_coh id id u.1 x = ap02 id (θ x))) ⬝e @sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(ε : @id A ~ id), hott.eq.refl ~ ε, Σ(θ : Π(x : A), rfl = ap id (u.1 x)), (Π(x : A), nat_coh id id (@hott.eq.refl A) x ⬝ ap02 id (u.2 x) = θ x) × (Π(x : A), u.2 x ⬝ nat_coh id id u.1 x = ap02 id (θ x))) (is_trunc.sigma_hty_is_contr (@hott.eq.refl A)) @[hott] def two_adj_id_equiv_no_rcoh_simplify : (Σ(θ : Π(x : A), rfl = ap id (hott.eq.refl x)), (Π(x : A), nat_coh id id (@hott.eq.refl A) x ⬝ ap02 id rfl = θ x) × (Π(x : A), rfl ⬝ nat_coh id id (@hott.eq.refl A) x = ap02 id (θ x))) ≃ Σ(θ : Π(x : A), hott.eq.refl x = hott.eq.refl x), (Π(x : A), hott.eq.refl (hott.eq.refl x) = θ x) × (Π(x : A), hott.eq.refl (hott.eq.refl x) = θ x) := begin fapply sigma.sigma_equiv_sigma_right, intro θ, apply prod.prod_equiv_prod, refl, apply pi.pi_equiv_pi_right, intro x, exact eq_equiv_eq_closed rfl (@ap_con_eq_con _ (λp : x = x, ap id p) (λp, ap_id p) _ _ (θ x) ⬝ idp_con (θ x)) end @[hott] def two_adj_id_equiv_no_r2coh : (Σ(θ : Π(x : A), hott.eq.refl x = hott.eq.refl x), (Π(x : A), hott.eq.refl (hott.eq.refl x) = θ x) × (Π(x : A), hott.eq.refl (hott.eq.refl x) = θ x)) ≃ Π(x : A), rfl = hott.eq.refl (hott.eq.refl x) := @sigma.sigma_equiv_sigma_right (Π(x : A), rfl = hott.eq.refl x) (λθ, (Π(x : A), rfl = θ x) × (Π(x : A), rfl = θ x) ) _ (λθ, (sigma.equiv_prod (Π(x : A), rfl = θ x) (Π(x : A), rfl = θ x))⁻¹ᵉ) ⬝e sigma.sigma_assoc_equiv (λu : Σ(θ : Π(x : A), rfl = hott.eq.refl x), Π(x : A), rfl = θ x, Π(x : A), rfl = u.1 x) ⬝e @sigma.sigma_equiv_of_is_contr_left _ (λu : Σ(θ : Π(x : A), rfl = hott.eq.refl x), Π(x : A), rfl = θ x, Π(x : A), rfl= u.1 x) (is_trunc.sigma_hty_is_contr (λx : A, @hott.eq.refl (x = x) (hott.eq.refl x))) -- Two full-adjoint equivalence is not a mere proposition @[hott] def two_adj_equiv_pi_refl_eq (f : A ≃ B) : two_adj f ≃ Π(x : A), hott.eq.refl (hott.eq.refl x) = rfl := by apply equiv.rec_on_ua_idp f; exact two_adj_id_equiv_no_linv ⬝e two_adj_id_equiv_no_rcoh ⬝e two_adj_id_equiv_no_rcoh_simplify ⬝e two_adj_id_equiv_no_r2coh end equiv end hott
a08cc9ea88d1f9bbe6154baf98217203f7aabbc2
f3849be5d845a1cb97680f0bbbe03b85518312f0
/tests/lean/run/cpdt2.lean
b2cab40d16c9ac6c9bdc3ad601e978c504b26e2b
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,798
lean
/- CPDT Chapter 2, Introducing Inductive Types -/ import tools.mini_crush universe variable u export nat (succ) def is_zero : ℕ → bool | 0 := tt | (succ _) := ff def plus : ℕ → ℕ → ℕ | 0 m := m | (succ n') m := succ (plus n' m) theorem n_plus_0 (n : ℕ) : plus n 0 = n := by mini_crush lemma plus_S (n1 n2 : nat) : plus n1 (succ n2) = succ (plus n1 n2) := by mini_crush inductive nat_list : Type | NNil : nat_list | NCons : nat → nat_list → nat_list open nat_list def nlength : nat_list → ℕ | NNil := 0 | (NCons _ ls') := succ (nlength ls') def napp : nat_list → nat_list → nat_list | NNil ls2 := ls2 | (NCons n ls1') ls2 := NCons n (napp ls1' ls2) theorem nlength_napp (ls1 ls2 : nat_list) : nlength (napp ls1 ls2) = plus (nlength ls1) (nlength ls2) := by mini_crush inductive nat_btree : Type | NLeaf : nat_btree | NNode : nat_btree → ℕ → nat_btree → nat_btree open nat_btree def nsize : nat_btree → ℕ | NLeaf := succ 0 | (NNode tr1 _ tr2) := plus (nsize tr1) (nsize tr2) def nsplice : nat_btree → nat_btree → nat_btree | NLeaf tr2 := NNode tr2 0 NLeaf | (NNode tr1' n tr2') tr2 := NNode (nsplice tr1' tr2) n tr2' @[simp] theorem plus_assoc (n1 n2 n3 : nat) : plus (plus n1 n2) n3 = plus n1 (plus n2 n3) := by mini_crush theorem nsize_nsplice (tr1 tr2 : nat_btree) : nsize (nsplice tr1 tr2) = plus (nsize tr2) (nsize tr1) := by mini_crush export list (nil cons) def length {α : Type u} : list α → ℕ | nil := 0 | (cons _ ls') := succ (length ls') def app {α : Type u} : list α → list α → list α | nil ls2 := ls2 | (cons x ls1') ls2 := cons x (app ls1' ls2) theorem length_app {α : Type u} (ls1 ls2 : list α) : length (app ls1 ls2) = plus (length ls1) (length ls2) := by mini_crush inductive pformula : Type | Truth : pformula | Falsehood : pformula | Conjunction : pformula → pformula → pformula. open pformula def pformula_denote : pformula → Prop | Truth := true | Falsehood := false | (Conjunction f1 f2) := pformula_denote f1 ∧ pformula_denote f2 open pformula inductive formula : Type | Eq : nat → nat → formula | And : formula → formula → formula | Forall : (nat → formula) → formula open formula example forall_refl : formula := Forall (λ x, Eq x x) def formula_denote : formula → Prop | (Eq n1 n2) := n1 = n2 | (And f1 f2) := formula_denote f1 ∧ formula_denote f2 | (Forall f') := ∀ n : nat, formula_denote (f' n) def swapper : formula → formula | (Eq n1 n2) := Eq n2 n1 | (And f1 f2) := And (swapper f2) (swapper f1) | (Forall f') := Forall (λ n, swapper (f' n)) theorem swapper_preserves_truth (f) : formula_denote f → formula_denote (swapper f) := by mini_crush
9d11e283c8c90c900782defdbf0890f58d54f6a2
a46270e2f76a375564f3b3e9c1bf7b635edc1f2c
/4.6.6.lean
3e6894b450e063d92e9bfbd68642351db33e013d
[ "CC0-1.0" ]
permissive
wudcscheme/lean-exercise
88ea2506714eac343de2a294d1132ee8ee6d3a20
5b23b9be3d361fff5e981d5be3a0a1175504b9f6
refs/heads/master
1,678,958,930,293
1,583,197,205,000
1,583,197,205,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
858
lean
variables (real : Type) [ordered_ring real] variables (log exp : real → real) variable log_exp_eq : ∀ x, log (exp x) = x variable exp_log_eq : ∀ {x}, x > 0 → exp (log x) = x variable exp_pos : ∀ x, exp x > 0 variable exp_add : ∀ x y, exp (x + y) = exp x * exp y -- this ensures the assumptions are available in tactic proofs include log_exp_eq exp_log_eq exp_pos exp_add example (x y z : real) : exp (x + y + z) = exp x * exp y * exp z := by rw [exp_add, exp_add] example (y : real) (h : y > 0) : exp (log y) = y := exp_log_eq h theorem log_mul {x y : real} (hx : x > 0) (hy : y > 0) : log (x * y) = log x + log y := eq.symm $ calc log x + log y = log (exp(log x + log y)): by rw [log_exp_eq] ... = log(exp(log x) * exp(log y)): by rw [exp_add] ... = log(x * y): by rw [exp_log_eq hx, exp_log_eq hy]
122a89a350e3cdd92889cc6519be2af136ae94b7
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/card_measurable_space.lean
d7dfb8c03f69150a3c9dcad418d6524ba71edc9c
[ "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
8,651
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Violeta Hernández Palacios -/ import measure_theory.measurable_space_def import set_theory.cardinal.cofinality import set_theory.cardinal.continuum /-! # Cardinal of sigma-algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. If a sigma-algebra is generated by a set of sets `s`, then the cardinality of the sigma-algebra is bounded by `(max (#s) 2) ^ ℵ₀`. This is stated in `measurable_space.cardinal_generate_measurable_le` and `measurable_space.cardinal_measurable_set_le`. In particular, if `#s ≤ 𝔠`, then the generated sigma-algebra has cardinality at most `𝔠`, see `measurable_space.cardinal_measurable_set_le_continuum`. For the proof, we rely on an explicit inductive construction of the sigma-algebra generated by `s` (instead of the inductive predicate `generate_measurable`). This transfinite inductive construction is parameterized by an ordinal `< ω₁`, and the cardinality bound is preserved along each step of the construction. We show in `measurable_space.generate_measurable_eq_rec` that this indeed generates this sigma-algebra. -/ universe u variables {α : Type u} open_locale cardinal open cardinal set local notation `ω₁` := (aleph 1 : cardinal.{u}).ord.out.α namespace measurable_space /-- Transfinite induction construction of the sigma-algebra generated by a set of sets `s`. At each step, we add all elements of `s`, the empty set, the complements of already constructed sets, and countable unions of already constructed sets. We index this construction by an ordinal `< ω₁`, as this will be enough to generate all sets in the sigma-algebra. This construction is very similar to that of the Borel hierarchy. -/ def generate_measurable_rec (s : set (set α)) : ω₁ → set (set α) | i := let S := ⋃ j : Iio i, generate_measurable_rec j.1 in s ∪ {∅} ∪ compl '' S ∪ set.range (λ (f : ℕ → S), ⋃ n, (f n).1) using_well_founded {dec_tac := `[exact j.2]} theorem self_subset_generate_measurable_rec (s : set (set α)) (i : ω₁) : s ⊆ generate_measurable_rec s i := begin unfold generate_measurable_rec, apply_rules [subset_union_of_subset_left], exact subset_rfl end theorem empty_mem_generate_measurable_rec (s : set (set α)) (i : ω₁) : ∅ ∈ generate_measurable_rec s i := begin unfold generate_measurable_rec, exact mem_union_left _ (mem_union_left _ (mem_union_right _ (mem_singleton ∅))) end theorem compl_mem_generate_measurable_rec {s : set (set α)} {i j : ω₁} (h : j < i) {t : set α} (ht : t ∈ generate_measurable_rec s j) : tᶜ ∈ generate_measurable_rec s i := begin unfold generate_measurable_rec, exact mem_union_left _ (mem_union_right _ ⟨t, mem_Union.2 ⟨⟨j, h⟩, ht⟩, rfl⟩) end theorem Union_mem_generate_measurable_rec {s : set (set α)} {i : ω₁} {f : ℕ → set α} (hf : ∀ n, ∃ j < i, f n ∈ generate_measurable_rec s j) : (⋃ n, f n) ∈ generate_measurable_rec s i := begin unfold generate_measurable_rec, exact mem_union_right _ ⟨λ n, ⟨f n, let ⟨j, hj, hf⟩ := hf n in mem_Union.2 ⟨⟨j, hj⟩, hf⟩⟩, rfl⟩ end theorem generate_measurable_rec_subset (s : set (set α)) {i j : ω₁} (h : i ≤ j) : generate_measurable_rec s i ⊆ generate_measurable_rec s j := λ x hx, begin rcases eq_or_lt_of_le h with rfl | h, { exact hx }, { convert Union_mem_generate_measurable_rec (λ n, ⟨i, h, hx⟩), exact (Union_const x).symm } end /-- At each step of the inductive construction, the cardinality bound `≤ (max (#s) 2) ^ ℵ₀` holds. -/ lemma cardinal_generate_measurable_rec_le (s : set (set α)) (i : ω₁) : #(generate_measurable_rec s i) ≤ (max (#s) 2) ^ aleph_0.{u} := begin apply (aleph 1).ord.out.wo.wf.induction i, assume i IH, have A := aleph_0_le_aleph 1, have B : aleph 1 ≤ (max (#s) 2) ^ aleph_0.{u} := aleph_one_le_continuum.trans (power_le_power_right (le_max_right _ _)), have C : ℵ₀ ≤ (max (#s) 2) ^ aleph_0.{u} := A.trans B, have J : #(⋃ j : Iio i, generate_measurable_rec s j.1) ≤ (max (#s) 2) ^ aleph_0.{u}, { apply (mk_Union_le _).trans, have D : (⨆ j : Iio i, #(generate_measurable_rec s j)) ≤ _ := csupr_le' (λ ⟨j, hj⟩, IH j hj), apply (mul_le_mul' ((mk_subtype_le _).trans (aleph 1).mk_ord_out.le) D).trans, rw mul_eq_max A C, exact max_le B le_rfl }, rw [generate_measurable_rec], apply_rules [(mk_union_le _ _).trans, add_le_of_le C, mk_image_le.trans], { exact (le_max_left _ _).trans (self_le_power _ one_lt_aleph_0.le) }, { rw [mk_singleton], exact one_lt_aleph_0.le.trans C }, { apply mk_range_le.trans, simp only [mk_pi, subtype.val_eq_coe, prod_const, lift_uzero, mk_denumerable, lift_aleph_0], have := @power_le_power_right _ _ ℵ₀ J, rwa [← power_mul, aleph_0_mul_aleph_0] at this } end /-- `generate_measurable_rec s` generates precisely the smallest sigma-algebra containing `s`. -/ theorem generate_measurable_eq_rec (s : set (set α)) : {t | generate_measurable s t} = ⋃ i, generate_measurable_rec s i := begin ext t, refine ⟨λ ht, _, λ ht, _⟩, { inhabit ω₁, induction ht with u hu u hu IH f hf IH, { exact mem_Union.2 ⟨default, self_subset_generate_measurable_rec s _ hu⟩ }, { exact mem_Union.2 ⟨default, empty_mem_generate_measurable_rec s _⟩ }, { rcases mem_Union.1 IH with ⟨i, hi⟩, obtain ⟨j, hj⟩ := exists_gt i, exact mem_Union.2 ⟨j, compl_mem_generate_measurable_rec hj hi⟩ }, { have : ∀ n, ∃ i, f n ∈ generate_measurable_rec s i := λ n, by simpa using IH n, choose I hI using this, refine mem_Union.2 ⟨ordinal.enum (<) (ordinal.lsub (λ n, ordinal.typein.{u} (<) (I n))) _, Union_mem_generate_measurable_rec (λ n, ⟨I n, _, hI n⟩)⟩, { rw ordinal.type_lt, refine ordinal.lsub_lt_ord_lift _ (λ i, ordinal.typein_lt_self _), rw [mk_denumerable, lift_aleph_0, is_regular_aleph_one.cof_eq], exact aleph_0_lt_aleph_one }, { rw [←ordinal.typein_lt_typein (<), ordinal.typein_enum], apply ordinal.lt_lsub (λ n : ℕ, _) } } }, { rcases ht with ⟨t, ⟨i, rfl⟩, hx⟩, revert t, apply (aleph 1).ord.out.wo.wf.induction i, intros j H t ht, unfold generate_measurable_rec at ht, rcases ht with (((h | h) | ⟨u, ⟨-, ⟨⟨k, hk⟩, rfl⟩, hu⟩, rfl⟩) | ⟨f, rfl⟩), { exact generate_measurable.basic t h }, { convert generate_measurable.empty }, { exact generate_measurable.compl u (H k hk u hu) }, { apply generate_measurable.union _ (λ n, _), obtain ⟨-, ⟨⟨k, hk⟩, rfl⟩, hf⟩ := (f n).prop, exact H k hk _ hf } } end /-- If a sigma-algebra is generated by a set of sets `s`, then the sigma-algebra has cardinality at most `(max (#s) 2) ^ ℵ₀`. -/ theorem cardinal_generate_measurable_le (s : set (set α)) : #{t | generate_measurable s t} ≤ (max (#s) 2) ^ aleph_0.{u} := begin rw generate_measurable_eq_rec, apply (mk_Union_le _).trans, rw (aleph 1).mk_ord_out, refine le_trans (mul_le_mul' aleph_one_le_continuum (csupr_le' (λ i, cardinal_generate_measurable_rec_le s i))) _, have := power_le_power_right (le_max_right (#s) 2), rw mul_eq_max aleph_0_le_continuum (aleph_0_le_continuum.trans this), exact max_le this le_rfl end /-- If a sigma-algebra is generated by a set of sets `s`, then the sigma algebra has cardinality at most `(max (#s) 2) ^ ℵ₀`. -/ theorem cardinal_measurable_set_le (s : set (set α)) : #{t | @measurable_set α (generate_from s) t} ≤ (max (#s) 2) ^ aleph_0.{u} := cardinal_generate_measurable_le s /-- If a sigma-algebra is generated by a set of sets `s` with cardinality at most the continuum, then the sigma algebra has the same cardinality bound. -/ theorem cardinal_generate_measurable_le_continuum {s : set (set α)} (hs : #s ≤ 𝔠) : #{t | generate_measurable s t} ≤ 𝔠 := (cardinal_generate_measurable_le s).trans begin rw ←continuum_power_aleph_0, exact_mod_cast power_le_power_right (max_le hs (nat_lt_continuum 2).le) end /-- If a sigma-algebra is generated by a set of sets `s` with cardinality at most the continuum, then the sigma algebra has the same cardinality bound. -/ theorem cardinal_measurable_set_le_continuum {s : set (set α)} : #s ≤ 𝔠 → #{t | @measurable_set α (generate_from s) t} ≤ 𝔠 := cardinal_generate_measurable_le_continuum end measurable_space
75cb623d150dfcd8ec8d6ad912a1da2186e96e65
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/topology/basic.lean
13dbe2a3b2305d16960563ddbeb28c1c4d579182
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
41,189
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import order.filter.bases /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `is_cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. This file also defines locally finite families of subsets of `α`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa [set.compl_inter] using union_mem sᶜ tᶜ hs ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (set.compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [t : topological_space α] include t /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open t s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ t lemma is_open_inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter t s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion t s h end lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open_union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : finite s) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open_inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open_inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [fintype β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open_and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open_inter /-- A set is closed if its complement is open -/ def is_closed (s : set α) : Prop := is_open sᶜ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by unfold is_closed; rw compl_empty; exact is_open_univ @[simp] lemma is_closed_univ : is_closed (univ : set α) := by unfold is_closed; rw compl_univ; exact is_open_empty lemma is_closed_union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by unfold is_closed; rw compl_union; exact is_open_inter h₁ h₂ lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := iff.rfl @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open_diff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open_inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed_inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by rw [is_closed, compl_inter]; exact is_open_union h₁ h₂ lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : finite s) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed_union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [fintype β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (Union s) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq lemma is_open_neg : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma interior_eq_of_open {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, interior_eq_of_open⟩ lemma subset_interior_iff_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma subset_interior_iff_subset_of_open {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := interior_eq_of_open is_open_empty @[simp] lemma interior_univ : interior (univ : set α) = univ := interior_eq_of_open is_open_univ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := interior_eq_of_open is_open_interior @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior) lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa subset_interior_iff_subset_of_open (is_open_diff hu₁ h₁), have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_open; simp only [subset_def, mem_interior] /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ lemma set.nonempty.closure {s : set α} (h : s.nonempty) : set.nonempty (closure s) := let ⟨x, hx⟩ := h in ⟨x, subset_closure hx⟩ @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin unfold interior closure is_closed, rw [compl_sUnion, compl_image_set_of], simp only [compl_subset_compl] end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁ nc) in hc (h₂ hs)⟩ lemma dense_iff_inter_open {s : set α} : closure s = univ ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h]) U U_op x_in }, { apply eq_univ_of_forall, intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end lemma dense_of_subset_dense {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : closure s₁ = univ) : closure s₂ = univ := by { rw [← univ_subset_iff, ← hd], exact closure_mono h } /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, interior_eq_of_open hs] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end /-! ### Neighborhoods -/ /-- neighbourhood filter -/ def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation `𝓝` := nhds" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := rfl lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ x, x) := has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open_inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_sets_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃t⊆s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi attribute [irreducible] nhds lemma mem_of_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_sets_iff.1 H in ht hs lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_nhds h lemma mem_nhds_sets {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_sets_iff.2 ⟨s, subset.refl _, hs, ha⟩ theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := iff.intro (λ h s os xs, h s (mem_nhds_sets os xs)) (λ h t, begin change t ∈ 𝓝 x → P t, rw mem_nhds_sets_iff, rintros ⟨s, hs, opens, xs⟩, exact hP _ _ hs (h s opens xs), end) theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_sets_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure_sets.2 $ mem_of_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := begin rw [tendsto, filter.map_pure], exact pure_le_nhds (f a) end @[simp] lemma nhds_ne_bot {a : α} : 𝓝 a ≠ ⊥ := ne_bot_of_le_ne_bot pure_ne_bot (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if 𝓝 x ⊓ F ≠ ⊥. Also known as an accumulation point or a limit point. -/ def cluster_pt (x : α) (F : filter α) : Prop := 𝓝 x ⊓ F ≠ ⊥ lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ {U V : set α}, U ∈ 𝓝 x → V ∈ F → (U ∩ V).nonempty := by rw [cluster_pt, inf_ne_bot_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) (h : f ≠ ⊥) : cluster_pt x f := by rwa [cluster_pt, inf_comm, inf_eq_left.mpr H] lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp [cluster_pt, inf_eq_left.mpr H] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ne_bot_of_le_ne_bot H $ inf_le_inf_left _ h lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} (hp : p ≠ ⊥) (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le_ne_bot (map_ne_bot hp) this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := set.ext $ λ x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by simp only [interior_eq_nhds, le_principal_iff]; refl lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := calc closure s = (interior sᶜ)ᶜ : closure_eq_compl_interior_compl ... = {a | ¬ 𝓝 a ≤ 𝓟 sᶜ} : by rw [interior_eq_nhds]; refl ... = {a | cluster_pt a (𝓟 s)} : set.ext $ assume a, not_congr (inf_eq_bot_iff_le_compl (show 𝓟 s ⊔ 𝓟 sᶜ = ⊤, by simp only [sup_principal, union_compl_self, principal_univ]) (by simp only [inf_principal, inter_compl_self, principal_empty])).symm theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := by simpa only [closure_eq_cluster_pts] theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff.trans ⟨λ H t ht, nonempty.mono (inter_subset_inter_left _ interior_subset) (H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)), λ H o oo ao, H _ (mem_nhds_sets oo ao)⟩ theorem mem_closure_iff_nhds_basis {a : α} {p : β → Prop} {s : β → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := mem_closure_iff_nhds.trans ⟨λ H i hi, let ⟨x, hx⟩ := (H _ $ h.mem_of_mem hi) in ⟨x, hx.2, hx.1⟩, λ H t' ht', let ⟨i, hi, hit⟩ := h.mem_iff.1 ht', ⟨x, xt, hx⟩ := H i hi in ⟨x, hit hx, xt⟩⟩ /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u.val ∧ u.val ≤ 𝓝 x := begin rw closure_eq_cluster_pts, change cluster_pt x (𝓟 s) ↔ _, symmetry, convert exists_ultrafilter_iff _, ext u, rw [←le_principal_iff, inf_comm, le_inf_iff] end lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma closure_inter_open {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := assume a ⟨hs, ht⟩, have s ∈ 𝓝 a, from mem_nhds_sets h hs, have 𝓝 a ⊓ 𝓟 s = 𝓝 a, by rwa [inf_eq_left, le_principal_iff], have cluster_pt a (𝓟 (s ∩ t)), from calc 𝓝 a ⊓ 𝓟 (s ∩ t) = 𝓝 a ⊓ (𝓟 s ⊓ 𝓟 t) : by rw inf_principal ... = 𝓝 a ⊓ 𝓟 t : by rw [←inf_assoc, this] ... ≠ ⊥ : by rw [closure_eq_cluster_pts] at ht; assumption, by rwa [closure_eq_cluster_pts] lemma dense_inter_of_open_left {s t : set α} (hs : closure s = univ) (ht : closure t = univ) (hso : is_open s) : closure (s ∩ t) = univ := eq_univ_of_subset (closure_minimal (closure_inter_open hso) is_closed_closure) $ by simp only [*, inter_univ] lemma dense_inter_of_open_right {s t : set α} (hs : closure s = univ) (ht : closure t = univ) (hto : is_open t) : closure (s ∩ t) = univ := inter_comm t s ▸ dense_inter_of_open_left ht hs hto lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma mem_of_closed_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hb : b ≠ ⊥) (hf : tendsto f b (𝓝 a)) (hs : is_closed s) (h : f ⁻¹' s ∈ b) : a ∈ s := have b.map f ≤ 𝓝 a ⊓ 𝓟 s, from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf_right _ hf), is_closed_iff_cluster_pt.mp hs a $ ne_bot_of_le_ne_bot (map_ne_bot hb) this lemma mem_of_closed_of_tendsto' {f : β → α} {x : filter β} {a : α} {s : set α} (hf : tendsto f x (𝓝 a)) (hs : is_closed s) (h : x ⊓ 𝓟 (f ⁻¹' s) ≠ ⊥) : a ∈ s := is_closed_iff_cluster_pt.mp hs _ $ ne_bot_of_le_ne_bot (@map_ne_bot _ _ _ f h) $ le_inf (le_trans (map_mono $ inf_le_left) hf) $ le_trans (map_mono $ inf_le_right_of_le $ by simp only [comap_principal, le_principal_iff]; exact subset.refl _) (@map_comap_le _ _ _ f) lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hb : b ≠ ⊥) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := mem_of_closed_of_tendsto hb hf (is_closed_closure) $ filter.mem_sets_of_superset h (preimage_mono subset_closure) /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma Lim_spec {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma lim_spec {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := Lim_spec h end lim /-! ### Locally finite families -/ /- locally finite family [General Topology (Bourbaki, 1995)] -/ section locally_finite /-- A family of sets in `set α` is locally finite if at every point `x:α`, there is a neighborhood of `x` which meets only finitely many sets in the family -/ def locally_finite (f : β → set α) := ∀x:α, ∃t ∈ 𝓝 x, finite {i | (f i ∩ t).nonempty } lemma locally_finite_of_finite {f : β → set α} (h : finite (univ : set β)) : locally_finite f := assume x, ⟨univ, univ_mem_sets, h.subset $ subset_univ _⟩ lemma locally_finite_subset {f₁ f₂ : β → set α} (hf₂ : locally_finite f₂) (hf : ∀b, f₁ b ⊆ f₂ b) : locally_finite f₁ := assume a, let ⟨t, ht₁, ht₂⟩ := hf₂ a in ⟨t, ht₁, ht₂.subset $ assume i hi, hi.mono $ inter_subset_inter (hf i) $ subset.refl _⟩ lemma is_closed_Union_of_locally_finite {f : β → set α} (h₁ : locally_finite f) (h₂ : ∀i, is_closed (f i)) : is_closed (⋃i, f i) := is_open_iff_nhds.mpr $ assume a, assume h : a ∉ (⋃i, f i), have ∀i, a ∈ (f i)ᶜ, from assume i hi, h $ mem_Union.2 ⟨i, hi⟩, have ∀i, (f i)ᶜ ∈ (𝓝 a), by simp only [mem_nhds_sets_iff]; exact assume i, ⟨(f i)ᶜ, subset.refl _, h₂ i, this i⟩, let ⟨t, h_sets, (h_fin : finite {i | (f i ∩ t).nonempty })⟩ := h₁ a in calc 𝓝 a ≤ 𝓟 (t ∩ (⋂ i∈{i | (f i ∩ t).nonempty }, (f i)ᶜ)) : begin rw [le_principal_iff], apply @filter.inter_mem_sets _ (𝓝 a) _ _ h_sets, apply @filter.Inter_mem_sets _ (𝓝 a) _ _ _ h_fin, exact assume i h, this i end ... ≤ 𝓟 (⋃i, f i)ᶜ : begin simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq, mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists, exists_imp_distrib, ne_empty_iff_nonempty, set.nonempty], exact assume x xt ht i xfi, ht i x xfi xt xfi end end locally_finite end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. -/ def continuous (f : α → β) := ∀s, is_open s → is_open (f ⁻¹' s) /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (hf _ is_open_interior) lemma continuous_id : continuous (id : α → α) := assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := assume s h, hf _ (hg s h) lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, hf _ ht⟩, subset.refl _⟩ lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, mem_nhds_sets hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := continuous_const.continuous_at lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, hf sᶜ hs, assume hf s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma continuous_at_iff_ultrafilter {f : α → β} (x) : continuous_at f x ↔ ∀ g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x g, is_ultrafilter g → g ≤ 𝓝 x → g.map f ≤ 𝓝 (f x) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] /-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g` are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/ lemma continuous_if {p : α → Prop} {f g : α → β} {h : ∀a, decidable (p a)} (hp : ∀a∈frontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λa, @ite (p a) (h a) β (f a) (g a)) := continuous_iff_is_closed.mpr $ assume s hs, have (λa, ite (p a) (f a) (g a)) ⁻¹' s = (closure {a | p a} ∩ f ⁻¹' s) ∪ (closure {a | ¬ p a} ∩ g ⁻¹' s), from set.ext $ assume a, classical.by_cases (assume : a ∈ frontier {a | p a}, have hac : a ∈ closure {a | p a}, from this.left, have hai : a ∈ closure {a | ¬ p a}, from have a ∈ (interior {a | p a})ᶜ, from this.right, by rwa [←closure_compl] at this, by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt}) (assume hf : a ∈ (frontier {a | p a})ᶜ, classical.by_cases (assume : p a, have hc : a ∈ closure {a | p a}, from subset_closure this, have hnc : a ∉ closure {a | ¬ p a}, by show a ∉ closure {a | p a}ᶜ; rw [closure_compl]; simpa [frontier, hc] using hf, by simp [this, hc, hnc]) (assume : ¬ p a, have hc : a ∈ closure {a | ¬ p a}, from subset_closure this, have hnc : a ∉ closure {a | p a}, begin have hc : a ∈ closure {a | p a}ᶜ, from hc, simp [closure_compl] at hc, simpa [frontier, hc] using hf end, by simp [this, hc, hnc])), by rw [this]; exact is_closed_union (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs) (is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs) /- Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_sets_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal_sets], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_sets_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_sets_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := have ∀ (a : α), cluster_pt a (𝓟 s) → cluster_pt (f a) (𝓟 (f '' s)), from assume a ha, have h₁ : ¬ map f (𝓝 a ⊓ 𝓟 s) = ⊥, by rwa[map_eq_bot_iff], have h₂ : map f (𝓝 a ⊓ 𝓟 s) ≤ 𝓝 (f a) ⊓ 𝓟 (f '' s), from le_inf (le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a) (le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _), ne_bot_of_le_ne_bot h₁ h₂, by simp [image_subset_iff, closure_eq_cluster_pts]; assumption lemma mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : ∀a∈s, f a ∈ t) : f a ∈ closure t := subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $ (mem_image_of_mem f ha) end continuous
742070ea2805e93a5aada843298c70776680bb6d
b147e1312077cdcfea8e6756207b3fa538982e12
/data/equiv/denumerable.lean
69cb4e3494f6cf0ae9ae2b98349b17f9d43c4939
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,884
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Denumerable (countably infinite) types, as a typeclass extending encodable. This is used to provide explicit encode/decode functions from nat, where the functions are known inverses of each other. -/ import data.equiv.encodable data.sigma open nat /-- A denumerable type is one which is (constructively) bijective with ℕ. Although we already have a name for this property, namely `α ≃ ℕ`, we are here interested in using it as a typeclass. -/ class denumerable (α : Type*) extends encodable α := (decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n) namespace denumerable section variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable @[simp] theorem decode_is_some (α) [denumerable α] (n : ℕ) : (decode α n).is_some := option.is_some_iff_exists.2 $ (decode_inv α n).imp $ λ a, Exists.fst def of_nat (α) [f : denumerable α] (n : ℕ) : α := option.get (decode_is_some α n) @[simp] theorem decode_eq_of_nat (α) [denumerable α] (n : ℕ) : decode α n = some (of_nat α n) := option.eq_some_of_is_some _ @[simp] theorem of_nat_of_decode {n b} (h : decode α n = some b) : of_nat α n = b := option.some.inj $ (decode_eq_of_nat _ _).symm.trans h @[simp] theorem encode_of_nat (n) : encode (of_nat α n) = n := let ⟨a, h, e⟩ := decode_inv α n in by rwa [of_nat_of_decode h] @[simp] theorem of_nat_encode (a) : of_nat α (encode a) = a := of_nat_of_decode (encodek _) def eqv (α) [denumerable α] : α ≃ ℕ := ⟨encode, of_nat α, of_nat_encode, encode_of_nat⟩ def mk' {α} (e : α ≃ ℕ) : denumerable α := { encode := e, decode := some ∘ e.symm, encodek := λ a, congr_arg some (e.inverse_apply_apply _), decode_inv := λ n, ⟨_, rfl, e.apply_inverse_apply _⟩ } def of_equiv (α) {β} [denumerable α] (e : β ≃ α) : denumerable β := { decode_inv := λ n, by simp [option.bind], ..encodable.of_equiv _ e } @[simp] theorem of_equiv_of_nat (α) {β} [denumerable α] (e : β ≃ α) (n) : @of_nat β (of_equiv _ e) n = e.symm (of_nat α n) := by apply of_nat_of_decode; show option.map _ _ = _; simp; refl def equiv₂ (α β) [denumerable α] [denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : denumerable nat := ⟨λ n, ⟨_, rfl, rfl⟩⟩ @[simp] theorem of_nat_nat (n) : of_nat ℕ n = n := rfl instance option : denumerable (option α) := ⟨λ n, by cases n; simp⟩ instance sum : denumerable (α ⊕ β) := ⟨λ n, begin suffices : ∃ a ∈ @decode_sum α β _ _ n, encode_sum a = bit (bodd n) (div2 n), {simpa [bit_decomp]}, simp [decode_sum]; cases bodd n; simp [decode_sum, bit], { refine or.inl ⟨_, rfl, _⟩, simp [encode_sum] }, { refine or.inr ⟨_, rfl, _⟩, simp [encode_sum] } end⟩ section sigma variables {γ : α → Type*} [∀ a, denumerable (γ a)] instance sigma : denumerable (sigma γ) := ⟨λ n, by simp [decode_sigma]; exact ⟨_, _, rfl, by simp⟩⟩ @[simp] theorem sigma_of_nat_val (n : ℕ) : of_nat (sigma γ) n = ⟨of_nat α (unpair n).1, of_nat (γ _) (unpair n).2⟩ := option.some.inj $ by rw [← decode_eq_of_nat, decode_sigma_val]; simp; refl end sigma instance prod : denumerable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem prod_of_nat_val (n : ℕ) : of_nat (α × β) n = (of_nat α (unpair n).1, of_nat β (unpair n).2) := by simp; refl @[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = unpair := by funext; simp instance int : denumerable ℤ := of_equiv _ equiv.int_equiv_nat instance ulift : denumerable (ulift α) := of_equiv _ equiv.ulift instance plift : denumerable (plift α) := of_equiv _ equiv.plift def pair : (α × α) ≃ α := equiv₂ _ _ end end denumerable
e240ff8be1b89b00fe459fe5f55ec85f10d7e0d0
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/uniform_space/compact_separated.lean
af478361c4274cbfc3b0ad22877d94a60a3b0fb3
[ "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
10,603
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.separation /-! # Compact separated uniform spaces ## Main statements * `compact_space_uniformity`: On a separated compact uniform space, the topology determines the uniform structure, entourages are exactly the neighborhoods of the diagonal. * `uniform_space_of_compact_t2`: every compact T2 topological structure is induced by a uniform structure. This uniform structure is described in the previous item. * Heine-Cantor theorem: continuous functions on compact separated uniform spaces with values in uniform spaces are automatically uniformly continuous. There are several variations, the main one is `compact_space.uniform_continuous_of_continuous`. ## Implementation notes The construction `uniform_space_of_compact_t2` is not declared as an instance, as it would badly loop. ## tags uniform space, uniform continuity, compact space -/ open_locale classical uniformity topological_space filter open filter uniform_space set variables {α β : Type*} [uniform_space α] [uniform_space β] /-! ### Uniformity on compact separated spaces -/ lemma compact_space_uniformity [compact_space α] [separated_space α] : 𝓤 α = ⨆ x : α, 𝓝 (x, x) := begin symmetry, refine le_antisymm nhds_le_uniformity _, by_contra H, obtain ⟨V, hV, h⟩ : ∃ V : set (α × α), (∀ x : α, V ∈ 𝓝 (x, x)) ∧ ne_bot (𝓤 α ⊓ 𝓟 Vᶜ), { rw le_iff_forall_inf_principal_compl at H, push_neg at H, simpa only [mem_supr_sets] using H }, let F := 𝓤 α ⊓ 𝓟 Vᶜ, haveI : ne_bot F := h, obtain ⟨⟨x, y⟩, hx⟩ : ∃ (p : α × α), cluster_pt p F := cluster_point_of_compact F, have : cluster_pt (x, y) (𝓤 α) := hx.of_inf_left, have hxy : x = y := eq_of_uniformity_inf_nhds this, subst hxy, have : cluster_pt (x, x) (𝓟 Vᶜ) := hx.of_inf_right, have : (x, x) ∉ interior V, { have : (x, x) ∈ closure Vᶜ, by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have : (x, x) ∈ interior V, { rw mem_interior_iff_mem_nhds, exact hV x }, contradiction end lemma unique_uniformity_of_compact_t2 {α : Type*} [t : topological_space α] [compact_space α] [t2_space α] {u u' : uniform_space α} (h : u.to_topological_space = t) (h' : u'.to_topological_space = t) : u = u' := begin apply uniform_space_eq, change uniformity _ = uniformity _, haveI : @compact_space α u.to_topological_space := by rw h ; assumption, haveI : @compact_space α u'.to_topological_space := by rw h' ; assumption, haveI : @separated_space α u := by rwa [separated_iff_t2, h], haveI : @separated_space α u' := by rwa [separated_iff_t2, h'], rw [compact_space_uniformity, compact_space_uniformity, h, h'] end /-- The unique uniform structure inducing a given compact Hausdorff topological structure. -/ def uniform_space_of_compact_t2 {α : Type*} [topological_space α] [compact_space α] [t2_space α] : uniform_space α := { uniformity := ⨆ x, 𝓝 (x, x), refl := begin simp_rw [filter.principal_le_iff, mem_supr_sets], rintros V V_in ⟨x, _⟩ ⟨⟩, exact mem_of_nhds (V_in x), end, symm := begin refine le_of_eq _, rw map_supr, congr' with x : 1, erw [nhds_prod_eq, ← prod_comm], end, comp := begin /- This is the difficult part of the proof. We need to prove that, for each neighborhood W of the diagonal Δ, W ○ W is still a neighborhood of the diagonal. -/ set 𝓝Δ := ⨆ x : α, 𝓝 (x, x), -- The filter of neighborhoods of Δ set F := 𝓝Δ.lift' (λ (s : set (α × α)), s ○ s), -- Compositions of neighborhoods of Δ -- If this weren't true, then there would be V ∈ 𝓝Δ such that F ⊓ 𝓟 Vᶜ ≠ ⊥ rw le_iff_forall_inf_principal_compl, intros V V_in, by_contra H, haveI : ne_bot (F ⊓ 𝓟 Vᶜ) := H, -- Hence compactness would give us a cluster point (x, y) for F ⊓ 𝓟 Vᶜ obtain ⟨⟨x, y⟩, hxy⟩ : ∃ (p : α × α), cluster_pt p (F ⊓ 𝓟 Vᶜ) := cluster_point_of_compact _, -- In particular (x, y) is a cluster point of 𝓟 Vᶜ, hence is not in the interior of V, -- and a fortiori not in Δ, so x ≠ y have clV : cluster_pt (x, y) (𝓟 $ Vᶜ) := hxy.of_inf_right, have : (x, y) ∉ interior V, { have : (x, y) ∈ closure (Vᶜ), by rwa mem_closure_iff_cluster_pt, rwa closure_compl at this }, have diag_subset : diagonal α ⊆ interior V, { rw subset_interior_iff_nhds, rintros ⟨x, x⟩ ⟨⟩, exact (mem_supr_sets.mp V_in : _) x }, have x_ne_y : x ≠ y, { intro h, apply this, apply diag_subset, simp [h] }, -- Since α is compact and Hausdorff, it is normal, hence regular. haveI : normal_space α := normal_of_compact_t2, -- So there are closed neighboords V₁ and V₂ of x and y contained in disjoint open neighborhoods -- U₁ and U₂. obtain ⟨U₁, V₁, U₁_in, V₁_in, U₂, V₂, U₂_in₂, V₂_in, V₁_cl, V₂_cl, U₁_op, U₂_op, VU₁, VU₂, hU₁₂⟩ : ∃ (U₁ V₁ ∈ 𝓝 x) (U₂ V₂ ∈ 𝓝 y), is_closed V₁ ∧ is_closed V₂ ∧ is_open U₁ ∧ is_open U₂ ∧ V₁ ⊆ U₁ ∧ V₂ ⊆ U₂ ∧ U₁ ∩ U₂ = ∅ := disjoint_nested_nhds x_ne_y, -- We set U₃ := (V₁ ∪ V₂)ᶜ so that W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃) is an open -- neighborhood of Δ. let U₃ := (V₁ ∪ V₂)ᶜ, have U₃_op : is_open U₃ := is_open_compl_iff.mpr (is_closed_union V₁_cl V₂_cl), let W := (U₁.prod U₁) ∪ (U₂.prod U₂) ∪ (U₃.prod U₃), have W_in : W ∈ 𝓝Δ, { rw mem_supr_sets, intros x, apply mem_nhds_sets (is_open_union (is_open_union _ _) _), { by_cases hx : x ∈ V₁ ∪ V₂, { left, cases hx with hx hx ; [left, right] ; split ; tauto }, { right, rw mem_prod, tauto }, }, all_goals { simp only [is_open_prod, *] } }, -- So W ○ W ∈ F by definition of F have : W ○ W ∈ F, { dsimp [F],-- Lean has weird elaboration trouble with this line exact mem_lift' W_in }, -- And V₁.prod V₂ ∈ 𝓝 (x, y) have hV₁₂ : V₁.prod V₂ ∈ 𝓝 (x, y) := prod_mem_nhds_sets V₁_in V₂_in, -- But (x, y) is also a cluster point of F so (V₁.prod V₂) ∩ (W ○ W) ≠ ∅ have clF : cluster_pt (x, y) F := hxy.of_inf_left, obtain ⟨p, p_in⟩ : ∃ p, p ∈ (V₁.prod V₂) ∩ (W ○ W) := cluster_pt_iff.mp clF hV₁₂ this, -- However the construction of W implies (V₁.prod V₂) ∩ (W ○ W) = ∅. -- Indeed assume for contradiction there is some (u, v) in the intersection. -- So u ∈ V₁, v ∈ V₂, and there exists some w such that (u, w) ∈ W and (w ,v) ∈ W. -- Because u is in V₁ which is disjoint from U₂ and U₃, (u, w) ∈ W forces (u, w) ∈ U₁.prod U₁. -- Similarly, because v ∈ V₂, (w ,v) ∈ W forces (w, v) ∈ U₂.prod U₂. -- Hence w ∈ U₁ ∩ U₂ which is empty. have inter_empty : (V₁.prod V₂) ∩ (W ○ W) = ∅, { rw eq_empty_iff_forall_not_mem, rintros ⟨u, v⟩ ⟨⟨u_in, v_in⟩, w, huw, hwv⟩, have uw_in : (u, w) ∈ U₁.prod U₁ := set.mem_prod.2 ((huw.resolve_right (λ h, (h.1 $ or.inl u_in))).resolve_right (λ h, have u ∈ U₁ ∩ U₂, from ⟨VU₁ u_in, h.1⟩, by rwa hU₁₂ at this)), have wv_in : (w, v) ∈ U₂.prod U₂ := set.mem_prod.2 ((hwv.resolve_right (λ h, (h.2 $ or.inr v_in))).resolve_left (λ h, have v ∈ U₁ ∩ U₂, from ⟨h.2, VU₂ v_in⟩, by rwa hU₁₂ at this)), have : w ∈ U₁ ∩ U₂ := ⟨uw_in.2, wv_in.1⟩, rwa hU₁₂ at this }, -- So we have a contradiction rwa inter_empty at p_in, end, is_open_uniformity := begin -- Here we need to prove the topology induced by the constructed uniformity is the -- topology we started with. suffices : ∀ x : α, comap (prod.mk x) (⨆ y, 𝓝 (y ,y)) = 𝓝 x, { intros s, change is_open s ↔ _, simp_rw [is_open_iff_mem_nhds, nhds_eq_comap_uniformity_aux, this] }, intros x, simp_rw [comap_supr, nhds_prod_eq, comap_prod, show prod.fst ∘ prod.mk x = λ y : α, x, by ext ; simp, show prod.snd ∘ (prod.mk x) = (id : α → α), by ext ; refl, comap_id], rw [supr_split_single _ x, comap_const_of_mem (λ V, mem_of_nhds)], suffices : ∀ y ≠ x, comap (λ (y : α), x) (𝓝 y) ⊓ 𝓝 y ≤ 𝓝 x, by simpa, intros y hxy, simp [comap_const_of_not_mem (compl_singleton_mem_nhds hxy) (by simp)], end } /-! ### Heine-Cantor theorem -/ /-- Heine-Cantor: a continuous function on a compact separated uniform space is uniformly continuous. -/ lemma compact_space.uniform_continuous_of_continuous [compact_space α] [separated_space α] {f : α → β} (h : continuous f) : uniform_continuous f := calc map (prod.map f f) (𝓤 α) = map (prod.map f f) (⨆ x, 𝓝 (x, x)) : by rw compact_space_uniformity ... = ⨆ x, map (prod.map f f) (𝓝 (x, x)) : by rw map_supr ... ≤ ⨆ x, 𝓝 (f x, f x) : supr_le_supr (λ x, (h.prod_map h).continuous_at) ... ≤ ⨆ y, 𝓝 (y, y) : supr_comp_le (λ y, 𝓝 (y, y)) f ... ≤ 𝓤 β : nhds_le_uniformity /-- Heine-Cantor: a continuous function on a compact separated set of a uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous' {s : set α} {f : α → β} (hs : is_compact s) (hs' : is_separated s) (hf : continuous_on f s) : uniform_continuous_on f s := begin rw uniform_continuous_on_iff_restrict, rw is_separated_iff_induced at hs', rw compact_iff_compact_space at hs, rw continuous_on_iff_continuous_restrict at hf, resetI, exact compact_space.uniform_continuous_of_continuous hf, end /-- Heine-Cantor: a continuous function on a compact set of a separated uniform space is uniformly continuous. -/ lemma is_compact.uniform_continuous_on_of_continuous [separated_space α] {s : set α} {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : uniform_continuous_on f s := hs.uniform_continuous_on_of_continuous' (is_separated_of_separated_space s) hf
e8e00afdec074f6f029e9b333d65b950dcd6857a
92b50235facfbc08dfe7f334827d47281471333b
/library/data/int/order.lean
617ddc8b002f30a87c88d17a5eebb7a55847ed6b
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
15,470
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Jeremy Avigad The order relation on the integers. We show that int is an instance of linear_comm_ordered_ring and transfer the results. -/ import .basic algebra.ordered_ring open nat open decidable open int eq.ops namespace int private definition nonneg (a : ℤ) : Prop := int.cases_on a (take n, true) (take n, false) definition le (a b : ℤ) : Prop := nonneg (sub b a) definition lt (a b : ℤ) : Prop := le (add a 1) b infix [priority int.prio] - := int.sub infix [priority int.prio] <= := int.le infix [priority int.prio] ≤ := int.le infix [priority int.prio] < := int.lt local attribute nonneg [reducible] private definition decidable_nonneg [instance] (a : ℤ) : decidable (nonneg a) := int.cases_on a _ _ definition decidable_le [instance] (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _ definition decidable_lt [instance] (a b : ℤ) : decidable (a < b) := decidable_nonneg _ private theorem nonneg.elim {a : ℤ} : nonneg a → ∃n : ℕ, a = n := int.cases_on a (take n H, exists.intro n rfl) (take n' H, false.elim H) private theorem nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) := int.cases_on a (take n, or.inl trivial) (take n, or.inr trivial) theorem le.intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b := have H1 : b - a = n, from (eq_add_neg_of_add_eq (!add.comm ▸ H))⁻¹, have H2 : nonneg n, from true.intro, show nonneg (b - a), from H1⁻¹ ▸ H2 theorem le.elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b := obtain (n : ℕ) (H1 : b - a = n), from nonneg.elim H, exists.intro n (!add.comm ▸ iff.mp' !add_eq_iff_eq_add_neg (H1⁻¹)) theorem le.total (a b : ℤ) : a ≤ b ∨ b ≤ a := or.elim (nonneg_or_nonneg_neg (b - a)) (assume H, or.inl H) (assume H : nonneg (-(b - a)), have H0 : -(b - a) = a - b, from neg_sub b a, have H1 : nonneg (a - b), from H0 ▸ H, -- too bad: can't do it in one step or.inr H1) theorem of_nat_le_of_nat_of_le {m n : ℕ} (H : #nat m ≤ n) : of_nat m ≤ of_nat n := obtain (k : ℕ) (Hk : m + k = n), from nat.le.elim H, le.intro (Hk ▸ (of_nat_add m k)⁻¹) theorem le_of_of_nat_le_of_nat {m n : ℕ} (H : of_nat m ≤ of_nat n) : (#nat m ≤ n) := obtain (k : ℕ) (Hk : of_nat m + of_nat k = of_nat n), from le.elim H, have H1 : m + k = n, from of_nat.inj (of_nat_add m k ⬝ Hk), nat.le.intro H1 theorem of_nat_le_of_nat (m n : ℕ) : of_nat m ≤ of_nat n ↔ m ≤ n := iff.intro le_of_of_nat_le_of_nat of_nat_le_of_nat_of_le theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n := le.intro (show a + 1 + n = a + succ n, from calc a + 1 + n = a + (1 + n) : add.assoc ... = a + (n + 1) : nat.add.comm ... = a + succ n : rfl) theorem lt.intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b := H ▸ lt_add_succ a n theorem lt.elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b := obtain (n : ℕ) (Hn : a + 1 + n = b), from le.elim H, have H2 : a + succ n = b, from calc a + succ n = a + 1 + n : by simp ... = b : Hn, exists.intro n H2 theorem of_nat_lt_of_nat (n m : ℕ) : of_nat n < of_nat m ↔ n < m := calc of_nat n < of_nat m ↔ of_nat n + 1 ≤ of_nat m : iff.refl ... ↔ of_nat (nat.succ n) ≤ of_nat m : of_nat_succ n ▸ !iff.refl ... ↔ nat.succ n ≤ m : of_nat_le_of_nat ... ↔ n < m : iff.symm (lt_iff_succ_le _ _) theorem lt_of_of_nat_lt_of_nat {m n : ℕ} (H : of_nat m < of_nat n) : #nat m < n := iff.mp !of_nat_lt_of_nat H theorem of_nat_lt_of_nat_of_lt {m n : ℕ} (H : #nat m < n) : of_nat m < of_nat n := iff.mp' !of_nat_lt_of_nat H /- show that the integers form an ordered additive group -/ theorem le.refl (a : ℤ) : a ≤ a := le.intro (add_zero a) theorem le.trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := obtain (n : ℕ) (Hn : a + n = b), from le.elim H1, obtain (m : ℕ) (Hm : b + m = c), from le.elim H2, have H3 : a + of_nat (n + m) = c, from calc a + of_nat (n + m) = a + (of_nat n + m) : {of_nat_add n m} ... = a + n + m : (add.assoc a n m)⁻¹ ... = b + m : {Hn} ... = c : Hm, le.intro H3 theorem le.antisymm : ∀ {a b : ℤ}, a ≤ b → b ≤ a → a = b := take a b : ℤ, assume (H₁ : a ≤ b) (H₂ : b ≤ a), obtain (n : ℕ) (Hn : a + n = b), from le.elim H₁, obtain (m : ℕ) (Hm : b + m = a), from le.elim H₂, have H₃ : a + of_nat (n + m) = a + 0, from calc a + of_nat (n + m) = a + (of_nat n + m) : of_nat_add ... = a + n + m : add.assoc ... = b + m : Hn ... = a : Hm ... = a + 0 : add_zero, have H₄ : of_nat (n + m) = of_nat 0, from add.left_cancel H₃, have H₅ : n + m = 0, from of_nat.inj H₄, have H₆ : n = 0, from nat.eq_zero_of_add_eq_zero_right H₅, show a = b, from calc a = a + 0 : add_zero ... = a + n : H₆ ... = b : Hn theorem lt.irrefl (a : ℤ) : ¬ a < a := (assume H : a < a, obtain (n : ℕ) (Hn : a + succ n = a), from lt.elim H, have H2 : a + succ n = a + 0, from calc a + succ n = a : Hn ... = a + 0 : by simp, have H3 : nat.succ n = 0, from add.left_cancel H2, have H4 : nat.succ n = 0, from of_nat.inj H3, absurd H4 !succ_ne_zero) theorem ne_of_lt {a b : ℤ} (H : a < b) : a ≠ b := (assume H2 : a = b, absurd (H2 ▸ H) (lt.irrefl b)) theorem le_of_lt {a b : ℤ} (H : a < b) : a ≤ b := obtain (n : ℕ) (Hn : a + succ n = b), from lt.elim H, le.intro Hn theorem lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (assume H, and.intro (le_of_lt H) (ne_of_lt H)) (assume H, have H1 : a ≤ b, from and.elim_left H, have H2 : a ≠ b, from and.elim_right H, obtain (n : ℕ) (Hn : a + n = b), from le.elim H1, have H3 : n ≠ 0, from (assume H' : n = 0, H2 (!add_zero ▸ H' ▸ Hn)), obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero H3, lt.intro (Hk ▸ Hn)) theorem le_iff_lt_or_eq (a b : ℤ) : a ≤ b ↔ (a < b ∨ a = b) := iff.intro (assume H, by_cases (assume H1 : a = b, or.inr H1) (assume H1 : a ≠ b, obtain (n : ℕ) (Hn : a + n = b), from le.elim H, have H2 : n ≠ 0, from (assume H' : n = 0, H1 (!add_zero ▸ H' ▸ Hn)), obtain (k : ℕ) (Hk : n = nat.succ k), from nat.exists_eq_succ_of_ne_zero H2, or.inl (lt.intro (Hk ▸ Hn)))) (assume H, or.elim H (assume H1, le_of_lt H1) (assume H1, H1 ▸ !le.refl)) theorem lt_succ (a : ℤ) : a < a + 1 := le.refl (a + 1) theorem add_le_add_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b := obtain (n : ℕ) (Hn : a + n = b), from le.elim H, have H2 : c + a + n = c + b, from calc c + a + n = c + (a + n) : add.assoc c a n ... = c + b : {Hn}, le.intro H2 theorem add_lt_add_left {a b : ℤ} (H : a < b) (c : ℤ) : c + a < c + b := let H' := le_of_lt H in (iff.mp' (lt_iff_le_and_ne _ _)) (and.intro (add_le_add_left H' _) (take Heq, let Heq' := add_left_cancel Heq in !lt.irrefl (Heq' ▸ H))) theorem mul_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a * b := obtain (n : ℕ) (Hn : 0 + n = a), from le.elim Ha, obtain (m : ℕ) (Hm : 0 + m = b), from le.elim Hb, le.intro (eq.symm (calc a * b = (0 + n) * b : Hn ... = n * b : nat.zero_add ... = n * (0 + m) : {Hm⁻¹} ... = n * m : nat.zero_add ... = 0 + n * m : zero_add)) theorem mul_pos {a b : ℤ} (Ha : 0 < a) (Hb : 0 < b) : 0 < a * b := obtain (n : ℕ) (Hn : 0 + nat.succ n = a), from lt.elim Ha, obtain (m : ℕ) (Hm : 0 + nat.succ m = b), from lt.elim Hb, lt.intro (eq.symm (calc a * b = (0 + nat.succ n) * b : Hn ... = nat.succ n * b : nat.zero_add ... = nat.succ n * (0 + nat.succ m) : {Hm⁻¹} ... = nat.succ n * nat.succ m : nat.zero_add ... = of_nat (nat.succ n * nat.succ m) : of_nat_mul ... = of_nat (nat.succ n * m + nat.succ n) : nat.mul_succ ... = of_nat (nat.succ (nat.succ n * m + n)) : nat.add_succ ... = 0 + nat.succ (nat.succ n * m + n) : zero_add)) theorem zero_lt_one : (0 : ℤ) < 1 := trivial theorem not_le_of_gt {a b : ℤ} (H : a < b) : ¬ b ≤ a := assume Hba, let Heq := le.antisymm (le_of_lt H) Hba in !lt.irrefl (Heq ▸ H) theorem lt_of_lt_of_le {a b c : ℤ} (Hab : a < b) (Hbc : b ≤ c) : a < c := let Hab' := le_of_lt Hab in let Hac := le.trans Hab' Hbc in (iff.mp' !lt_iff_le_and_ne) (and.intro Hac (assume Heq, not_le_of_gt (Heq ▸ Hab) Hbc)) theorem lt_of_le_of_lt {a b c : ℤ} (Hab : a ≤ b) (Hbc : b < c) : a < c := let Hbc' := le_of_lt Hbc in let Hac := le.trans Hab Hbc' in (iff.mp' !lt_iff_le_and_ne) (and.intro Hac (assume Heq, not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab)) section migrate_algebra open [classes] algebra protected definition linear_ordered_comm_ring [reducible] : algebra.linear_ordered_comm_ring int := ⦃algebra.linear_ordered_comm_ring, int.integral_domain, le := le, le_refl := le.refl, le_trans := @le.trans, le_antisymm := @le.antisymm, lt := lt, le_of_lt := @le_of_lt, lt_irrefl := lt.irrefl, lt_of_lt_of_le := @lt_of_lt_of_le, lt_of_le_of_lt := @lt_of_le_of_lt, add_le_add_left := @add_le_add_left, mul_nonneg := @mul_nonneg, mul_pos := @mul_pos, le_iff_lt_or_eq := le_iff_lt_or_eq, le_total := le.total, zero_ne_one := zero_ne_one, zero_lt_one := zero_lt_one, add_lt_add_left := @add_lt_add_left⦄ protected definition decidable_linear_ordered_comm_ring [reducible] : algebra.decidable_linear_ordered_comm_ring int := ⦃algebra.decidable_linear_ordered_comm_ring, int.linear_ordered_comm_ring, decidable_lt := decidable_lt⦄ local attribute int.integral_domain [instance] local attribute int.linear_ordered_comm_ring [instance] local attribute int.decidable_linear_ordered_comm_ring [instance] definition ge [reducible] (a b : ℤ) := algebra.has_le.ge a b definition gt [reducible] (a b : ℤ) := algebra.has_lt.gt a b infix >= := int.ge infix ≥ := int.ge infix > := int.gt definition decidable_ge [instance] (a b : ℤ) : decidable (a ≥ b) := show decidable (b ≤ a), from _ definition decidable_gt [instance] (a b : ℤ) : decidable (a > b) := show decidable (b < a), from _ definition min : ℤ → ℤ → ℤ := algebra.min definition max : ℤ → ℤ → ℤ := algebra.max definition abs : ℤ → ℤ := algebra.abs definition sign : ℤ → ℤ := algebra.sign migrate from algebra with int replacing has_le.ge → ge, has_lt.gt → gt, dvd → dvd, sub → sub, min → min, max → max, abs → abs, sign → sign attribute le.trans ge.trans lt.trans gt.trans [trans] attribute lt_of_lt_of_le lt_of_le_of_lt gt_of_gt_of_ge gt_of_ge_of_gt [trans] end migrate_algebra /- more facts specific to int -/ theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial theorem of_nat_pos {n : ℕ} (Hpos : #nat n > 0) : of_nat n > 0 := of_nat_lt_of_nat_of_lt Hpos theorem of_nat_succ_pos (n : nat) : of_nat (nat.succ n) > 0 := of_nat_pos !nat.succ_pos theorem exists_eq_of_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = of_nat n := obtain (n : ℕ) (H1 : 0 + of_nat n = a), from le.elim H, exists.intro n (!zero_add ▸ (H1⁻¹)) theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(of_nat n) := have H2 : -a ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos H, obtain (n : ℕ) (Hn : -a = of_nat n), from exists_eq_of_nat H2, exists.intro n (eq_neg_of_eq_neg (Hn⁻¹)) theorem of_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : of_nat (nat_abs a) = a := obtain (n : ℕ) (Hn : a = of_nat n), from exists_eq_of_nat H, Hn⁻¹ ▸ congr_arg of_nat (nat_abs_of_nat n) theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : of_nat (nat_abs a) = -a := have H1 : (-a) ≥ 0, from iff.mp' !neg_nonneg_iff_nonpos H, calc of_nat (nat_abs a) = of_nat (nat_abs (-a)) : nat_abs_neg ... = -a : of_nat_nat_abs_of_nonneg H1 theorem of_nat_nat_abs (b : ℤ) : nat_abs b = abs b := or.elim (le.total 0 b) (assume H : b ≥ 0, of_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹) (assume H : b ≤ 0, of_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹) theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := abs.by_cases rfl !nat_abs_neg theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := obtain n (H1 : a + 1 + n = b), from le.elim H, have H2 : a + succ n = b, by rewrite [-H1, add.assoc, add.comm 1], lt.intro H2 theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := obtain n (H1 : a + succ n = b), from lt.elim H, have H2 : a + 1 + n = b, by rewrite [-H1, add.assoc, add.comm 1], le.intro H2 theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := lt_add_of_le_of_pos H trivial theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H, le_of_add_le_add_right H1 theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := lt_of_add_one_le (!sub_add_cancel⁻¹ ▸ H) theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := !sub_add_cancel ▸ add_one_le_of_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_of_lt_add_one (!sub_add_cancel⁻¹ ▸ H) theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := !sub_add_cancel ▸ (lt_add_one_of_le H) theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := sign_of_pos (of_nat_pos !nat.succ_pos) theorem exists_eq_neg_succ_of_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[1+m] := int.cases_on a (take m H, absurd (of_nat_nonneg m : 0 ≤ m) (not_le_of_gt H)) (take m H, exists.intro m rfl) theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := have H2 : a * b > 0, by rewrite H'; apply trivial, have H3 : b > 0, from pos_of_mul_pos_left H2 H, have H4 : a > 0, from pos_of_mul_pos_right H2 (le_of_lt H3), or.elim (le_or_gt a 1) (assume H5 : a ≤ 1, show a = 1, from le.antisymm H5 (add_one_le_of_lt H4)) (assume H5 : a > 1, assert H6 : a * b ≥ 2 * 1, from mul_le_mul (add_one_le_of_lt H5) (add_one_le_of_lt H3) trivial H, have H7 : false, by rewrite [H' at H6]; apply H6, false.elim H7) theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (!mul.comm ▸ H') theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul a)⁻¹) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := dvd.elim H' (take b, assume H1 : 1 = a * b, eq_one_of_mul_eq_one_right H H1⁻¹) end int
2fa70c7fe7caf008d42a6e8ef6c10e4420b6173e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/rat/encodable.lean
f846045858aff6b7b744257d5ae149467e53083e
[ "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
690
lean
/- Copyright (c) 2019 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 logic.encodable.basic import data.nat.gcd.basic import data.rat.init /-! # The rationals are `encodable`. As a consequence we also get the instance `countable ℚ`. This is kept separate from `data.rat.defs` in order to minimize imports. -/ namespace rat instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ end rat
7e4df37476838f976d1e2aae5625abf90961f132
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/field_theory/finite/polynomial.lean
0e3373f8cd5da326aa729adf288744432d0b3427
[ "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
7,611
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import field_theory.finite.basic import field_theory.mv_polynomial import data.mv_polynomial.expand import linear_algebra.basic import linear_algebra.finite_dimensional /-! ## Polynomials over finite fields -/ namespace mv_polynomial variables {σ : Type*} /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) : C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 := C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _ section frobenius variables {p : ℕ} [fact p.prime] lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) : frobenius _ p f = expand p f := begin apply induction_on f, { intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], }, { simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] }, { simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul], intros _ _ hf, rw [hf, frobenius_def], }, end lemma expand_zmod (f : mv_polynomial σ (zmod p)) : expand p f = f ^ p := (frobenius_zmod _).symm end frobenius end mv_polynomial namespace mv_polynomial noncomputable theory open_locale big_operators classical open set linear_map submodule variables {K : Type*} {σ : Type*} variables [field K] [fintype K] [fintype σ] def indicator (a : σ → K) : mv_polynomial σ K := ∏ n, (1 - (X n - C (a n))^(fintype.card K - 1)) lemma eval_indicator_apply_eq_one (a : σ → K) : eval a (indicator a) = 1 := have 0 < fintype.card K - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by { simp only [indicator, (eval a).map_prod, ring_hom.map_sub, (eval a).map_one, (eval a).map_pow, eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] } lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (eval a).map_prod, ring_hom.map_sub, (eval a).map_one, (eval a).map_pow, eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → K) : degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) • {s} := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X' _ end lemma indicator_mem_restrict_degree (c : σ → K) : indicator c ∈ restrict_degree σ K (fintype.card K - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), simp_rw [ ← multiset.coe_count_add_monoid_hom, (multiset.count_add_monoid_hom n).map_sum, add_monoid_hom.map_nsmul, multiset.coe_count_add_monoid_hom, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_singleton, if_neg ne.symm, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_singleton_self, mul_one] } end section variables (K σ) def evalₗ : mv_polynomial σ K →ₗ[K] (σ → K) → K := { to_fun := λ p e, eval e p, map_add' := λ p q, by { ext x, rw ring_hom.map_add, refl, }, map_smul' := λ a p, by { ext e, rw [smul_eq_C_mul, ring_hom.map_mul, eval_C], refl } } end lemma evalₗ_apply (p : mv_polynomial σ K) (e : σ → K) : evalₗ K σ p e = eval e p := rfl lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ := begin refine top_unique (set_like.le_def.2 $ assume e _, mem_map.2 _), refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial open_locale classical open linear_map submodule universe u variables (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] @[derive [add_comm_group, module K, inhabited]] def R : Type u := restrict_degree σ K (fintype.card K - 1) noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance lemma dim_R : module.rank K (R σ K) = fintype.card (σ → K) := calc module.rank K (R σ K) = module.rank K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} : by rw [finsupp.dim_eq, dim_self, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } : begin refine quotient.sound ⟨equiv.subtype_equiv finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card K}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)⟩ ... = cardinal.mk (σ → fin (fintype.card K)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → K) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (fintype.equiv_fin K).symm⟩ ... = fintype.card (σ → K) : cardinal.fintype_card _ instance : finite_dimensional K (R σ K) := is_noetherian.iff_dim_lt_omega.mpr (by simpa only [dim_R] using cardinal.nat_lt_omega (fintype.card (σ → K))) lemma finrank_R : finite_dimensional.finrank K (R σ K) = fintype.card (σ → K) := finite_dimensional.finrank_eq_of_dim_eq (dim_R σ K) def evalᵢ : R σ K →ₗ[K] (σ → K) → K := ((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ K).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ K).ker = ⊥ := begin refine (ker_eq_bot_iff_range_eq_top_of_finrank_eq_finrank _).mpr (range_evalᵢ _ _), rw [finite_dimensional.finrank_fintype_fun_eq_card, finrank_R] end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ K) (h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) : p = 0 := let p' : R σ K := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ K).ker := by { rw [mem_ker], ext v, exact h v }, show p'.1 = (0 : R σ K).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
5c894408da9b7b2d574c5a956d05fa0e4e04c404
4727251e0cd73359b15b664c3170e5d754078599
/src/data/rat/sqrt.lean
9839b5edfc4d2da7999d7ee85062f776a06b41b0
[ "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
1,173
lean
/- Copyright (c) 2019 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 data.rat.order import data.int.sqrt /-! # Square root on rational numbers This file defines the square root function on rational numbers `rat.sqrt` and proves several theorems about it. -/ namespace rat /-- Square root function on rational numbers, defined by taking the (integer) square root of the numerator and the square root (on natural numbers) of the denominator. -/ @[pp_nodot] def sqrt (q : ℚ) : ℚ := rat.mk (int.sqrt q.num) (nat.sqrt q.denom) theorem sqrt_eq (q : ℚ) : rat.sqrt (q*q) = |q| := by rw [sqrt, mul_self_num, mul_self_denom, int.sqrt_eq, nat.sqrt_eq, abs_def] theorem exists_mul_self (x : ℚ) : (∃ q, q * q = x) ↔ rat.sqrt x * rat.sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, abs_mul_abs_self], λ h, ⟨rat.sqrt x, h⟩⟩ theorem sqrt_nonneg (q : ℚ) : 0 ≤ rat.sqrt q := nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $ nat.pos_of_ne_zero $ λ H, pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 $ int.coe_nat_nonneg _ end rat
51cba7adaabfccdb9fbd1389c6e6a4ad146debf2
bdb33f8b7ea65f7705fc342a178508e2722eb851
/set_theory/cardinal.lean
a2974ac464a7074f717bfe4e0de61b009d058f01
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
27,443
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro Cardinal arithmetic. Cardinals are represented as quotient over equinumerous types. -/ import data.set.finite data.quot logic.schroeder_bernstein logic.function noncomputable theory open function lattice set classical local attribute [instance] prop_decidable universes u v w x instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal of a type -/ def mk : Type u → cardinal := quotient.mk @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ instance : linear_order cardinal.{u} := { le := (≤), le_refl := assume a, quot.induction_on a $ λ α, ⟨embedding.refl _⟩, le_trans := assume a b c, quotient.induction_on₃ a b c $ assume α β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩, le_antisymm := assume a b, quotient.induction_on₂ a b $ assume α β ⟨e₁⟩ ⟨e₂⟩, quotient.sound (e₁.antisymm e₂), le_total := assume a b, quotient.induction_on₂ a b $ assume α β, embedding.total } instance : decidable_linear_order cardinal.{u} := { decidable_le := by apply_instance, ..cardinal.linear_order } instance : distrib_lattice cardinal.{u} := by apply_instance instance : has_zero cardinal.{u} := ⟨⟦ulift empty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.ulift.symm⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).down.elim⟩ instance : has_one cardinal.{u} := ⟨⟦ulift unit⟧⟩ instance : zero_ne_one_class cardinal.{u} := { zero := 0, one := 1, zero_ne_one := ne.symm $ ne_zero_iff_nonempty.2 ⟨⟨()⟩⟩ } theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, ⟨()⟩, λ a b _, h _ _⟩⟩⟩ instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.sum_congr equiv.ulift (equiv.refl α)) (equiv.empty_sum α)⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.prod_congr equiv.ulift (equiv.refl α)) $ equiv.trans (equiv.empty_prod α) equiv.ulift.symm⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.trans (equiv.prod_congr equiv.ulift (equiv.refl α)) (equiv.unit_prod α)⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr equiv.ulift (equiv.refl α)) $ equiv.trans equiv.arrow_empty_unit $ equiv.ulift.symm⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr equiv.ulift (equiv.refl α)) $ equiv.unit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨ equiv.trans (equiv.arrow_congr (equiv.refl α) equiv.ulift) $ equiv.trans (equiv.arrow_unit_equiv_unit α) $ equiv.ulift.symm⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans $ equiv.bool_equiv_unit_sum_unit.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, have nonempty α, from ne_zero_iff_nonempty.1 heq, let a := choice this in have (α → empty) ≃ empty, from ⟨λf, f a, λe a, e, assume f, (f a).rec_on (λ_, (λa', f a) = f), assume e, rfl⟩, quotient.sound ⟨equiv.trans (equiv.arrow_congr (equiv.refl α) equiv.ulift) $ equiv.trans this equiv.ulift.symm⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) section order_properties open sum theorem zero_le (a : cardinal) : 0 ≤ a := quot.induction_on a $ λ α, ⟨embedding.of_not_nonempty $ λ ⟨⟨a⟩⟩, a.elim⟩ theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 := by simp [le_antisymm_iff, zero_le] theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 := by simp [lt_iff_le_and_ne, eq_comm, zero_le] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one theorem add_le_add {a b c d : cardinal} : a ≤ b → c ≤ d → a + c ≤ b + d := quotient.induction_on₂ a b $ assume α β, quotient.induction_on₂ c d $ assume γ δ ⟨e₁⟩ ⟨e₂⟩, ⟨embedding.sum_congr e₁ e₂⟩ theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := add_le_add (le_refl _) theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c := add_le_add h (le_refl _) theorem le_add_right (a b : cardinal) : a ≤ a + b := by simpa using add_le_add_left a (zero_le b) theorem le_add_left (a b : cardinal) : a ≤ b + a := by simpa using add_le_add_right a (zero_le b) theorem mul_le_mul {a b c d : cardinal} : a ≤ b → c ≤ d → a * c ≤ b * d := quotient.induction_on₂ a b $ assume α β, quotient.induction_on₂ c d $ assume γ δ ⟨e₁⟩ ⟨e₂⟩, ⟨embedding.prod_congr e₁ e₂⟩ theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c := mul_le_mul (le_refl _) theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c := mul_le_mul h (le_refl _) theorem power_le_power_left {a b c : cardinal} : a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := quotient.induction_on₃ a b c $ assume α β γ hα ⟨e⟩, have nonempty α, from classical.by_contradiction $ assume hnα, hα $ quotient.sound ⟨equiv.trans (equiv.empty_of_not_nonempty hnα) equiv.ulift.symm⟩, let ⟨a⟩ := this in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ↥-range f) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩ end order_properties instance : canonically_ordered_monoid cardinal.{u} := { add_le_add_left := λ a b h c, add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, le_imp_le_iff_lt_imp_lt.1 (add_le_add_left _), le_iff_exists_add := @le_iff_exists_add, ..cardinal.comm_semiring, ..cardinal.linear_order } instance : order_bot cardinal.{u} := { bot := 0, bot_le := zero_le, ..cardinal.linear_order } theorem cantor (a : cardinal.{u}) : a < 2 ^ a := by rw ← prop_eq_two; exact quot.induction_on a (λ α, ⟨⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩) instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.injective_min _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.injective_min _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩), cases classical.not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.inj h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨embedding.sigma_congr_right $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} (f : ι → cardinal) (a) : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := (sup_le _ _).2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := (sup_le _ _).2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin conv in (f _) {rw ← mk_out (f i)}, simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def], exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩, end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.empty_of_not_nonempty $ by exact λ ⟨h⟩, h.elim0).trans equiv.ulift.symm⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) @[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *] @[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp] theorem nat_succ (n : ℕ) : succ n = n.succ := le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _) @[simp] theorem succ_zero : succ 0 = 1 := by simpa using nat_succ 0 theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩ theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in classical.not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := some_spec (P n (λ y _, F y)), rw [← show F n = some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, have : ∀ i, ¬ ∀ b, ∃ a, G ⟨i, a⟩ i = b, { refine λ i h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective h⟩ }, simp [classical.not_forall] at this, exact let ⟨C, hc⟩ := axiom_of_choice this, ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _), end end cardinal
ca5168b0ab6818f704fc3ae5cc5f6063e3ea4b77
41ebf3cb010344adfa84907b3304db00e02db0a6
/uexp/src/uexp/rules/transitiveInferenceJoin3wayAgg.lean
553ccb262053a1d2a5303f2d45e588ddc8affbf7
[ "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
2,942
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..meta.ucongr import ..meta.TDP open Expr open Proj open Pred open SQL open tree open binary_operators notation `int` := datatypes.int variable integer_1: const datatypes.int variable integer_7: const datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_deptno)) (COUNT(uvariable (right⋅emp_slacker)))) FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt) GROUP BY (right⋅emp_deptno))) (product (table rel_emp) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅left)) (uvariable (right⋅right⋅left⋅emp_deptno))) (equal (uvariable (right⋅right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno))))) :SQL Γ _) = denoteSQL ((SELECT1 (e2p (constantExpr integer_1)) FROM1 (product ((SELECT (combineGroupByProj PLAIN(uvariable (right⋅emp_deptno)) (COUNT(uvariable (right⋅emp_slacker)))) FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt) GROUP BY (right⋅emp_deptno))) (product ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))) ((SELECT * FROM1 (table rel_emp) WHERE (castPred (combine (right⋅emp_deptno) (e2p (constantExpr integer_7)) ) predicates.gt))))) WHERE (and (equal (uvariable (right⋅left⋅left)) (uvariable (right⋅right⋅left⋅emp_deptno))) (equal (uvariable (right⋅right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno))))) :SQL Γ _) := begin intros, unfold_all_denotations, funext, try {simp}, print_size, try {TDP' ucongr}, sorry end
72a6d699aa06680cc032ff50374b3b850ce5b8ab
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/sub_module.lean
38eee37970b0a7826b7e2d1737f1f554ad954a3f
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
3,995
lean
import .group_representation import .morphism universe variables u v w variables {G : Type u} {R : Type v} {M : Type w} [group G] [ring R] [add_comm_group M] [module R M] namespace stability variables {p : submodule R M} /-- Technical lemma to deal with `submodule p` of `M`. -/ lemma submodule_ext (x y : p) : (x : M) = (y : M) → x = y := begin intros,rcases x,rcases y,congr; try {assumption}, end lemma coersion₂ ( f g : M ≃ₗ[R] M) : ⇑ f ∘ ⇑ g = ⇑ (f * g) := rfl /-- Let `ρ : G →* M ≃ₗ[R] M` a representation. A submodule `p` of `M` is `ρ-stable` when : `∀ g ∈ G, ∀ x ∈ p, ρ g x ∈ p`. It induce a `sub-representation` : ` Res ρ p : G →* p ≃ₗ[R] p ` -/ def stable_submodule (ρ : group_representation G R M)(p : submodule R M) := ∀ g : G, ∀ x : p, ρ g x ∈ p --- better with x : M, x ∈ p → ρ g x ∈ p ? variables {ρ : group_representation G R M} /-- Restriction map : `res ρ : G → (p → p)`. -/ def res (stab : stable_submodule ρ p): G → p → p := λ g x, ⟨( ρ g ) x, stab g x⟩ variables (stab : stable_submodule ρ p)(g : G) lemma coersion (x : p) : ((res stab g x) : M) = (ρ g : M ≃ₗ[R] M) (x : M) := rfl lemma res_add (g : G) (x y : p) : res stab g (x+y) = res stab g x + res stab g y := begin apply submodule_ext, change ρ _ _ = _, erw (ρ g).map_add, exact rfl, end lemma res_smul (g : G) (r : R) ( x : p) : res stab g ( r • x) = r • res stab g x := begin apply submodule_ext, change ρ _ _ = _, erw (ρ g).map_smul, exact rfl, end /-- `res` is linear map. -/ def res_linear (stab : stable_submodule ρ p) (g : G) : p →ₗ[R]p := { to_fun := res stab g, add := res_add stab g, smul := res_smul stab g } /-- ` ∀ g :G, res ρ g` has an inverse given by ` res ρ g⁻¹`. -/ lemma res_mul (stab : stable_submodule ρ p ) (g1 g2 : G) : res stab (g1 * g2) = res stab g1 ∘ res stab g2 := begin ext, apply submodule_ext, rw [ coersion, ρ.map_mul], exact rfl, end lemma res_one (stab : stable_submodule ρ p) : res stab 1 = id := begin ext,apply submodule_ext,rw [coersion,ρ.map_one], exact rfl, end /-- `res` is an `set` equivalence -/ def res_equiv (h : stable_submodule ρ p) (g : G) : (p ≃ p) := { to_fun := (res h g), inv_fun := (res h g⁻¹), left_inv := begin intros x, apply submodule_ext, change (ρ _ * _) x = _, rw ← ρ.map_mul, rw [inv_mul_self, ρ.map_one ], exact rfl, end , right_inv := begin intros x, apply submodule_ext, change (ρ g * _) x = _, rw ← ρ.map_mul, rw mul_inv_self, rw ρ.map_one, exact rfl, end } /-- We make `G → p ≃ₗ[R]p` -/ def res_equiv_linear (stab : stable_submodule ρ p) (g : G) : p ≃ₗ[R]p := { .. res_linear stab g, .. res_equiv stab g} lemma res_equiv_coersion (stab : stable_submodule ρ p) (g : G)(x : p) : (res_equiv_linear stab g) x = res stab g x:= rfl /-- the restriction representation `G →* p ≃ₗ[R]p` -/ def Res (stab : stable_submodule ρ p) : group_representation G R p := { to_fun := res_equiv_linear stab, map_one' := begin ext,apply submodule_ext, change (ρ 1) x = _, rw ρ.map_one, exact rfl, end, map_mul' := begin intros g1 g2, ext, apply submodule_ext, change (ρ (g1 * g2)) x = _ , rw ρ.map_mul, exact rfl, end} /- i have to study more the notion -/ theorem Res.apply (g : G) (x : p) : (Res stab g x : M) = ρ g x := rfl /-- make a morphism : `Res stab → ρ` -/ def res.subtype (stab : stable_submodule ρ p) : Res stab ⟶ ρ := { ℓ := submodule.subtype p, commute := by {intros g, exact rfl} } end stability
e98613c3566c146ef040d41fd1c49f31a3ee7c1f
0c1546a496eccfb56620165cad015f88d56190c5
/library/init/category/combinators.lean
29aa1334d2c4e00a5ae3e66dd6e613b4ed7097cc
[ "Apache-2.0" ]
permissive
Solertis/lean
491e0939957486f664498fbfb02546e042699958
84188c5aa1673fdf37a082b2de8562dddf53df3f
refs/heads/master
1,610,174,257,606
1,486,263,620,000
1,486,263,620,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,327
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Monad combinators, as in Haskell's Control.Monad. -/ prelude import init.category.monad init.data.list.basic universe variables u v w namespace monad def mapm {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (f : α → m β) : list α → m (list β) | [] := return [] | (h :: t) := do h' ← f h, t' ← mapm t, return (h' :: t') def mapm' {m : Type → Type v} [monad m] {α : Type u} {β : Type} (f : α → m β) : list α → m unit | [] := return () | (h :: t) := f h >> mapm' t def for {m : Type u → Type v} [monad m] {α : Type w} {β : Type u} (l : list α) (f : α → m β) : m (list β) := mapm f l def for' {m : Type → Type v} [monad m] {α : Type u} {β : Type} (l : list α) (f : α → m β) : m unit := mapm' f l def sequence {m : Type u → Type v} [monad m] {α : Type u} : list (m α) → m (list α) | [] := return [] | (h :: t) := do h' ← h, t' ← sequence t, return (h' :: t') def sequence' {m : Type → Type u} [monad m] {α : Type} : list (m α) → m unit | [] := return () | (h :: t) := h >> sequence' t infix ` =<< `:2 := λ u v, v >>= u infix ` >=> `:2 := λ s t a, s a >>= t infix ` <=< `:2 := λ t s a, s a >>= t def join {m : Type u → Type u} [monad m] {α : Type u} (a : m (m α)) : m α := bind a id def filter {m : Type → Type v} [monad m] {α : Type} (f : α → m bool) : list α → m (list α) | [] := return [] | (h :: t) := do b ← f h, t' ← filter t, cond b (return (h :: t')) (return t') def foldl {m : Type u → Type v} [monad m] {s : Type u} {α : Type w} : (s → α → m s) → s → list α → m s | f s [] := return s | f s (h :: r) := do s' ← f s h, foldl f s' r def when {m : Type → Type} [monad m] (c : Prop) [h : decidable c] (t : m unit) : m unit := ite c t (pure ()) def whenb {m : Type → Type} [monad m] (b : bool) (t : m unit) : m unit := cond b t (return ()) def unlessb {m : Type → Type} [monad m] (b : bool) (t : m unit) : m unit := cond b (return ()) t def cond {m : Type → Type} [monad m] {α : Type} (mbool : m bool) (tm fm : m α) : m α := do b ← mbool, cond b tm fm def lift {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → φ) (ma : m α) : m φ := do a ← ma, return (f a) def lift₂ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → φ) (ma₁ ma₂: m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, return (f a₁ a₂) def lift₃ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → φ) (ma₁ ma₂ ma₃ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, return (f a₁ a₂ a₃) def lift₄ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → α → φ) (ma₁ ma₂ ma₃ ma₄ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, a₄ ← ma₄, return (f a₁ a₂ a₃ a₄) def lift₅ {m : Type u → Type v} [monad m] {α φ : Type u} (f : α → α → α → α → α → φ) (ma₁ ma₂ ma₃ ma₄ ma₅ : m α) : m φ := do a₁ ← ma₁, a₂ ← ma₂, a₃ ← ma₃, a₄ ← ma₄, a₅ ← ma₅, return (f a₁ a₂ a₃ a₄ a₅) end monad
b7f6bf8deb791310767c1f600c84c0f885e87a76
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/quotient_group.lean
1d89a98d86bae424f8125d4f438d081c2e49d9d8
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
3,219
lean
import group_theory.quotient_group import for_mathlib.group -- Some stuff is now in mathlib namespace quotient_group theorem map_id {G : Type*} [group G] (K : set G) [normal_subgroup K] (g : quotient K) : map K K id (λ x h, h) g = g := by induction g; refl theorem map_comp {G : Type*} {H : Type*} {J : Type*} [group G] [group H] [group J] (a : G → H) [is_group_hom a] (b : H → J) [is_group_hom b] {G1 : set G} {H1 : set H} {J1 : set J} [normal_subgroup G1] [normal_subgroup H1] [normal_subgroup J1] (h1 : G1 ⊆ a ⁻¹' H1) (h2 : H1 ⊆ b ⁻¹' J1) (g : quotient G1) : map H1 J1 b h2 (map G1 H1 a h1 g) = map G1 J1 (b ∘ a) (λ _ hx, h2 $ h1 hx) g := by induction g; refl end quotient_group open quotient_group -- I don't use this any more, first because group_equiv.quotient is more general -- and second because I don't like the definition of the function via quotient_group.map def group_equiv.quotient' {G : Type*} {H : Type*} [group G] [group H] (h : group_equiv G H) (K : set H) [normal_subgroup K] : group_equiv (quotient_group.quotient (h.to_equiv ⁻¹' K)) (quotient_group.quotient K) := { to_fun := map (h.to_equiv ⁻¹' K) K h.to_fun (le_refl (h.to_equiv ⁻¹' K)), inv_fun := map K (h.to_equiv ⁻¹' K) h.symm.to_fun (λ x H, show h.to_fun (h.inv_fun x) ∈ K, by rwa h.right_inv x), left_inv := λ g, begin rw quotient_group.map_comp, convert map_id _ g, ext x, exact h.left_inv x end, right_inv := λ g, begin rw quotient_group.map_comp, convert map_id _ g, ext x, exact h.right_inv x end, hom := ⟨begin have H : is_group_hom (map (h.to_equiv ⁻¹' K) K h.to_fun (le_refl (h.to_equiv ⁻¹' K))) := by apply_instance, cases H with H, exact H, end⟩} -- This version is better, but Mario points out that really I shuold be using a -- relation rather than h2 : he.to_equiv ⁻¹' K = J. def group_equiv.quotient {G : Type*} {H : Type*} [group G] [group H] (he : group_equiv G H) (J : set G) [normal_subgroup J] (K : set H) [normal_subgroup K] (h2 : he.to_equiv ⁻¹' K = J) : group_equiv (quotient_group.quotient J) (quotient_group.quotient K) := { to_fun := quotient_group.lift J (λ g, quotient_group.mk (he.to_equiv g)) begin unfold set.preimage at h2, intros g hg, rw ←h2 at hg, rw ←is_group_hom.mem_ker (quotient_group.mk : H → quotient_group.quotient K), rwa quotient_group.ker_mk, end, inv_fun := quotient_group.lift K (λ h, quotient_group.mk (he.symm.to_equiv h)) begin intros h hh, rw ←is_group_hom.mem_ker (quotient_group.mk : G → quotient_group.quotient J), rw quotient_group.ker_mk, show he.to_equiv.symm h ∈ J, rw ←h2, show he.to_equiv (he.to_equiv.symm h) ∈ K, convert hh, exact he.to_equiv.right_inv h end, left_inv := λ g, begin induction g, conv begin to_rhs, rw ←he.to_equiv.left_inv g, end, refl, refl, end, right_inv := λ h, begin induction h, conv begin to_rhs, rw ←he.to_equiv.right_inv h, end, refl, refl, end, hom := ⟨begin have H := quotient_group.is_group_hom_quotient_lift J _ _, cases H with H, exact H, -- ! end⟩ }
ecb63ecc84442976e2f13ebb7ddb29df9eddefab
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/function.lean
35a8b6de2bf1627d43b673bdbd39555d50a2911a
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
6,643
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, Haitao Zhang -/ prelude import init.data.prod init.funext init.logic /-! # General operations on functions -/ universes u₁ u₂ u₃ u₄ namespace function variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁} /-- Composition of functions: `(f ∘ g) x = f (g x)`. -/ @[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ := λ x, f (g x) /-- Composition of dependent functions: `(f ∘' g) x = f (g x)`, where type of `g x` depends on `x` and type of `f (g x)` depends on `x` and `g x`. -/ @[inline, reducible] def dcomp {β : α → Sort u₂} {φ : Π {x : α}, β x → Sort u₃} (f : Π {x : α} (y : β x), φ y) (g : Π x, β x) : Π x, φ (g x) := λ x, f (g x) infixr ` ∘ ` := function.comp infixr ` ∘' `:80 := function.dcomp @[reducible] def comp_right (f : β → β → β) (g : α → β) : β → α → β := λ b a, f b (g a) @[reducible] def comp_left (f : β → β → β) (g : α → β) : α → β → β := λ a b, f (g a) b /-- Given functions `f : β → β → φ` and `g : α → β`, produce a function `α → α → φ` that evaluates `g` on each argument, then applies `f` to the results. Can be used, e.g., to transfer a relation from `β` to `α`. -/ @[reducible] def on_fun (f : β → β → φ) (g : α → β) : α → α → φ := λ x y, f (g x) (g y) @[reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ) : α → β → ζ := λ x y, op (f x y) (g x y) /-- Constant `λ _, a`. -/ @[reducible] def const (β : Sort u₂) (a : α) : β → α := λ x, a @[reducible] def swap {φ : α → β → Sort u₃} (f : Π x y, φ x y) : Π y x, φ x y := λ y x, f x y @[reducible] def app {β : α → Sort u₂} (f : Π x, β x) (x : α) : β x := f x infixl ` on `:2 := on_fun notation f ` -[` op `]- ` g := combine f op g lemma left_id (f : α → β) : id ∘ f = f := rfl lemma right_id (f : α → β) : f ∘ id = f := rfl @[simp] lemma comp_app (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl lemma comp.assoc (f : φ → δ) (g : β → φ) (h : α → β) : (f ∘ g) ∘ h = f ∘ (g ∘ h) := rfl @[simp] lemma comp.left_id (f : α → β) : id ∘ f = f := rfl @[simp] lemma comp.right_id (f : α → β) : f ∘ id = f := rfl lemma comp_const_right (f : β → φ) (b : β) : f ∘ (const α b) = const α (f b) := rfl /-- A function `f : α → β` is called injective if `f x = f y` implies `x = y`. -/ @[reducible] def injective (f : α → β) : Prop := ∀ ⦃a₁ a₂⦄, f a₁ = f a₂ → a₁ = a₂ lemma injective.comp {g : β → φ} {f : α → β} (hg : injective g) (hf : injective f) : injective (g ∘ f) := assume a₁ a₂, assume h, hf (hg h) /-- A function `f : α → β` is calles surjective if every `b : β` is equal to `f a` for some `a : α`. -/ @[reducible] def surjective (f : α → β) : Prop := ∀ b, ∃ a, f a = b lemma surjective.comp {g : β → φ} {f : α → β} (hg : surjective g) (hf : surjective f) : surjective (g ∘ f) := λ (c : φ), exists.elim (hg c) (λ b hb, exists.elim (hf b) (λ a ha, exists.intro a (show g (f a) = c, from (eq.trans (congr_arg g ha) hb)))) /-- A function is called bijective if it is both injective and surjective. -/ def bijective (f : α → β) := injective f ∧ surjective f lemma bijective.comp {g : β → φ} {f : α → β} : bijective g → bijective f → bijective (g ∘ f) | ⟨h_ginj, h_gsurj⟩ ⟨h_finj, h_fsurj⟩ := ⟨h_ginj.comp h_finj, h_gsurj.comp h_fsurj⟩ /-- `left_inverse g f` means that g is a left inverse to f. That is, `g ∘ f = id`. -/ def left_inverse (g : β → α) (f : α → β) : Prop := ∀ x, g (f x) = x /-- `has_left_inverse f` means that `f` has an unspecified left inverse. -/ def has_left_inverse (f : α → β) : Prop := ∃ finv : β → α, left_inverse finv f /-- `right_inverse g f` means that g is a right inverse to f. That is, `f ∘ g = id`. -/ def right_inverse (g : β → α) (f : α → β) : Prop := left_inverse f g /-- `has_right_inverse f` means that `f` has an unspecified right inverse. -/ def has_right_inverse (f : α → β) : Prop := ∃ finv : β → α, right_inverse finv f lemma left_inverse.injective {g : β → α} {f : α → β} : left_inverse g f → injective f := assume h a b faeqfb, calc a = g (f a) : (h a).symm ... = g (f b) : congr_arg g faeqfb ... = b : h b lemma has_left_inverse.injective {f : α → β} : has_left_inverse f → injective f := assume h, exists.elim h (λ finv inv, inv.injective) lemma right_inverse_of_injective_of_left_inverse {f : α → β} {g : β → α} (injf : injective f) (lfg : left_inverse f g) : right_inverse f g := assume x, have h : f (g (f x)) = f x, from lfg (f x), injf h lemma right_inverse.surjective {f : α → β} {g : β → α} (h : right_inverse g f) : surjective f := assume y, ⟨g y, h y⟩ lemma has_right_inverse.surjective {f : α → β} : has_right_inverse f → surjective f | ⟨finv, inv⟩ := inv.surjective lemma left_inverse_of_surjective_of_right_inverse {f : α → β} {g : β → α} (surjf : surjective f) (rfg : right_inverse f g) : left_inverse f g := assume y, exists.elim (surjf y) (λ x hx, calc f (g y) = f (g (f x)) : hx ▸ rfl ... = f x : eq.symm (rfg x) ▸ rfl ... = y : hx) lemma injective_id : injective (@id α) := assume a₁ a₂ h, h lemma surjective_id : surjective (@id α) := assume a, ⟨a, rfl⟩ lemma bijective_id : bijective (@id α) := ⟨injective_id, surjective_id⟩ end function namespace function variables {α : Type u₁} {β : Type u₂} {φ : Type u₃} /-- Interpret a function on `α × β` as a function with two arguments. -/ @[inline] def curry : (α × β → φ) → α → β → φ := λ f a b, f (a, b) /-- Interpret a function with two arguments as a function on `α × β` -/ @[inline] def uncurry : (α → β → φ) → α × β → φ := λ f a, f a.1 a.2 @[simp] lemma curry_uncurry (f : α → β → φ) : curry (uncurry f) = f := rfl @[simp] lemma uncurry_curry (f : α × β → φ) : uncurry (curry f) = f := funext (λ ⟨a, b⟩, rfl) protected lemma left_inverse.id {g : β → α} {f : α → β} (h : left_inverse g f) : g ∘ f = id := funext h protected def right_inverse.id {g : β → α} {f : α → β} (h : right_inverse g f) : f ∘ g = id := funext h end function
46af75d3232968fcde568e815394e50a2dbe7673
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/AuxDeclCache.lean
8060bff9569f84a47c52daff1402998ee34cc693
[ "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
937
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.CompilerM import Lean.Compiler.LCNF.DeclHash import Lean.Compiler.LCNF.Internalize namespace Lean.Compiler.LCNF abbrev AuxDeclCache := PHashMap Decl Name builtin_initialize auxDeclCacheExt : EnvExtension AuxDeclCache ← registerEnvExtension (pure {}) inductive CacheAuxDeclResult where | new | alreadyCached (declName : Name) def cacheAuxDecl (decl : Decl) : CompilerM CacheAuxDeclResult := do let key := { decl with name := .anonymous } let key ← normalizeFVarIds key match auxDeclCacheExt.getState (← getEnv) |>.find? key with | some declName => return .alreadyCached declName | none => modifyEnv fun env => auxDeclCacheExt.modifyState env fun s => s.insert key decl.name return .new end Lean.Compiler.LCNF
5787eb95d49862be0492ee4d0bbf7cb663cb992c
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/mv_polynomial/basic.lean
bc253c5c7728b54bfd7f1d32727688f14b84e0e2
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,286
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, Johan Commelin, Mario Carneiro -/ import data.polynomial.eval /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring R] {p q : mv_polynomial σ R} instance decidable_eq_mv_polynomial [decidable_eq σ] [decidable_eq R] : decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq instance : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring instance : inhabited (mv_polynomial σ R) := ⟨0⟩ instance : has_scalar R (mv_polynomial σ R) := add_monoid_algebra.has_scalar instance : semimodule R (mv_polynomial σ R) := add_monoid_algebra.semimodule instance : algebra R (mv_polynomial σ R) := add_monoid_algebra.algebra /-- The coercion turning an `mv_polynomial` into the function which reports the coefficient of a given monomial. -/ def coeff_coe_to_fun : has_coe_to_fun (mv_polynomial σ R) := finsupp.has_coe_to_fun local attribute [instance] coeff_coe_to_fun /-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/ def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* mv_polynomial σ R := { to_fun := monomial 0, map_zero' := by simp [monomial], map_one' := rfl, map_add' := λ a a', single_add, map_mul' := λ a a', by simp [monomial, single_mul_single] } variables (R σ) theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl variables {R σ} /-- `X n` is the degree `1` monomial $X_n$. -/ def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1 @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n := by induction n; simp [pow_succ, *] lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] : function.injective (C : R → mv_polynomial σ R) := finsupp.single_injective _ lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) (hσ : ¬ nonempty σ) : function.surjective (C : R → mv_polynomial σ R) := begin refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩, simpa [(finsupp.ext (λ x, absurd (nonempty.intro x) hσ) : a = 0), C, monomial], end lemma C_surjective_fin_0 {R : Type*} [comm_ring R] : function.surjective (mv_polynomial.C : R → mv_polynomial (fin 0) R) := C_surjective (fin 0) (λ h, let ⟨n⟩ := h in fin_zero_elim n) @[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) : (C r : mv_polynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] : infinite (mv_polynomial σ R) := infinite.of_injective C (C_injective _ _) instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R] [nontrivial R] : infinite (mv_polynomial σ R) := infinite.of_injective (λ i : ℕ, monomial (single (classical.arbitrary σ) i) 1) begin intros m n h, have := (single_eq_single_iff _ _ _ _).mp h, simp only [and_true, eq_self_iff_true, or_false, one_ne_zero, and_self, single_eq_single_iff, eq_self_iff_true, true_and] at this, rcases this with (rfl|⟨rfl, rfl⟩); refl end lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n := by induction n; simp [nat.succ_eq_add_one, *] theorem C_mul' : mv_polynomial.C a * p = a • p := begin apply finsupp.induction p, { exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero R (mv_polynomial σ R) _ _ _ a).symm }, intros p b f haf hb0 ih, rw [mul_add, ih, @smul_add R (mv_polynomial σ R) _ _ _ a], congr' 1, rw [add_monoid_algebra.mul_def, finsupp.smul_single], simp only [mv_polynomial.C], dsimp [mv_polynomial.monomial], rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add], { rw [mul_zero, finsupp.single_zero] }, { rw finsupp.sum_single_index, all_goals { rw [zero_mul, finsupp.single_zero] }, } end lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma single_eq_C_mul_X {s : σ} {a : R} {n : ℕ} : monomial (single s n) a = C a * (X s)^n := by { rw [← zero_add (single s n), monomial_add_single, C], refl } @[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} : monomial s a + monomial s b = monomial s (a + b) := by simp [monomial] @[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := by rw [monomial, monomial, monomial, add_monoid_algebra.single_mul_single] @[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 := by rw [monomial, single_zero]; refl @[simp] lemma sum_monomial {A : Type*} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := sum_single_index w lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) := begin apply @finsupp.induction σ ℕ _ _ s, { simp only [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm], { simp only [pow_zero], }, { intro a, simp only [pow_zero], }, { intros, rw pow_add, }, } end @[recursor 5] lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [add_comm, monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) attribute [elab_as_eliminator] theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this, show P (monomial 0 0), from h1 0 0) (λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf) @[ext] lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A} (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := by { ext, exacts [hC _, hX _] } lemma hom_eq_hom [semiring S₂] (f g : mv_polynomial σ R →+* S₂) (hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) : f p = g p := ring_hom.congr_fun (ring_hom_ext hC hX) p lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) : f p = p := hom_eq_hom f (ring_hom.id _) hC hX p @[ext] lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A] {f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := by { ext, exact hf _ } @[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) : f (C r) = C r := f.commutes r section coeff section -- While setting up `coeff`, we make `mv_polynomial` reducible so we can treat it as a function. local attribute [reducible] mv_polynomial /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := p m end @[ext] lemma ext (p q : mv_polynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ R) : p = q ↔ (∀ m, coeff m p = coeff m q) := ⟨ λ h m, by rw h, ext p q⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply p q m @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ R) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m, map_zero := coeff_zero m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) := (s.sum_hom _).symm lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) := by simp [monomial_eq] @[simp] lemma coeff_monomial (m n) (a) : coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 := by convert single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 := by convert single_apply lemma coeff_X_pow (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:R), rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' (i : σ) (m) : coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ R) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def], simp only [C, monomial], dsimp, rw [monomial], rw sum_single_index, { simp only [zero_add], convert sum_apply, simp only [single_apply, finsupp.sum], rw finset.sum_eq_single m, { rw if_pos rfl, refl }, { intros m' hm' H, apply if_neg, exact H }, { intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] } }, simp only [zero_mul, single_zero, zero_add, sum_zero], end lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x in (antidiagonal n).support, coeff x.1 p * coeff x.2 q := begin rw mul_def, -- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`, -- so we need to turn both sides into a sum over a product. have := @finset.sum_product (σ →₀ ℕ) R _ _ p.support q.support (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only }, convert single_apply }, symmetry, -- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`. apply finset.sum_bij_ne_zero (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)) _ _, (x.1, x.2)), { intros x hx hx', simp only [mem_antidiagonal_support, eq_self_iff_true, if_false, forall_true_iff], contrapose! hx', rw [if_neg hx'] }, { rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl', simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro }, { rintros ⟨i, j⟩ hij hij', refine ⟨⟨i, j⟩, _, _⟩, { simp only [mem_support_iff, finset.mem_product], contrapose! hij', exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' }, { rw [mem_antidiagonal_support] at hij, simp only [exists_prop, true_and, ne.def, if_pos hij, hij', not_false_iff] } }, { intros x hx hx', simp only [ne.def] at hx' ⊢, split_ifs with H, { refl }, { rw if_neg H at hx', contradiction } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal_support] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' with t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { delta coeff, rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H, rcases H with ⟨j, hj, i', hi', H⟩, delta X monomial at hi', rw mem_support_single at hi', cases hi', subst i', erw finset.mem_singleton at H, subst m, rw [mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 } end lemma eq_zero_iff {p : mv_polynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by { rw ext_iff, simp only [coeff_zero], } lemma ne_zero_iff {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by { rw [ne.def, eq_zero_iff], push_neg, } lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0, let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i), use ψ, apply mv_polynomial.ext, intro i, simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'], split_ifs with hi hi, { rw hc }, { rw finsupp.not_mem_support_iff at hi, rwa mul_zero } }, end end coeff section constant_coeff /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff : mv_polynomial σ R →+* R := { to_fun := coeff 0, map_one' := by simp [coeff, add_monoid_algebra.one_def], map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero], map_zero' := coeff_zero _, map_add' := coeff_add _ } lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl @[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r := by simp [constant_coeff_eq] @[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 := by simp [constant_coeff_eq] lemma constant_coeff_monomial (d : σ →₀ ℕ) (r : R) : constant_coeff (monomial d r) = if d = 0 then r else 0 := by rw [constant_coeff_eq, coeff_monomial] variables (σ R) @[simp] lemma constant_coeff_comp_C : constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R := by { ext, apply constant_coeff_C } @[simp] lemma constant_coeff_comp_algebra_map : constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R := constant_coeff_comp_C _ _ end constant_coeff section as_sum @[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) : ∑ v in p.support, monomial v (coeff v p) = p := finsupp.sum_single p lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end as_sum section eval₂ variables [comm_semiring S₁] variables (f : R →+* S₁) (g : σ → S₁) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ R) : S₁ := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i := rfl lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i := by { simp only [eval₂_eq, ← finsupp.prod_pow], refl } @[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 := finsupp.sum_zero_index section @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [is_semiring_hom.map_zero f]) (by simp [add_mul, is_semiring_hom.map_add f]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 := (eval₂_C _ _ _).trans (is_semiring_hom.map_one f) @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, is_semiring_hom.map_one f, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, is_semiring_hom.map_one f, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_polynomial.induction_on q, { simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] }, { simp [mul_add, eval₂_add] {contextual := tt} }, { simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end @[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := eval₂_one _ _ | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ p q, eval₂_add _ _, map_mul := λ p q, eval₂_mul _ _ } /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g) @[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := by rintros rfl rfl rfl; refl end @[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) : eval₂_hom f g (C r) = f r := eval₂_C f g r @[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) : eval₂_hom f g (X i) = g i := eval₂_X f g i @[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) := begin apply mv_polynomial.ring_hom_ext, { intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] }, { intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] } end lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) := by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X'] section local attribute [instance, priority 10] is_semiring_hom.comp lemma eval₂_comp_left {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, k.map_add, eval₂_mul, k.map_mul] {contextual := tt} end @[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end @[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) := (s.prod_hom _).symm @[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) := (s.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := begin show _ = eval₂_hom f g (eval₂ C q p), rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp, end end eval₂ section eval variables {f : σ → R} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i := rfl lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i := eval₂_eq' (ring_hom.id R) x f lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _ @[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p := by rw [smul_eq_C_mul, (eval x).map_mul, eval_C] lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) := (eval g).map_sum _ _ @[to_additive] lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) := (eval g).map_prod _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : eval (eval g ∘ f) p = eval g (eval₂ C f p) := begin rw eval₂_comp_left (eval g), unfold eval, simp only [coe_eval₂_hom], congr' with a, simp end end eval section map variables [comm_semiring S₁] variables (f : R →+* S₁) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _ theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta theorem map_map [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : map g (map f p) = map (g.comp f) p := (eval₂_comp_left (map g) (C.comp f) X p).trans $ begin congr, { ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], }, { ext1 n, simp only [map_X, comp_app], } end theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) : p.eval₂ f g = eval g (map f p) := begin unfold map eval, simp only [coe_eval₂_hom], have h := eval₂_comp_left (eval₂_hom _ g), dsimp at h, rw h, congr, { ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], }, { ext1 n, simp only [comp_app, eval₂_X], }, end lemma eval₂_comp_right {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero }, { intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add }, { intros p i hp m, simp only [hp, (map f).map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw is_semiring_hom.map_zero f } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) := begin intros p q h, simp only [ext_iff, coeff_map] at h ⊢, intro m, exact hf (h m), end @[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval g (map f p) = eval₂ f g p := by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } } @[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (map f p) = eval₂ (φ.comp f) g p := by { rw [← eval_map, ← eval_map, map_map], } @[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p := eval₂_map f g φ p @[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) : constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) := coeff_map f φ 0 lemma constant_coeff_comp_map (f : R →+* S₁) : (constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff := by { ext; simp } lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support := begin intro x, simp only [finsupp.mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f end lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) : (map f p).support = p.support := begin apply finset.subset.antisymm, { exact mv_polynomial.support_map_subset _ _ }, intros x hx, rw finsupp.mem_support_iff, contrapose! hx, simp only [not_not, finsupp.mem_support_iff], change (map f p).coeff x = 0 at hx, rw [coeff_map, ← f.map_zero] at hx, exact hf hx end lemma C_dvd_iff_map_hom_eq_zero (q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r') (φ : mv_polynomial σ R) : C r ∣ φ ↔ map q φ = 0 := begin rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff], simp only [coeff_map, ring_hom.coe_of, coeff_zero, hr], end lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) : map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ := begin rw mv_polynomial.ext_iff, apply forall_congr, intro m, rw [coeff_map], apply eq_iff_eq_cancel_right.mpr, refl end end map section aeval /-! ### The algebra of multivariate polynomials -/ variables (f : σ → S₁) variables [comm_semiring S₁] [algebra R S₁] [comm_semiring S₂] /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval : mv_polynomial σ R →ₐ[R] S₁ := { commutes' := λ r, eval₂_C _ _ _ .. eval₂_hom (algebra_map R S₁) f } theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) : aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl @[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _ @[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _ theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) : φ = aeval (φ ∘ X) := by { ext i, simp } lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B] (φ : S₁ →ₐ[R] B) : φ.comp (aeval f) = aeval (λ i, φ (f i)) := by { ext i, simp } @[simp] lemma map_aeval {B : Type*} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } @[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) := begin suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff, from ring_hom.congr_fun this p, ext; simp end @[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) := eval₂_hom_zero f p @[simp] lemma aeval_zero (p : mv_polynomial σ R) : aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := eval₂_hom_zero (algebra_map R S₁) p @[simp] lemma aeval_zero' (p : mv_polynomial σ R) : aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := aeval_zero p lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) := eval₂_hom_monomial _ _ _ _ lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) : eval₂_hom f g φ = 0 := begin rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero], intros d hd, obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd), rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hgi, zero_pow], rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff] end lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) : aeval f φ = 0 := eval₂_hom_eq_zero _ _ _ h end aeval end comm_semiring end mv_polynomial
6d865e462b3f847f5a592df56e03f2679e849830
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Init/Control/State.lean
25c1c66f0e0b4b466ea8d1c1c9698ffd2829741d
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,478
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, Sebastian Ullrich The State monad transformer. -/ prelude import Init.Control.Basic import Init.Control.Id import Init.Control.Except universes u v w def StateT (σ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := σ → m (α × σ) @[inline] def StateT.run {σ : Type u} {m : Type u → Type v} {α : Type u} (x : StateT σ m α) (s : σ) : m (α × σ) := x s @[inline] def StateT.run' {σ : Type u} {m : Type u → Type v} [Functor m] {α : Type u} (x : StateT σ m α) (s : σ) : m α := (·.1) <$> x s @[reducible] def StateM (σ α : Type u) : Type u := StateT σ Id α instance {σ α} [Subsingleton σ] [Subsingleton α] : Subsingleton (StateM σ α) where allEq x y := by apply funext intro s match x s, y s with | (a₁, s₁), (a₂, s₂) => rw [Subsingleton.elim a₁ a₂, Subsingleton.elim s₁ s₂] namespace StateT section variables {σ : Type u} {m : Type u → Type v} variables [Monad m] {α β : Type u} @[inline] protected def pure (a : α) : StateT σ m α := fun s => pure (a, s) @[inline] protected def bind (x : StateT σ m α) (f : α → StateT σ m β) : StateT σ m β := fun s => do let (a, s) ← x s; f a s @[inline] protected def map (f : α → β) (x : StateT σ m α) : StateT σ m β := fun s => do let (a, s) ← x s; pure (f a, s) instance : Monad (StateT σ m) where pure := StateT.pure bind := StateT.bind map := StateT.map @[inline] protected def orElse [Alternative m] {α : Type u} (x₁ x₂ : StateT σ m α) : StateT σ m α := fun s => x₁ s <|> x₂ s @[inline] protected def failure [Alternative m] {α : Type u} : StateT σ m α := fun s => failure instance [Alternative m] : Alternative (StateT σ m) where failure := StateT.failure orElse := StateT.orElse @[inline] protected def get : StateT σ m σ := fun s => pure (s, s) @[inline] protected def set : σ → StateT σ m PUnit := fun s' s => pure (⟨⟩, s') @[inline] protected def modifyGet (f : σ → α × σ) : StateT σ m α := fun s => pure (f s) @[inline] protected def lift {α : Type u} (t : m α) : StateT σ m α := fun s => do let a ← t; pure (a, s) instance : MonadLift m (StateT σ m) := ⟨StateT.lift⟩ instance (σ m) [Monad m] : MonadFunctor m (StateT σ m) := ⟨fun f x s => f (x s)⟩ instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (StateT σ m) := { throw := StateT.lift ∘ throwThe ε tryCatch := fun x c s => tryCatchThe ε (x s) (fun e => c e s) } end end StateT section variables {σ : Type u} {m : Type u → Type v} instance [Monad m] : MonadStateOf σ (StateT σ m) where get := StateT.get set := StateT.set modifyGet := StateT.modifyGet end instance StateT.monadControl (σ : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (StateT σ m) where stM := fun α => α × σ liftWith := fun f => do let s ← get; liftM (f (fun x => x.run s)) restoreM := fun x => do let (a, s) ← liftM x; set s; pure a instance StateT.tryFinally {m : Type u → Type v} {σ : Type u} [MonadFinally m] [Monad m] : MonadFinally (StateT σ m) where tryFinally' := fun x h s => do let ((a, _), (b, s'')) ← tryFinally' (x s) fun | some (a, s') => h (some a) s' | none => h none s pure ((a, b), s'')
18a22291e0d68ff8c9272eca6026fe56918901df
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/witt_vector/compare.lean
7e5ff4a2eccadf432fd13c865058dc325b2b419a
[ "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
8,286
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import ring_theory.witt_vector.truncated import ring_theory.witt_vector.identities import data.padics.ring_homs /-! # Comparison isomorphism between `witt_vector p (zmod p)` and `ℤ_[p]` We construct a ring isomorphism between `witt_vector p (zmod p)` and `ℤ_[p]`. This isomorphism follows from the fact that both satisfy the universal property of the inverse limit of `zmod (p^n)`. ## Main declarations * `witt_vector.to_zmod_pow`: a family of compatible ring homs `𝕎 (zmod p) → zmod (p^k)` * `witt_vector.equiv`: the isomorphism ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ noncomputable theory variables {p : ℕ} [hp : fact p.prime] local notation `𝕎` := witt_vector p include hp namespace truncated_witt_vector variables (p) (n : ℕ) (R : Type*) [comm_ring R] lemma eq_of_le_of_cast_pow_eq_zero [char_p R p] (i : ℕ) (hin : i ≤ n) (hpi : (p ^ i : truncated_witt_vector p n R) = 0) : i = n := begin contrapose! hpi, replace hin := lt_of_le_of_ne hin hpi, clear hpi, have : (↑p ^ i : truncated_witt_vector p n R) = witt_vector.truncate n (↑p ^ i), { rw [ring_hom.map_pow, ring_hom.map_nat_cast] }, rw [this, ext_iff, not_forall], clear this, use ⟨i, hin⟩, rw [witt_vector.coeff_truncate, coeff_zero, fin.coe_mk, witt_vector.coeff_p_pow], haveI : nontrivial R := char_p.nontrivial_of_char_ne_one hp.ne_one, exact one_ne_zero end section iso variables (p n) {R} lemma card_zmod : fintype.card (truncated_witt_vector p n (zmod p)) = p ^ n := by rw [card, zmod.card] lemma char_p_zmod : char_p (truncated_witt_vector p n (zmod p)) (p ^ n) := char_p_of_prime_pow_injective _ _ _ (card_zmod _ _) (eq_of_le_of_cast_pow_eq_zero p n (zmod p)) local attribute [instance] char_p_zmod /-- The unique isomorphism between `zmod p^n` and `truncated_witt_vector p n (zmod p)`. This isomorphism exists, because `truncated_witt_vector p n (zmod p)` is a finite ring with characteristic and cardinality `p^n`. -/ def zmod_equiv_trunc : zmod (p^n) ≃+* truncated_witt_vector p n (zmod p) := zmod.ring_equiv (truncated_witt_vector p n (zmod p)) (card_zmod _ _) lemma zmod_equiv_trunc_apply {x : zmod (p^n)} : zmod_equiv_trunc p n x = zmod.cast_hom (by refl) (truncated_witt_vector p n (zmod p)) x := rfl /-- The following diagram commutes: ```text zmod (p^n) ----------------------------> zmod (p^m) | | | | v v truncated_witt_vector p n (zmod p) ----> truncated_witt_vector p m (zmod p) ``` Here the vertical arrows are `truncated_witt_vector.zmod_equiv_trunc`, the horizontal arrow at the top is `zmod.cast_hom`, and the horizontal arrow at the bottom is `truncated_witt_vector.truncate`. -/ lemma commutes {m : ℕ} (hm : n ≤ m) : (truncate hm).comp (zmod_equiv_trunc p m).to_ring_hom = (zmod_equiv_trunc p n).to_ring_hom.comp (zmod.cast_hom (pow_dvd_pow p hm) _) := ring_hom.ext_zmod _ _ lemma commutes' {m : ℕ} (hm : n ≤ m) (x : zmod (p^m)) : truncate hm (zmod_equiv_trunc p m x) = zmod_equiv_trunc p n (zmod.cast_hom (pow_dvd_pow p hm) _ x) := show (truncate hm).comp (zmod_equiv_trunc p m).to_ring_hom x = _, by rw commutes _ _ hm; refl lemma commutes_symm' {m : ℕ} (hm : n ≤ m) (x : truncated_witt_vector p m (zmod p)) : (zmod_equiv_trunc p n).symm (truncate hm x) = zmod.cast_hom (pow_dvd_pow p hm) _ ((zmod_equiv_trunc p m).symm x) := begin apply (zmod_equiv_trunc p n).injective, rw ← commutes', simp end /-- The following diagram commutes: ```text truncated_witt_vector p n (zmod p) ----> truncated_witt_vector p m (zmod p) | | | | v v zmod (p^n) ----------------------------> zmod (p^m) ``` Here the vertical arrows are `(truncated_witt_vector.zmod_equiv_trunc p _).symm`, the horizontal arrow at the top is `zmod.cast_hom`, and the horizontal arrow at the bottom is `truncated_witt_vector.truncate`. -/ lemma commutes_symm {m : ℕ} (hm : n ≤ m) : (zmod_equiv_trunc p n).symm.to_ring_hom.comp (truncate hm) = (zmod.cast_hom (pow_dvd_pow p hm) _).comp (zmod_equiv_trunc p m).symm.to_ring_hom := by ext; apply commutes_symm' end iso end truncated_witt_vector namespace witt_vector open truncated_witt_vector variables (p) /-- `to_zmod_pow` is a family of compatible ring homs. We get this family by composing `truncated_witt_vector.zmod_equiv_trunc` (in right-to-left direction) with `witt_vector.truncate`. -/ def to_zmod_pow (k : ℕ) : 𝕎 (zmod p) →+* zmod (p ^ k) := (zmod_equiv_trunc p k).symm.to_ring_hom.comp (truncate k) lemma to_zmod_pow_compat (m n : ℕ) (h : m ≤ n) : (zmod.cast_hom (pow_dvd_pow p h) (zmod (p ^ m))).comp (to_zmod_pow p n) = to_zmod_pow p m := calc (zmod.cast_hom _ (zmod (p ^ m))).comp ((zmod_equiv_trunc p n).symm.to_ring_hom.comp (truncate n)) = ((zmod_equiv_trunc p m).symm.to_ring_hom.comp (truncated_witt_vector.truncate h)).comp (truncate n) : by rw [commutes_symm, ring_hom.comp_assoc] ... = (zmod_equiv_trunc p m).symm.to_ring_hom.comp (truncate m) : by rw [ring_hom.comp_assoc, truncate_comp_witt_vector_truncate] /-- `to_padic_int` lifts `to_zmod_pow : 𝕎 (zmod p) →+* zmod (p ^ k)` to a ring hom to `ℤ_[p]` using `padic_int.lift`, the universal property of `ℤ_[p]`. -/ def to_padic_int : 𝕎 (zmod p) →+* ℤ_[p] := padic_int.lift $ to_zmod_pow_compat p lemma zmod_equiv_trunc_compat (k₁ k₂ : ℕ) (hk : k₁ ≤ k₂) : (truncated_witt_vector.truncate hk).comp ((zmod_equiv_trunc p k₂).to_ring_hom.comp (padic_int.to_zmod_pow k₂)) = (zmod_equiv_trunc p k₁).to_ring_hom.comp (padic_int.to_zmod_pow k₁) := by rw [← ring_hom.comp_assoc, commutes, ring_hom.comp_assoc, padic_int.zmod_cast_comp_to_zmod_pow] /-- `from_padic_int` uses `witt_vector.lift` to lift `truncated_witt_vector.zmod_equiv_trunc` composed with `padic_int.to_zmod_pow` to a ring hom `ℤ_[p] →+* 𝕎 (zmod p)`. -/ def from_padic_int : ℤ_[p] →+* 𝕎 (zmod p) := witt_vector.lift (λ k, (zmod_equiv_trunc p k).to_ring_hom.comp (padic_int.to_zmod_pow k)) $ zmod_equiv_trunc_compat _ lemma to_padic_int_comp_from_padic_int : (to_padic_int p).comp (from_padic_int p) = ring_hom.id ℤ_[p] := begin rw ← padic_int.to_zmod_pow_eq_iff_ext, intro n, rw [← ring_hom.comp_assoc, to_padic_int, padic_int.lift_spec], simp only [from_padic_int, to_zmod_pow, ring_hom.comp_id], rw [ring_hom.comp_assoc, truncate_comp_lift, ← ring_hom.comp_assoc], simp only [ring_equiv.symm_to_ring_hom_comp_to_ring_hom, ring_hom.id_comp] end lemma to_padic_int_comp_from_padic_int_ext (x) : (to_padic_int p).comp (from_padic_int p) x = ring_hom.id ℤ_[p] x := by rw to_padic_int_comp_from_padic_int lemma from_padic_int_comp_to_padic_int : (from_padic_int p).comp (to_padic_int p) = ring_hom.id (𝕎 (zmod p)) := begin apply witt_vector.hom_ext, intro n, rw [from_padic_int, ← ring_hom.comp_assoc, truncate_comp_lift, ring_hom.comp_assoc], simp only [to_padic_int, to_zmod_pow, ring_hom.comp_id, padic_int.lift_spec, ring_hom.id_comp, ← ring_hom.comp_assoc, ring_equiv.to_ring_hom_comp_symm_to_ring_hom] end lemma from_padic_int_comp_to_padic_int_ext (x) : (from_padic_int p).comp (to_padic_int p) x = ring_hom.id (𝕎 (zmod p)) x := by rw from_padic_int_comp_to_padic_int /-- The ring of Witt vectors over `zmod p` is isomorphic to the ring of `p`-adic integers. This equivalence is witnessed by `witt_vector.to_padic_int` with inverse `witt_vector.from_padic_int`. -/ def equiv : 𝕎 (zmod p) ≃+* ℤ_[p] := { to_fun := to_padic_int p, inv_fun := from_padic_int p, left_inv := from_padic_int_comp_to_padic_int_ext _, right_inv := to_padic_int_comp_from_padic_int_ext _, map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _ } end witt_vector
0cb41b6d39a62d00d49a0fcce843ff88ab92db69
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/test/monotonicity/test_cases.lean
f6fdcab8bf99326fc7d8bdcf0be6d186d702d4ba
[ "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
3,125
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.monotonicity.interactive open list tactic tactic.interactive meta class elaborable (α : Type) (β : out_param Type) := (elaborate : α → tactic β) export elaborable (elaborate) meta instance : elaborable pexpr expr := ⟨ to_expr ⟩ meta instance elaborable_list {α α'} [elaborable α α'] : elaborable (list α) (list α') := ⟨ mmap elaborate ⟩ meta def mono_function.elaborate : mono_function ff → tactic mono_function | (mono_function.non_assoc x y z) := mono_function.non_assoc <$> elaborate x <*> elaborate y <*> elaborate z | (mono_function.assoc x y z) := mono_function.assoc <$> elaborate x <*> traverse elaborate y <*> traverse elaborate z | (mono_function.assoc_comm x y) := mono_function.assoc_comm <$> elaborate x <*> elaborate y meta instance elaborable_mono_function : elaborable (mono_function ff) mono_function := ⟨ mono_function.elaborate ⟩ meta instance prod_elaborable {α α' β β' : Type} [elaborable α α'] [elaborable β β'] : elaborable (α × β) (α' × β') := ⟨ λ i, prod.rec_on i (λ x y, prod.mk <$> elaborate x <*> elaborate y) ⟩ meta def parse_mono_function' (l r : pexpr) := do l' ← to_expr l, r' ← to_expr r, parse_ac_mono_function { mono_cfg . } l' r' run_cmd do xs ← mmap to_expr [``(1),``(2),``(3)], ys ← mmap to_expr [``(1),``(2),``(4)], x ← match_prefix { unify := ff } xs ys, p ← elaborate ([``(1),``(2)] , [``(3)], [``(4)]), guard $ x = p run_cmd do xs ← mmap to_expr [``(1),``(2),``(3),``(6),``(7)], ys ← mmap to_expr [``(1),``(2),``(4),``(5),``(6),``(7)], x ← match_assoc { unify := ff } xs ys, p ← elaborate ([``(1), ``(2)], [``(3)], ([``(4), ``(5)], [``(6), ``(7)])), guard (x = p) run_cmd do x ← to_expr ``(7 + 3 : ℕ) >>= check_ac, x ← pp x.2.2.1, let y := "(some (is_left_id.left_id, (is_right_id.right_id, 0)))", guard (x.to_string = y) <|> fail ("guard: " ++ x.to_string) meta def test_pp {α} [has_to_tactic_format α] (tag : format) (expected : string) (prog : tactic α) : tactic unit := do r ← prog, pp_r ← pp r, guard (pp_r.to_string = expected) <|> fail format!"test_pp: {tag}" run_cmd do test_pp "test1" "(3 + 6, (4 + 5, ([], has_add.add _ 2 + 1)))" (parse_mono_function' ``(1 + 3 + 2 + 6) ``(4 + 2 + 1 + 5)), test_pp "test2" "([1] ++ [3] ++ [2] ++ [6], ([4] ++ [2] ++ [1] ++ [5], ([], append none _ none)))" (parse_mono_function' ``([1] ++ [3] ++ [2] ++ [6]) ``([4] ++ [2] ++ ([1] ++ [5]))), test_pp "test3" "([3] ++ [2], ([5] ++ [4], ([], append (some [1]) _ (some [2]))))" (parse_mono_function' ``([1] ++ [3] ++ [2] ++ [2]) ``([1] ++ [5] ++ ([4] ++ [2]))) @[mono] lemma test {α : Type*} [preorder α] : monotone (id : α → α) := λ x y h, h example : id 0 ≤ id 1 := begin mono, simp, end
72a2db62d75f9adb58ba62007b9d5fad5444dc65
f3849be5d845a1cb97680f0bbbe03b85518312f0
/old_library/init/quot.lean
4a53b494f35cf17403233e9c19f3c7ad4c122f55
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,780
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Quotient types. -/ prelude import init.sigma init.setoid init.logic open setoid universe variables u v constant quot : Π {A : Type u}, setoid A → Type u -- Remark: if we do not use propext here, then we would need a quot.lift for propositions. constant propext {a b : Prop} : (a ↔ b) → a = b -- iff can now be used to do substitutions in a calculation attribute [subst] theorem iff_subst {a b : Prop} {P : Prop → Prop} (H₁ : a ↔ b) (H₂ : P a) : P b := eq.subst (propext H₁) H₂ namespace quot protected constant mk : Π {A : Type u} [s : setoid A], A → quot s notation `⟦`:max a `⟧`:0 := quot.mk a constant sound : Π {A : Type u} [s : setoid A] {a b : A}, a ≈ b → ⟦a⟧ = ⟦b⟧ constant lift : Π {A : Type u} {B : Type v} [s : setoid A] (f : A → B), (∀ a b, a ≈ b → f a = f b) → quot s → B constant ind : ∀ {A : Type u} [s : setoid A] {B : quot s → Prop}, (∀ a, B ⟦a⟧) → ∀ q, B q attribute [elab_as_eliminator] lift ind init_quotient protected theorem lift_beta {A : Type u} {B : Type v} [setoid A] (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) (a : A) : lift f c ⟦a⟧ = f a := rfl protected theorem ind_beta {A : Type u} [s : setoid A] {B : quot s → Prop} (p : ∀ a, B ⟦a⟧) (a : A) : (ind p ⟦a⟧ : B ⟦a⟧) = p a := rfl attribute [reducible, elab_as_eliminator] protected definition lift_on {A : Type u} {B : Type v} [s : setoid A] (q : quot s) (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) : B := lift f c q attribute [elab_as_eliminator] protected theorem induction_on {A : Type u} [s : setoid A] {B : quot s → Prop} (q : quot s) (H : ∀ a, B ⟦a⟧) : B q := ind H q theorem exists_rep {A : Type u} [s : setoid A] (q : quot s) : ∃ a : A, ⟦a⟧ = q := quot.induction_on q (λ a, ⟨a, rfl⟩) section variable {A : Type u} variable [s : setoid A] variable {B : quot s → Type v} include s attribute [reducible] protected definition indep (f : Π a, B ⟦a⟧) (a : A) : Σ q, B q := ⟨⟦a⟧, f a⟩ protected lemma indep_coherent (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), (eq.rec (f a) (sound p) : B ⟦b⟧) = f b) : ∀ a b, a ≈ b → quot.indep f a = quot.indep f b := λ a b e, sigma.eq (sound e) (H a b e) protected lemma lift_indep_pr1 (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), (eq.rec (f a) (sound p) : B ⟦b⟧) = f b) (q : quot s) : (lift (quot.indep f) (quot.indep_coherent f H) q).1 = q := quot.ind (λ (a : A), eq.refl (quot.indep f a).1) q attribute [reducible, elab_as_eliminator] protected definition rec (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), (eq.rec (f a) (sound p) : B ⟦b⟧) = f b) (q : quot s) : B q := eq.rec_on (quot.lift_indep_pr1 f H q) ((lift (quot.indep f) (quot.indep_coherent f H) q).2) attribute [reducible, elab_as_eliminator] protected definition rec_on (q : quot s) (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), (eq.rec (f a) (sound p) : B ⟦b⟧) = f b) : B q := quot.rec f H q attribute [reducible, elab_as_eliminator] protected definition rec_on_subsingleton [H : ∀ a, subsingleton (B ⟦a⟧)] (q : quot s) (f : Π a, B ⟦a⟧) : B q := quot.rec f (λ a b h, subsingleton.elim _ (f b)) q attribute [reducible, elab_as_eliminator] protected definition hrec_on (q : quot s) (f : Π a, B ⟦a⟧) (c : ∀ (a b : A) (p : a ≈ b), f a == f b) : B q := quot.rec_on q f (λ a b p, eq_of_heq (calc (eq.rec (f a) (sound p) : B ⟦b⟧) == f a : eq_rec_heq (sound p) (f a) ... == f b : c a b p)) end section universe variables u_a u_b u_c variables {A : Type u_a} {B : Type u_b} {C : Type u_c} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ attribute [reducible, elab_as_eliminator] protected definition lift₂ (f : A → B → C)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : quot s₁) (q₂ : quot s₂) : C := quot.lift (λ (a₁ : A), quot.lift (f a₁) (λ (a b : B), c a₁ a a₁ b (setoid.refl a₁)) q₂) (λ (a b : A) (H : a ≈ b), @quot.ind B s₂ (λ (a_1 : quot s₂), (quot.lift (f a) (λ (a_1 b : B), c a a_1 a b (setoid.refl a)) a_1) = (quot.lift (f b) (λ (a b_1 : B), c b a b b_1 (setoid.refl b)) a_1)) (λ (a' : B), c a a' b a' H (setoid.refl a')) q₂) q₁ attribute [reducible, elab_as_eliminator] protected definition lift_on₂ (q₁ : quot s₁) (q₂ : quot s₂) (f : A → B → C) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : C := quot.lift₂ f c q₁ q₂ attribute [elab_as_eliminator] protected theorem ind₂ {C : quot s₁ → quot s₂ → Prop} (H : ∀ a b, C ⟦a⟧ ⟦b⟧) (q₁ : quot s₁) (q₂ : quot s₂) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected theorem induction_on₂ {C : quot s₁ → quot s₂ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (H : ∀ a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ attribute [elab_as_eliminator] protected theorem induction_on₃ [s₃ : setoid C] {D : quot s₁ → quot s₂ → quot s₃ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (q₃ : quot s₃) (H : ∀ a b c, D ⟦a⟧ ⟦b⟧ ⟦c⟧) : D q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, H a₁ a₂ a₃) q₃) q₂) q₁ end section exact variable {A : Type u} variable [s : setoid A] include s private definition rel (q₁ q₂ : quot s) : Prop := quot.lift_on₂ q₁ q₂ (λ a₁ a₂, a₁ ≈ a₂) (λ a₁ a₂ b₁ b₂ a₁b₁ a₂b₂, propext (iff.intro (λ a₁a₂, setoid.trans (setoid.symm a₁b₁) (setoid.trans a₁a₂ a₂b₂)) (λ b₁b₂, setoid.trans a₁b₁ (setoid.trans b₁b₂ (setoid.symm a₂b₂))))) local infix `~` := rel private lemma rel.refl : ∀ q : quot s, q ~ q := λ q, quot.induction_on q (λ a, setoid.refl a) private lemma eq_imp_rel {q₁ q₂ : quot s} : q₁ = q₂ → q₁ ~ q₂ := assume h, eq.rec_on h (rel.refl q₁) theorem exact {a b : A} : ⟦a⟧ = ⟦b⟧ → a ≈ b := assume h, eq_imp_rel h end exact section universe variables u_a u_b u_c variables {A : Type u_a} {B : Type u_b} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ attribute [reducible, elab_as_eliminator] protected definition rec_on_subsingleton₂ {C : quot s₁ → quot s₂ → Type u_c} [H : ∀ a b, subsingleton (C ⟦a⟧ ⟦b⟧)] (q₁ : quot s₁) (q₂ : quot s₂) (f : Π a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂:= @quot.rec_on_subsingleton _ s₁ (λ q, C q q₂) (λ a, quot.ind (λ b, H a b) q₂) q₁ (λ a, quot.rec_on_subsingleton q₂ (λ b, f a b)) end end quot attribute quot.mk open decidable attribute [instance] definition quot.has_decidable_eq {A : Type u} {s : setoid A} [decR : ∀ a b : A, decidable (a ≈ b)] : decidable_eq (quot s) := λ q₁ q₂ : quot s, quot.rec_on_subsingleton₂ q₁ q₂ (λ a₁ a₂, match (decR a₁ a₂) with | (is_true h₁) := is_true (quot.sound h₁) | (is_false h₂) := is_false (λ h, absurd (quot.exact h) h₂) end)
979ead45cd29f361e1952a41bf6048c6e5dbc440
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/set_theory/cardinal.lean
0bb237bce0fc0c8f8a21143fef38398377859152
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
46,542
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Mario Carneiro -/ import data.set.countable import set_theory.schroeder_bernstein import data.fintype.card /-! # Cardinal Numbers We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity. We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic: addition, multiplication, power, cardinal successor, minimum, supremum, infinitary sums and products The fact that the cardinality of `α × α` coincides with that of `α` when `α` is infinite is not proved in this file, as it relies on facts on well-orders. Instead, it is in `cardinal_ordinal.lean` (together with many other facts on cardinals, for instance the cardinality of `list α`). ## Implementation notes * There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)` is the quotient of types in `Type u`. There is a lift operation lifting cardinal numbers to a higher level. * Cardinal arithmetic specifically for infinite cardinals (like `κ * κ = κ`) is in the file `set_theory/ordinal.lean`, because concepts from that file are used in the proof. ## References * <https://en.wikipedia.org/wiki/Cardinal_number> ## Tags cardinal number, cardinal arithmetic, cardinal exponentiation, omega -/ open function set open_locale classical universes u v w x variables {α β : Type u} /-- The equivalence relation on types given by equivalence (bijective correspondence) of types. Quotienting by this equivalence relation gives the cardinal numbers. -/ instance cardinal.is_equivalent : setoid (Type u) := { r := λα β, nonempty (α ≃ β), iseqv := ⟨λα, ⟨equiv.refl α⟩, λα β ⟨e⟩, ⟨e.symm⟩, λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `cardinal.{u}` is the type of cardinal numbers in `Type u`, defined as the quotient of `Type u` by existence of an equivalence (a bijection with explicit inverse). -/ def cardinal : Type (u + 1) := quotient cardinal.is_equivalent namespace cardinal /-- The cardinal number of a type -/ def mk : Type u → cardinal := quotient.mk localized "notation `#` := cardinal.mk" in cardinal protected lemma eq : mk α = mk β ↔ nonempty (α ≃ β) := quotient.eq @[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl @[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _ /-- We define the order on cardinal numbers by `mk α ≤ mk β` if and only if there exists an embedding (injective function) from α to β. -/ instance : has_le cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩ theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β := ⟨⟨f, hf⟩⟩ theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α := ⟨embedding.of_surjective f hf⟩ theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} : c ≤ mk α ↔ ∃ p : set α, mk p = c := ⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩, ⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩, λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩ theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) := by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl } noncomputable instance : linear_order cardinal.{u} := { le := (≤), le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩, le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩, le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂), le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total, decidable_le := classical.dec_rel _ } noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩ instance : inhabited cardinal.{u} := ⟨0⟩ theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α := not_iff_comm.1 ⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩, λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩ instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩ instance : nontrivial cardinal.{u} := ⟨⟨1, 0, ne_zero_iff_nonempty.2 ⟨punit.star⟩⟩⟩ theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α := ⟨λ ⟨f⟩, ⟨λ a b, f.injective (subsingleton.elim _ _)⟩, λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩ theorem one_lt_iff_nontrivial {α : Type u} : 1 < mk α ↔ nontrivial α := by { rw [← not_iff_not, not_nontrivial_iff_subsingleton, ← le_one_iff_subsingleton], simp } instance : has_add cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩ @[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl instance : has_mul cardinal.{u} := ⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩ @[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl private theorem add_comm (a b : cardinal.{u}) : a + b = b + a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩ private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a := quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩ private theorem zero_add (a : cardinal.{u}) : 0 + a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩ private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩ private theorem one_mul (a : cardinal.{u}) : 1 * a = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩ private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩ protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {a b : cardinal.{u}} : a * b = 0 → a = 0 ∨ b = 0 := begin refine quotient.induction_on b _, refine quotient.induction_on a _, intros a b h, contrapose h, simp_rw [not_or_distrib, ← ne.def] at h, have := @prod.nonempty a b (ne_zero_iff_nonempty.mp h.1) (ne_zero_iff_nonempty.mp h.2), exact ne_zero_iff_nonempty.mpr this end instance : comm_semiring cardinal.{u} := { zero := 0, one := 1, add := (+), mul := (*), zero_add := zero_add, add_zero := assume a, by rw [add_comm a 0, zero_add a], add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_assoc α β γ⟩, add_comm := add_comm, zero_mul := zero_mul, mul_zero := assume a, by rw [mul_comm a 0, zero_mul a], one_mul := one_mul, mul_one := assume a, by rw [mul_comm a 1, one_mul a], mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_assoc α β γ⟩, mul_comm := mul_comm, left_distrib := left_distrib, right_distrib := assume a b c, by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] } /-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/ protected def power (a b : cardinal.{u}) : cardinal.{u} := quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩, quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩ instance : has_pow cardinal cardinal := ⟨cardinal.power⟩ local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow @[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl @[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_arrow_equiv_punit α⟩ @[simp] theorem power_one {a : cardinal} : a ^ 1 = a := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_arrow_equiv α⟩ @[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 := quotient.induction_on a $ assume α, quotient.sound ⟨equiv.arrow_punit_equiv_punit α⟩ @[simp] theorem prop_eq_two : mk (ulift Prop) = 2 := quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 := quotient.induction_on a $ assume α heq, nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a, quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩ theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 := quotient.induction_on₂ a b $ λ α β h, let ⟨a⟩ := ne_zero_iff_nonempty.1 h in ne_zero_iff_nonempty.2 ⟨λ _, a⟩ theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩ theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c := quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩ theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) := by rw [_root_.mul_comm b c]; from (quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩) @[simp] lemma pow_cast_right (κ : cardinal.{u}) : ∀ n : ℕ, (κ ^ (↑n : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow κ n | 0 := by simp | (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right] section order_properties open sum protected theorem zero_le : ∀(a : cardinal), 0 ≤ a := by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩ protected theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.sum_map e₂⟩ protected theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c := cardinal.add_le_add (le_refl _) protected theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c := ⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩, have (α ⊕ ((range f)ᶜ : set β)) ≃ β, from (equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $ (equiv.set.sum_compl (range f)), ⟨⟦↥(range f)ᶜ⟧, quotient.sound ⟨this.symm⟩⟩, λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ cardinal.add_le_add_left _ (cardinal.zero_le _)⟩ instance : order_bot cardinal.{u} := { bot := 0, bot_le := cardinal.zero_le, ..cardinal.linear_order } instance : canonically_ordered_comm_semiring cardinal.{u} := { add_le_add_left := λ a b h c, cardinal.add_le_add_left _ h, lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (cardinal.add_le_add_left _), le_iff_exists_add := @cardinal.le_iff_exists_add, eq_zero_or_eq_zero_of_mul_eq_zero := @cardinal.eq_zero_or_eq_zero_of_mul_eq_zero, ..cardinal.order_bot, ..cardinal.comm_semiring, ..cardinal.linear_order } @[simp] theorem zero_lt_one : (0 : cardinal) < 1 := lt_of_le_of_ne (zero_le _) zero_ne_one lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 := by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le } theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in ⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩ theorem power_le_max_power_one {a b c : cardinal} (h : b ≤ c) : a ^ b ≤ max (a ^ c) 1 := begin by_cases ha : a = 0, simp [ha, zero_power_le], exact le_trans (power_le_power_left ha h) (le_max_left _ _) end theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c := quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩ end order_properties theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a := by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨ ⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩, λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $ λ s t h, by funext a; injection congr_fun (hf h) a⟩ instance : no_top_order cardinal.{u} := { no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order } /-- The minimum cardinal in a family of cardinals (the existence of which is provided by `injective_min`). -/ noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal := f $ classical.some $ @embedding.min_injective _ (λ i, (f i).out) I theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i := ⟨_, rfl⟩ theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i := by rw [← mk_out (min I f), ← mk_out (f i)]; exact let ⟨g⟩ := classical.some_spec (@embedding.min_injective _ (λ i, (f i).out) I) in ⟨g i⟩ theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ protected theorem wf : @well_founded cardinal.{u} (<) := ⟨λ a, classical.by_contradiction $ λ h, let ι := {c :cardinal // ¬ acc (<) c}, f : ι → cardinal := subtype.val, ⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in hc (acc.intro _ (λ j ⟨_, h'⟩, classical.by_contradiction $ λ hj, h' $ by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩ instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩ instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩ /-- The successor cardinal - the smallest cardinal greater than `c`. This is not the same as `c + 1` except in the case of finite `c`. -/ noncomputable def succ (c : cardinal) : cardinal := @min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val theorem lt_succ_self (c : cardinal) : c < succ c := by cases min_eq _ _ with s e; rw [succ, e]; exact s.2 theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), λ h, by exact min_le _ (subtype.mk b h)⟩ theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c := begin refine quot.induction_on c (λ α, _) (lt_succ_self c), refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _), cases h.left with f, have : ¬ surjective f := λ hn, ne_of_lt h (quotient.sound ⟨equiv.of_bijective f ⟨f.injective, hn⟩⟩), cases not_forall.1 this with b nex, refine ⟨⟨sum.rec (by exact f) _, _⟩⟩, { exact λ _, b }, { intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩, { rw f.injective h }, { exact nex.elim ⟨_, h⟩ }, { exact nex.elim ⟨_, h.symm⟩ }, { refl } } end lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 := by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le } /-- The indexed sum of cardinals is the cardinality of the indexed disjoint union, i.e. sigma type. -/ def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f := by rw ← quotient.out_eq (f i); exact ⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩ @[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) := quot.sound ⟨equiv.sigma_congr_right $ λ i, classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩ theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a := quotient.induction_on a $ λ α, by simp; exact quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩ theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g := ⟨(embedding.refl _).sigma_map $ λ i, classical.choice $ by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩ /-- The indexed supremum of cardinals is the smallest cardinal above everything in the family. -/ noncomputable def sup {ι} (f : ι → cardinal) : cardinal := @min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1) theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f := by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩ theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g := sup_le.2 $ λ i, le_trans (H i) (le_sup _ _) theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f := sup_le.2 $ le_sum _ theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f := by rw ← sum_const; exact sum_le_sum _ _ (le_sup _) theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 := by { rw [← nonpos_iff_eq_zero, sup_le], intro x, exfalso, exact h x } /-- The indexed product of cardinals is the cardinality of the Pi type (dependent product). -/ def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out) @[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) := quot.sound ⟨equiv.Pi_congr_right $ λ i, classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩ theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι := quotient.induction_on a $ by simp theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g := ⟨embedding.Pi_congr_right $ λ i, classical.choice $ by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩ theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 := begin suffices : nonempty (Π i, (f i).out) ↔ ∀ i, nonempty (f i).out, { simpa [← ne_zero_iff_nonempty, prod] }, exact classical.nonempty_pi end theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 := not_iff_not.1 $ by simpa using prod_ne_zero f /-- The universe lift operation on cardinals. You can specify the universes explicitly with `lift.{u v} : cardinal.{u} → cardinal.{max u v}` -/ def lift (c : cardinal.{u}) : cardinal.{max u v} := quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩, quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩ theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl theorem lift_umax : lift.{u (max u v)} = lift.{u v} := funext $ λ a, quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_id' (a : cardinal) : lift a = a := quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a := quot.induction_on a $ λ α, quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩ theorem lift_mk_le {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) := ⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩, λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩ theorem lift_mk_eq {α : Type u} {β : Type v} : lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩, λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩ @[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b := quotient.induction_on₂ a b $ λ α β, by rw ← lift_umax; exact lift_mk_le @[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b := by simp [le_antisymm_iff] @[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b := by simp [lt_iff_le_not_le, -not_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩ @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b := quotient.induction_on₂ a b $ λ α β, quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩ @[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a := by simp [bit0] @[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a → ∃ a', lift a' = b := quotient.induction_on₂ a b $ λ α β, by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2 ⟨embedding.equiv_of_surjective (embedding.cod_restrict _ f set.mem_range_self) $ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩ theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := le_antisymm (le_of_not_gt $ λ h, begin rcases lt_lift_iff.1 h with ⟨b, e, h⟩, rw [lt_succ, ← lift_le, e] at h, exact not_lt_of_le h (lt_succ_self _) end) (succ_le.2 $ lift_lt.2 $ lt_succ_self _) @[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} : lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{u v} a = lift.{v u} b := calc lift.{u (max v w)} a = lift.{v (max u w)} b ↔ lift.{(max u v) w} (lift.{u v} a) = lift.{(max u v) w} (lift.{v u} b) : by simp ... ↔ lift.{u v} a = lift.{v u} b : lift_inj theorem mk_prod {α : Type u} {β : Type v} : mk (α × β) = lift.{u v} (mk α) * lift.{v u} (mk β) := quotient.sound ⟨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symm⟩ theorem sum_const_eq_lift_mul (ι : Type u) (a : cardinal.{v}) : sum (λ _:ι, a) = lift.{u v} (mk ι) * lift.{v u} a := begin apply quotient.induction_on a, intro α, simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id], convert mk_prod using 1, exact quotient.sound ⟨equiv.sigma_equiv_prod ι α⟩, end /-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/ def omega : cardinal.{u} := lift (mk ℕ) lemma mk_nat : mk nat = omega := (lift_id _).symm theorem omega_ne_zero : omega ≠ 0 := ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩ theorem omega_pos : 0 < omega := pos_iff_ne_zero.2 omega_ne_zero @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /- properties about the cast from nat -/ @[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n | 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩ | (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact quotient.sound (fintype.card_eq.1 $ by simp) @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n; simp * lemma lift_eq_nat_iff {a : cardinal.{u}} {n : ℕ} : lift.{u v} a = n ↔ a = n := by rw [← lift_nat_cast.{u v} n, lift_inj] lemma nat_eq_lift_eq_iff {n : ℕ} {a : cardinal.{u}} : (n : cardinal) = lift.{u v} a ↔ (n : cardinal) = a := by rw [← lift_nat_cast.{u v} n, lift_inj] theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α := by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}]; exact fintype.card_eq.1 (by simp) theorem card_le_of_finset {α} (s : finset α) : (s.card : cardinal) ≤ cardinal.mk α := begin rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)), { exact ⟨function.embedding.subtype _⟩ }, rw [cardinal.fintype_card, fintype.card_coe] end @[simp, norm_cast] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n := by induction n; simp [pow_succ', -_root_.add_comm, power_add, *] @[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n := by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact ⟨λ ⟨⟨f, hf⟩⟩, begin have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf, simp at this, rw [← fintype.card_fin n, ← this], exact finset.card_le_of_subset (finset.subset_univ _) end, λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h, have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩ @[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n := by simp [lt_iff_le_not_le, -not_le] @[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n := by simp [le_antisymm_iff] @[simp, norm_cast, priority 900] theorem nat_succ (n : ℕ) : (n.succ : cardinal) = succ n := le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) @[simp] theorem succ_zero : succ 0 = 1 := by norm_cast theorem card_le_of {α : Type u} {n : ℕ} (H : ∀ s : finset α, s.card ≤ n) : # α ≤ n := begin refine lt_succ.1 (lt_of_not_ge $ λ hn, _), rw [← cardinal.nat_succ, ← cardinal.lift_mk_fin n.succ] at hn, cases hn with f, refine not_lt_of_le (H $ finset.univ.map f) _, rw [finset.card_map, ← fintype.card, fintype.card_ulift, fintype.card_fin], exact n.lt_succ_self end theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a := by rw [← succ_le, (by norm_cast : succ 1 = 2)] at hb; exact lt_of_lt_of_le (cantor _) (power_le_power_right hb) theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 := by rw [one_le_iff_pos, pos_iff_ne_zero] theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega := succ_le.1 $ by rw [← nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact ⟨⟨coe, λ a b, fin.ext⟩⟩ @[simp] theorem one_lt_omega : 1 < omega := by simpa using nat_lt_omega 1 theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n := ⟨λ h, begin rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩, rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩, suffices : finite S, { cases this, resetI, existsi fintype.card S, rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] }, by_contra nf, have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a := λ n IH, let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in not_forall.1 (λ h, nf ⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩), let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)), refine not_le_of_lt h' ⟨⟨F, _⟩⟩, suffices : ∀ (n : ℕ) (m < n), F m ≠ F n, { refine λ m n, not_imp_not.1 (λ ne, _), rcases lt_trichotomy m n with h|h|h, { exact this n m h }, { contradiction }, { exact (this m n h).symm } }, intros n m h, have := classical.some_spec (P n (λ y _, F y)), rw [← show F n = classical.some (P n (λ y _, F y)), from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this, exact λ e, this ⟨m, h, e⟩, end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩ theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ h, le_of_not_lt $ λ hn, begin rcases lt_omega.1 hn with ⟨n, rfl⟩, exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1))) end⟩ theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) := lt_omega.trans ⟨λ ⟨n, e⟩, begin rw [← lift_mk_fin n] at e, cases quotient.exact e with f, exact ⟨fintype.of_equiv _ f.symm⟩ end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩ theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S := lt_omega_iff_fintype instance can_lift_cardinal_nat : can_lift cardinal ℕ := ⟨ coe, λ x, x < omega, λ x hx, let ⟨n, hn⟩ := lt_omega.mp hx in ⟨n, hn.symm⟩⟩ theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end lemma add_lt_omega_iff {a b : cardinal} : a + b < omega ↔ a < omega ∧ b < omega := ⟨λ h, ⟨lt_of_le_of_lt (self_le_add_right _ _) h, lt_of_le_of_lt (self_le_add_left _ _) h⟩, λ⟨h1, h2⟩, add_lt_omega h1 h2⟩ theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega end lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega ↔ a = 0 ∨ b = 0 ∨ a < omega ∧ b < omega := begin split, { intro h, by_cases ha : a = 0, { left, exact ha }, right, by_cases hb : b = 0, { left, exact hb }, right, rw [← ne, ← one_le_iff_ne_zero] at ha hb, split, { rw [← mul_one a], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul (le_refl a) hb) h }, { rw [← _root_.one_mul b], refine lt_of_le_of_lt (canonically_ordered_semiring.mul_le_mul ha (le_refl b)) h }}, rintro (rfl|rfl|⟨ha,hb⟩); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero] end lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a ≠ 0) (hb : b ≠ 0) : a * b < omega ↔ a < omega ∧ b < omega := by simp [mul_lt_omega_iff, ha, hb] theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega end lemma eq_one_iff_subsingleton_and_nonempty {α : Type*} : mk α = 1 ↔ (subsingleton α ∧ nonempty α) := calc mk α = 1 ↔ mk α ≤ 1 ∧ ¬mk α < 1 : eq_iff_le_not_lt ... ↔ subsingleton α ∧ nonempty α : begin apply and_congr le_one_iff_subsingleton, push_neg, rw [one_le_iff_ne_zero, ne_zero_iff_nonempty] end theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α := by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype] lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega := begin rw [countable_iff_exists_injective], split, rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩, rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩ end lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega := ⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩, λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩ lemma mk_int : mk ℤ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma mk_pnat : mk ℕ+ = omega := denumerable_iff.mp ⟨by apply_instance⟩ lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y := begin split, { rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h }, { rintro ⟨x, y, h⟩, by_contra h', rw [not_le, ←nat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h', apply h, exactI subsingleton.elim _ _ } end lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y := begin rw [two_le_iff], split, { rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩), rw [←h'] at h, exact ⟨z, h⟩ }, { rintro ⟨y, h⟩, exact ⟨x, y, h⟩ } end /-- König's theorem -/ theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g := lt_of_not_ge $ λ ⟨F⟩, begin have : inhabited (Π (i : ι), (g i).out), { refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩, rw mk_out, exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI, let G := inv_fun F, have sG : surjective G := inv_fun_surjective F.2, choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b, { assume i, simp only [- not_exists, not_exists.symm, not_forall.symm], refine λ h, not_le_of_lt (H i) _, rw [← mk_out (f i), ← mk_out (g i)], exact ⟨embedding.of_surjective _ h⟩ }, exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _)) end @[simp] theorem mk_empty : mk empty = 0 := fintype_card empty @[simp] theorem mk_pempty : mk pempty = 0 := fintype_card pempty @[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 := quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩ theorem mk_unit : mk unit = 1 := (fintype_card unit).trans nat.cast_one @[simp] theorem mk_punit : mk punit = 1 := (fintype_card punit).trans nat.cast_one @[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 := quotient.sound ⟨equiv.set.singleton x⟩ @[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 := quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩ @[simp] theorem mk_bool : mk bool = 2 := quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩ @[simp] theorem mk_Prop : mk Prop = 2 := (quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool @[simp] theorem mk_set {α : Type u} : mk (set α) = 2 ^ mk α := begin rw [← prop_eq_two, cardinal.power_def (ulift Prop) α, cardinal.eq], exact ⟨equiv.arrow_congr (equiv.refl _) equiv.ulift.symm⟩, end @[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 := quotient.sound ⟨equiv.option_equiv_sum_punit α⟩ theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) := calc mk (list α) = mk (Σ n, vector α n) : quotient.sound ⟨(equiv.sigma_preimage_equiv list.length).symm⟩ ... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, ⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩ ... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n, equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩ ... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk] theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α := mk_le_of_surjective quot.exists_rep theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α := mk_quot_le theorem mk_subtype_le {α : Type u} (p : α → Prop) : mk (subtype p) ≤ mk α := ⟨embedding.subtype p⟩ theorem mk_subtype_le_of_subset {α : Type u} {p q : α → Prop} (h : ∀ ⦃x⦄, p x → q x) : mk (subtype p) ≤ mk (subtype q) := ⟨embedding.subtype_map (embedding.refl α) h⟩ @[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 := quotient.sound ⟨equiv.set.pempty α⟩ lemma mk_emptyc_iff {α : Type u} {s : set α} : mk s = 0 ↔ s = ∅ := begin split, { intro h, have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h], refine set.eq_empty_iff_forall_not_mem.mpr (λ _ hx, _), rcases cardinal.eq.mp h2 with ⟨f, _⟩, cases f ⟨_, hx⟩ }, { intro, convert mk_emptyc _ } end theorem mk_univ {α : Type u} : mk (@univ α) = mk α := quotient.sound ⟨equiv.set.univ α⟩ theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s := mk_le_of_surjective surjective_onto_image theorem mk_image_le_lift {α : Type u} {β : Type v} {f : α → β} {s : set α} : lift.{v u} (mk (f '' s)) ≤ lift.{u v} (mk s) := lift_mk_le.{v u 0}.mpr ⟨embedding.of_surjective _ surjective_onto_image⟩ theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α := mk_le_of_surjective surjective_onto_range lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α := quotient.sound ⟨(equiv.set.range f h).symm⟩ lemma mk_range_eq_of_injective {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v u} (mk (range f)) = lift.{u v} (mk α) := begin have := (@lift_mk_eq.{v u max u v} (range f) α).2 ⟨(equiv.set.range f hf).symm⟩, simp only [lift_umax.{u v}, lift_umax.{v u}] at this, exact this end lemma mk_range_eq_lift {α : Type u} {β : Type v} {f : α → β} (hf : injective f) : lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# α) := lift_mk_eq.mpr ⟨(equiv.set.range f hf).symm⟩ theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image f s hf).symm⟩ theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) := calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f) ... = sum (λ i, mk (f i)) : (sum_mk _).symm theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) : mk (⋃ i, f i) = sum (λ i, mk (f i)) := calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩ ... = sum (λi, mk (f i)) : (sum_mk _).symm lemma mk_Union_le {α ι : Type u} (f : ι → set α) : mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) := le_trans mk_Union_le_sum_mk (sum_le_sup _) lemma mk_sUnion_le {α : Type u} (A : set (set α)) : mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) := by { rw [sUnion_eq_Union], apply mk_Union_le } lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) : mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) := by { rw [bUnion_eq_Union], apply mk_Union_le } @[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) := by rw [fintype_card, nat_cast_inj, fintype.card_coe] lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega := by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ } theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union_sum_inter S T⟩ /-- The cardinality of a union is at most the sum of the cardinalities of the two sets. -/ lemma mk_union_le {α : Type u} (S T : set α) : mk (S ∪ T : set α) ≤ mk S + mk T := @mk_union_add_mk_inter α S T ▸ self_le_add_right (mk (S ∪ T : set α)) (mk (S ∩ T : set α)) theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T := quot.sound ⟨equiv.set.union H⟩ lemma mk_sum_compl {α} (s : set α) : #s + #(sᶜ : set α) = #α := quotient.sound ⟨equiv.set.sum_compl s⟩ lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t := ⟨set.embedding_of_subset s t h⟩ lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} := ⟨embedding_of_subset _ _ h⟩ lemma mk_set_le (s : set α) : mk s ≤ mk α := mk_subtype_le s lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩ lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) := lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) : mk (f '' s) = mk s := quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩ lemma mk_subtype_of_equiv {α β : Type u} (p : β → Prop) (e : α ≃ β) : mk {a : α // p (e a)} = mk {b : β // p b} := quotient.sound ⟨equiv.subtype_equiv_of_subtype e⟩ lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } := quotient.sound ⟨equiv.set.sep s t⟩ lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) := begin rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2), apply subtype.coind_injective, exact h.comp subtype.val_injective end lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β) (h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) := begin rw lift_mk_le.{v u 0}, refine ⟨⟨_, _⟩⟩, { rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ }, rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩, simp, intro hxx', rw hxx' end lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) := le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2) lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) : mk (f ⁻¹' s) ≤ mk s := by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_subset_range (f : α → β) (s : set β) (h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) := by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] } lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β) (h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s := by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] } lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl } lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) : mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) := by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl } theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} : c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c := begin rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype], apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective end /-- The function α^{<β}, defined to be sup_{γ < β} α^γ. We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a higher universe -/ noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} := sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s) infix ` ^< `:80 := powerlt theorem powerlt_aux {c c' : cardinal} (h : c < c') : ∃(s : {s : set c'.out // mk s < c'}), mk s = c := begin cases out_embedding.mp (le_of_lt h) with f, have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 }, exact ⟨⟨range f, by convert h⟩, this⟩ end lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ := by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s } lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ := begin rw [powerlt, sup_le], split, { intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s }, intros h s, exact h _ s.2 end lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c := by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h } lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ := begin apply le_antisymm, { rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] }, { apply le_powerlt, apply lt_succ_self } end lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) := by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] } lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 := begin apply le_antisymm, { rw [powerlt_le], intros c hc, apply zero_power_le }, convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero] end lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 := by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le } end cardinal
3d0ead6f54a14a42f889af9bcd0a7413ec93da82
32c054a763e4aa96bcb6e8bc87775e0f403a1804
/src/spec/initialstate.lean
fe245695a5d15c6bbfa387723f374b8ce823387f
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
Claudiusgonzo/AliveInLean
7fac3f82722c27acc5551260ea12a36519f6e24e
a21bfb90dee0c6c6e00a955b6de92c631198c5ba
refs/heads/master
1,635,381,727,801
1,555,783,536,000
1,555,783,536,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,634
lean
-- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the MIT license. import ..smtexpr import ..smtcompile import ..bitvector import .spec import .lemmas import .lemmas_basic import .irstate import .freevar import .equiv import .closed import smt2.syntax import system.io import init.meta.tactic import init.meta.interactive namespace spec open irsem open freevar -- get_free_*_name lemma get_free_name_diff: ∀ n, get_free_sbitvec_name n ≠ get_free_sbool_name n := begin intros, intros H, unfold get_free_sbitvec_name at H, unfold get_free_sbool_name at H, rw string.eq_list at H, rw string.append_to_list at H, rw string.append_to_list at H, have H' := list.append_eq2 H, cases H' end lemma closed_regfile_apply_add_b_bv: ∀ (rf:regfile irsem_smt) (η:freevar.env) vname vz bname vb (HC:closed_regfile (rf.apply_to_values irsem_smt (env.replace_valty η))), closed_regfile (rf.apply_to_values irsem_smt (env.replace_valty ((η.add_bv vname vz).add_b bname vb))) := begin intros, revert HC, apply regfile.induction rf, { unfold closed_regfile, intros, rw regfile.empty_apply_empty, apply closed_regfile_empty }, { intros rf IH, intros, unfold closed_regfile, intros, rw regfile.apply_update_comm at HC, rw regfile.apply_update_comm, unfold closed_regfile at IH, rw closed_regfile_update_split at HC, cases HC with HC HCval, have HC := IH HC, rw closed_regfile_update_split, split, { assumption }, { cases v, unfold freevar.env.replace_valty at HCval, rw closed_ival_split at HCval, cases HCval with HCval1 HCval2, unfold freevar.env.replace_valty, rw closed_ival_split, split, { have H := closed_b_add_bv vname vz HCval1, have H := closed_b_add_b bname vb H, assumption }, { have H := closed_bv_add_bv vname vz HCval2, have H := closed_bv_add_b bname vb H, assumption } } } end lemma regfile_update_ival_closed: ∀ rf rf' (η:freevar.env) regn sz vn pn bvn p (HCRF: closed_regfile (regfile.apply_to_values irsem_smt rf (env.replace_valty η))) (HRF': rf' = regfile.update irsem_smt rf regn (valty.ival sz (sbitvec.var sz vn) (sbool.var pn))), closed_regfile (regfile.apply_to_values irsem_smt rf' (env.replace_valty (env.add_b (env.add_bv η vn bvn) pn p))) := begin intros, have H1 : closed_regfile (regfile.apply_to_values irsem_smt rf (env.replace_valty (env.add_b (env.add_bv η vn bvn) pn p))), { apply closed_regfile_apply_add_b_bv, assumption }, have H2 : closed_valty ((env.add_b (env.add_bv η vn bvn) pn p) ⟦valty.ival sz (sbitvec.var sz vn) (sbool.var pn)⟧), { apply ival_closed }, rw HRF', rw regfile.apply_update_comm, rw closed_regfile_update_split, split, assumption, assumption end lemma updatereg_closed: ∀ (ss ss':irstate_smt) (η:freevar.env) regn sz vn pn bvn p (HC:closed_irstate (η⟦ss⟧)) (HNOTIN1: vn ∉ η) (HNOTIN2: pn ∉ η) (HNOTEQ: vn ≠ pn) (HS:ss' = irstate.updatereg irsem_smt ss regn (irsem.valty.ival sz (sbitvec.var sz vn) (sbool.var pn))), closed_irstate (((η.add_bv vn bvn).add_b pn p)⟦ss'⟧) := begin intros, cases ss with sub srf, cases ss' with sub' srf', unfold freevar.env.replace at *, rw ← irstate.setub_apply_to_values at *, unfold irstate.getub at *, simp at *, unfold irstate.setub at *, unfold irstate.apply_to_values at *, rw closed_irstate_split, rw closed_irstate_split at HC, cases HC with HCUB HCRF, unfold irstate.updatereg at HS, simp at *, injection HS, subst h_1, split, { have H0: closed_b ((env.add_bv η vn bvn)⟦sub'⟧), { apply closed_b_add_bv, apply HCUB }, apply closed_b_add_b, { assumption } }, { apply regfile_update_ival_closed, assumption, assumption } end -- encode -- Note that `irstate_equiv η⟦iss⟧ ise` does not imply -- closed_irstate η⟦iss⟧. It is because, for example, -- `b_equiv (sbool.and (sbool.var _) (sbool.ff)) ff` holds. -- Then why `encode iss ise` is needed? -> encode is -- the only way to relate ise and iss. lemma init_var_encode_intty: ∀ ise iss ise' iss' (sg sg':std_gen) η n t (HENC: encode iss ise η) (HCLOSED: closed_irstate (η⟦iss⟧)) (HNOTIN1: get_free_sbitvec_name n ∉ η) (HNOTIN2: get_free_sbool_name n ∉ η) (HIE:(ise', sg') = create_init_var_exec n t (ise, sg)) (HIS:iss' = create_init_var_smt n t iss), ∃ η', (encode iss' ise' η' ∧ closed_irstate (η'⟦iss'⟧) ∧ env.added2 η (get_free_sbitvec_name n) (get_free_sbool_name n) η') := begin intros, unfold create_init_var_smt at HIS, simp at HIS, unfold create_init_var_exec at HIE, simp at HIE, generalize Hrbv':(get_rand_bv (get_sz_from_ty t) sg) = rbv', cases rbv' with rbv' sg'', rw Hrbv' at *, unfold create_init_var_exec._match_2 at HIE, generalize Hrb':(get_rand_bool sg'') = rb', cases rb' with rb' sg''', rw Hrb' at *, unfold create_init_var_exec._match_1 at HIE, injection HIE with HIE HIE_sg, simp at HIE, existsi ((η.add_b (get_free_sbool_name n) rb') .add_bv (get_free_sbitvec_name n) rbv'.to_int), split, { unfold encode, rw HIS, rw replace_updatereg, rw HIE, rw env.not_in_add_bv_irstate_comm, rw env.not_in_add_b_irstate_comm, rw HCLOSED, rw HCLOSED, rw env.not_in_add_bv_valty_comm, rw env.not_in_add_b_valty_comm, unfold freevar.env.replace_valty, -- making value.. unfold get_free_sbitvec, rw env.not_in_replace_sbv, rw env.add_b_replace_sbv, rw env.empty_replace_sbv, rw env.add_bv_replace_match, -- making poison.. unfold get_free_sbool, rw env.not_in_replace_sb, rw env.add_b_replace_match, rw env.replace_sb_of_bool, apply irstate.updatereg_equiv, { intros, cases rb', { -- poison apply val_equiv.poison_intty, { constructor, constructor }, { refl }, { refl } }, { apply val_equiv.concrete_intty, { constructor, constructor }, { cases rbv', rw sbitvec_of_int_const, constructor }, { refl } } }, { rw sbitvec_of_int_const, unfold equals_size, simp }, { apply HENC }, any_goals { assumption }, any_goals { apply env.not_in_add_b, apply get_free_name_diff, assumption }, }, split, { unfold closed_irstate, intros, rw HIS, rw replace_updatereg, rw env.not_in_add_bv_irstate_comm, rw env.not_in_add_b_irstate_comm, rw HCLOSED, rw HCLOSED, rw env.not_in_add_bv_valty_comm, rw env.not_in_add_b_valty_comm, unfold freevar.env.replace_valty, -- making value.. unfold get_free_sbitvec, rw env.not_in_replace_sbv, rw env.add_b_replace_sbv, rw env.empty_replace_sbv, rw env.add_bv_replace_match, -- making poison.. unfold get_free_sbool, rw env.not_in_replace_sb, rw env.add_b_replace_match, rw env.replace_sb_of_bool, rw replace_updatereg, unfold freevar.env.replace_valty, rw env.replace_sbv_of_int, rw env.replace_sb_of_bool, rw HCLOSED, any_goals { assumption }, apply env.not_in_add_b, apply get_free_name_diff, assumption, apply env.not_in_add_b, apply get_free_name_diff, assumption }, { unfold env.added2, split, { intros n_1 H1 H2, cases H2, apply env.not_in_add_bv, assumption, apply env.not_in_add_b, assumption, rw env.not_in_split at H1, rw env.not_in_split, assumption }, { intros n_1 H, unfold env.add_b, unfold env.add_bv, unfold has_mem.mem, simp, cases H, { rw if_neg, rw if_neg, unfold has_mem.mem at H, cases H, left, assumption, right, assumption, intros H', rw H' at H, apply HNOTIN1, assumption, intros H', rw H' at H, apply HNOTIN2, assumption, }, { cases H, { right, rw if_pos, intros H0, cases H0, assumption }, { left, rw if_pos, intros H0, cases H0, assumption } } } } end def fv_smt_names (fvnames:list string) := fvnames.map get_free_sbitvec_name ++ fvnames.map get_free_sbool_name lemma init_state_encode_strong: ∀ (freevars:list (string × ty)) (sg sg':std_gen) ise iss (HUNQ: list.unique $ freevars.map prod.fst) (HIE:(ise, sg') = create_init_state_exec freevars sg) (HIS:iss = create_init_state_smt freevars), ∃ η, (encode iss ise η ∧ closed_irstate (η⟦iss⟧) ∧ env.has_only η (fv_smt_names $ freevars.map prod.fst)) := begin intros, revert ise iss sg sg', induction freevars, { intros, unfold create_init_state_exec at HIE, unfold create_init_state_smt at HIS, simp at HIE,simp at HIS, injection HIE with HIE _, rw [HIS, HIE], existsi (freevar.env.empty), unfold encode, rw empty_replace_st, constructor, constructor, constructor, any_goals { constructor }, { apply closed_irstate_empty }, { unfold fv_smt_names, simp, unfold env.has_only, intros, split, { intros H, cases H }, { intros H, have H := (env.not_in_empty name) H, cases H } } }, { intros, rename freevars_tl tl, cases freevars_hd with vname vty, have HEtmp: ∀ h t, create_init_state_exec (h::t) sg = create_init_var_exec h.1 h.2 (create_init_state_exec t sg), { intros, refl }, rw HEtmp at HIE, clear HEtmp, have HStmp: ∀ h t, create_init_state_smt (h::t) = create_init_var_smt h.1 h.2 (create_init_state_smt t), { intros, refl }, rw HStmp at HIS, clear HStmp, generalize HE0: create_init_state_exec tl sg = ise_sg0, generalize HS0: create_init_state_smt tl = iss0, rw HE0 at *, rw HS0 at *, cases ise_sg0 with ise0 sg0, simp at HIE HIS, have HEX: (∃ (η0 : env), encode iss0 ise0 η0 ∧ closed_irstate (η0⟦iss0⟧) ∧ env.has_only η0 (fv_smt_names $ tl.map prod.fst)), { apply freevars_ih, { simp at HUNQ, cases HUNQ, assumption }, apply (eq.symm HE0), refl }, cases HEX with η0 HEX, cases HEX with HEX1 HEX2, cases HEX2 with HEX2 HEX3, -- Now add a new variable to each irstate have HUPDATED: ∃ η', (encode iss ise η' ∧ closed_irstate (η'⟦iss⟧) ∧ env.added2 η0 (get_free_sbitvec_name vname) (get_free_sbool_name vname) η'), { apply init_var_encode_intty, apply HEX1, apply HEX2, { -- get_free_sbitvec_name vname ∉ η0 simp at HUNQ, cases HUNQ, apply env.has_only_not_in, { apply HEX3 }, { unfold fv_smt_names, unfold get_free_sbitvec_name, apply list.not_mem_append, apply slist_prefix_notin, assumption, apply slist_prefix_notin2 "v_" "b_" 'v' 'b', assumption, { intros H0, cases H0 }, refl, refl } }, { -- get_free_sbool_name vname ∉ η0 simp at HUNQ, cases HUNQ, apply env.has_only_not_in, { apply HEX3 }, { unfold fv_smt_names, unfold get_free_sbool_name, apply list.not_mem_append, apply slist_prefix_notin2 "b_" "v_" 'b' 'v', assumption, { intros H0, cases H0 }, refl, refl, apply slist_prefix_notin, assumption, } }, assumption, assumption }, cases HUPDATED with η HUPDATED, cases HUPDATED with HUPDATED Htmp, -- env.has_only_added2 (Honly) (Hadd2) cases Htmp with HUPDATED2 HUPDATED3, have Hη := env.has_only_added2 HEX3 HUPDATED3, existsi η, split, assumption, split, assumption, { unfold fv_smt_names, simp, unfold fv_smt_names at Hη, simp at Hη, rw ← list.cons_append, rw ← env.has_only_shuffle (get_free_sbool_name vname), simp, rw env.has_only_shuffle2, apply Hη } } end theorem init_state_encode_prf: init_state_encode := begin unfold init_state_encode, intros, have H := init_state_encode_strong freevars sg sg' ise iss HUNQ HIE HIS, cases H with η H, cases H, existsi η, assumption end -- Future work: theorem that `freevars.get` correctly returns all -- free variables. end spec
0de05cfb3ed2df75bd2b6d97c7f2840527f61dfc
022215fec0be87ac6243b0f4fa3cc2939361d7d0
/src/category_theory/instances/Top/presheaf.lean
63823087c32b00814b0442b3095f75c26c4dbe3f
[ "Apache-2.0" ]
permissive
PaulGustafson/mathlib
4aa7bc81ca971fdd7b6e50bf3a245fade2978391
c49ac06ff9fa1371e9b6050a121df618cfd3fb80
refs/heads/master
1,590,798,947,521
1,559,220,227,000
1,559,220,227,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,304
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison, Mario Carneiro, Reid Barton import category_theory.instances.Top.opens import category_theory.whiskering universes v u open category_theory open category_theory.instances open topological_space open opposite variables (C : Type u) [𝒞 : category.{v+1} C] include 𝒞 namespace category_theory.instances.Top def presheaf (X : Top.{v}) := (opens X)ᵒᵖ ⥤ C instance category_presheaf (X : Top.{v}) : category (X.presheaf C) := by dsimp [presheaf]; apply_instance namespace presheaf variables {C} def pushforward {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C := (opens.map f).op ⋙ ℱ infix ` _* `: 80 := pushforward def pushforward_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) : f _* ℱ ≅ g _* ℱ := iso_whisker_right (nat_iso.op (opens.map_iso f g h).symm) ℱ lemma pushforward_eq_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h₁ h₂ : f = g) (ℱ : X.presheaf C) : ℱ.pushforward_eq h₁ = ℱ.pushforward_eq h₂ := rfl namespace pushforward variables {X : Top.{v}} (ℱ : X.presheaf C) def id : (𝟙 X) _* ℱ ≅ ℱ := (iso_whisker_right (nat_iso.op (opens.map_id X).symm) ℱ) ≪≫ functor.left_unitor _ @[simp] lemma id_hom_app' (U) (p) : (id ℱ).hom.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } local attribute [tidy] tactic.op_induction' @[simp] lemma id_hom_app (U) : (id ℱ).hom.app U = ℱ.map (eq_to_hom (opens.op_map_id_obj U)) := by tidy @[simp] lemma id_inv_app' (U) (p) : (id ℱ).inv.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } def comp {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) := iso_whisker_right (nat_iso.op (opens.map_comp f g).symm) ℱ @[simp] lemma comp_hom_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).hom.app U = 𝟙 _ := begin dsimp [pushforward, comp], tidy, end @[simp] lemma comp_inv_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).inv.app U = 𝟙 _ := begin dsimp [pushforward, comp], tidy, end end pushforward end presheaf end category_theory.instances.Top
a213d5e393045e32fc37f35440d4274bf9b119f1
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Compiler/IR/Borrow.lean
fb41bd53fea02c004bae3851514cd21b64160d9e
[ "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
11,058
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.Compiler.ExportAttr import Lean.Compiler.IR.CompilerM import Lean.Compiler.IR.NormIds namespace Lean namespace IR namespace Borrow namespace OwnedSet abbrev Key := FunId × Index def beq : Key → Key → Bool | (f₁, x₁), (f₂, x₂) => f₁ == f₂ && x₁ == x₂ instance : BEq Key := ⟨beq⟩ def getHash : Key → UInt64 | (f, x) => mixHash (hash f) (hash x) instance : Hashable Key := ⟨getHash⟩ end OwnedSet open OwnedSet (Key) in abbrev OwnedSet := Std.HashMap Key Unit def OwnedSet.insert (s : OwnedSet) (k : OwnedSet.Key) : OwnedSet := Std.HashMap.insert s k () def OwnedSet.contains (s : OwnedSet) (k : OwnedSet.Key) : Bool := Std.HashMap.contains s k /- We perform borrow inference in a block of mutually recursive functions. Join points are viewed as local functions, and are identified using their local id + the name of the surrounding function. We keep a mapping from function and joint points to parameters (`Array Param`). Recall that `Param` contains the field `borrow`. -/ namespace ParamMap inductive Key where | decl (name : FunId) | jp (name : FunId) (jpid : JoinPointId) deriving BEq def getHash : Key → UInt64 | Key.decl n => hash n | Key.jp n id => mixHash (hash n) (hash id) instance : Hashable Key := ⟨getHash⟩ end ParamMap open ParamMap (Key) abbrev ParamMap := Std.HashMap Key (Array Param) def ParamMap.fmt (map : ParamMap) : Format := let fmts := map.fold (fun fmt k ps => let k := match k with | ParamMap.Key.decl n => format n | ParamMap.Key.jp n id => format n ++ ":" ++ format id fmt ++ Format.line ++ k ++ " -> " ++ formatParams ps) Format.nil "{" ++ (Format.nest 1 fmts) ++ "}" instance : ToFormat ParamMap := ⟨ParamMap.fmt⟩ instance : ToString ParamMap := ⟨fun m => Format.pretty (format m)⟩ namespace InitParamMap /- Mark parameters that take a reference as borrow -/ def initBorrow (ps : Array Param) : Array Param := ps.map $ fun p => { p with borrow := p.ty.isObj } /- We do perform borrow inference for constants marked as `export`. Reason: we current write wrappers in C++ for using exported functions. These wrappers use smart pointers such as `object_ref`. When writing a new wrapper we need to know whether an argument is a borrow inference or not. We can revise this decision when we implement code for generating the wrappers automatically. -/ def initBorrowIfNotExported (exported : Bool) (ps : Array Param) : Array Param := if exported then ps else initBorrow ps partial def visitFnBody (fnid : FunId) : FnBody → StateM ParamMap Unit | FnBody.jdecl j xs v b => do modify fun m => m.insert (ParamMap.Key.jp fnid j) (initBorrow xs) visitFnBody fnid v visitFnBody fnid b | FnBody.case _ _ _ alts => alts.forM fun alt => visitFnBody fnid alt.body | e => do unless e.isTerminal do let (instr, b) := e.split visitFnBody fnid b def visitDecls (env : Environment) (decls : Array Decl) : StateM ParamMap Unit := decls.forM fun decl => match decl with | Decl.fdecl (f := f) (xs := xs) (body := b) .. => do let exported := isExport env f modify fun m => m.insert (ParamMap.Key.decl f) (initBorrowIfNotExported exported xs) visitFnBody f b | _ => pure () end InitParamMap def mkInitParamMap (env : Environment) (decls : Array Decl) : ParamMap := (InitParamMap.visitDecls env decls *> get).run' {} /- Apply the inferred borrow annotations stored at `ParamMap` to a block of mutually recursive functions. -/ namespace ApplyParamMap partial def visitFnBody (fn : FunId) (paramMap : ParamMap) : FnBody → FnBody | FnBody.jdecl j xs v b => let v := visitFnBody fn paramMap v let b := visitFnBody fn paramMap b match paramMap.find? (ParamMap.Key.jp fn j) with | some ys => FnBody.jdecl j ys v b | none => unreachable! | FnBody.case tid x xType alts => FnBody.case tid x xType $ alts.map $ fun alt => alt.modifyBody (visitFnBody fn paramMap) | e => if e.isTerminal then e else let (instr, b) := e.split let b := visitFnBody fn paramMap b instr.setBody b def visitDecls (decls : Array Decl) (paramMap : ParamMap) : Array Decl := decls.map fun decl => match decl with | Decl.fdecl f xs ty b info => let b := visitFnBody f paramMap b match paramMap.find? (ParamMap.Key.decl f) with | some xs => Decl.fdecl f xs ty b info | none => unreachable! | other => other end ApplyParamMap def applyParamMap (decls : Array Decl) (map : ParamMap) : Array Decl := -- dbgTrace ("applyParamMap " ++ toString map) $ fun _ => ApplyParamMap.visitDecls decls map structure BorrowInfCtx where env : Environment decls : Array Decl -- block of mutually recursive functions currFn : FunId := arbitrary -- Function being analyzed. paramSet : IndexSet := {} -- Set of all function parameters in scope. This is used to implement the heuristic at `ownArgsUsingParams` structure BorrowInfState where /- Set of variables that must be `owned`. -/ owned : OwnedSet := {} modified : Bool := false paramMap : ParamMap abbrev M := ReaderT BorrowInfCtx (StateM BorrowInfState) def getCurrFn : M FunId := do let ctx ← read pure ctx.currFn def markModified : M Unit := modify fun s => { s with modified := true } def ownVar (x : VarId) : M Unit := do -- dbgTrace ("ownVar " ++ toString x) $ fun _ => let currFn ← getCurrFn modify fun s => if s.owned.contains (currFn, x.idx) then s else { s with owned := s.owned.insert (currFn, x.idx), modified := true } def ownArg (x : Arg) : M Unit := match x with | Arg.var x => ownVar x | _ => pure () def ownArgs (xs : Array Arg) : M Unit := xs.forM ownArg def isOwned (x : VarId) : M Bool := do let currFn ← getCurrFn let s ← get pure $ s.owned.contains (currFn, x.idx) /- Updates `map[k]` using the current set of `owned` variables. -/ def updateParamMap (k : ParamMap.Key) : M Unit := do let currFn ← getCurrFn let s ← get match s.paramMap.find? k with | some ps => do let ps ← ps.mapM fun (p : Param) => do if !p.borrow then pure p else if (← isOwned p.x) then markModified pure { p with borrow := false } else pure p modify fun s => { s with paramMap := s.paramMap.insert k ps } | none => pure () def getParamInfo (k : ParamMap.Key) : M (Array Param) := do let s ← get match s.paramMap.find? k with | some ps => pure ps | none => match k with | ParamMap.Key.decl fn => do let ctx ← read match findEnvDecl ctx.env fn with | some decl => pure decl.params | none => unreachable! | _ => unreachable! /- For each ps[i], if ps[i] is owned, then mark xs[i] as owned. -/ def ownArgsUsingParams (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM fun i => do let x := xs[i] let p := ps[i] unless p.borrow do ownArg x /- For each xs[i], if xs[i] is owned, then mark ps[i] as owned. We use this action to preserve tail calls. That is, if we have a tail call `f xs`, if the i-th parameter is borrowed, but `xs[i]` is owned we would have to insert a `dec xs[i]` after `f xs` and consequently "break" the tail call. -/ def ownParamsUsingArgs (xs : Array Arg) (ps : Array Param) : M Unit := xs.size.forM fun i => do let x := xs[i] let p := ps[i] match x with | Arg.var x => if (← isOwned x) then ownVar p.x | _ => pure () /- Mark `xs[i]` as owned if it is one of the parameters `ps`. We use this action to mark function parameters that are being "packed" inside constructors. This is a heuristic, and is not related with the effectiveness of the reset/reuse optimization. It is useful for code such as ``` def f (x y : obj) := let z := ctor_1 x y; ret z ``` -/ def ownArgsIfParam (xs : Array Arg) : M Unit := do let ctx ← read xs.forM fun x => do match x with | Arg.var x => if ctx.paramSet.contains x.idx then ownVar x | _ => pure () def collectExpr (z : VarId) : Expr → M Unit | Expr.reset _ x => ownVar z *> ownVar x | Expr.reuse x _ _ ys => ownVar z *> ownVar x *> ownArgsIfParam ys | Expr.ctor _ xs => ownVar z *> ownArgsIfParam xs | Expr.proj _ x => do if (← isOwned x) then ownVar z if (← isOwned z) then ownVar x | Expr.fap g xs => do let ps ← getParamInfo (ParamMap.Key.decl g) ownVar z *> ownArgsUsingParams xs ps | Expr.ap x ys => ownVar z *> ownVar x *> ownArgs ys | Expr.pap _ xs => ownVar z *> ownArgs xs | other => pure () def preserveTailCall (x : VarId) (v : Expr) (b : FnBody) : M Unit := do let ctx ← read match v, b with | (Expr.fap g ys), (FnBody.ret (Arg.var z)) => if ctx.decls.any (·.name == g) && x == z then let ps ← getParamInfo (ParamMap.Key.decl g) ownParamsUsingArgs ys ps | _, _ => pure () def updateParamSet (ctx : BorrowInfCtx) (ps : Array Param) : BorrowInfCtx := { ctx with paramSet := ps.foldl (fun s p => s.insert p.x.idx) ctx.paramSet } partial def collectFnBody : FnBody → M Unit | FnBody.jdecl j ys v b => do withReader (fun ctx => updateParamSet ctx ys) (collectFnBody v) let ctx ← read updateParamMap (ParamMap.Key.jp ctx.currFn j) collectFnBody b | FnBody.vdecl x _ v b => collectFnBody b *> collectExpr x v *> preserveTailCall x v b | FnBody.jmp j ys => do let ctx ← read let ps ← getParamInfo (ParamMap.Key.jp ctx.currFn j) ownArgsUsingParams ys ps -- for making sure the join point can reuse ownParamsUsingArgs ys ps -- for making sure the tail call is preserved | FnBody.case _ _ _ alts => alts.forM fun alt => collectFnBody alt.body | e => do unless e.isTerminal do collectFnBody e.body partial def collectDecl : Decl → M Unit | Decl.fdecl (f := f) (xs := ys) (body := b) .. => withReader (fun ctx => let ctx := updateParamSet ctx ys; { ctx with currFn := f }) do collectFnBody b updateParamMap (ParamMap.Key.decl f) | _ => pure () /- Keep executing `x` until it reaches a fixpoint -/ @[inline] partial def whileModifing (x : M Unit) : M Unit := do modify fun s => { s with modified := false } x let s ← get if s.modified then whileModifing x else pure () def collectDecls : M ParamMap := do whileModifing ((← read).decls.forM collectDecl) let s ← get pure s.paramMap def infer (env : Environment) (decls : Array Decl) : ParamMap := collectDecls { env, decls } |>.run' { paramMap := mkInitParamMap env decls } end Borrow def inferBorrow (decls : Array Decl) : CompilerM (Array Decl) := do let env ← getEnv let paramMap := Borrow.infer env decls pure (Borrow.applyParamMap decls paramMap) end IR end Lean
40a7b8a65295abcfd360b37f535775e9fc10a67c
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/data/multiset.lean
31ed541f87aeeb2566e6240aabd211f79811776a
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
121,201
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.list.basic data.list.perm data.list.sort data.quot data.string 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*} local infix ` • ` := add_monoid.smul instance list.perm.setoid (α : Type*) : setoid (list α) := setoid.mk perm ⟨perm.refl, @perm.symm _, @perm.trans _⟩ /-- `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.perm.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 /- 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_of_forall_not_mem H; refl 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 @[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 _, ..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 @[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 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)⟩ 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 _ _ _ @[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 _ _ 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` -/ def prod [comm_monoid α] : multiset α → α := foldr (*) (λ x y z, by simp [mul_left_comm]) 1 attribute [to_additive multiset.sum._proof_1] prod._proof_1 attribute [to_additive multiset.sum] prod @[to_additive multiset.sum_eq_foldr] theorem prod_eq_foldr [comm_monoid α] (s : multiset α) : prod s = foldr (*) (λ x y z, by simp [mul_left_comm]) 1 s := rfl @[to_additive multiset.sum_eq_foldl] 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 multiset.coe_sum] theorem coe_prod [comm_monoid α] (l : list α) : prod ↑l = l.prod := prod_eq_foldl _ @[simp, to_additive multiset.sum_zero] theorem prod_zero [comm_monoid α] : @prod α _ 0 = 1 := rfl @[simp, to_additive multiset.sum_cons] theorem prod_cons [comm_monoid α] (a : α) (s) : prod (a :: s) = a * prod s := foldr_cons _ _ _ _ _ @[to_additive multiset.sum_singleton] theorem prod_singleton [comm_monoid α] (a : α) : prod (a :: 0) = a := by simp @[simp, to_additive multiset.sum_add] theorem prod_add [comm_monoid α] (s t : multiset α) : prod (s + t) = prod s * prod t := quotient.induction_on₂ s t $ λ l₁ l₂, by simp @[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 multiset.sum_repeat] 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 multiset.sum_map_zero] prod_map_one @[simp, to_additive multiset.sum_map_add] 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 multiset.sum_map_sum_map] 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]) /- 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 multiset.sum_bind] 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] 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]) 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 /- diagonal -/ theorem revzip_powerset_aux {l : list α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux l)) : s + t = ↑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 α} ⦃s t⦄ (h : (s, t) ∈ revzip (powerset_aux' l)) : s + t = ↑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 : ∀ ⦃s t⦄, (s, t) ∈ revzip l' → s + t = ↑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 def diagonal (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 diagonal_coe (l : list α) : @diagonal α l = revzip (powerset_aux l) := rfl @[simp] theorem diagonal_coe' (l : list α) : @diagonal α l = revzip (powerset_aux' l) := quot.sound revzip_powerset_aux_perm_aux' @[simp] theorem mem_diagonal {s₁ s₂ t : multiset α} : (s₁, s₂) ∈ diagonal t ↔ s₁ + s₂ = t := quotient.induction_on t $ λ l, begin simp [diagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩, haveI := classical.dec_eq α, simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm], exact ⟨_, le_add_right _ _, rfl, add_sub_cancel_left _ _⟩ end @[simp] theorem diagonal_map_fst (s : multiset α) : (diagonal s).map prod.fst = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_map_snd (s : multiset α) : (diagonal s).map prod.snd = powerset s := quotient.induction_on s $ λ l, by simp [powerset_aux'] @[simp] theorem diagonal_zero : @diagonal α 0 = (0, 0)::0 := rfl @[simp] theorem diagonal_cons (a : α) (s) : diagonal (a::s) = map (prod.map id (cons a)) (diagonal s) + map (prod.map (cons a) id) (diagonal 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_diagonal (s : multiset α) : card (diagonal s) = 2 ^ card s := by have := card_powerset s; rwa [← diagonal_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 ((diagonal 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 /- 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] 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 @[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 @[extensionality] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 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 [max_min_distrib_left], ..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 (assume a b, 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 [*] 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⟩ 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)⟩ @[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₂⟩ 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⟩ @[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] 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 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 end multiset
8693e1d94d0dc76610487f62ffd3f442900020dc
e61bd74d1f38315f3bf7c924da3ee8d67d73fdab
/src/semantics.lean
81e0aeabb80592fafb27c5f2bdcfd04b9debebb3
[]
no_license
maxd13/logic-soundness
4e0ef2ca8be1ed24ae0f1b4b9e50e63c6f231fb7
8821cc01ffcd3a73ed1e0eaaf2c97694fb4f422a
refs/heads/master
1,670,286,287,157
1,598,023,967,000
1,598,023,967,000
263,057,652
4
0
null
null
null
null
UTF-8
Lean
false
false
15,233
lean
import syntax universe u namespace logic -- namespace semantics (have to figure out how to use nested namespaces properly) open list tactic set -- a structure for the language define by σ, with domain in type α. structure signature.structure (σ : signature) (α : Type u) [nonempty α] := -- functional interpretation (I₁ : Π {n}, σ.nary n → (fin n → α) → α) -- relational interpretation (I₂ : Π {n}, σ.nrary n → (fin n → α) → Prop) -- type of variable assignments def signature.vasgn (σ : signature) (α : Type u) := σ.vars → α variables {σ : signature} {α : Type u} [nonempty α] -- the reference of a term in a structure relative to an assignment. def signature.structure.reference' (M : σ.structure α) : σ.term → σ.vasgn α → α | (signature.term.var x) asg := asg x | (@signature.term.app _ 0 f _) _ := M.I₁ f fin_zero_elim | (@signature.term.app _ (n+1) f v) asg := let v₂ := λ k, signature.structure.reference' (v k) asg in M.I₁ f v₂ -- The reference of a denotative term is independent from an assignment. -- Note: We adopt the convention that functions ending with ' -- depend on assignments, and others do not. def signature.structure.reference (M : σ.structure α) : σ.hterm → α := begin -- Although idk if it is a good idea to define functions using tactics. -- What happens if I unfold their definitions later? intro t, obtain ⟨t, den⟩ := t, induction t, simp [set_of] at den, revert den, dunfold signature.term.denotes signature.term.vars, intro den, replace den := eq_empty_iff_forall_not_mem.mp den, specialize den t, simp at den, contradiction, cases t_n, exact M.I₁ t_f fin_zero_elim, have den_v : ∀ x, (t_v x).denotes, intro x, simp [set_of] at den, revert den, dunfold signature.term.denotes signature.term.vars, simp, intro den, have c := set.subset_Union (signature.term.vars ∘ t_v) x, simp [den] at c, -- could have used the set lemma, -- but library search finished -- this one off. exact eq_bot_iff.mpr c, have ih := λ x, t_ih x (den_v x), exact M.I₁ t_f ih, end -- bind the value of a variable to `val` in an assignment -- (generates a new assignment). def signature.vasgn.bind (ass : σ.vasgn α) (x : σ.vars) (val : α) : σ.vasgn α := λy, if y = x then val else ass y -- tells whether a formula is true in a structure, relative to -- an assignment. def signature.structure.satisfies' : σ.structure α → σ.formula → σ.vasgn α → Prop | M ( signature.formula.relational r v) asg := M.I₂ r $ λm, M.reference' (v m) asg | M ( signature.formula.for_all x φ) ass := ∀ (a : α), M.satisfies' φ (ass.bind x a) | M ( signature.formula.if_then φ ψ) asg := let x := M.satisfies' φ asg, y := M.satisfies' ψ asg in x → y | M ( signature.formula.equation t₁ t₂) asg := let x := M.reference' t₁ asg, y := M.reference' t₂ asg in x = y | M signature.formula.false _ := false -- tells whether a formula is true in a structure, absolutely. def signature.structure.satisfies : σ.structure α → σ.formula → Prop | M φ := ∀ (ass : σ.vasgn α), M.satisfies' φ ass -- will reserve ⊨ without subscript for -- semantic consequence of theories. local infixr `⊨₁`:55 := signature.structure.satisfies -- so here is some easy corollary. lemma false_is_unsat : ¬∃ M : σ.structure α, M ⊨₁ signature.formula.false := begin intro h, obtain ⟨M, h⟩ := h, apply nonempty.elim _inst_1, intro x, exact h (λ_, x), end -- tells whether a model satisfies a set of formulas. -- Ended up being an useless definition so far. def signature.structure.for : σ.structure α → set σ.formula → Prop | M Γ := ∀ φ ∈ Γ, M ⊨₁ φ variables (Γ : set σ.formula) (φ : σ.formula) -- semantic consequence. -- Tells whether φ is true in every model/assignment in which Γ is true. -- Ended up being a complex definition because of the synthesizer/elaborator, -- maybe we can simplify it later? def signature.follows (σ : signature) (Γ : set σ.formula) (φ : σ.formula) : Prop := ∀{α : Type u}[h : nonempty α] (M : @signature.structure σ α h) (ass : σ.vasgn α), (∀ ψ ∈ Γ, @signature.structure.satisfies' σ α h M ψ ass) → @signature.structure.satisfies' σ α h M φ ass local infixr `⊨`:55 := signature.follows σ -- Here we move closer to the proof itself. -- In order to prove it we need to prove several -- auxiliary lemmas: lemma bind_symm : ∀ {ass : σ.vasgn α} {x y : σ.vars} {a b}, x ≠ y → (ass.bind x a).bind y b = (ass.bind y b).bind x a := begin intros ass x y a b h, simp [signature.vasgn.bind], ext z, replace h := ne.symm h, by_cases eq : z = y; simp[eq, h], end lemma bind₁ : ∀ {ass : σ.vasgn α} {x : σ.vars}, ass.bind x (ass x) = ass := begin intros ass x, simp [signature.vasgn.bind], ext y, by_cases y = x; simp[h], end lemma bind₂ : ∀ {ass : σ.vasgn α} {x : σ.vars} {a b}, (ass.bind x a).bind x b = ass.bind x b := begin intros ass x a b, simp [signature.vasgn.bind], ext y, by_cases y = x; simp[h], end lemma bind_term : ∀ {M : σ.structure α} {ass : σ.vasgn α} {x : σ.vars} {t : σ.term} {a}, x ∉ t.vars → M.reference' t (signature.vasgn.bind ass x a) = M.reference' t ass := begin intros M ass x t a, induction t; dunfold signature.term.vars; simp; intro h, dunfold signature.structure.reference' signature.vasgn.bind, simp [ne.symm h], cases t_n; dunfold signature.structure.reference'; simp, congr, ext y, specialize h y, exact t_ih y h, end -- Some things to note here: -- . It seems it would be impossible to prove this without generalizing the assignment in the induction. -- . It seems it would be impossible to prove just one side of the ↔ alone. -- . I've learned this the hard way. lemma bind₃ : ∀ {M : σ.structure α} {φ: σ.formula}{ass : σ.vasgn α}{x : σ.vars}{a}, x ∉ φ.free → (M.satisfies' φ (ass.bind x a) ↔ M.satisfies' φ ass) := begin intros M φ ass x a, induction φ generalizing ass; dunfold signature.formula.free signature.structure.satisfies'; simp; intros h₀, swap 3, replace h₀ := not_or_distrib.mp h₀, obtain ⟨h₀, h₁⟩ := h₀, constructor; intros h₂ h₃; have ih₁ := @φ_ih_a ass h₀; have ih₂ := @φ_ih_a_1 ass h₁, replace ih₁ := ih₁.2 h₃, apply ih₂.mp, exact h₂ ih₁, replace ih₁ := ih₁.mp h₃, apply ih₂.2, exact h₂ ih₁, focus { constructor, all_goals{ intro h₁, convert h₁, ext y, specialize h₀ y, revert h₀, induction φ_v y; dunfold signature.term.vars signature.structure.reference' signature.vasgn.bind; intro h₀, simp at h₀, replace h₀ := ne.symm h₀, simp [h₀], cases n; dunfold signature.structure.reference', refl, simp at *, congr, ext z, exact ih z (h₀ z), }, }, constructor; intro h₁; intro a₂; classical; all_goals{ by_cases (x ∈ φ_a_1.free), specialize h₁ a₂, revert h₁, rw (h₀ h), rw bind₂, intro h₁, exact h₁, by_cases eq : x = φ_a, specialize h₁ a₂, revert h₁, rw eq, rw bind₂, intro h₁, exact h₁, specialize h₁ a₂, }, rw bind_symm eq at h₁, exact (φ_ih h).mp h₁, rw bind_symm eq, exact (φ_ih h).2 h₁, push_neg at h₀, obtain ⟨h₀, h₁⟩ := h₀, rw [bind_term h₀, bind_term h₁], end -- Here is the most important lemma I suppose. -- It's an easy corollary of the last one. -- That one was hard. lemma fundamental : ∀ y x (M : σ.structure α) ass, abstract_in y Γ → (∀ φ ∈ Γ, M.satisfies' φ ass) → ( ∀φ ∈ Γ, M.satisfies' φ (ass.bind y x)) := begin intros y x M ass h₁ h₂ φ H, simp [abstract_in] at h₁, specialize h₁ φ H, specialize h₂ φ H, exact (bind₃ h₁).2 h₂, end lemma term_rw_semantics : ∀ {M : σ.structure α} {ass:σ.vasgn α} {x} {t₁ t₂ : σ.term}, M.reference' (t₁.rw x t₂) ass = M.reference' t₁ (ass.bind x (M.reference' t₂ ass)) := begin intros M ass x t₁ t₂, induction t₁, dunfold signature.term.rw signature.structure.reference', by_cases x = t₁; simp [signature.vasgn.bind, h], dunfold signature.structure.reference', simp [ne.symm h], cases t₁_n; dunfold signature.term.rw signature.structure.reference'; simp, congr, ext y, exact t₁_ih y, end lemma rw_semantics : ∀ {M : σ.structure α} {ass:σ.vasgn α} {x t} {φ: σ.formula}, φ.substitutable x t → (M.satisfies' (φ.rw x t) ass ↔ M.satisfies' φ (ass.bind x (M.reference' t ass))) := begin intros M ass x t φ, induction φ generalizing ass; dunfold signature.formula.substitutable signature.formula.rw signature.structure.satisfies'; try{simp}, focus { constructor; intro h, all_goals{ convert h, ext y, induction φ_v y; dunfold signature.term.rw signature.structure.reference' signature.vasgn.bind, by_cases eq : a = x; simp [eq], replace eq := ne.symm eq, simp [eq], dunfold signature.structure.reference', refl, simp, cases n; dunfold signature.structure.reference'; simp, congr, ext z, exact ih z,}, }, focus{ intro h, by_cases c : φ_a = x, simp [c, bind₂], simp [c], cases h, revert h, dunfold signature.formula.free, simp_intros h, classical, replace h : x ∉ φ_a_1.free, by_contradiction H, replace h := eq.symm (h H), contradiction, constructor; intros hyp a; specialize hyp a, rw formula_rw h t at hyp, rw bind_symm (ne.symm c), rwa bind₃ h, rw formula_rw h t, rw bind_symm (ne.symm c) at hyp, rwa bind₃ h at hyp, obtain ⟨h₁, h₂⟩ := h, constructor; intros hyp a; specialize hyp a; have ih := @φ_ih (signature.vasgn.bind ass φ_a a) h₂; rw bind_term h₁ at ih, rw bind_symm (ne.symm c), exact ih.mp hyp, rw bind_symm (ne.symm c) at hyp, apply ih.2, exact hyp, }, intros sub₁ sub₂, constructor; intros h₁ h₂; have ih₁ := @φ_ih_a ass sub₁; have ih₂ := @φ_ih_a_1 ass sub₂, replace h₂ := ih₁.2 h₂, apply ih₂.mp, apply_assumption, exact h₂, replace h₂ := ih₁.mp h₂, apply ih₂.2, apply_assumption, exact h₂, simp [term_rw_semantics], end -- We will generalize this notation to a typeclass later. -- For now it is a local notation in both modules. local infixr `⊢`:55 := proof -- And here is the proof itself. -- It proceeds by induction on the proof Γ ⊢ φ. -- So pretty. theorem soundness : Γ ⊢ φ → Γ ⊨ φ := begin intros proof α ne M ass h, induction proof generalizing ass, -- case reflexivity exact h proof_φ proof_h, -- case transitivity apply proof_ih_h₂, intros ψ H, exact proof_ih_h₁ ψ H ass h, -- case modus ponens have c₁ := proof_ih_h₁ ass h, have c₂ := proof_ih_h₂ ass h, revert c₁, dunfold signature.structure.satisfies', simp, intro c₁, exact c₁ c₂, -- case intro intro h₂, have sat := proof_ih, apply sat, intros ψ H, cases H, exact h ψ H, simp at H, rwa H, -- case universal intro intro x, have c := @fundamental σ α ne proof_Γ proof_x x, specialize c M ass proof_abs h, have ih := proof_ih (@signature.vasgn.bind σ α ne ass proof_x x), apply ih, exact c, -- case universal elim have ih := proof_ih ass h, rename proof_sub sub, clear proof_ih, revert ih, dunfold signature.structure.satisfies', intro ih, set ref := @signature.structure.reference' σ α ne M proof_t ass, specialize ih ref, exact (@rw_semantics σ α ne M ass proof_x proof_t proof_φ sub).2 ih, -- case exfalso exfalso, have ih := proof_ih ass h, revert ih, dunfold signature.structure.satisfies', contradiction, -- case by contradiction classical, by_contradiction, have ih := proof_ih ass h, revert ih, dunfold signature.formula.not signature.structure.satisfies', simp, intro ih, apply ih, intro insanity, contradiction, -- case identity intro dunfold signature.structure.satisfies', simp, -- case identity elimination have ih₁ := proof_ih_h ass h, have ih₂ := proof_ih_eq ass h, rename proof_sub₁ sub₁, rename proof_sub₂ sub₂, replace ih₁ := (@rw_semantics σ α ne M ass proof_x proof_t₁ proof_φ sub₁).mp ih₁, apply (rw_semantics sub₂).2, convert ih₁ using 2, revert ih₂, dunfold signature.structure.satisfies', simp, intro ih₂, rw ←ih₂, end instance inhabited_structure : inhabited (σ.structure unit) := ⟨{ I₁ := λ _ _ _, unit.star, I₂ := λ _ _ _, true }⟩ theorem consistency : consistent (∅ : set σ.formula) := begin intro h, obtain ⟨x⟩ := h, have h := @soundness σ ∅ signature.formula.false x, revert h, dunfold signature.follows, simp, intro h, have M : σ.structure unit := default _, specialize @h unit unit.star M, apply @false_is_unsat σ unit, dunfold signature.structure.satisfies, existsi M, exact h, end -- end semantics end logic
86918b257c7678d324d7ff8a9efbbfac1e12783f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/pairing.lean
0dad86e65afa313473621809b89d16188592aeea
[ "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
6,575
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, Mario Carneiro -/ import data.nat.sqrt import data.set.lattice import algebra.group.prod import algebra.order.monoid.min_max /-! # Naturals pairing function > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines a pairing function for the naturals as follows: ```text 0 1 4 9 16 2 3 5 10 17 6 7 8 11 18 12 13 14 15 19 20 21 22 23 24 ``` It has the advantage of being monotone in both directions and sending `⟦0, n^2 - 1⟧` to `⟦0, n - 1⟧²`. -/ open prod decidable function namespace nat /-- Pairing function for the natural numbers. -/ @[pp_nodot] def mkpair (a b : ℕ) : ℕ := if a < b then b*b + a else a*a + a + b /-- Unpairing function for the natural numbers. -/ @[pp_nodot] def unpair (n : ℕ) : ℕ × ℕ := let s := sqrt n in if n - s*s < s then (n - s*s, s) else (s, n - s*s - s) @[simp] theorem mkpair_unpair (n : ℕ) : mkpair (unpair n).1 (unpair n).2 = n := begin dsimp only [unpair], set s := sqrt n, have sm : s * s + (n - s * s) = n := add_tsub_cancel_of_le (sqrt_le _), split_ifs, { simp [mkpair, h, sm] }, { have hl : n - s*s - s ≤ s := tsub_le_iff_left.mpr (tsub_le_iff_left.mpr $ by rw ← add_assoc; apply sqrt_le_add), simp [mkpair, hl.not_lt, add_assoc, add_tsub_cancel_of_le (le_of_not_gt h), sm] } end theorem mkpair_unpair' {n a b} (H : unpair n = (a, b)) : mkpair a b = n := by simpa [H] using mkpair_unpair n @[simp] theorem unpair_mkpair (a b : ℕ) : unpair (mkpair a b) = (a, b) := begin dunfold mkpair, split_ifs, { show unpair (b * b + a) = (a, b), have be : sqrt (b * b + a) = b, from sqrt_add_eq _ (le_trans (le_of_lt h) (nat.le_add_left _ _)), simp [unpair, be, add_tsub_cancel_right, h] }, { show unpair (a * a + a + b) = (a, b), have ae : sqrt (a * a + (a + b)) = a, { rw sqrt_add_eq, exact add_le_add_left (le_of_not_gt h) _ }, simp [unpair, ae, nat.not_lt_zero, add_assoc] } end /-- An equivalence between `ℕ × ℕ` and `ℕ`. -/ @[simps { fully_applied := ff }] def mkpair_equiv : ℕ × ℕ ≃ ℕ := ⟨uncurry mkpair, unpair, λ ⟨a, b⟩, unpair_mkpair a b, mkpair_unpair⟩ lemma surjective_unpair : surjective unpair := mkpair_equiv.symm.surjective @[simp] lemma mkpair_eq_mkpair {a b c d : ℕ} : mkpair a b = mkpair c d ↔ a = c ∧ b = d := mkpair_equiv.injective.eq_iff.trans (@prod.ext_iff ℕ ℕ (a, b) (c, d)) theorem unpair_lt {n : ℕ} (n1 : 1 ≤ n) : (unpair n).1 < n := let s := sqrt n in begin simp [unpair], change sqrt n with s, by_cases h : n - s * s < s; simp [h], { exact lt_of_lt_of_le h (sqrt_le_self _) }, { simp at h, have s0 : 0 < s := sqrt_pos.2 n1, exact lt_of_le_of_lt h (tsub_lt_self n1 (mul_pos s0 s0)) } end @[simp] lemma unpair_zero : unpair 0 = 0 := by { rw unpair, simp } theorem unpair_left_le : ∀ (n : ℕ), (unpair n).1 ≤ n | 0 := by simp | (n+1) := le_of_lt (unpair_lt (nat.succ_pos _)) theorem left_le_mkpair (a b : ℕ) : a ≤ mkpair a b := by simpa using unpair_left_le (mkpair a b) theorem right_le_mkpair (a b : ℕ) : b ≤ mkpair a b := begin by_cases h : a < b; simp [mkpair, h], exact le_trans (le_mul_self _) (nat.le_add_right _ _) end theorem unpair_right_le (n : ℕ) : (unpair n).2 ≤ n := by simpa using right_le_mkpair n.unpair.1 n.unpair.2 theorem mkpair_lt_mkpair_left {a₁ a₂} (b) (h : a₁ < a₂) : mkpair a₁ b < mkpair a₂ b := begin by_cases h₁ : a₁ < b; simp [mkpair, h₁, add_assoc], { by_cases h₂ : a₂ < b; simp [mkpair, h₂, h], simp at h₂, apply add_lt_add_of_le_of_lt, exact mul_self_le_mul_self h₂, exact lt_add_right _ _ _ h }, { simp at h₁, simp [not_lt_of_gt (lt_of_le_of_lt h₁ h)], apply add_lt_add, exact mul_self_lt_mul_self h, apply add_lt_add_right; assumption } end theorem mkpair_lt_mkpair_right (a) {b₁ b₂} (h : b₁ < b₂) : mkpair a b₁ < mkpair a b₂ := begin by_cases h₁ : a < b₁; simp [mkpair, h₁, add_assoc], { simp [mkpair, lt_trans h₁ h, h], exact mul_self_lt_mul_self h }, { by_cases h₂ : a < b₂; simp [mkpair, h₂, h], simp at h₁, rw [add_comm, add_comm _ a, add_assoc, add_lt_add_iff_left], rwa [add_comm, ← sqrt_lt, sqrt_add_eq], exact le_trans h₁ (nat.le_add_left _ _) } end theorem mkpair_lt_max_add_one_sq (m n : ℕ) : mkpair m n < (max m n + 1) ^ 2 := begin rw [mkpair, add_sq, mul_one, two_mul, sq, add_assoc, add_assoc], cases lt_or_le m n, { rw [if_pos h, max_eq_right h.le, add_lt_add_iff_left, add_assoc], exact h.trans_le (self_le_add_right n _) }, { rw [if_neg h.not_lt, max_eq_left h, add_lt_add_iff_left, add_assoc, add_lt_add_iff_left], exact lt_succ_of_le h } end theorem max_sq_add_min_le_mkpair (m n : ℕ) : max m n ^ 2 + min m n ≤ mkpair m n := begin rw mkpair, cases lt_or_le m n, { rw [if_pos h, max_eq_right h.le, min_eq_left h.le, sq], }, { rw [if_neg h.not_lt, max_eq_left h, min_eq_right h, sq, add_assoc, add_le_add_iff_left], exact le_add_self } end theorem add_le_mkpair (m n : ℕ) : m + n ≤ mkpair m n := (max_sq_add_min_le_mkpair _ _).trans' $ by { rw [sq, ←min_add_max, add_comm, add_le_add_iff_right], exact le_mul_self _ } theorem unpair_add_le (n : ℕ) : (unpair n).1 + (unpair n).2 ≤ n := (add_le_mkpair _ _).trans_eq (mkpair_unpair _) end nat open nat section complete_lattice lemma supr_unpair {α} [complete_lattice α] (f : ℕ → ℕ → α) : (⨆ n : ℕ, f n.unpair.1 n.unpair.2) = ⨆ i j : ℕ, f i j := by rw [← (supr_prod : (⨆ i : ℕ × ℕ, f i.1 i.2) = _), ← nat.surjective_unpair.supr_comp] lemma infi_unpair {α} [complete_lattice α] (f : ℕ → ℕ → α) : (⨅ n : ℕ, f n.unpair.1 n.unpair.2) = ⨅ i j : ℕ, f i j := supr_unpair (show ℕ → ℕ → αᵒᵈ, from f) end complete_lattice namespace set lemma Union_unpair_prod {α β} {s : ℕ → set α} {t : ℕ → set β} : (⋃ n : ℕ, s n.unpair.fst ×ˢ t n.unpair.snd) = (⋃ n, s n) ×ˢ (⋃ n, t n) := by { rw [← Union_prod], convert surjective_unpair.Union_comp _, refl } lemma Union_unpair {α} (f : ℕ → ℕ → set α) : (⋃ n : ℕ, f n.unpair.1 n.unpair.2) = ⋃ i j : ℕ, f i j := supr_unpair f lemma Inter_unpair {α} (f : ℕ → ℕ → set α) : (⋂ n : ℕ, f n.unpair.1 n.unpair.2) = ⋂ i j : ℕ, f i j := infi_unpair f end set
c643f0e06718ca08e0f1a195183e51b53bc9ed2b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/wiedijk_100_theorems/konigsberg.lean
fe5abdbe02a38f615a28da8bdfd8cc416af7b114
[ "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,912
lean
/- Copyright (c) 2022 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.trails import tactic.derive_fintype /-! # The Königsberg bridges problem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We show that a graph that represents the islands and mainlands of Königsberg and seven bridges between them has no Eulerian trail. -/ namespace konigsberg /-- The vertices for the Königsberg graph; four vertices for the bodies of land and seven vertices for the bridges. -/ @[derive [decidable_eq, fintype], nolint has_inhabited_instance] inductive verts : Type | V1 | V2 | V3 | V4 -- The islands and mainlands | B1 | B2 | B3 | B4 | B5 | B6 | B7 -- The bridges open verts /-- Each of the connections between the islands/mainlands and the bridges. These are ordered pairs, but the data becomes symmetric in `konigsberg.adj`. -/ def edges : list (verts × verts) := [ (V1, B1), (V1, B2), (V1, B3), (V1, B4), (V1, B5), (B1, V2), (B2, V2), (B3, V4), (B4, V3), (B5, V3), (V2, B6), (B6, V4), (V3, B7), (B7, V4) ] /-- The adjacency relation for the Königsberg graph. -/ def adj (v w : verts) : bool := ((v, w) ∈ edges) || ((w, v) ∈ edges) /-- The Königsberg graph structure. While the Königsberg bridge problem is usually described using a multigraph, the we use a "mediant" construction to transform it into a simple graph -- every edge in the multigraph is subdivided into a path of two edges. This construction preserves whether a graph is Eulerian. (TODO: once mathlib has multigraphs, either prove the mediant construction preserves the Eulerian property or switch this file to use multigraphs. -/ @[simps] def graph : simple_graph verts := { adj := λ v w, adj v w, symm := begin dsimp [symmetric, adj], dec_trivial, end, loopless := begin dsimp [irreflexive, adj], dec_trivial end } instance : decidable_rel graph.adj := λ a b, decidable_of_bool (adj a b) iff.rfl /-- To speed up the proof, this is a cache of all the degrees of each vertex, proved in `konigsberg.degree_eq_degree`. -/ @[simp] def degree : verts → ℕ | V1 := 5 | V2 := 3 | V3 := 3 | V4 := 3 | B1 := 2 | B2 := 2 | B3 := 2 | B4 := 2 | B5 := 2 | B6 := 2 | B7 := 2 @[simp] lemma degree_eq_degree (v : verts) : graph.degree v = degree v := by cases v; refl /-- The Königsberg graph is not Eulerian. -/ theorem not_is_eulerian {u v : verts} (p : graph.walk u v) (h : p.is_eulerian) : false := begin have : {v | odd (graph.degree v)} = {verts.V1, verts.V2, verts.V3, verts.V4}, { ext w, simp only [degree_eq_degree, nat.odd_iff_not_even, set.mem_set_of_eq, set.mem_insert_iff, set.mem_singleton_iff], cases w; simp, }, have h := h.card_odd_degree, simp_rw [this] at h, norm_num at h, end end konigsberg
ce2fd7ceee631711cc293797c77072eec16b47f3
590f94277ab689acdc713c44e3bbca2e012fc074
/Sequent Calculus (Lean)/src/basics.lean
371c996a176f9ce3fe384705235d82963690b260
[]
no_license
Bpalkmim/iALC
bd3f882ad942c876d65c2d33cb50a36b2f8e5d16
9c2982ae916d01d9ebab9d58e0842292ed974876
refs/heads/master
1,689,527,062,560
1,631,502,537,000
1,631,502,537,000
108,029,498
0
0
null
null
null
null
UTF-8
Lean
false
false
4,496
lean
-- Arquivo com as definições dos tipos básicos de iALC e de seu cálculo de sequentes. -- Autor: Bernardo Alkmim -- bpalkmim@gmail.com --import .list namespace iALCbasics open list constant Concept : Type constant Nominal : Type constant Role : Type constant Top : Concept constant Bot : Concept -- Fórmulas (tanto conceitos quanto asserções) inductive Formula | simple : Concept → Formula | univ : Role → Formula → Formula | exis : Role → Formula → Formula | subj : Formula → Formula → Formula | conj : Formula → Formula → Formula | disj : Formula → Formula → Formula | neg : Formula → Formula | elemOf : Nominal → Formula → Formula -- Asserções também são fórmulas | relation : Role → Nominal → Nominal → Formula -- Funções para serem passadas ao map de listas para promoção -- Devem manter asserções inalteradas def add_nom (x : Nominal) : Formula → Formula | (Formula.simple c) := Formula.elemOf x (Formula.simple c) | (Formula.univ r f) := Formula.elemOf x (Formula.univ r f) | (Formula.exis r f) := Formula.elemOf x (Formula.exis r f) | (Formula.subj c d) := Formula.elemOf x (Formula.subj c d) | (Formula.conj c d) := Formula.elemOf x (Formula.conj c d) | (Formula.disj c d) := Formula.elemOf x (Formula.disj c d) | (Formula.neg c) := Formula.elemOf x (Formula.neg c) | (Formula.elemOf y c) := Formula.elemOf y c | (Formula.relation rel y z):= Formula.relation rel y z def add_univ (r : Role) : Formula → Formula | (Formula.simple c) := Formula.univ r (Formula.simple c) | (Formula.univ rel f) := Formula.univ r (Formula.univ rel f) | (Formula.exis rel f) := Formula.univ r (Formula.exis rel f) | (Formula.subj c d) := Formula.univ r (Formula.subj c d) | (Formula.conj c d) := Formula.univ r (Formula.conj c d) | (Formula.disj c d) := Formula.univ r (Formula.disj c d) | (Formula.neg c) := Formula.univ r (Formula.neg c) | (Formula.elemOf y c) := Formula.elemOf y c | (Formula.relation rel y z):= Formula.relation rel y z def add_exis (r : Role) : Formula → Formula | (Formula.simple c) := Formula.exis r (Formula.simple c) | (Formula.univ rel f) := Formula.exis r (Formula.univ rel f) | (Formula.exis rel f) := Formula.exis r (Formula.exis rel f) | (Formula.subj c d) := Formula.exis r (Formula.subj c d) | (Formula.conj c d) := Formula.exis r (Formula.conj c d) | (Formula.disj c d) := Formula.exis r (Formula.disj c d) | (Formula.neg c) := Formula.univ r (Formula.neg c) | (Formula.elemOf y c) := Formula.elemOf y c | (Formula.relation rel y z):= Formula.relation rel y z constant Sequent : list Formula → Formula → Prop constant Proof : Prop → Type /- -- Definições úteis para a definição de um sequente válido, utilizada na prova de correção constant Interpretation : list Formula → Prop constant Model : Interpretation → Nominal → list Formula → Prop -- Função que mapeia a validade de um sequente a partir de uma lista de nominals -- para a validade de um sequente a partir da conjunção das validades para cada -- nominal def model_list : Interpretation → list Nominal → list Formula → Prop | I l nil := ff | I nil Δ := tt | I (x :: l) Δ := (Model I x Δ) ∧ (model_list I l Δ) -- Função que busca por uma relação entre dois nominals numa lista de fórmulas def rel_in_formula_list : Role → Nominal → Nominal → list Formula → Prop | r x y nil := ff | r x y ((Formula.relation rel x y) :: l) := tt | r x y (_ :: l) := in_formula_list r x y l -- Função que busca numa lista de fórmulas pelas relações entre -- o nominal da esquerda e os da lista à direita def prec_general : Role → Nominal → list Nominal → list Formula → Prop | r x nil Δ := ff | r x (y :: l) Δ := (rel_in_formula_list r x y Δ) ∧ prec_general r x l Δ -- Função auxiliar para obter os nominals externos de uma lista de fórmulas def nom_ext : list Formula → list Nominal | nil := nil | ((Formula.elemOf y c) :: l) := y :: (nom_ext l) | (_ :: l) := nom_ext l -- Definição de sequente válido def valid_seq {prec : Role} {Θ Γ : list Formula} {δ : Formula} : Proof (Sequent (Θ ++ Γ) δ) → ∀ I : Interpretation, ((∀ x : Nominal, Model I x Θ) → (∀ x : nom_ext (δ :: Γ), (prec_general prec x (nom_ext (δ :: Γ)) (δ :: Γ) → (model_list I (nom_ext (δ :: Γ)) Γ → model_list I (nom_ext (δ :: Γ)) (δ :: nil)) ) ) ) -/ end iALCbasics
1ac5e67d572b71fc6049edb24822a4283117e6ed
1dd482be3f611941db7801003235dc84147ec60a
/src/tactic/linarith.lean
0da7c5bfe7ab6f80fb92cfac7709a34a32207c6b
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
31,522
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination. `linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ. @TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains @TODO: perform slightly better on ℤ by strengthening t < 0 hyps to t + 1 ≤ 0 @TODO: alternative discharger to `ring` @TODO: delay proofs of denominator normalization and nat casting until after contradiction is found -/ import tactic.ring data.nat.gcd data.list.basic meta.rb_map meta def nat.to_pexpr : ℕ → pexpr | 0 := ``(0) | 1 := ``(1) | n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2))) open native namespace linarith section lemmas lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0] lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0] lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff] lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le] lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 := by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt] lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 := by simp * lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 := by simp * lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 := by simp * lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 := by simp * lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 := by simp * lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 := have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha, neg_of_neg_pos (by simpa) lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 := have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha, nonpos_of_neg_nonneg (by simp at this; exact this) lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 := by simp * lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b := le_antisymm (le_of_not_gt h2) (le_of_not_gt h1) lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *] lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) : n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *] lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp * private meta def apnn : tactic unit := `[norm_num] lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2) (h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 := have h3 : n1 * n2 = k, from h3, by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) : k * (e1 / e2) = t1 := by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul] end lemmas section datatypes @[derive decidable_eq] inductive ineq | eq | le | lt open ineq def ineq.max : ineq → ineq → ineq | eq a := a | le a := a | lt a := lt def ineq.is_lt : ineq → ineq → bool | eq le := tt | eq lt := tt | le lt := tt | _ _ := ff def ineq.to_string : ineq → string | eq := "=" | le := "≤" | lt := "<" instance : has_to_string ineq := ⟨ineq.to_string⟩ /-- The main datatype for FM elimination. Variables are represented by natural numbers, each of which has an integer coefficient. Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1. The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]). str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0? -/ meta structure comp := (str : ineq) (coeffs : rb_map ℕ int) meta instance : inhabited comp := ⟨⟨ineq.eq, mk_rb_map⟩⟩ meta inductive comp_source | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source meta def comp_source.flatten : comp_source → rb_map ℕ ℕ | (comp_source.assump n) := mk_rb_map.insert n 1 | (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2) | (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n) meta def comp_source.to_string : comp_source → string | (comp_source.assump e) := to_string e | (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2 | (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c meta instance comp_source.has_to_format : has_to_format comp_source := ⟨λ a, comp_source.to_string a⟩ meta structure pcomp := (c : comp) (src : comp_source) meta def map_lt (m1 m2 : rb_map ℕ int) : bool := list.lex (prod.lex (<) (<)) m1.to_list m2.to_list -- make more efficient meta def comp.lt (c1 c2 : comp) : bool := (c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩ meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩ meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ := c.coeffs.zfind a meta def comp.scale (c : comp) (n : ℕ) : comp := { c with coeffs := c.coeffs.map ((*) (n : ℤ)) } meta def comp.add (c1 c2 : comp) : comp := ⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩ meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp := ⟨c.c.scale n, comp_source.scale n c.src⟩ meta def pcomp.add (c1 c2 : pcomp) : pcomp := ⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩ meta instance pcomp.to_format : has_to_format pcomp := ⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩ meta instance comp.to_format : has_to_format comp := ⟨λ p, to_fmt p.coeffs⟩ end datatypes section fm_elim /-- If c1 and c2 both contain variable a with opposite coefficients, produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/ meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) := let v1 := c1.coeff_of a, v2 := c2.coeff_of a in if v1 * v2 < 0 then let vlcm := nat.lcm v1.nat_abs v2.nat_abs, v1' := vlcm / v1.nat_abs, v2' := vlcm / v2.nat_abs in some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩ else none meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp := do (n1, n2, c) ← elim_var p1.c p2.c a, return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩ meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp := if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else comps.fold mk_rb_set $ λ pc s, match pelim_var p pc a with | some pc := s.insert pc | none := s end /-- The state for the elimination monad. vars: the set of variables present in comps comps: a set of comparisons inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0, indexed by ℕ. has_false: stores a pcomp of 0 < 0 if one has been found TODO: is it more efficient to store comps as a list, to avoid comparisons? -/ meta structure linarith_structure := (vars : rb_set ℕ) (comps : rb_set pcomp) @[reducible] meta def linarith_monad := state_t linarith_structure (except_t pcomp id) meta instance : monad linarith_monad := state_t.monad meta instance : monad_except pcomp linarith_monad := state_t.monad_except pcomp meta def get_vars : linarith_monad (rb_set ℕ) := linarith_structure.vars <$> get meta def get_var_list : linarith_monad (list ℕ) := rb_set.to_list <$> get_vars meta def get_comps : linarith_monad (rb_set pcomp) := linarith_structure.comps <$> get meta def validate : linarith_monad unit := do ⟨_, comps⟩ ← get, match comps.to_list.find (λ p : pcomp, p.is_contr) with | none := return () | some c := throw c end meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit := state_t.put ⟨vars, comps⟩ >> validate meta def monad.elim_var (a : ℕ) : linarith_monad unit := do vs ← get_vars, when (vs.contains a) $ do comps ← get_comps, let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)), update (vs.erase a) cs' meta def elim_all_vars : linarith_monad unit := get_var_list >>= list.mmap' monad.elim_var end fm_elim section parse open ineq tactic meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) := match c1.keys, c2.keys with | [0], _ := some $ c2.scale (c1.zfind 0) | _, [0] := some $ c1.scale (c2.zfind 0) | _, _ := none end /-- Turns an expression into a map from ℕ to ℤ, for use in a comp object. The expr_map ℕ argument identifies which expressions have already been assigned numbers. Returns a new map. -/ meta def map_of_expr : expr_map ℕ → expr → option (expr_map ℕ × rb_map ℕ ℤ) | m e@`(%%e1 * %%e2) := (do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, mp ← map_of_expr_mul_aux comp1 comp2, return (m', mp)) <|> (match m.find e with | some k := return (m, mk_rb_map.insert k 1) | none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end) | m `(%%e1 + %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add comp2) | m `(%%e1 - %%e2) := do (m', comp1) ← map_of_expr m e1, (m', comp2) ← map_of_expr m' e2, return (m', comp1.add (comp2.scale (-1))) | m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1)) | m e := match e.to_int, m.find e with | some 0, _ := return ⟨m, mk_rb_map⟩ | some z, _ := return ⟨m, mk_rb_map.insert 0 z⟩ | none, some k := return (m, mk_rb_map.insert k 1) | none, none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1) end meta def parse_into_comp_and_expr : expr → option (ineq × expr) | `(%%e < 0) := (ineq.lt, e) | `(%%e ≤ 0) := (ineq.le, e) | `(%%e = 0) := (ineq.eq, e) | _ := none meta def to_comp (e : expr) (m : expr_map ℕ) : option (comp × expr_map ℕ) := do (iq, e) ← parse_into_comp_and_expr e, (m', comp') ← map_of_expr m e, return ⟨⟨iq, comp'⟩, m'⟩ meta def to_comp_fold : expr_map ℕ → list expr → (list (option comp) × expr_map ℕ) | m [] := ([], m) | m (h::t) := match to_comp h m with | some (c, m') := let (l, mp) := to_comp_fold m' t in (c::l, mp) | none := let (l, mp) := to_comp_fold m t in (none::l, mp) end /-- Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure. -/ meta def mk_linarith_structure (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) := do pftps ← l.mmap infer_type, let (l', map) := to_comp_fold mk_rb_map pftps, let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b), let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)), let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ, let pc : rb_set pcomp := rb_map.set_of_list $ lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩), --trace pc, trace prmap, return (⟨vars, pc⟩, prmap) meta def linarith_monad.run {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) := do (struct, inputs) ← mk_linarith_structure l, match (state_t.run (validate >> tac) struct).run with | (except.ok (a, _)) := return (sum.inr a, inputs) | (except.error contr) := return (sum.inl contr, inputs) end end parse section prove open ineq tactic meta def get_rel_sides : expr → tactic (expr × expr) | `(%%a < %%b) := return (a, b) | `(%%a ≤ %%b) := return (a, b) | `(%%a = %%b) := return (a, b) | `(%%a ≥ %%b) := return (a, b) | `(%%a > %%b) := return (a, b) | _ := failed meta def mul_expr (n : ℕ) (e : expr) : pexpr := if n = 1 then ``(%%e) else ``(%%(nat.to_pexpr n) * %%e) meta def add_exprs_aux : pexpr → list pexpr → pexpr | p [] := p | p [a] := ``(%%p + %%a) | p (h::t) := add_exprs_aux ``(%%p + %%h) t meta def add_exprs : list pexpr → pexpr | [] := ``(0) | (h::t) := add_exprs_aux h t meta def find_contr (m : rb_set pcomp) : option pcomp := m.keys.find (λ p, p.c.is_contr) meta def ineq_const_mul_nm : ineq → name | lt := ``mul_neg | le := ``mul_nonpos | eq := ``mul_eq meta def ineq_const_nm : ineq → ineq → (name × ineq) | eq eq := (``eq_of_eq_of_eq, eq) | eq le := (``le_of_eq_of_le, le) | eq lt := (``lt_of_eq_of_lt, lt) | le eq := (``le_of_le_of_eq, le) | le le := (`add_nonpos, le) | le lt := (`add_neg_of_nonpos_of_neg, lt) | lt eq := (``lt_of_lt_of_eq, lt) | lt le := (`add_neg_of_neg_of_nonpos, lt) | lt lt := (`add_neg, lt) meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) := do tp ← infer_type h, some (iq, e) ← return $ parse_into_comp_and_expr tp, if c = 0 then do e' ← mk_app ``zero_mul [e], return (eq, e') else if c = 1 then return (iq, h) else do nm ← resolve_name (ineq_const_mul_nm iq), tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type, cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0), (_, ex) ← solve_aux cpos `[norm_num, done], -- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why? e' ← to_expr ``(%%nm %%h %%ex) ff, return (iq, e') meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) := do (iq, h') ← mk_single_comp_zero_pf coeff npf, let (nm, niq) := ineq_const_nm c iq, n ← resolve_name nm, e' ← to_expr ``(%%n %%pf %%h'), return (niq, e') /-- Takes a list of coefficients [c] and list of expressions, of equal length. Each expression is a proof of a prop of the form t {<, ≤, =} 0. Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible. -/ meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr | _ [] := fail "no linear hypotheses found" | [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h | (c::ct) (h::t) := do (iq, h') ← mk_single_comp_zero_pf c h, prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h') | _ _ := fail "not enough args to mk_lt_zero_pf" meta def term_of_ineq_prf (prf : expr) : tactic expr := do (lhs, _) ← infer_type prf >>= get_rel_sides, return lhs meta structure linarith_config := (discharger : tactic unit := `[ring]) (restrict_type : option Type := none) (restrict_type_reflect : reflected restrict_type . apply_instance) (exfalso : bool := tt) meta def ineq_pf_tp (pf : expr) : tactic expr := do (_, z) ← infer_type pf >>= get_rel_sides, infer_type z meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr := to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp))) /-- Assumes e is a proof that t = 0. Creates a proof that -t = 0. -/ meta def mk_neg_eq_zero_pf (e : expr) : tactic expr := to_expr ``(neg_eq_zero.mpr %%e) meta def add_neg_eq_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h, match iq with | ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl | _ := list.cons h <$> add_neg_eq_pfs t end /-- Takes a list of proofs of propositions of the form t {<, ≤, =} 0, and tries to prove the goal `false`. -/ meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit | [] := fail "no args to linarith" | l@(h::t) := do l' ← add_neg_eq_pfs l, hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf, --list.mmap' (λ e, infer_type e >>= trace) (hz::l') , (sum.inl contr, inputs) ← elim_all_vars.run (hz::l') | fail "linarith failed to find a contradiction", let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)), let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1), let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0), let (coeffs, pfs) := zip.unzip, mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)), sm ← to_expr $ add_exprs mls, tgt ← to_expr ``(%%sm = 0), (a, b) ← solve_aux tgt (cfg.discharger >> done), pf ← mk_lt_zero_pf coeffs pfs, pftp ← infer_type pf, (_, nep, _) ← rewrite_core b pftp, pf' ← mk_eq_mp nep pf, mk_app `lt_irrefl [pf'] >>= exact end prove section normalize open tactic set_option eqn_compiler.max_steps 50000 meta def rem_neg (prf : expr) : expr → tactic expr | `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf) | `(_ < _) := to_expr ``(le_of_not_gt %%prf) | `(_ > _) := to_expr ``(le_of_not_gt %%prf) | `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf) | e := failed meta def rearr_comp : expr → expr → tactic expr | prf `(%%a ≤ 0) := return prf | prf `(%%a < 0) := return prf | prf `(%%a = 0) := return prf | prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf) | prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf) | prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf) | prf `(0 = %%a) := to_expr ``(eq.symm %%prf) | prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf) | prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf) | prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf) | prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf) | prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf) | prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp | prf _ := fail "couldn't rearrange comp" meta def is_numeric : expr → option ℚ | `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2 | `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2 | `(-%%e) := rat.neg <$> is_numeric e | e := e.to_rat inductive {u} tree (α : Type u) : Type u | nil {} : tree | node : α → tree → tree → tree def tree.repr {α} [has_repr α] : tree α → string | tree.nil := "nil" | (tree.node a t1 t2) := "tree.node " ++ repr a ++ " (" ++ tree.repr t1 ++ ") (" ++ tree.repr t2 ++ ")" instance {α} [has_repr α] : has_repr (tree α) := ⟨tree.repr⟩ meta def find_cancel_factor : expr → ℕ × tree ℕ | `(%%e1 + %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 - %%e2) := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in (lcm, tree.node lcm t1 t2) | `(%%e1 * %%e2) := match is_numeric e1, is_numeric e2 with | none, none := (1, tree.node 1 tree.nil tree.nil) | _, _ := let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in (pd, tree.node pd t1 t2) end | `(%%e1 / %%e2) := match is_numeric e2 with | some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in (n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil)) | none := (1, tree.node 1 tree.nil tree.nil) end | `(-%%e) := find_cancel_factor e | _ := (1, tree.node 1 tree.nil tree.nil) open tree meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr | v (node _ lhs rhs) `(%%e1 + %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2] | v (node _ lhs rhs) `(%%e1 - %%e2) := do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2] | v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2, ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v, ntp ← to_expr ``(%%ln' * %%vln' = %%v'), (_, npf) ← solve_aux ntp `[norm_num, done], mk_app ``mul_subst [v1, v2, npf] | v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) := do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1, rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v, ntp ← to_expr ``(%%rn' / %%e2 = 1), (_, npf) ← solve_aux ntp `[norm_num, done], ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'), (_, npf2) ← solve_aux ntp2 `[norm_num, done], mk_app ``div_subst [v1, npf, npf2] | v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v'] | v _ e := do tp ← infer_type e, v' ← tp.of_nat v, e' ← to_expr ``(%%v' * %%e), mk_app `eq.refl [e'] /-- e is a term with rational division. produces a natural number n and a proof that n*e = e', where e' has no division. -/ meta def kill_factors (e : expr) : tactic (ℕ × expr) := let (n, t) := find_cancel_factor e in do e' ← mk_prod_prf n t e, return (n, e') open expr meta def expr_contains (n : name) : expr → bool | (const nm _) := nm = n | (lam _ _ _ bd) := expr_contains bd | (pi _ _ _ bd) := expr_contains bd | (app e1 e2) := expr_contains e1 || expr_contains e2 | _ := ff lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 := by rwa he at hl meta def norm_hyp_aux (h' lhs : expr) : tactic expr := do (v, lhs') ← kill_factors lhs, if v = 1 then return h' else do (ih, h'') ← mk_single_comp_zero_pf v h', (_, nep, _) ← infer_type h'' >>= rewrite_core lhs', mk_eq_mp nep h'' meta def norm_hyp (h : expr) : tactic expr := do htp ← infer_type h, h' ← rearr_comp h htp, some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h', if expr_contains `has_div.div lhs then norm_hyp_aux h' lhs else return h' meta def get_contr_lemma_name : expr → option name | `(%%a < %%b) := return `lt_of_not_ge | `(%%a ≤ %%b) := return `le_of_not_gt | `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt | `(%%a ≥ %%b) := return `le_of_not_gt | `(%%a > %%b) := return `lt_of_not_ge | `(¬ %%a < %%b) := return `not.intro | `(¬ %%a ≤ %%b) := return `not.intro | `(¬ %%a = %%b) := return `not.intro | `(¬ %%a ≥ %%b) := return `not.intro | `(¬ %%a > %%b) := return `not.intro | _ := none -- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality meta def cast_expr (e : expr) : tactic (expr × expr) := do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one, ``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul, ``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one, ``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk, ce ← to_expr ``(↑%%e : ℤ), simplify s [] ce {fail_if_unchanged := ff} meta def is_nat_int_coe : expr → option expr | `((↑(%%n : ℕ) : ℤ)) := some n | _ := none meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr := mk_app `int.coe_nat_nonneg [e] meta def get_nat_comps : expr → list expr | `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b) | `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b) | e := match is_nat_int_coe e with | some e' := [e'] | none := [] end meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) := (get_nat_comps e).mmap mk_coe_nat_nonneg_prf meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) := do (a', prfa) ← cast_expr a, (b', prfb) ← cast_expr b, la ← mk_coe_nat_nonneg_prfs a', lb ← mk_coe_nat_nonneg_prfs b', pf' ← mk_app ln [pf, prfa, prfb], return $ pf'::(la.append lb) meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) := do tp ← infer_type pf, match tp with | `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst | `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst | `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst | `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst | `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst | `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst | `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst | `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst | `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst | _ := fail "mk_coe_comp_prf failed: proof is not an inequality" end meta def guard_is_nat_prop : expr → tactic unit | `(%%a = _) := infer_type a >>= unify `(ℕ) | `(%%a ≤ _) := infer_type a >>= unify `(ℕ) | `(%%a < _) := infer_type a >>= unify `(ℕ) | `(%%a ≥ _) := infer_type a >>= unify `(ℕ) | `(%%a > _) := infer_type a >>= unify `(ℕ) | `(¬ %%p) := guard_is_nat_prop p | _ := failed meta def replace_nat_pfs : list expr → tactic (list expr) | [] := return [] | (h::t) := (do infer_type h >>= guard_is_nat_prop, ls ← mk_int_pfs_of_nat_pf h, list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t meta def partition_by_type_aux : rb_lmap expr expr → list expr → tactic (rb_lmap expr expr) | m [] := return m | m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) := partition_by_type_aux mk_rb_map l private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit := (first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed" /-- Takes a list of proofs of propositions. Filters out the proofs of linear (in)equalities, and tries to use them to prove `false`. If pref_type is given, starts by working over this type -/ meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit := do l' ← replace_nat_pfs l, ls ← list.reduce_option <$> l'.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none) >>= partition_by_type, pref_type ← (unify pref_type.iget `(ℕ) >> return (some `(ℤ) : option expr)) <|> return pref_type, match cfg.restrict_type, ls.values, pref_type with | some rtp, _, _ := do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m, prove_false_by_linarith1 cfg (ls.ifind m) | none, [ls'], _ := prove_false_by_linarith1 cfg ls' | none, ls', none := try_linarith_on_lists cfg ls' | none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (ls.erase t).values end end normalize end linarith section open tactic linarith open lean lean.parser interactive tactic interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def linarith.interactive_aux (cfg : linarith_config) : option expr → parse ident* → (parse (tk "using" *> pexpr_list)?) → tactic unit | pt l (some pe) := pe.mmap (λ p, i_to_expr p >>= note_anon) >> linarith.interactive_aux pt l none | pt [] none := do t ← target, if t = `(false) then local_context >>= prove_false_by_linarith cfg pt else match get_contr_lemma_name t with | some nm := seq (applyc nm) (do t ← intro1 >>= ineq_pf_tp, linarith.interactive_aux (some t) [] none) | none := if cfg.exfalso then exfalso >> linarith.interactive_aux pt [] none else fail "linarith failed: target type is not an inequality." end | pt ls none := (ls.mmap get_local) >>= prove_false_by_linarith cfg pt /-- Tries to prove a goal of `false` by linear arithmetic on hypotheses. If the goal is a linear (in)equality, tries to prove it by contradiction. If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the hypotheses. `linarith` will use all relevant hypotheses in the local context. `linarith h1 h2 h3` will only use hypotheses h1, h2, h3. `linarith using [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context. Config options: `linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false` `linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T` `linarith {discharger := tac}` will use `tac` instead of `ring` for normalization. Options: `ring2`, `ring SOP`, `simp` -/ meta def tactic.interactive.linarith (ids : parse (many ident)) (using_hyps : parse (tk "using" *> pexpr_list)?) (cfg : linarith_config := {}) : tactic unit := linarith.interactive_aux cfg none ids using_hyps end
a272b0fd54ddbd0cc2a468091a968d27c33fa176
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/elements.lean
3b830d6b88b8050ae8ed45a727991562c8455b0d
[ "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
9,424
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.structured_arrow import category_theory.groupoid import category_theory.punit /-! # The category of elements This file defines the category of elements, also known as (a special case of) the Grothendieck construction. Given a functor `F : C ⥤ Type`, an object of `F.elements` is a pair `(X : C, x : F.obj X)`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. ## Implementation notes This construction is equivalent to a special case of a comma construction, so this is mostly just a more convenient API. We prove the equivalence in `category_theory.category_of_elements.structured_arrow_equivalence`. ## References * [Emily Riehl, *Category Theory in Context*, Section 2.4][riehl2017] * <https://en.wikipedia.org/wiki/Category_of_elements> * <https://ncatlab.org/nlab/show/category+of+elements> ## Tags category of elements, Grothendieck construction, comma category -/ namespace category_theory universes w v u variables {C : Type u} [category.{v} C] /-- The type of objects for the category of elements of a functor `F : C ⥤ Type` is a pair `(X : C, x : F.obj X)`. -/ @[nolint has_inhabited_instance] def functor.elements (F : C ⥤ Type w) := (Σ c : C, F.obj c) /-- The category structure on `F.elements`, for `F : C ⥤ Type`. A morphism `(X, x) ⟶ (Y, y)` is a morphism `f : X ⟶ Y` in `C`, so `F.map f` takes `x` to `y`. -/ instance category_of_elements (F : C ⥤ Type w) : category.{v} F.elements := { hom := λ p q, { f : p.1 ⟶ q.1 // (F.map f) p.2 = q.2 }, id := λ p, ⟨𝟙 p.1, by obviously⟩, comp := λ p q r f g, ⟨f.val ≫ g.val, by obviously⟩ } namespace category_of_elements @[ext] lemma ext (F : C ⥤ Type w) {x y : F.elements} (f g : x ⟶ y) (w : f.val = g.val) : f = g := subtype.ext_val w @[simp] lemma comp_val {F : C ⥤ Type w} {p q r : F.elements} {f : p ⟶ q} {g : q ⟶ r} : (f ≫ g).val = f.val ≫ g.val := rfl @[simp] lemma id_val {F : C ⥤ Type w} {p : F.elements} : (𝟙 p : p ⟶ p).val = 𝟙 p.1 := rfl end category_of_elements noncomputable instance groupoid_of_elements {G : Type u} [groupoid.{v} G] (F : G ⥤ Type w) : groupoid F.elements := { inv := λ p q f, ⟨inv f.val, calc F.map (inv f.val) q.2 = F.map (inv f.val) (F.map f.val p.2) : by rw f.2 ... = (F.map f.val ≫ F.map (inv f.val)) p.2 : by simp ... = p.2 : by {rw ←functor.map_comp, simp}⟩, } namespace category_of_elements variable (F : C ⥤ Type w) /-- The functor out of the category of elements which forgets the element. -/ @[simps] def π : F.elements ⥤ C := { obj := λ X, X.1, map := λ X Y f, f.val } /-- A natural transformation between functors induces a functor between the categories of elements. -/ @[simps] def map {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : F₁.elements ⥤ F₂.elements := { obj := λ t, ⟨t.1, α.app t.1 t.2⟩, map := λ t₁ t₂ k, ⟨k.1, by simpa [←k.2] using (functor_to_types.naturality _ _ α k.1 t₁.2).symm⟩ } @[simp] lemma map_π {F₁ F₂ : C ⥤ Type w} (α : F₁ ⟶ F₂) : map α ⋙ π F₂ = π F₁ := rfl /-- The forward direction of the equivalence `F.elements ≅ (*, F)`. -/ def to_structured_arrow : F.elements ⥤ structured_arrow punit F := { obj := λ X, structured_arrow.mk (λ _, X.2), map := λ X Y f, structured_arrow.hom_mk f.val (by tidy) } @[simp] lemma to_structured_arrow_obj (X) : (to_structured_arrow F).obj X = { left := punit.star, right := X.1, hom := λ _, X.2 } := rfl @[simp] lemma to_comma_map_right {X Y} (f : X ⟶ Y) : ((to_structured_arrow F).map f).right = f.val := rfl /-- The reverse direction of the equivalence `F.elements ≅ (*, F)`. -/ def from_structured_arrow : structured_arrow punit F ⥤ F.elements := { obj := λ X, ⟨X.right, X.hom (punit.star)⟩, map := λ X Y f, ⟨f.right, congr_fun f.w'.symm punit.star⟩ } @[simp] lemma from_structured_arrow_obj (X) : (from_structured_arrow F).obj X = ⟨X.right, X.hom (punit.star)⟩ := rfl @[simp] lemma from_structured_arrow_map {X Y} (f : X ⟶ Y) : (from_structured_arrow F).map f = ⟨f.right, congr_fun f.w'.symm punit.star⟩ := rfl /-- The equivalence between the category of elements `F.elements` and the comma category `(*, F)`. -/ @[simps] def structured_arrow_equivalence : F.elements ≌ structured_arrow punit F := equivalence.mk (to_structured_arrow F) (from_structured_arrow F) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) (nat_iso.of_components (λ X, { hom := { right := 𝟙 _ }, inv := { right := 𝟙 _ } }) (by tidy)) open opposite /-- The forward direction of the equivalence `F.elementsᵒᵖ ≅ (yoneda, F)`, given by `category_theory.yoneda_sections`. -/ @[simps] def to_costructured_arrow (F : Cᵒᵖ ⥤ Type v) : (F.elements)ᵒᵖ ⥤ costructured_arrow yoneda F := { obj := λ X, costructured_arrow.mk ((yoneda_sections (unop (unop X).fst) F).inv (ulift.up (unop X).2)), map := λ X Y f, begin fapply costructured_arrow.hom_mk, exact f.unop.val.unop, ext y, simp only [costructured_arrow.mk_hom_eq_self, yoneda_map_app, functor_to_types.comp, op_comp, yoneda_sections_inv_app, functor_to_types.map_comp_apply, quiver.hom.op_unop, subtype.val_eq_coe], congr, exact f.unop.2, end } /-- The reverse direction of the equivalence `F.elementsᵒᵖ ≅ (yoneda, F)`, given by `category_theory.yoneda_equiv`. -/ @[simps] def from_costructured_arrow (F : Cᵒᵖ ⥤ Type v) : (costructured_arrow yoneda F)ᵒᵖ ⥤ F.elements := { obj := λ X, ⟨op (unop X).1, yoneda_equiv.1 (unop X).3⟩, map := λ X Y f, ⟨f.unop.1.op, begin convert (congr_fun ((unop X).hom.naturality f.unop.left.op) (𝟙 _)).symm, simp only [equiv.to_fun_as_coe, quiver.hom.unop_op, yoneda_equiv_apply, types_comp_apply, category.comp_id, yoneda_obj_map], have : yoneda.map f.unop.left ≫ (unop X).hom = (unop Y).hom, { convert f.unop.3, erw category.comp_id }, erw ← this, simp only [yoneda_map_app, functor_to_types.comp], erw category.id_comp end ⟩} @[simp] lemma from_costructured_arrow_obj_mk (F : Cᵒᵖ ⥤ Type v) {X : C} (f : yoneda.obj X ⟶ F) : (from_costructured_arrow F).obj (op (costructured_arrow.mk f)) = ⟨op X, yoneda_equiv.1 f⟩ := rfl /-- The unit of the equivalence `F.elementsᵒᵖ ≅ (yoneda, F)` is indeed iso. -/ lemma from_to_costructured_arrow_eq (F : Cᵒᵖ ⥤ Type v) : (to_costructured_arrow F).right_op ⋙ from_costructured_arrow F = 𝟭 _ := begin apply functor.ext, intros X Y f, have : ∀ {a b : F.elements} (H : a = b), ↑(eq_to_hom H) = eq_to_hom (show a.fst = b.fst, by { cases H, refl }) := λ _ _ H, by { cases H, refl }, ext, simp[this], tidy end /-- The counit of the equivalence `F.elementsᵒᵖ ≅ (yoneda, F)` is indeed iso. -/ lemma to_from_costructured_arrow_eq (F : Cᵒᵖ ⥤ Type v) : (from_costructured_arrow F).right_op ⋙ to_costructured_arrow F = 𝟭 _ := begin apply functor.hext, { intro X, cases X, cases X_right, simp only [functor.id_obj, functor.right_op_obj, to_costructured_arrow_obj, functor.comp_obj, costructured_arrow.mk], congr, ext x f, convert congr_fun (X_hom.naturality f.op).symm (𝟙 X_left), simp only [quiver.hom.unop_op, yoneda_obj_map], erw category.comp_id }, intros X Y f, cases X, cases Y, cases f, cases X_right, cases Y_right, simp[costructured_arrow.hom_mk], delta costructured_arrow.mk, congr, { ext x f, convert congr_fun (X_hom.naturality f.op).symm (𝟙 X_left), simp only [quiver.hom.unop_op, category_theory.yoneda_obj_map], erw category.comp_id }, { ext x f, convert congr_fun (Y_hom.naturality f.op).symm (𝟙 Y_left), simp only [quiver.hom.unop_op, category_theory.yoneda_obj_map], erw category.comp_id }, simp, exact proof_irrel_heq _ _, end /-- The equivalence `F.elementsᵒᵖ ≅ (yoneda, F)` given by yoneda lemma. -/ @[simps] def costructured_arrow_yoneda_equivalence (F : Cᵒᵖ ⥤ Type v) : (F.elements)ᵒᵖ ≌ costructured_arrow yoneda F := equivalence.mk (to_costructured_arrow F) (from_costructured_arrow F).right_op (nat_iso.op (eq_to_iso (from_to_costructured_arrow_eq F))) (eq_to_iso $ to_from_costructured_arrow_eq F) /-- The equivalence `(-.elements)ᵒᵖ ≅ (yoneda, -)` of is actually a natural isomorphism of functors. -/ lemma costructured_arrow_yoneda_equivalence_naturality {F₁ F₂ : Cᵒᵖ ⥤ Type v} (α : F₁ ⟶ F₂) : (map α).op ⋙ to_costructured_arrow F₂ = to_costructured_arrow F₁ ⋙ costructured_arrow.map α := begin fapply functor.ext, { intro X, simp only [costructured_arrow.map_mk, to_costructured_arrow_obj, functor.op_obj, functor.comp_obj], congr, ext x f, simpa using congr_fun (α.naturality f.op).symm (unop X).snd }, { intros X Y f, ext, have : ∀ {F : Cᵒᵖ ⥤ Type v} {a b : costructured_arrow yoneda F} (H : a = b), comma_morphism.left (eq_to_hom H) = eq_to_hom (show a.left = b.left, by { cases H, refl }) := λ _ _ _ H, by { cases H, refl }, simp [this] } end end category_of_elements end category_theory
67eee28a066e4cbbd8ac8e1e6aa4ae42200f1a2d
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/associated.lean
4675cc8c8a8430ae417dafc9372cae99b8eaea86
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
25,124
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, Jens Wagemaker -/ import data.multiset /-! # Associated, prime, and irreducible elements. -/ variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} @[simp] theorem is_unit_zero_iff [semiring α] : is_unit (0 : α) ↔ (0:α) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, begin haveI := subsingleton_of_zero_eq_one _ h, refine ⟨⟨0, 0, _, _⟩, rfl⟩; apply subsingleton.elim end⟩ @[simp] theorem not_is_unit_zero [semiring α] [nonzero α] : ¬ is_unit (0 : α) := mt is_unit_zero_iff.1 zero_ne_one lemma is_unit_pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ theorem is_unit_iff_dvd_one [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_semiring α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem mul_dvd_of_is_unit_left [comm_semiring α] {x y z : α} (h : is_unit x) : x * y ∣ z ↔ y ∣ z := ⟨dvd_trans (dvd_mul_left _ _), dvd_trans $ by simpa using mul_dvd_mul_right (is_unit_iff_dvd_one.1 h) y⟩ theorem mul_dvd_of_is_unit_right [comm_semiring α] {x y z : α} (h : is_unit y) : x * y ∣ z ↔ x ∣ z := by rw [mul_comm, mul_dvd_of_is_unit_left h] @[simp] lemma unit_mul_dvd_iff [comm_semiring α] {a b : α} {u : units α} : (u : α) * a ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_left (is_unit_unit _) lemma mul_unit_dvd_iff [comm_semiring α] {a b : α} {u : units α} : a * u ∣ b ↔ a ∣ b := units.coe_mul_dvd _ _ _ theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨begin rintro ⟨u, rfl⟩, exact (int.units_eq_one_or u).elim (by simp) (by simp) end, λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_semiring α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [integral_domain α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ x ≠ 0 ∧ ∃ d : α, ¬ is_unit d ∧ y = x * d := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, (domain.mul_right_inj hx0).1 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ lemma pow_dvd_pow_iff [integral_domain α] {x : α} {n m : ℕ} (h0 : x ≠ 0) (h1 : ¬ is_unit x) : x ^ n ∣ x ^ m ↔ n ≤ m := begin split, { intro h, rw [← not_lt], intro hmn, apply h1, have : x * x ^ m ∣ 1 * x ^ m, { rw [← pow_succ, one_mul], exact dvd_trans (pow_dvd_pow _ (nat.succ_le_of_lt hmn)) h }, rwa [mul_dvd_mul_iff_right, ← is_unit_iff_dvd_one] at this, apply pow_ne_zero m h0 }, { apply pow_dvd_pow } end /-- prime element of a semiring -/ def prime [comm_semiring α] (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) namespace prime lemma ne_zero [comm_semiring α] {p : α} (hp : prime p) : p ≠ 0 := hp.1 lemma not_unit [comm_semiring α] {p : α} (hp : prime p) : ¬ is_unit p := hp.2.1 lemma div_or_div [comm_semiring α] {p : α} (hp : prime p) {a b : α} (h : p ∣ a * b) : p ∣ a ∨ p ∣ b := hp.2.2 a b h end prime @[simp] lemma not_prime_zero [comm_semiring α] : ¬ prime (0 : α) := λ h, h.ne_zero rfl @[simp] lemma not_prime_one [comm_semiring α] : ¬ prime (1 : α) := λ h, h.not_unit is_unit_one lemma exists_mem_multiset_dvd_of_prime [comm_semiring α] {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.not_unit $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.div_or_div this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b namespace irreducible lemma not_unit [monoid α] {p : α} (hp : irreducible p) : ¬ is_unit p := hp.1 lemma is_unit_or_is_unit [monoid α] {p : α} (hp : irreducible p) {a b : α} (h : p = a * b) : is_unit a ∨ is_unit b := hp.2 a b h end irreducible @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem irreducible.ne_zero [semiring α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end lemma irreducible_of_prime [integral_domain α] {p : α} (hp : prime p) : irreducible p := ⟨hp.not_unit, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.div_or_div (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show a ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show b ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [integral_domain α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, _root_.pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.ne_zero, have hpd : p ∣ x * y, from ⟨z, by rwa [domain.mul_right_inj hp0] at h⟩, (hp.div_or_div hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) /-- Two elements of a `monoid` are `associated` if one of them is another one multiplied by a unit on the right. -/ def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, (one_mul _).symm⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin haveI := classical.dec_eq α, rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have : a * 1 = a * (c * d), { simpa [mul_assoc] using a_eq }, have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this, exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩ end lemma exists_associated_mem_of_dvd_prod [integral_domain α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.not_unit]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.div_or_div hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).2 p u hu).resolve_left hp.not_unit with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_semiring α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ mul_unit_dvd_iff.symm lemma dvd_mul_unit_iff [comm_semiring α] {a b : α} {u : units α} : a ∣ b * u ↔ a ∣ b := units.dvd_coe_mul _ _ _ lemma dvd_iff_dvd_of_rel_right [comm_semiring α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ dvd_mul_unit_iff.symm lemma eq_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.ne_zero, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.not_unit ⟨v * u⁻¹, by simp [hv, hu.symm]⟩, hu ▸ by { simp [mul_unit_dvd_iff], intros a b, exact hp.div_or_div }⟩⟩ lemma prime_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv]⟩)⟩ lemma irreducible_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [integral_domain α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), (domain.mul_right_inj ha).1 begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [integral_domain α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ instance [monoid α] : inhabited (associates α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := λa b, ∃c, a * c = b, le_refl := assume a, ⟨1, by simp⟩, le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩} instance : has_dvd (associates α) := ⟨(≤)⟩ @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1 | ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1 theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := ⟨a, one_mul a⟩ theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_semiring variables [comm_semiring α] @[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ @[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 := by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero] @[simp] protected theorem zero_mul : ∀(a : associates α), 0 * a = 0 := by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul] theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated ... ↔ a = 0 : associated_zero_iff_eq_zero a theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d⁻¹) * c, calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one] ... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd def prime (p : associates α) : Prop := p ≠ 0 ∧ p ≠ 1 ∧ (∀a b, p ≤ a * b → p ≤ a ∨ p ≤ b) lemma prime.ne_zero {p : associates α} (hp : prime p) : p ≠ 0 := hp.1 lemma prime.ne_one {p : associates α} (hp : prime p) : p ≠ 1 := hp.2.1 lemma prime.le_or_le {p : associates α} (hp : prime p) {a b : associates α} (h : p ≤ a * b) : p ≤ a ∨ p ≤ b := hp.2.2 a b h lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.ne_one (mul_eq_one_iff.1 eq).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match hp.le_or_le this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [associates.prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_zero_eq] }, apply and_congr, { rw [(≠), ← is_unit_iff_eq_one, is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff] end end comm_semiring section integral_domain variable [integral_domain α] instance : partial_order (associates α) := { le_antisymm := assume a' b', quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩, (quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂, let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in quotient.sound $ associated_of_dvd_dvd (h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) (h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂ .. associates.preorder } instance : order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : order_top (associates α) := { top := 0, le_top := assume a, ⟨0, mul_zero a⟩, .. associates.partial_order } theorem zero_ne_one : (0 : associates α) ≠ 1 := assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl)) (by simp [or_imp_distrib] {contextual := tt}) theorem prod_eq_zero_iff {s : multiset (associates α)} : s.prod = 0 ↔ (0 : associates α) ∈ s := multiset.induction_on s (by simp; exact zero_ne_one.symm) $ assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt} theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp [irreducible, is_unit_mk], apply and_congr iff.rfl, split, { assume h x y eq, have : is_unit (associates.mk x) ∨ is_unit (associates.mk y), from h _ _ (by rw [eq]; refl), simpa [is_unit_mk] }, { refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _), rcases quotient.exact eq.symm with ⟨u, eq⟩, have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ this } end lemma eq_of_mul_eq_mul_left : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, eq_of_mul_eq_mul_left (mt (mk_zero_eq a).2 ha) hu⟩ end lemma le_of_mul_le_mul_left (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (le_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end end integral_domain end associates
3798f5347ea9697dd590fb5111f65886a98a02e2
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/measure_theory/measurable_space.lean
d3e5de8a0f407d7b2bc0f22753f87307393aadce
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
55,134
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 data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice import order.filter.basic /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, measurable function, dynkin system -/ open set encodable function open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (is_measurable' : set α → Prop) (is_measurable_empty : is_measurable' ∅) (is_measurable_compl : ∀ s, is_measurable' s → is_measurable' sᶜ) (is_measurable_Union : ∀ f : ℕ → set α, (∀ i, is_measurable' (f i)) → is_measurable' (⋃ i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable' @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := s.compl_compl ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.bUnion_decode2 [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) (n : ℕ) : is_measurable (⋃ b ∈ decode2 β n, f b) := encodable.Union_decode2_cases is_measurable.empty h lemma is_measurable.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := begin rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union _ (is_measurable.bUnion_decode2 h) end lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma set.finite.is_measurable_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := is_measurable.bUnion hs.countable h lemma finset.is_measurable_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := s.finite_to_set.is_measurable_bUnion h lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := by { rw sUnion_eq_bUnion, exact is_measurable.bUnion hs h } lemma set.finite.is_measurable_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := is_measurable.sUnion hs.countable h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := by { by_cases p; simp [h, hf, is_measurable.empty] } lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := is_measurable.compl_iff.1 $ by { rw compl_Inter, exact is_measurable.Union (λ b, (h b).compl) } lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.compl_iff.1 $ by { rw compl_bInter, exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.is_measurable_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.bInter hs.countable h lemma finset.is_measurable_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := s.finite_to_set.is_measurable_bInter h lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := by { rw sInter_eq_bInter, exact is_measurable.bInter hs h } lemma set.finite.is_measurable_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := is_measurable.sInter hs.countable h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := by { by_cases p; simp [h, hf, is_measurable.univ] } @[simp] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by { rw union_eq_Union, exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀ i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) @[simp] lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by { by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ } end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.is_measurable' ≤ m₂.is_measurable', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable' := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.is_measurable' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable' t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_is_measurable [measurable_space α] : generate_from {s : set α | is_measurable s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, is_measurable_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable' t} = g) : measurable_space α := { is_measurable' := λ s, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @is_measurable α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable' := λ s, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @is_measurable_empty _ ⊥) (λ s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂ m ∈ ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λ m, {s | @is_measurable _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable' ∪ m₂.is_measurable') s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @is_measurable _ m s} s := begin change @is_measurable' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @is_measurable _ (m i) s} s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable' := λ s, m.is_measurable' $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by { rw [preimage_Union], exact m.is_measurable_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable' := λ s, ∃s', m.is_measurable' s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃ i, s' i, m.is_measurable_Union _ (λ i, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥ : measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} : (⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤ : measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀ t ∈ s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) lemma subsingleton.measurable [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable.piecewise {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end /-- this is slightly different from `measurable.piecewise`. It can be used to show `measurable (ite (x=0) 0 1)` by `exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const`, but replacing `measurable.ite` by `measurable.piecewise` in that example proof does not work. -/ lemma measurable.ite {p : α → Prop} {_ : decidable_pred p} {f g : α → β} (hp : is_measurable {a : α | p a}) (hf : measurable f) (hg : measurable g) : measurable (λ x, ite (p x) (f x) (g x)) := measurable.piecewise hp hf hg @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, is_measurable.const (a ∈ s) lemma measurable.indicator [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one [has_one α] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 end measurable_functions section constructions variables [measurable_space α] [measurable_space β] [measurable_space γ] instance : measurable_space empty := ⊤ instance : measurable_space unit := ⊤ instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] {f : β → α} (h : ∀ y, is_measurable (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine is_measurable.Union (λ y, is_measurable.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, is_measurable.empty] } end lemma measurable_unit (f : unit → α) : measurable f := measurable_from_top section nat lemma measurable_from_nat {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat {f : α → ℕ} : (∀ y, is_measurable (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ nat.find_greatest_le lemma measurable_find_greatest {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, is_measurable.const, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl, hN]; try { intros } } end lemma measurable_find {p : α → ℕ → Prop} (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, is_measurable {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), simp only [set.preimage, mem_singleton_iff, nat.find_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, hm, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl]; try { intros } } end end nat section subtype instance {α} {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λ a : α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λ a : s, f a)) (hd : measurable (λ a : t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable_fst : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).1) := measurable_fst.comp hf lemma measurable_snd : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).2) := measurable_snd.comp hf lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λ a, (f a).1)) (hf₂ : measurable (λ a, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λ a, (f a).1) ∧ measurable (λ a, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ lemma measurable.prod_mk {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a, g a)) := measurable.prod hf hg lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ lemma is_measurable.prod {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (s.prod t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) lemma is_measurable_prod_of_nonempty {s : set α} {t : set β} (h : (s.prod t).nonempty) : is_measurable (s.prod t) ↔ is_measurable s ∧ is_measurable t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : is_measurable ((λ x, (x, y)) ⁻¹' s.prod t) := measurable_id.prod_mk measurable_const hst, have : is_measurable (prod.mk x ⁻¹' s.prod t) := measurable_const.prod_mk measurable_id hst, simp * at * end lemma is_measurable_prod {s : set α} {t : set β} : is_measurable (s.prod t) ↔ (is_measurable s ∧ is_measurable t) ∨ s = ∅ ∨ t = ∅ := begin cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, is_measurable_prod_of_nonempty h] } end lemma is_measurable_swap_iff {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ end prod section pi variables {π : δ → Type*} instance measurable_space.pi [m : Π a, measurable_space (π a)] : measurable_space (Π a, π a) := ⨆ a, (m a).comap (λ b, b a) variables [Π a, measurable_space (π a)] [measurable_space γ] lemma measurable_pi_apply (a : δ) : measurable (λ f : Π a, π a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable_pi_lambda (f : α → Π a, π a) (hf : ∀ a, measurable (λ c, f c a)) : measurable f := measurable.of_le_map $ supr_le $ assume a, measurable_space.comap_le_iff_le_map.2 (hf a) lemma is_measurable_pi {s : set δ} {t : Π i : δ, set (π i)} (hs : countable s) (ht : ∀ i ∈ s, is_measurable (t i)) : is_measurable (s.pi t) := begin rw [pi_def], exact is_measurable.bInter hs (λ i hi, measurable_pi_apply _ (ht i hi)) end end pi instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_elim {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (sum.elim f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by { rw [this], exact is_measurable.empty }⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable.univ.inl_image } lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by { rw [this], exact is_measurable.empty }, show is_measurable (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable_inr_image is_measurable.univ } end sum instance {α} {β : α → Type*} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) namespace measurable_equiv variables (α β) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] instance : has_coe_to_fun (measurable_equiv α β) := ⟨λ _, α → β, λ e, e.to_equiv⟩ variables {α β} lemma coe_eq (e : measurable_equiv α β) : (e : α → β) = e.to_equiv := rfl protected lemma measurable (e : measurable_equiv α β) : measurable (e : α → β) := e.measurable_to_fun /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : measurable_equiv α α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } instance : inhabited (measurable_equiv α α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ @[simps] def trans (ab : measurable_equiv α β) (bc : measurable_equiv β γ) : measurable_equiv α γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } /-- The inverse of an equivalence between measurable spaces. -/ @[simps] def symm (ab : measurable_equiv α β) : measurable_equiv β α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : measurable_equiv α β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable_coe_iff {f : β → γ} (e : measurable_equiv α β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λ h, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α × γ) (β × δ) := { to_equiv := equiv.prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := (ab.measurable_to_fun.comp measurable_id.fst).prod_mk (cd.measurable_to_fun.comp measurable_id.snd), measurable_inv_fun := (ab.measurable_inv_fun.comp measurable_id.fst).prod_mk (cd.measurable_inv_fun.comp measurable_id.snd) } /-- Products of measurable spaces are symmetric. -/ def prod_comm : measurable_equiv (α × β) (β × α) := { to_equiv := equiv.prod_comm α β, measurable_to_fun := measurable_id.snd.prod_mk measurable_id.fst, measurable_inv_fun := measurable_id.snd.prod_mk measurable_id.fst } /-- Products of measurable spaces are associative. -/ def prod_assoc : measurable_equiv ((α × β) × γ) (α × (β × γ)) := { to_equiv := equiv.prod_assoc α β γ, measurable_to_fun := measurable_fst.fst.prod_mk $ measurable_fst.snd.prod_mk measurable_snd, measurable_inv_fun := (measurable_fst.prod_mk measurable_snd.fst).prod_mk measurable_snd.snd } /-- Sums of measurable spaces are symmetric. -/ def sum_congr (ab : measurable_equiv α β) (cd : measurable_equiv γ δ) : measurable_equiv (α ⊕ γ) (β ⊕ δ) := { to_equiv := equiv.sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod (s : set α) (t : set β) : measurable_equiv (s.prod t) (s × t) := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable_id.subtype_coe.fst.subtype_mk.prod_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable_id.fst.subtype_coe.prod_mk measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : measurable_equiv (univ : set α) α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton (a : α) : measurable_equiv ({a} : set α) unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image (f : α → β) (s : set α) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : measurable_equiv s (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, equiv.set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range (f : α → β) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : measurable_equiv α (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl : measurable_equiv (range sum.inl : set (α ⊕ β)) α := { to_fun := λ ab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ a, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr : measurable_equiv (range sum.inr : set (α ⊕ β)) β := { to_fun := λ ab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ b, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv ((α ⊕ β) × γ) ((α × γ) ⊕ (β × γ)) := { to_equiv := equiv.sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp measurable_fst).prod_mk measurable_snd) ((measurable_inr.comp measurable_fst).prod_mk measurable_snd) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : measurable_equiv (α × (β ⊕ γ)) ((α × β) ⊕ (α × γ)) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : measurable_equiv ((α ⊕ β) × (γ ⊕ δ)) (((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ))) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_is_measurable [measurable_space α] : is_pi_system {s : set α | is_measurable s} := λ s t hs ht _, hs.inter ht /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable', has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable' := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀ n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃ n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).is_measurable' s := generate_le (of_measurable_space (generate_from C)) (λ t, is_measurable_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, is_measurable_generate_from ht) }) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, is_measurable t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, is_measurable (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, is_measurable t → C t := have eq : is_measurable = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, is_measurable t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot_sets, is_measurable.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem_sets, is_measurable.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, is_measurable s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, ht⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf_sets hs'f hs'g, hmf.inter hmg, _⟩, exact subset.trans (inter_subset_inter hs'sf hs'sg) ht end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ is_measurable s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ is_measurable.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi_iff] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, hVs⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi_iff], refine ⟨t, ht, U, hUf, subset.refl _⟩ }, { haveI := ht.countable.to_encodable, refine is_measurable.Inter (λ i, (hU i).1) }, { exact subset.trans (Inter_subset_Inter $ λ i, (hU i).2) hVs } end end filter /-- We say that a collection of sets is countably spanning if a countable subset spans the whole type. This is a useful condition in various parts of measure theory. For example, it is a needed condition to show that the product of two collections generate the product sigma algebra, see `generate_from_prod_eq`. -/ def is_countably_spanning (C : set (set α)) : Prop := ∃ (s : ℕ → set α), (∀ n, s n ∈ C) ∧ (⋃ n, s n) = univ lemma is_countably_spanning_is_measurable [measurable_space α] : is_countably_spanning {s : set α | is_measurable s} := ⟨λ _, univ, λ _, is_measurable.univ, Union_const _⟩
20a313ab865f89e60ca7281dc5287300656647ad
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/field_theory/finite/basic.lean
9d2fbf9e1ecfb3b6efe303206d67be998bb48b8a
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,771
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Joey van Langen, Casper Putz -/ import tactic.apply_fun import data.equiv.ring import data.zmod.algebra import linear_algebra.finite_dimensional import ring_theory.integral_domain import field_theory.separable import field_theory.splitting_field /-! # Finite fields This file contains basic results about finite fields. Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. See `ring_theory.integral_domain` for the fact that the unit group of a finite field is a cyclic group, as well as the fact that every finite integral domain is a field (`field_of_integral_domain`). ## Main results 1. `card_units`: The unit group of a finite field is has cardinality `q - 1`. 2. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is - `q-1` if `q-1 ∣ i` - `0` otherwise 3. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`. See `card'` for a variant. ## Notation Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. -/ variables {K : Type*} [field K] [fintype K] variables {R : Type*} [comm_ring R] [integral_domain R] local notation `q` := fintype.card K open_locale big_operators namespace finite_field open finset function section polynomial open polynomial /-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n` polynomial -/ lemma card_image_polynomial_eval [decidable_eq R] [fintype R] {p : polynomial R} (hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card := finset.card_le_mul_card_image _ _ (λ a _, calc _ = (p - C a).roots.to_finset.card : congr_arg card (by simp [finset.ext_iff, mem_roots_sub_C hp]) ... ≤ (p - C a).roots.card : multiset.to_finset_card_le _ ... ≤ _ : card_roots_sub_C' hp) /-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/ lemma exists_root_sum_quadratic [fintype R] {f g : polynomial R} (hf2 : degree f = 2) (hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 := by letI := classical.dec_eq R; exact suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))), begin simp only [disjoint_left, mem_image] at this, push_neg at this, rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩, exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩ end, assume hd : disjoint _ _, lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $ calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card ≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_univ _) ... = fintype.card R + fintype.card R : two_mul _ ... < nat_degree f * (univ.image (λ x : R, eval x f)).card + nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card : add_lt_add_of_lt_of_le (lt_of_le_of_ne (card_image_polynomial_eval (by rw hf2; exact dec_trivial)) (mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR]))) (card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial)) ... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card : by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2, nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add] end polynomial lemma card_units : fintype.card (units K) = fintype.card K - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : K)⟩)], haveI := set_fintype {a : K | a ≠ 0}, haveI := set_fintype (@set.univ K), rw [fintype.card_congr (equiv.units_equiv_ne_zero _), ← @set.card_insert _ _ {a : K | a ≠ 0} _ (not_not.2 (eq.refl (0 : K))) (set.fintype_insert _ _), fintype.card_congr (equiv.set.univ K).symm], congr; simp [set.ext_iff, classical.em] end lemma prod_univ_units_id_eq_neg_one : (∏ x : units K, x) = (-1 : units K) := begin classical, have : (∏ x in (@univ (units K) _).erase (-1), x) = 1, from prod_involution (λ x _, x⁻¹) (by simp) (λ a, by simp [units.inv_eq_self_iff] {contextual := tt}) (λ a, by simp [@inv_eq_iff_inv_eq _ _ a, eq_comm] {contextual := tt}) (by simp), rw [← insert_erase (mem_univ (-1 : units K)), prod_insert (not_mem_erase _ _), this, mul_one] end lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (q - 1) = 1 := calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : units K) : by rw [units.coe_pow, units.coe_mk0] ... = 1 : by { classical, rw [← card_units, pow_card_eq_one], refl } lemma pow_card (a : K) : a ^ q = a := begin have hp : 0 < fintype.card K := lt_trans zero_lt_one fintype.one_lt_card, by_cases h : a = 0, { rw h, apply zero_pow hp }, rw [← nat.succ_pred_eq_of_pos hp, pow_succ, nat.pred_eq_sub_one, pow_card_sub_one_eq_one a h, mul_one], end lemma pow_card_pow (n : ℕ) (a : K) : a ^ q ^ n = a := begin induction n with n ih, { simp, }, { simp [pow_succ, pow_mul, ih, pow_card], }, end variable (K) theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := begin haveI hp : fact p.prime := ⟨char_p.char_is_prime K p⟩, letI : module (zmod p) K := { .. (zmod.cast_hom dvd_rfl K).to_module }, obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K, rw zmod.card at h, refine ⟨⟨n, _⟩, hp.1, h⟩, apply or.resolve_left (nat.eq_zero_or_pos n), rintro rfl, rw pow_zero at h, have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) }, exact absurd this zero_ne_one, end theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩ @[simp] lemma cast_card_eq_zero : (q : K) = 0 := begin rcases char_p.exists K with ⟨p, _char_p⟩, resetI, rcases card K p with ⟨n, hp, hn⟩, simp only [char_p.cast_eq_zero_iff K p, hn], conv { congr, rw [← pow_one p] }, exact pow_dvd_pow _ n.2, end lemma forall_pow_eq_one_iff (i : ℕ) : (∀ x : units K, x ^ i = 1) ↔ q - 1 ∣ i := begin obtain ⟨x, hx⟩ := is_cyclic.exists_generator (units K), classical, rw [← card_units, ← order_of_eq_card_of_forall_mem_gpowers hx, order_of_dvd_iff_pow_eq_one], split, { intro h, apply h }, { intros h y, simp_rw ← mem_powers_iff_mem_gpowers at hx, rcases hx y with ⟨j, rfl⟩, rw [← pow_mul, mul_comm, pow_mul, h, one_pow], } end /-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q` is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/ lemma sum_pow_units (i : ℕ) : ∑ x : units K, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 := begin let φ : units K →* K := { to_fun := λ x, x ^ i, map_one' := by rw [units.coe_one, one_pow], map_mul' := by { intros, rw [units.coe_mul, mul_pow] } }, haveI : decidable (φ = 1), { classical, apply_instance }, calc ∑ x : units K, φ x = if φ = 1 then fintype.card (units K) else 0 : sum_hom_units φ ... = if (q - 1) ∣ i then -1 else 0 : _, suffices : (q - 1) ∣ i ↔ φ = 1, { simp only [this], split_ifs with h h, swap, refl, rw [card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub], show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ }, rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff], apply forall_congr, intro x, rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply], refl, end /-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q` is equal to `0` if `i < q - 1`. -/ lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) : ∑ x : K, x ^ i = 0 := begin by_cases hi : i = 0, { simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], }, classical, have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h }, let φ : units K ↪ K := ⟨coe, units.ext⟩, have : univ.map φ = univ \ {0}, { ext x, simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero, mem_univ, mem_map, exists_prop_of_true, mem_singleton] }, calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i : by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton, zero_pow (nat.pos_of_ne_zero hi), add_zero] ... = ∑ x : units K, x ^ i : by { rw [← this, univ.sum_map φ], refl } ... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, } end section is_splitting_field open polynomial section variables (K' : Type*) [field K'] {p n : ℕ} lemma X_pow_card_sub_X_nat_degree_eq (hp : 1 < p) : (X ^ p - X : polynomial K').nat_degree = p := begin have h1 : (X : polynomial K').degree < (X ^ p : polynomial K').degree, { rw [degree_X_pow, degree_X], exact_mod_cast hp }, rw [nat_degree_eq_of_degree_eq (degree_sub_eq_left_of_degree_lt h1), nat_degree_X_pow], end lemma X_pow_card_pow_sub_X_nat_degree_eq (hn : n ≠ 0) (hp : 1 < p) : (X ^ p ^ n - X : polynomial K').nat_degree = p ^ n := X_pow_card_sub_X_nat_degree_eq K' $ nat.one_lt_pow _ _ (nat.pos_of_ne_zero hn) hp lemma X_pow_card_sub_X_ne_zero (hp : 1 < p) : (X ^ p - X : polynomial K') ≠ 0 := ne_zero_of_nat_degree_gt $ calc 1 < _ : hp ... = _ : (X_pow_card_sub_X_nat_degree_eq K' hp).symm lemma X_pow_card_pow_sub_X_ne_zero (hn : n ≠ 0) (hp : 1 < p) : (X ^ p ^ n - X : polynomial K') ≠ 0 := X_pow_card_sub_X_ne_zero K' $ nat.one_lt_pow _ _ (nat.pos_of_ne_zero hn) hp end variables (p : ℕ) [fact p.prime] [char_p K p] lemma roots_X_pow_card_sub_X : roots (X^q - X : polynomial K) = finset.univ.val := begin classical, have aux : (X^q - X : polynomial K) ≠ 0 := X_pow_card_sub_X_ne_zero K fintype.one_lt_card, have : (roots (X^q - X : polynomial K)).to_finset = finset.univ, { rw eq_univ_iff_forall, intro x, rw [multiset.mem_to_finset, mem_roots aux, is_root.def, eval_sub, eval_pow, eval_X, sub_eq_zero, pow_card] }, rw [←this, multiset.to_finset_val, eq_comm, multiset.erase_dup_eq_self], apply nodup_roots, rw separable_def, convert is_coprime_one_right.neg_right, rw [derivative_sub, derivative_X, derivative_X_pow, ←C_eq_nat_cast, C_eq_zero.mpr (char_p.cast_card_eq_zero K), zero_mul, zero_sub], end instance : is_splitting_field (zmod p) K (X^q - X) := { splits := begin have h : (X^q - X : polynomial K).nat_degree = q := X_pow_card_sub_X_nat_degree_eq K fintype.one_lt_card, rw [←splits_id_iff_splits, splits_iff_card_roots, map_sub, map_pow, map_X, h, roots_X_pow_card_sub_X K, ←finset.card_def, finset.card_univ], end, adjoin_roots := begin classical, transitivity algebra.adjoin (zmod p) ((roots (X^q - X : polynomial K)).to_finset : set K), { simp only [map_pow, map_X, map_sub], convert rfl }, { rw [roots_X_pow_card_sub_X, val_to_finset, coe_univ, algebra.adjoin_univ], } end } end is_splitting_field variables {K} theorem frobenius_pow {p : ℕ} [fact p.prime] [char_p K p] {n : ℕ} (hcard : q = p^n) : (frobenius K p) ^ n = 1 := begin ext, conv_rhs { rw [ring_hom.one_def, ring_hom.id_apply, ← pow_card x, hcard], }, clear hcard, induction n, {simp}, rw [pow_succ, pow_succ', pow_mul, ring_hom.mul_def, ring_hom.comp_apply, frobenius_def, n_ih] end open polynomial lemma expand_card (f : polynomial K) : expand K q f = f ^ q := begin cases char_p.exists K with p hp, letI := hp, rcases finite_field.card K p with ⟨⟨n, npos⟩, ⟨hp, hn⟩⟩, haveI : fact p.prime := ⟨hp⟩, dsimp at hn, rw hn at *, rw ← map_expand_pow_char, rw [frobenius_pow hn, ring_hom.one_def, map_id], end end finite_field namespace zmod open finite_field polynomial lemma sq_add_sq (p : ℕ) [hp : fact p.prime] (x : zmod p) : ∃ a b : zmod p, a^2 + b^2 = x := begin cases hp.1.eq_two_or_odd with hp2 hp_odd, { substI p, change fin 2 at x, fin_cases x, { use 0, simp }, { use [0, 1], simp } }, let f : polynomial (zmod p) := X^2, let g : polynomial (zmod p) := X^2 - C x, obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 := @exists_root_sum_quadratic _ _ _ _ f g (degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]), refine ⟨a, b, _⟩, rw ← sub_eq_zero, simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab, end end zmod namespace char_p lemma sq_add_sq (R : Type*) [comm_ring R] [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) : ∃ a b : ℕ, (a^2 + b^2 : R) = x := begin haveI := char_is_prime_of_pos R p, obtain ⟨a, b, hab⟩ := zmod.sq_add_sq p x, refine ⟨a.val, b.val, _⟩, simpa using congr_arg (zmod.cast_hom dvd_rfl R) hab end end char_p open_locale nat open zmod /-- The **Fermat-Euler totient theorem**. `nat.modeq.pow_totient` is an alternative statement of the same theorem. -/ @[simp] lemma zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ φ n = 1 := by rw [← card_units_eq_totient, pow_card_eq_one] /-- The **Fermat-Euler totient theorem**. `zmod.pow_totient` is an alternative statement of the same theorem. -/ lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] := begin cases n, {simp}, rw ← zmod.eq_iff_modeq_nat, let x' : units (zmod (n+1)) := zmod.unit_of_coprime _ h, have := zmod.pow_totient x', apply_fun (coe : units (zmod (n+1)) → zmod (n+1)) at this, simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one, nat.cast_one, coe_unit_of_coprime, units.coe_pow], end section variables {V : Type*} [add_comm_group V] [module K V] -- should this go in a namespace? -- finite_dimensional would be natural, -- but we don't assume it... lemma card_eq_pow_finrank [fintype V] : fintype.card V = q ^ (finite_dimensional.finrank K V) := begin let b := is_noetherian.finset_basis K V, rw [module.card_fintype b, ← finite_dimensional.finrank_eq_card_basis b], end end open finite_field namespace zmod /-- A variation on Fermat's little theorem. See `zmod.pow_card_sub_one_eq_one` -/ @[simp] lemma pow_card {p : ℕ} [fact p.prime] (x : zmod p) : x ^ p = x := by { have h := finite_field.pow_card x, rwa zmod.card p at h } @[simp] lemma pow_card_pow {n p : ℕ} [fact p.prime] (x : zmod p) : x ^ p ^ n = x := begin induction n with n ih, { simp, }, { simp [pow_succ, pow_mul, ih, pow_card], }, end @[simp] lemma frobenius_zmod (p : ℕ) [fact p.prime] : frobenius (zmod p) p = ring_hom.id _ := by { ext a, rw [frobenius_def, zmod.pow_card, ring_hom.id_apply] } @[simp] lemma card_units (p : ℕ) [fact p.prime] : fintype.card (units (zmod p)) = p - 1 := by rw [card_units, card] /-- **Fermat's Little Theorem**: for every unit `a` of `zmod p`, we have `a ^ (p - 1) = 1`. -/ theorem units_pow_card_sub_one_eq_one (p : ℕ) [fact p.prime] (a : units (zmod p)) : a ^ (p - 1) = 1 := by rw [← card_units p, pow_card_eq_one] /-- **Fermat's Little Theorem**: for all nonzero `a : zmod p`, we have `a ^ (p - 1) = 1`. -/ theorem pow_card_sub_one_eq_one {p : ℕ} [fact p.prime] {a : zmod p} (ha : a ≠ 0) : a ^ (p - 1) = 1 := by { have h := pow_card_sub_one_eq_one a ha, rwa zmod.card p at h } open polynomial lemma expand_card {p : ℕ} [fact p.prime] (f : polynomial (zmod p)) : expand (zmod p) p f = f ^ p := by { have h := finite_field.expand_card f, rwa zmod.card p at h } end zmod
5347a512a76a2fa732abb34000d02465842a1a2e
5fbbd711f9bfc21ee168f46a4be146603ece8835
/lean/natural_number_game/inequality/11.lean
7b4f644b4146e617f060b25e70d15aa8f0d3c023
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
goedel-gang/maths
22596f71e3fde9c088e59931f128a3b5efb73a2c
a20a6f6a8ce800427afd595c598a5ad43da1408d
refs/heads/master
1,623,055,941,960
1,621,599,441,000
1,621,599,441,000
169,335,840
0
0
null
null
null
null
UTF-8
Lean
false
false
154
lean
theorem add_le_add_right (a b : mynat) : a ≤ b → ∀ t, (a + t) ≤ (b + t) := begin intros h t, cases h with n hn, use n, rw hn, ring, end
6c78876cfc04b8e16998c39021579cb4369de0f4
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Init/Data.lean
082afdbc402819a5c5432a693b4562f61f1bb77d
[ "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
671
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.Data.Basic import Init.Data.Nat import Init.Data.Char import Init.Data.String import Init.Data.List import Init.Data.Int import Init.Data.Array import Init.Data.ByteArray import Init.Data.FloatArray import Init.Data.Fin import Init.Data.UInt import Init.Data.Float import Init.Data.Option import Init.Data.Ord import Init.Data.Random import Init.Data.ToString import Init.Data.Range import Init.Data.Hashable import Init.Data.OfScientific import Init.Data.Format import Init.Data.Stream
d9aa2b3983c0d3618bc6908463a146d701d1a371
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/set_theory/ordinal_arithmetic.lean
433a5613d02ddd489016ed32bea5fb60809e6609
[ "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
70,453
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.ordinal /-! # Ordinal arithmetic Ordinals have an addition (corresponding to disjoint union) that turns them into an additive monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns them into a monoid. One can also define correspondingly a subtraction, a division, a successor function, a power function and a logarithm function. We also define limit ordinals and prove the basic induction principle on ordinals separating successor ordinals and limit ordinals, in `limit_rec_on`. ## Main definitions and results * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. * `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`. * `o₁ * o₂` is the lexicographic order on `o₂ × o₁`. * `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the divisibility predicate, and a modulo operation. * `succ o = o + 1` is the successor of `o`. * `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`. We also define the power function and the logarithm function on ordinals, and discuss the properties of casts of natural numbers of and of `omega` with respect to these operations. Some properties of the operations are also used to discuss general tools on ordinals: * `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor. * `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. * `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. * `nfp f a`: the next fixed point of a function `f` on ordinals, above `a`. It behaves well for normal functions. * `CNF b o` is the Cantor normal form of the ordinal `o` in base `b`. * `sup`: the supremum of an indexed family of ordinals in `Type u`, as an ordinal in `Type u`. * `bsup`: the supremum of a set of ordinals indexed by ordinals less than a given ordinal `o`. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} namespace ordinal /-! ### Further properties of addition on ordinals -/ @[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) := by unfold succ; simp only [lift_add, lift_one] theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c := ⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨ have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a, by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply] using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂) ((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a, have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin intro b, cases e : f (sum.inr b), { rw ← fl at e, have := f.inj' e, contradiction }, { exact ⟨_, rfl⟩ } end, let g (b) := (this b).1 in have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2, ⟨⟨⟨g, λ x y h, by injection f.inj' (by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩, λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding, initial_seg.coe_fn_to_rel_embedding, function.embedding.coe_fn_mk] using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩, λ a b H, begin rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩, { rw fl at h, cases h }, { rw fr at h, exact ⟨a', sum.inr.inj h⟩ } end⟩⟩, λ h, add_le_add_left h _⟩ theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) := (add_assoc _ _ _).symm @[simp] theorem succ_zero : succ 0 = 1 := zero_add _ theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o := by rw [← succ_zero, succ_le] theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 := by rw [one_le_iff_pos, ordinal.pos_iff_ne_zero] theorem succ_pos (o : ordinal) : 0 < succ o := lt_of_le_of_lt (ordinal.zero_le _) (lt_succ_self _) theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 := ne_of_gt $ succ_pos o @[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 := by simp only [succ, card_add, card_one] theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c := by simp only [le_antisymm_iff, add_le_add_iff_left] theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b := by rw [← not_le, succ_le, not_lt] theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c := by rw [← not_le, ← not_le, add_le_add_iff_left] theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c := lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _) @[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b := by rw [lt_succ, succ_le] @[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 succ_lt_succ theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b := by simp only [le_antisymm_iff, succ_le_succ] theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b := by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero], rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]] theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b := by simp only [le_antisymm_iff, add_le_add_iff_right] /-! ### The zero ordinal -/ @[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 := ⟨induction_on o $ λ α r _ h, begin refine le_antisymm (le_of_not_lt $ λ hn, mk_ne_zero_iff.2 _ h) (ordinal.zero_le _), rw [← succ_le, succ_zero] at hn, cases hn with f, exact ⟨f punit.star⟩ end, λ e, by simp only [e, card_zero]⟩ @[simp] theorem type_eq_zero_of_empty [is_well_order α r] [is_empty α] : type r = 0 := card_eq_zero.symm.mpr (mk_eq_zero _) @[simp] theorem type_eq_zero_iff_is_empty [is_well_order α r] : type r = 0 ↔ is_empty α := (@card_eq_zero (type r)).symm.trans mk_eq_zero_iff theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α := (not_congr (@card_eq_zero (type r))).symm.trans mk_ne_zero_iff protected lemma one_ne_zero : (1 : ordinal) ≠ 0 := type_ne_zero_iff_nonempty.2 ⟨punit.star⟩ instance : nontrivial ordinal.{u} := ⟨⟨1, 0, ordinal.one_ne_zero⟩⟩ theorem zero_lt_one : (0 : ordinal) < 1 := lt_iff_le_and_ne.2 ⟨ordinal.zero_le _, ne.symm $ ordinal.one_ne_zero⟩ /-! ### The predecessor of an ordinal -/ /-- The ordinal predecessor of `o` is `o'` if `o = succ o'`, and `o` otherwise. -/ def pred (o : ordinal.{u}) : ordinal.{u} := if h : ∃ a, o = succ a then classical.some h else o @[simp] theorem pred_succ (o) : pred (succ o) = o := by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩; simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm theorem pred_le_self (o) : pred o ≤ o := if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _) else by rw [pred, dif_neg h] theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a := ⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e, λ h, dif_neg h⟩ theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a := iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le]) (iff_not_comm.1 pred_eq_iff_not_succ).symm theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a := ⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩ theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o := ⟨lt_trans (lt_succ_self _), λ l, lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩ theorem lt_pred {a b} : a < pred b ↔ succ a < b := if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in by rw [e, pred_succ, succ_lt_succ] else by simp only [pred, dif_neg h, succ_lt_of_not_succ h] theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b := le_iff_le_iff_lt_iff_lt.2 lt_pred @[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) := ⟨λ ⟨a, h⟩, let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $ h.symm ▸ lt_succ_self _ in ⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩, λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩ @[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) := if h : ∃ a, o = succ a then by cases h with a e; simp only [e, pred_succ, lift_succ] else by rw [pred_eq_iff_not_succ.2 h, pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)] /-! ### Limit ordinals -/ /-- A limit ordinal is an ordinal which is not zero and not a successor. -/ def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o theorem not_zero_is_limit : ¬ is_limit 0 | ⟨h, _⟩ := h rfl theorem not_succ_is_limit (o) : ¬ is_limit (succ o) | ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _)) theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a | ⟨a, e⟩ := not_succ_is_limit a (e ▸ h) theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o := ⟨lt_trans (lt_succ_self _), h.2 _⟩ theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a := le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a := ⟨λ h x l, le_trans (le_of_lt l) h, λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn, not_lt_of_le (H _ hn) (lt_succ_self _)⟩ theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x := by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a) @[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o := and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0) ⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h), λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in by rw [← e, ← lift_succ, lift_lt]; rw [← e, lift_lt] at h; exact H a' h⟩ theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o := lt_of_le_of_ne (ordinal.zero_le _) h.1.symm theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o := by simpa only [succ_zero] using h.2 _ h.pos theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := h.pos | (n+1) := h.2 _ (is_limit.nat_lt n) theorem zero_or_succ_or_limit (o : ordinal) : o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o := if o0 : o = 0 then or.inl o0 else if h : ∃ a, o = succ a then or.inr (or.inl h) else or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ /-- Main induction principle of ordinals: if one can prove a property by induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/ @[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*} (o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o)) (H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o := wf.fix (λ o IH, if o0 : o = 0 then by rw o0; exact H₁ else if h : ∃ a, o = succ a then by rw ← succ_pred_iff_is_succ.2 h; exact H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h) else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o @[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ := by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl @[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) : @limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) := begin have h : ∃ a, succ o = succ a := ⟨_, rfl⟩, rw [limit_rec_on, well_founded.fix_eq, dif_neg (succ_ne_zero o), dif_pos h], generalize : limit_rec_on._proof_2 (succ o) h = h₂, generalize : limit_rec_on._proof_3 (succ o) h = h₃, revert h₂ h₃, generalize e : pred (succ o) = o', intros, rw pred_succ at e, subst o', refl end @[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) : @limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) := by rw [limit_rec_on, well_founded.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r] (h : (type r).is_limit) (x : α) : ∃y, r x y := begin use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)), convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein] end lemma type_subrel_lt (o : ordinal.{u}) : type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u+1} o := begin refine quotient.induction_on o _, rintro ⟨α, r, wo⟩, resetI, apply quotient.sound, constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (typein_iso r) end lemma mk_initial_seg (o : ordinal.{u}) : #{o' : ordinal | o' < o} = cardinal.lift.{u+1} o.card := by rw [lift_card, ←type_subrel_lt, card_type] /-! ### Normal ordinal functions -/ /-- A normal ordinal function is a strictly increasing function which is order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for `a < o`. -/ def is_normal (f : ordinal → ordinal) : Prop := (∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o → ∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2 theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} : a < f o ↔ ∃ b < o, a < f b := not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b := strict_mono.lt_iff_lt $ λ a b, limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _)) (λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim (λ h, lt_trans (IH h) (H.1 _)) (λ e, e ▸ H.1 _)) (λ b l IH h, lt_of_lt_of_le (H.1 a) ((H.2 _ l _).1 (le_refl _) _ (l.2 _ h))) theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_iff theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b := by simp only [le_antisymm_iff, H.le_iff] theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a := limit_rec_on a (ordinal.zero_le _) (λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _)) (λ a l IH, (limit_le l).2 $ λ b h, le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h) theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f a ≤ o := ⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h, λ h, begin revert H₂, apply limit_rec_on S, { intro H₂, cases p0 with x px, have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px), rw this at px, exact h _ px }, { intros S _ H₂, rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) }, { intros S L _ H₂, apply (H.2 _ L _).2, intros a h', rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩, exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) } end⟩ theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal) (p0 : ∃ x, p x) (S) (H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} : f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o := (H.le_set (λ x, ∃ y, p y ∧ x = g y) (let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _ (λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1, λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans ⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩ theorem is_normal.refl : is_normal id := ⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩ theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (λ x, f (g x)) := ⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩ theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) := ⟨ne_of_gt $ lt_of_le_of_lt (ordinal.zero_le _) $ H.lt_iff.2 l.pos, λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩ theorem add_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c := ⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin resetI, suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l), { cases enum _ _ l with x x, { cases this (enum s 0 h.pos) }, { exact irrefl _ (this _) } }, intros x, rw [← typein_lt_typein (sum.lex r s), typein_enum], have := H _ (h.2 _ (typein_lt_type s x)), rw [add_succ, succ_le] at this, refine lt_of_le_of_lt (type_le'.2 ⟨rel_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this, { rcases a with ⟨a | b, h⟩, { exact sum.inl a }, { exact sum.inr ⟨b, by cases h; assumption⟩ } }, { rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂; rintro ⟨⟩; constructor; assumption } end) h H⟩ theorem add_is_normal (a : ordinal) : is_normal ((+) a) := ⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _), λ b l c, add_le_of_limit l⟩ theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) := (add_is_normal a).is_limit /-! ### Subtraction on ordinals-/ /-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/ def sub (a b : ordinal.{u}) : ordinal.{u} := omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩ instance : has_sub ordinal := ⟨sub⟩ theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) := omin_mem {o | a ≤ b+o} _ theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c := ⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _), λ h, omin_le h⟩ theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le sub_le theorem add_sub_cancel (a b : ordinal) : a + b - a = b := le_antisymm (sub_le.2 $ le_refl _) ((add_le_add_iff_left a).1 $ le_add_sub _ _) theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b := h ▸ add_sub_cancel _ _ theorem sub_le_self (a b : ordinal) : a - b ≤ a := sub_le.2 $ le_add_left _ _ protected theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a := le_antisymm begin rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l, { simp only [e, add_zero, h] }, { rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self }, { exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) } end (le_add_sub _ _) @[simp] theorem sub_zero (a : ordinal) : a - 0 = a := by simpa only [zero_add] using add_sub_cancel 0 a @[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 := by rw ← ordinal.le_zero; apply sub_le_self @[simp] theorem sub_self (a : ordinal) : a - a = 0 := by simpa only [add_zero] using add_sub_cancel a 0 protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b := ⟨λ h, by simpa only [h, add_zero] using le_add_sub a b, λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩ theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) := eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c := by rw [← sub_sub, add_sub_cancel] theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) := ⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero, λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩ @[simp] theorem one_add_omega : 1 + omega.{u} = omega := begin refine le_antisymm _ (le_add_left _ _), rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add], have : is_well_order unit empty_relation := by apply_instance, refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩, { apply sum.rec, exact λ _, 0, exact nat.succ }, { intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H; [cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] } end @[simp, priority 990] theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o := by rw [← ordinal.add_sub_cancel_of_le h, ← add_assoc, one_add_omega] /-! ### Multiplication of ordinals-/ /-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on `o₂ × o₁`. -/ instance : monoid ordinal.{u} := { mul := λ a b, quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.prod_lex_congr g f⟩, one := 1, mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin rcases a with ⟨⟨a₁, a₂⟩, a₃⟩, rcases b with ⟨⟨b₁, b₂⟩, b₃⟩, simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc] end⟩⟩, mul_one := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩; simp only [prod.lex_def, empty_relation, false_or]; simp only [eq_self_iff_true, true_and]; refl⟩⟩, one_mul := λ a, induction_on a $ λ α r _, quotient.sound ⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩; simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ } @[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl @[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans (rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _) (rel_iso.preimage equiv.ulift _)).symm⟩ @[simp] theorem card_mul (a b) : card (a * b) = card a * card b := quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, mul_comm (mk β) (mk α) @[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty @[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 := induction_on a $ λ α _ _, by exactI type_eq_zero_of_empty theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def, sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr, sum_prod_distrib_apply_left, sum_prod_distrib_apply_right]; simp only [sum.inl.inj_iff, true_or, false_and, false_or] end⟩⟩ @[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a := by simp only [mul_add, mul_one] @[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _ theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, (f a.1, a.2)) (λ a b h, _)⟩, clear_, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') }, { exact prod.lex.right _ h' } end theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c := quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin resetI, refine type_le'.2 ⟨rel_embedding.of_monotone (λ a, (a.1, f a.2)) (λ a b h, _)⟩, cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h', { exact prod.lex.left _ _ h' }, { exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') } end theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d := le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁) private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s] {c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c) (l : c < type r * type s) : false := begin suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l), { cases enum _ _ l with b a, exact irrefl _ (this _ _) }, intros a b, rw [← typein_lt_typein (prod.lex s r), typein_enum], have := H _ (h.2 _ (typein_lt_type s b)), rw [mul_succ] at this, have := lt_of_lt_of_le ((add_lt_add_iff_left _).2 (typein_lt_type _ a)) this, refine lt_of_le_of_lt _ this, refine (type_le'.2 _), constructor, refine rel_embedding.of_monotone (λ a, _) (λ a b, _), { rcases a with ⟨⟨b', a'⟩, h⟩, by_cases e : b = b', { refine sum.inr ⟨a', _⟩, subst e, cases h with _ _ _ _ h _ _ _ h, { exact (irrefl _ h).elim }, { exact h } }, { refine sum.inl (⟨b', _⟩, a'), cases h with _ _ _ _ h _ _ _ h, { exact h }, { exact (e rfl).elim } } }, { rcases a with ⟨⟨b₁, a₁⟩, h₁⟩, rcases b with ⟨⟨b₂, a₂⟩, h₂⟩, intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂, { substs b₁ b₂, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h }, { subst b₁, simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢, cases h₂; [exact asymm h h₂_h, exact e₂ rfl] }, { simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] }, { simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } } end theorem mul_le_of_limit {a b c : ordinal.{u}} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c := ⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h, λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _, by exactI mul_le_of_limit_aux) h H⟩ theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) := ⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h, λ b l c, mul_le_of_limit l⟩ theorem lt_mul_of_limit {a b c : ordinal.{u}} (h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' := by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h) theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c := (mul_is_normal a0).lt_iff theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c := (mul_is_normal a0).le_iff theorem mul_lt_mul_of_pos_left {a b c : ordinal} (h : a < b) (c0 : 0 < c) : c * a < c * b := (mul_lt_mul_iff_left c0).2 h theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b := by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁ theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 := by simpa only [ordinal.pos_iff_ne_zero] using mul_pos theorem le_of_mul_le_mul_left {a b c : ordinal} (h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b := le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c := (mul_is_normal a0).inj theorem mul_is_limit {a b : ordinal} (a0 : 0 < a) : is_limit b → is_limit (a * b) := (mul_is_normal a0).is_limit theorem mul_is_limit_left {a b : ordinal} (l : is_limit a) (b0 : 0 < b) : is_limit (a * b) := begin rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb, { exact (lt_irrefl _).elim b0 }, { rw mul_succ, exact add_is_limit _ l }, { exact mul_is_limit l.pos lb } end /-! ### Division on ordinals -/ protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} := ⟨a, succ_le.1 $ by simpa only [succ_zero, one_mul] using mul_le_mul_right (succ a) (succ_le.2 (ordinal.pos_iff_ne_zero.2 h))⟩ /-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/ protected def div (a b : ordinal.{u}) : ordinal.{u} := if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h) instance : has_div ordinal := ⟨ordinal.div⟩ @[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl lemma div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) := by rw div_def a h; exact omin_mem {o | a < b * succ o} _ theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b := by simpa only [mul_succ] using lt_mul_succ_div a h theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c := ⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h), λ h, by rw div_def a b0; exact omin_le h⟩ theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b := by rw [← not_le, div_le c0, not_lt] theorem le_div {a b c : ordinal} (c0 : c ≠ 0) : a ≤ b / c ↔ c * a ≤ b := begin apply limit_rec_on a, { simp only [mul_zero, ordinal.zero_le] }, { intros, rw [succ_le, lt_div c0] }, { simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} } end theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) : a / b < c ↔ a < b * c := lt_iff_lt_of_le_iff_le $ le_div b0 theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c := if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else (div_le b0).2 $ lt_of_le_of_lt h $ mul_lt_mul_of_pos_left (lt_succ_self _) (ordinal.pos_iff_ne_zero.2 b0) theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b := lt_imp_lt_of_le_imp_le div_le_of_le_mul @[simp] theorem zero_div (a : ordinal) : 0 / a = 0 := ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _ theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a := if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 (le_refl _) theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b := begin apply le_antisymm, { apply (div_le b0).2, rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left], apply lt_mul_div_add _ b0 }, { rw [le_div b0, mul_add, add_le_add_iff_left], apply mul_div_le } end theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 := begin rw [← ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ lt_of_le_of_lt (ordinal.zero_le _) h], simpa only [succ_zero, mul_one] using h end @[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a := by simpa only [add_zero, zero_div] using mul_add_div a b0 0 @[simp] theorem div_one (a : ordinal) : a / 1 = a := by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero @[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 := by simpa only [mul_one] using mul_div_cancel 1 h theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c := if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else eq_of_forall_ge_iff $ λ d, by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0] theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) := begin split; intro h, { by_cases h' : b = 0, { rw [h', add_zero] at h, right, exact ⟨h', h⟩ }, left, rw [←add_sub_cancel a b], apply sub_is_limit h, suffices : a + 0 < a + b, simpa only [add_zero], rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] }, rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero] end theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c) | a _ c ⟨b, rfl⟩ := ⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩, λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩ theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c := (dvd_add_iff h₁).2 theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩ theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 := ⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩ theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩ theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b | a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0] theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b | a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a (one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0)) theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b := if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂) /-- `a % b` is the unique ordinal `o'` satisfying `a = b * o + o'` with `o' < b`. -/ instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩ theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl @[simp] theorem mod_zero (a : ordinal) : a % 0 = a := by simp only [mod_def, div_zero, zero_mul, sub_zero] theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a := by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero] @[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 := by simp only [mod_def, zero_div, mul_zero, sub_self] theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a := ordinal.add_sub_cancel_of_le $ mul_div_le _ _ theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b := (add_lt_add_iff_left (b * (a / b))).1 $ by rw div_add_mod; exact lt_mul_div_add a h @[simp] theorem mod_self (a : ordinal) : a % a = 0 := if a0 : a = 0 then by simp only [a0, zero_mod] else by simp only [mod_def, div_self a0, mul_one, sub_self] @[simp] theorem mod_one (a : ordinal) : a % 1 = 0 := by simp only [mod_def, div_one, one_mul, sub_self] /-! ### Supremum of a family of ordinals -/ /-- The supremum of a family of ordinals -/ def sup {ι} (f : ι → ordinal) : ordinal := omin {c | ∀ i, f i ≤ c} ⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $ cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩ theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f := omin_mem {c | ∀ i, f i ≤ c} _ theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a := ⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩ theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i := by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a) theorem is_normal.sup {f} (H : is_normal f) {ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) := eq_of_forall_ge_iff $ λ a, by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)]; intros; simp only [sup_le, true_implies_iff] theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord := eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le] lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) := by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup } lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α) (h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) := begin apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h, refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y, apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self end /-- The supremum of a family of ordinals indexed by the set of ordinals less than some `o : ordinal.{u}`. (This is not a special case of `sup` over the subtype, because `{a // a < o} : Type (u+1)` and `sup` only works over families in `Type u`.) -/ def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} := match o, o.out, o.out_eq with | _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _)) end theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a := match o, o.out, o.out_eq, f : ∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}), bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with | _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI ⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩ end theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) : bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) := eq_of_forall_ge_iff $ λ o, by rw [bsup_le, sup_le]; exact ⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩ theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f := bsup_le.1 (le_refl _) _ _ theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal} (hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha') (ho : o.is_limit) (i h) : f i h < bsup o f := lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h) theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o := begin apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt, rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)), apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption end theorem is_normal.bsup {f} (H : is_normal f) {o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) := induction_on o $ λ α r _ g h, by resetI; rw [bsup_type, H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type] theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) : bsup.{u} o (λx _, f x) = f o := by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] } /-! ### Ordinal exponential -/ /-- The ordinal exponential, defined by transfinite recursion. -/ def power (a b : ordinal) : ordinal := if a = 0 then 1 - b else limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b) instance : has_pow ordinal ordinal := ⟨power⟩ local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a := by simp only [pow, power, if_pos rfl] @[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 := by rwa [zero_power', ordinal.sub_eq_zero_iff_le, one_le_iff_ne_zero] @[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 := by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero], simp only [pow, power, if_neg h, limit_rec_on_zero]] @[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a := if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero] else by simp only [pow, power, limit_rec_on_succ, if_neg h] theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b = bsup.{u u} b (λ c _, a ^ c) := by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) : a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c := by rw [power_limit a0 h, bsup_le] theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) : a < b ^ c ↔ ∃ c' < c, a < b ^ c' := by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and] @[simp] theorem power_one (a : ordinal) : a ^ 1 = a := by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul] @[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 := begin apply limit_rec_on a, { simp only [power_zero] }, { intros _ ih, simp only [power_succ, ih, mul_one] }, refine λ b l IH, eq_of_forall_ge_iff (λ c, _), rw [power_le_of_limit ordinal.one_ne_zero l], exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos, λ H b' h, by rwa IH _ h⟩, end theorem power_pos {a : ordinal} (b) (a0 : 0 < a) : 0 < a ^ b := begin have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]}, apply limit_rec_on b, { exact h0 }, { intros b IH, rw [power_succ], exact mul_pos IH a0 }, { exact λ b l _, (lt_power_of_limit (ordinal.pos_iff_ne_zero.1 a0) l).2 ⟨0, l.pos, h0⟩ }, end theorem power_ne_zero {a : ordinal} (b) (a0 : a ≠ 0) : a ^ b ≠ 0 := ordinal.pos_iff_ne_zero.1 $ power_pos b $ ordinal.pos_iff_ne_zero.2 a0 theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) := have a0 : 0 < a, from lt_trans zero_lt_one h, ⟨λ b, by simpa only [mul_one, power_succ] using (mul_lt_mul_iff_left (power_pos b a0)).2 h, λ b l c, power_le_of_limit (ne_of_gt a0) l⟩ theorem power_lt_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b < a ^ c ↔ b < c := (power_is_normal a1).lt_iff theorem power_le_power_iff_right {a b c : ordinal} (a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c := (power_is_normal a1).le_iff theorem power_right_inj {a b c : ordinal} (a1 : 1 < a) : a ^ b = a ^ c ↔ b = c := (power_is_normal a1).inj theorem power_is_limit {a b : ordinal} (a1 : 1 < a) : is_limit b → is_limit (a ^ b) := (power_is_normal a1).is_limit theorem power_is_limit_left {a b : ordinal} (l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) := begin rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l', { exact absurd e hb }, { rw power_succ, exact mul_is_limit (power_pos _ l.pos) l }, { exact power_is_limit l.one_lt l' } end theorem power_le_power_right {a b c : ordinal} (h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c := begin cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁, { exact (power_le_power_iff_right h₁).2 h₂ }, { subst a, simp only [one_power] } end theorem power_le_power_left {a b : ordinal} (c) (ab : a ≤ b) : a ^ c ≤ b ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, { subst c, simp only [power_zero] }, { simp only [zero_power c0, ordinal.zero_le] } }, { apply limit_rec_on c, { simp only [power_zero] }, { intros c IH, simpa only [power_succ] using mul_le_mul IH ab }, { exact λ c l IH, (power_le_of_limit a0 l).2 (λ b' h, le_trans (IH _ h) (power_le_power_right (lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } } end theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b := (power_is_normal a1).le_self _ theorem power_lt_power_left_of_succ {a b c : ordinal} (ab : a < b) : a ^ succ c < b ^ succ c := by rw [power_succ, power_succ]; exact lt_of_le_of_lt (mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab) (mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (ordinal.zero_le _) ab))) theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c := begin by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]}, have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le (ordinal.pos_iff_ne_zero.2 c0) (le_add_left _ _)), simp only [zero_power c0, zero_power this, mul_zero] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power, mul_one] }, apply limit_rec_on c, { simp only [add_zero, power_zero, mul_one] }, { intros c IH, rw [add_succ, power_succ, IH, power_succ, mul_assoc] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (add_is_normal b)).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (((mul_is_normal $ power_pos b (ordinal.pos_iff_ne_zero.2 a0)).trans (power_is_normal a1)).limit_le l).symm } end theorem power_dvd_power (a) {b c : ordinal} (h : b ≤ c) : a ^ b ∣ a ^ c := by { rw [← ordinal.add_sub_cancel_of_le h, power_add], apply dvd_mul_right } theorem power_dvd_power_iff {a b c : ordinal} (a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c := ⟨λ h, le_of_not_lt $ λ hn, not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $ le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h, power_dvd_power _⟩ theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c := begin by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]}, by_cases a0 : a = 0, { subst a, by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]}, simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] }, cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1, { subst a1, simp only [one_power] }, apply limit_rec_on c, { simp only [mul_zero, power_zero] }, { intros c IH, rw [mul_succ, power_add, IH, power_succ] }, { intros c l IH, refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans (mul_is_normal (ordinal.pos_iff_ne_zero.2 b0))).limit_le l).trans _), simp only [IH] {contextual := tt}, exact (power_le_of_limit (power_ne_zero _ a0) l).symm } end /-! ### Ordinal logarithm -/ /-- The ordinal logarithm is the solution `u` to the equation `x = b ^ u * v + w` where `v < b` and `w < b`. -/ def log (b : ordinal) (x : ordinal) : ordinal := if h : 1 < b then pred $ omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩ else 0 @[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 := by simp only [log, dif_neg b1] theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x = pred (omin {o | x < b^o} (log._proof_1 b x b1)) := by simp only [log, dif_pos b1] @[simp] theorem log_zero (b : ordinal) : log b 0 = 0 := if b1 : 1 < b then by rw [log_def b1, ← ordinal.le_zero, pred_le]; apply omin_le; change 0<b^succ 0; rw [succ_zero, power_one]; exact lt_trans zero_lt_one b1 else by simp only [log_not_one_lt b1] theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) = omin {o | x < b^o} (log._proof_1 b x b1) := begin let t := omin {o | x < b^o} (log._proof_1 b x b1), have : x < b ^ t := omin_mem {o | x < b^o} _, rcases zero_or_succ_or_limit t with h|h|h, { refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim, simpa only [h, power_zero] }, { rw [show log b x = pred t, from log_def b1 x, succ_pred_iff_is_succ.2 h] }, { rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩, exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) } end theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) : x < b ^ succ (log b x) := begin cases lt_or_eq_of_le (ordinal.zero_le x) with x0 x0, { rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ }, { subst x, apply power_pos _ (lt_trans zero_lt_one b1) } end theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) : b ^ log b x ≤ x := begin by_cases b0 : b = 0, { rw [b0, zero_power'], refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _), have := @omin_le {o | x < b^o} _ _ h, rwa ← succ_log_def b1 x0 at this }, { rw [← b1, one_power], exact one_le_iff_pos.2 x0 } end theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : c ≤ log b x ↔ b ^ c ≤ x := ⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0), λ h, le_of_not_lt $ λ hn, not_le_of_lt (lt_power_succ_log b1 x) $ le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩ theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) : log b x < c ↔ x < b ^ c := lt_iff_lt_of_le_iff_le (le_log b1 x0) theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) : log b x ≤ log b y := if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else have x0 : 0 < x, from ordinal.pos_iff_ne_zero.2 x0, if b1 : 1 < b then (le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy else by simp only [log_not_one_lt b1, ordinal.zero_le] theorem log_le_self (b x : ordinal) : log b x ≤ x := if x0 : x = 0 then by simp only [x0, log_zero, ordinal.zero_le] else if b1 : 1 < b then le_trans (le_power_self _ b1) (power_log_le b (ordinal.pos_iff_ne_zero.2 x0)) else by simp only [log_not_one_lt b1, ordinal.zero_le] /-! ### The Cantor normal form -/ theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : o % b ^ log b o < o := lt_of_lt_of_le (mod_lt _ $ power_ne_zero _ b0) (power_log_le _ $ ordinal.pos_iff_ne_zero.2 o0) /-- Proving properties of ordinals by induction over their Cantor normal form. -/ @[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0) {C : ordinal → Sort*} (H0 : C 0) (H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o) : ∀ o, C o | o := if o0 : o = 0 then by rw o0; exact H0 else have _, from CNF_aux b0 o0, H o o0 this (CNF_rec (o % b ^ log b o)) using_well_founded {dec_tac := `[assumption]} @[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 := by rw [CNF_rec, dif_pos rfl]; refl @[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) : @CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) := by rw [CNF_rec, dif_neg o0] /-- The Cantor normal form of an ordinal is the list of coefficients in the base-`b` expansion of `o`. CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/ noncomputable def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) := if b0 : b = 0 then [] else CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o @[simp] theorem zero_CNF (o) : CNF 0 o = [] := dif_pos rfl @[simp] theorem CNF_zero (b) : CNF b 0 = [] := if b0 : b = 0 then dif_pos b0 else (dif_neg b0).trans $ CNF_rec_zero _ theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) : CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) := by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0] theorem one_CNF {o : ordinal} (o0 : o ≠ 0) : CNF 1 o = [(0, o)] := by rw [CNF_ne_zero ordinal.one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one, CNF_zero, div_one] theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) : (CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o := CNF_rec b0 (by rw CNF_zero; refl) (λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o theorem CNF_pairwise_aux (b := omega) (o) : (∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧ (CNF b o).pairwise (λ p q, q.1 < p.1) := begin by_cases b0 : b = 0, { simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim }, cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1, { refine CNF_rec b0 _ _ o, { simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim }, intros o o0 H IH, cases IH with IH₁ IH₂, simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true], refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩, { exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) }, { refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _), { rw ordinal.pos_iff_ne_zero, intro e, rw e at m, simpa only [CNF_zero] using m }, { exact mod_lt _ (power_ne_zero _ b0) } } }, { by_cases o0 : o = 0, { simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim }, rw [← b1, one_CNF o0], simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] } end theorem CNF_pairwise (b := omega) (o) : (CNF b o).pairwise (λ p q, prod.fst q < p.1) := (CNF_pairwise_aux _ _).2 theorem CNF_fst_le_log (b := omega) (o) : ∀ p ∈ CNF b o, prod.fst p ≤ log b o := (CNF_pairwise_aux _ _).1 theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o := le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _) theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) : ∀ p ∈ CNF b o, prod.snd p < b := begin have b0 := ne_of_gt (lt_trans zero_lt_one b1), refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o, intros o o0 H IH, simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, forall_eq_or_imp, iff_true_intro IH, and_true], rw [div_lt (power_ne_zero _ b0), ← power_succ], exact lt_power_succ_log b1 _, end theorem CNF_sorted (b := omega) (o) : ((CNF b o).map prod.fst).sorted (>) := by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o /-! ### Casting naturals into ordinals, compatibility with operations -/ @[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n := by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero], rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]] @[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n := by induction n with n IH; [simp only [pow_zero, nat.cast_zero, power_zero, nat.cast_one], rw [pow_succ', nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]] @[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n := by rw [← cardinal.ord_nat, ← cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le] @[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n := by simp only [lt_iff_le_not_le, nat_cast_le] @[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n := by simp only [le_antisymm_iff, nat_cast_le] @[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 := @nat_cast_inj n 0 theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 := not_congr nat_cast_eq_zero @[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n := @nat_cast_lt 0 n @[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n := (_root_.le_total m n).elim (λ h, by rw [tsub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl) (λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add, add_tsub_cancel_of_le h, ordinal.add_sub_cancel_of_le (nat_cast_le.2 h)]) @[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n := if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else have n0':_, from nat_cast_ne_zero.2 n0, le_antisymm (by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm]; apply nat.div_mul_le_self) (by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul, nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)]; apply nat.lt_succ_self) @[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n := by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add, nat.div_add_mod] @[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o := ⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h, λ h, card_nat n ▸ card_le_card h⟩ @[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o := by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl @[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n := lt_iff_lt_of_le_iff_le nat_le_card @[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n := le_iff_le_iff_lt_iff_lt.2 nat_lt_card @[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n := by simp only [le_antisymm_iff, card_le_nat, nat_le_card] @[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n := by rw [← card_eq_nat, card_type, mk_fin] @[simp] theorem lift_nat_cast (n : ℕ) : lift n = n := by induction n with n ih; [simp only [nat.cast_zero, lift_zero], simp only [nat.cast_succ, lift_add, ih, lift_one]] theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n := by simp only [type_fin, lift_nat_cast] theorem type_fintype (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α := by rw [← card_eq_nat, card_type, mk_fintype] end ordinal /-! ### Properties of `omega` -/ namespace cardinal open ordinal @[simp] theorem ord_omega : ord.{u} omega = ordinal.omega := le_antisymm (ord_le.2 $ le_refl _) $ le_of_forall_lt $ λ o h, begin rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩, rw [lt_ord, ← lift_card, ← lift_omega.{0 u}, lift_lt, ← typein_enum (<) h'], exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩ end @[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c := by rw [add_comm, ← card_ord c, ← card_one, ← card_add, one_add_of_omega_le]; rwa [← ord_omega, ord_le_ord] end cardinal namespace ordinal theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n := by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat] theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega := lt_omega.2 ⟨_, rfl⟩ theorem omega_pos : 0 < omega := nat_lt_omega 0 theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1 theorem omega_is_limit : is_limit omega := ⟨omega_ne_zero, λ o h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e]; exact nat_lt_omega (n+1)⟩ theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o := ⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h, λ H, le_of_forall_lt $ λ a h, let ⟨n, e⟩ := lt_omega.1 h in by rw [e, ← succ_le]; exact H (n+1)⟩ theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o | 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm | (n+1) := h.2 _ (nat_lt_limit n) theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o := omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := begin rcases lt_omega.1 h with ⟨n, rfl⟩, clear h, induction n with n IH, { rw [nat.cast_zero, zero_add] }, { rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] } end theorem add_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a + b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega end theorem mul_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a * b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_mul]; apply nat_lt_omega end theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a := begin refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩, { refine (limit_le l).2 (λ x hx, le_of_lt _), rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero, mul_succ, add_le_of_limit omega_is_limit], intros b hb, rcases lt_omega.1 hb with ⟨n, rfl⟩, exact le_trans (add_le_add_right (mul_div_le _ _) _) (le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) }, { rcases h with ⟨a0, b, rfl⟩, refine mul_is_limit_left omega_is_limit (ordinal.pos_iff_ne_zero.2 $ mt _ a0), intro e, simp only [e, mul_zero] } end local infixr ^ := @pow ordinal ordinal ordinal.has_pow theorem power_lt_omega {a b : ordinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega := match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_power]; apply nat_lt_omega end theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, apply limit_rec_on b, { intro h, rw [power_zero, ← succ_zero, lt_succ, ordinal.le_zero] at h, rw [h, zero_add] }, { intros b _ h, rw [power_succ] at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [power_succ, ← mul_add, add_omega xo] }, { intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, refine (((add_is_normal a).trans (power_is_normal one_lt_omega)) .limit_le l).2 (λ y yb, _), let z := max x y, have := IH z (max_lt xb yb) (lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)), exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _) (le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) } end theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) : a + b < omega ^ c := by rwa [← add_omega_power h₁, add_lt_add_iff_left] theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c := by rw [← ordinal.add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁] theorem add_absorp_iff {o : ordinal} (o0 : 0 < o) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a := ⟨λ H, ⟨log omega o, begin refine ((lt_or_eq_of_le (power_log_le _ o0)) .resolve_left $ λ h, _).symm, have := H _ h, have := lt_power_succ_log one_lt_omega o, rw [power_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]}, simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH] end⟩, λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩ theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a) (l : is_limit c) (IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) : (a + b) * c = a * c := le_antisymm ((mul_le_of_limit l).2 $ λ c' h, begin apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)), rw IH _ h, apply le_trans (add_le_add_left _ _), { rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) }, { rw ← ba, exact le_add_right _ _ } end) (mul_le_mul_right _ (le_add_right _ _)) theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) : (a + b) * succ c = a * succ c + b := begin apply limit_rec_on c, { simp only [succ_zero, mul_one] }, { intros c IH, rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] }, { intros c l IH, have := add_mul_limit_aux ba l IH, rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] } end theorem add_mul_limit {a b c : ordinal} (ba : b + a = a) (l : is_limit c) : (a + b) * c = a * c := add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba) theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := le_antisymm ((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb)) (by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0)) theorem mul_lt_omega_power {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw power_succ at ha, rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _, rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)], exact mul_lt_omega hn hb }, { rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _, rw [← power_succ, power_lt_power_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h}, refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)), rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _, rw [← power_add, add_omega_power xb] end theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (λ b hb, le_of_lt (power_lt_omega h hb))) (le_power_self _ a1) /-! ### Fixed points of normal functions -/ /-- The next fixed point function, the least fixed point of the normal function `f` above `a`. -/ def nfp (f : ordinal → ordinal) (a : ordinal) := sup (λ n : ℕ, f^[n] a) theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a := le_sup _ n theorem le_nfp_self (f a) : a ≤ nfp f a := iterate_le_nfp f a 0 theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} : f b < nfp f a ↔ b < nfp f a := lt_sup.trans $ iff.trans (by exact ⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩, λ ⟨n, h⟩, ⟨n+1, by rw iterate_succ'; exact H.lt_iff.2 h⟩⟩) lt_sup.symm theorem is_normal.nfp_le {f} (H : is_normal f) {a b} : nfp f a ≤ f b ↔ nfp f a ≤ b := le_iff_le_iff_lt_iff_lt.2 H.lt_nfp theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b} (ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b := sup_le.2 $ λ i, begin induction i with i IH generalizing a, {exact ab}, exact IH (le_trans (H.le_iff.2 ab) h), end theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a := begin refine le_antisymm _ (H.le_self _), cases le_or_lt (f a) a with aa aa, { rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) }, rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l, { refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1), simp only [e, ordinal.zero_le] }, { have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]), rw [e, lt_succ] at this, have ab : a ≤ b, { rw [← lt_succ, ← e], exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) }, refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this)) (le_trans this (le_of_lt _)), simp only [e, lt_succ_self] }, { exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) } end theorem is_normal.le_nfp {f} (H : is_normal f) {a b} : f b ≤ nfp f a ↔ b ≤ nfp f a := ⟨le_trans (H.le_self _), λ h, by simpa only [H.nfp_fp] using H.le_iff.2 h⟩ theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a := le_antisymm (sup_le.mpr $ λ i, by rw [iterate_fixed h]) (le_nfp_self f a) /-- The derivative of a normal function `f` is the sequence of fixed points of `f`. -/ def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal := limit_rec_on o (nfp f 0) (λ a IH, nfp f (succ IH)) (λ a l, bsup.{u u} a) @[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _ @[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) := limit_rec_on_succ _ _ _ _ theorem deriv_limit (f) {o} : is_limit o → deriv f o = bsup.{u u} o (λ a _, deriv f a) := limit_rec_on_limit _ _ _ _ theorem deriv_is_normal (f) : is_normal (deriv f) := ⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self, λ o l a, by rw [deriv_limit _ l, bsup_le]⟩ theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o := begin apply limit_rec_on o, { rw [deriv_zero, H.nfp_fp] }, { intros o ih, rw [deriv_succ, H.nfp_fp] }, intros o l IH, rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1], refine eq_of_forall_ge_iff (λ c, _), simp only [bsup_le, IH] {contextual:=tt} end theorem is_normal.fp_iff_deriv {f} (H : is_normal f) {a} : f a ≤ a ↔ ∃ o, a = deriv f o := ⟨λ ha, begin suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o, from this a ((deriv_is_normal _).le_self _), intro o, apply limit_rec_on o, { intros h₁, refine ⟨0, le_antisymm h₁ _⟩, rw deriv_zero, exact H.nfp_le_fp (ordinal.zero_le _) ha }, { intros o IH h₁, cases le_or_lt a (deriv f o), {exact IH h}, refine ⟨succ o, le_antisymm h₁ _⟩, rw deriv_succ, exact H.nfp_le_fp (succ_le.2 h) ha }, { intros o l IH h₁, cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩}, rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h, exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) } end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩ end ordinal
436930ba245dae6769660387d4917e5f1229bc1d
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/normed_space/spectrum.lean
96c73416faba33b460d4055fbc03675110fbed8c
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
27,832
lean
/- Copyright (c) 2021 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.algebra.spectrum import analysis.special_functions.pow import analysis.complex.liouville import analysis.complex.polynomial import analysis.analytic.radius_liminf import topology.algebra.module.character_space import analysis.normed_space.exponential /-! # The spectrum of elements in a complete normed algebra This file contains the basic theory for the resolvent and spectrum of a Banach algebra. ## Main definitions * `spectral_radius : ℝ≥0∞`: supremum of `‖k‖₊` for all `k ∈ spectrum 𝕜 a` * `normed_ring.alg_equiv_complex_of_complete`: **Gelfand-Mazur theorem** For a complex Banach division algebra, the natural `algebra_map ℂ A` is an algebra isomorphism whose inverse is given by selecting the (unique) element of `spectrum ℂ a` ## Main statements * `spectrum.is_open_resolvent_set`: the resolvent set is open. * `spectrum.is_closed`: the spectrum is closed. * `spectrum.subset_closed_ball_norm`: the spectrum is a subset of closed disk of radius equal to the norm. * `spectrum.is_compact`: the spectrum is compact. * `spectrum.spectral_radius_le_nnnorm`: the spectral radius is bounded above by the norm. * `spectrum.has_deriv_at_resolvent`: the resolvent function is differentiable on the resolvent set. * `spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius`: Gelfand's formula for the spectral radius in Banach algebras over `ℂ`. * `spectrum.nonempty`: the spectrum of any element in a complex Banach algebra is nonempty. ## TODO * compute all derivatives of `resolvent a`. -/ open_locale ennreal nnreal /-- The *spectral radius* is the supremum of the `nnnorm` (`‖⬝‖₊`) of elements in the spectrum, coerced into an element of `ℝ≥0∞`. Note that it is possible for `spectrum 𝕜 a = ∅`. In this case, `spectral_radius a = 0`. It is also possible that `spectrum 𝕜 a` be unbounded (though not for Banach algebras, see `spectrum.is_bounded`, below). In this case, `spectral_radius a = ∞`. -/ noncomputable def spectral_radius (𝕜 : Type*) {A : Type*} [normed_field 𝕜] [ring A] [algebra 𝕜 A] (a : A) : ℝ≥0∞ := ⨆ k ∈ spectrum 𝕜 a, ‖k‖₊ variables {𝕜 : Type*} {A : Type*} namespace spectrum section spectrum_compact open filter variables [normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] local notation `σ` := spectrum 𝕜 local notation `ρ` := resolvent_set 𝕜 local notation `↑ₐ` := algebra_map 𝕜 A @[simp] lemma spectral_radius.of_subsingleton [subsingleton A] (a : A) : spectral_radius 𝕜 a = 0 := by simp [spectral_radius] @[simp] lemma spectral_radius_zero : spectral_radius 𝕜 (0 : A) = 0 := by { nontriviality A, simp [spectral_radius] } lemma mem_resolvent_set_of_spectral_radius_lt {a : A} {k : 𝕜} (h : spectral_radius 𝕜 a < ‖k‖₊) : k ∈ ρ a := not_not.mp $ λ hn, h.not_le $ le_supr₂ k hn variable [complete_space A] lemma is_open_resolvent_set (a : A) : is_open (ρ a) := units.is_open.preimage ((continuous_algebra_map 𝕜 A).sub continuous_const) protected lemma is_closed (a : A) : is_closed (σ a) := (is_open_resolvent_set a).is_closed_compl lemma mem_resolvent_set_of_norm_lt_mul {a : A} {k : 𝕜} (h : ‖a‖ * ‖(1 : A)‖ < ‖k‖) : k ∈ ρ a := begin rw [resolvent_set, set.mem_set_of_eq, algebra.algebra_map_eq_smul_one], nontriviality A, have hk : k ≠ 0, from ne_zero_of_norm_ne_zero ((mul_nonneg (norm_nonneg _) (norm_nonneg _)).trans_lt h).ne', let ku := units.map (↑ₐ).to_monoid_hom (units.mk0 k hk), rw [←inv_inv (‖(1 : A)‖), mul_inv_lt_iff (inv_pos.2 $ norm_pos_iff.2 (one_ne_zero : (1 : A) ≠ 0))] at h, have hku : ‖-a‖ < ‖(↑ku⁻¹:A)‖⁻¹ := by simpa [ku, norm_algebra_map] using h, simpa [ku, sub_eq_add_neg, algebra.algebra_map_eq_smul_one] using (ku.add (-a) hku).is_unit, end lemma mem_resolvent_set_of_norm_lt [norm_one_class A] {a : A} {k : 𝕜} (h : ‖a‖ < ‖k‖) : k ∈ ρ a := mem_resolvent_set_of_norm_lt_mul (by rwa [norm_one, mul_one]) lemma norm_le_norm_mul_of_mem {a : A} {k : 𝕜} (hk : k ∈ σ a) : ‖k‖ ≤ ‖a‖ * ‖(1 : A)‖ := le_of_not_lt $ mt mem_resolvent_set_of_norm_lt_mul hk lemma norm_le_norm_of_mem [norm_one_class A] {a : A} {k : 𝕜} (hk : k ∈ σ a) : ‖k‖ ≤ ‖a‖ := le_of_not_lt $ mt mem_resolvent_set_of_norm_lt hk lemma subset_closed_ball_norm_mul (a : A) : σ a ⊆ metric.closed_ball (0 : 𝕜) (‖a‖ * ‖(1 : A)‖) := λ k hk, by simp [norm_le_norm_mul_of_mem hk] lemma subset_closed_ball_norm [norm_one_class A] (a : A) : σ a ⊆ metric.closed_ball (0 : 𝕜) (‖a‖) := λ k hk, by simp [norm_le_norm_of_mem hk] lemma is_bounded (a : A) : metric.bounded (σ a) := (metric.bounded_iff_subset_ball 0).mpr ⟨‖a‖ * ‖(1 : A)‖, subset_closed_ball_norm_mul a⟩ protected theorem is_compact [proper_space 𝕜] (a : A) : is_compact (σ a) := metric.is_compact_of_is_closed_bounded (spectrum.is_closed a) (is_bounded a) theorem spectral_radius_le_nnnorm [norm_one_class A] (a : A) : spectral_radius 𝕜 a ≤ ‖a‖₊ := by { refine supr₂_le (λ k hk, _), exact_mod_cast norm_le_norm_of_mem hk } lemma exists_nnnorm_eq_spectral_radius_of_nonempty [proper_space 𝕜] {a : A} (ha : (σ a).nonempty) : ∃ k ∈ σ a, (‖k‖₊ : ℝ≥0∞) = spectral_radius 𝕜 a := begin obtain ⟨k, hk, h⟩ := (spectrum.is_compact a).exists_forall_ge ha continuous_nnnorm.continuous_on, exact ⟨k, hk, le_antisymm (le_supr₂ k hk) (supr₂_le $ by exact_mod_cast h)⟩, end lemma spectral_radius_lt_of_forall_lt_of_nonempty [proper_space 𝕜] {a : A} (ha : (σ a).nonempty) {r : ℝ≥0} (hr : ∀ k ∈ σ a, ‖k‖₊ < r) : spectral_radius 𝕜 a < r := Sup_image.symm.trans_lt $ ((spectrum.is_compact a).Sup_lt_iff_of_continuous ha (ennreal.continuous_coe.comp continuous_nnnorm).continuous_on (r : ℝ≥0∞)).mpr (by exact_mod_cast hr) open ennreal polynomial variable (𝕜) theorem spectral_radius_le_pow_nnnorm_pow_one_div (a : A) (n : ℕ) : spectral_radius 𝕜 a ≤ (‖a ^ (n + 1)‖₊) ^ (1 / (n + 1) : ℝ) * (‖(1 : A)‖₊) ^ (1 / (n + 1) : ℝ) := begin refine supr₂_le (λ k hk, _), /- apply easy direction of the spectral mapping theorem for polynomials -/ have pow_mem : k ^ (n + 1) ∈ σ (a ^ (n + 1)), by simpa only [one_mul, algebra.algebra_map_eq_smul_one, one_smul, aeval_monomial, one_mul, eval_monomial] using subset_polynomial_aeval a (monomial (n + 1) (1 : 𝕜)) ⟨k, hk, rfl⟩, /- power of the norm is bounded by norm of the power -/ have nnnorm_pow_le : (↑(‖k‖₊ ^ (n + 1)) : ℝ≥0∞) ≤ ‖a ^ (n + 1)‖₊ * ‖(1 : A)‖₊, { simpa only [real.to_nnreal_mul (norm_nonneg _), norm_to_nnreal, nnnorm_pow k (n + 1), ennreal.coe_mul] using coe_mono (real.to_nnreal_mono (norm_le_norm_mul_of_mem pow_mem)) }, /- take (n + 1)ᵗʰ roots and clean up the left-hand side -/ have hn : 0 < ((n + 1 : ℕ) : ℝ), by exact_mod_cast nat.succ_pos', convert monotone_rpow_of_nonneg (one_div_pos.mpr hn).le nnnorm_pow_le, erw [coe_pow, ←rpow_nat_cast, ←rpow_mul, mul_one_div_cancel hn.ne', rpow_one], rw [nat.cast_succ, ennreal.coe_mul_rpow], end theorem spectral_radius_le_liminf_pow_nnnorm_pow_one_div (a : A) : spectral_radius 𝕜 a ≤ at_top.liminf (λ n : ℕ, (‖a ^ n‖₊ : ℝ≥0∞) ^ (1 / n : ℝ)) := begin refine ennreal.le_of_forall_lt_one_mul_le (λ ε hε, _), by_cases ε = 0, { simp only [h, zero_mul, zero_le'] }, have hε' : ε⁻¹ ≠ ∞, from λ h', h (by simpa only [inv_inv, inv_top] using congr_arg (λ (x : ℝ≥0∞), x⁻¹) h'), simp only [ennreal.mul_le_iff_le_inv h (hε.trans_le le_top).ne, mul_comm ε⁻¹, liminf_eq_supr_infi_of_nat', ennreal.supr_mul, ennreal.infi_mul hε'], rw [←ennreal.inv_lt_inv, inv_one] at hε, obtain ⟨N, hN⟩ := eventually_at_top.mp (ennreal.eventually_pow_one_div_le (ennreal.coe_ne_top : ↑‖(1 : A)‖₊ ≠ ∞) hε), refine (le_trans _ (le_supr _ (N + 1))), refine le_infi (λ n, _), simp only [←add_assoc], refine (spectral_radius_le_pow_nnnorm_pow_one_div 𝕜 a (n + N)).trans _, norm_cast, exact mul_le_mul_left' (hN (n + N + 1) (by linarith)) _, end end spectrum_compact section resolvent open filter asymptotics variables [nontrivially_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] local notation `ρ` := resolvent_set 𝕜 local notation `↑ₐ` := algebra_map 𝕜 A theorem has_deriv_at_resolvent {a : A} {k : 𝕜} (hk : k ∈ ρ a) : has_deriv_at (resolvent a) (-(resolvent a k) ^ 2) k := begin have H₁ : has_fderiv_at ring.inverse _ (↑ₐk - a) := has_fderiv_at_ring_inverse hk.unit, have H₂ : has_deriv_at (λ k, ↑ₐk - a) 1 k, { simpa using (algebra.linear_map 𝕜 A).has_deriv_at.sub_const a }, simpa [resolvent, sq, hk.unit_spec, ← ring.inverse_unit hk.unit] using H₁.comp_has_deriv_at k H₂, end /- TODO: Once there is sufficient API for bornology, we should get a nice filter / asymptotics version of this, for example: `tendsto (resolvent a) (cobounded 𝕜) (𝓝 0)` or more specifically `(resolvent a) =O[cobounded 𝕜] (λ z, z⁻¹)`. -/ lemma norm_resolvent_le_forall (a : A) : ∀ ε > 0, ∃ R > 0, ∀ z : 𝕜, R ≤ ‖z‖ → ‖resolvent a z‖ ≤ ε := begin obtain ⟨c, c_pos, hc⟩ := (@normed_ring.inverse_one_sub_norm A _ _).exists_pos, rw [is_O_with_iff, eventually_iff, metric.mem_nhds_iff] at hc, rcases hc with ⟨δ, δ_pos, hδ⟩, simp only [cstar_ring.norm_one, mul_one] at hδ, intros ε hε, have ha₁ : 0 < ‖a‖ + 1 := lt_of_le_of_lt (norm_nonneg a) (lt_add_one _), have min_pos : 0 < min (δ * (‖a‖ + 1)⁻¹) (ε * c⁻¹), from lt_min (mul_pos δ_pos (inv_pos.mpr ha₁)) (mul_pos hε (inv_pos.mpr c_pos)), refine ⟨(min (δ * (‖a‖ + 1)⁻¹) (ε * c⁻¹))⁻¹, inv_pos.mpr min_pos, (λ z hz, _)⟩, have hnz : z ≠ 0 := norm_pos_iff.mp (lt_of_lt_of_le (inv_pos.mpr min_pos) hz), replace hz := inv_le_of_inv_le min_pos hz, rcases (⟨units.mk0 z hnz, units.coe_mk0 hnz⟩ : is_unit z) with ⟨z, rfl⟩, have lt_δ : ‖z⁻¹ • a‖ < δ, { rw [units.smul_def, norm_smul, units.coe_inv, norm_inv], calc ‖(z : 𝕜)‖⁻¹ * ‖a‖ ≤ δ * (‖a‖ + 1)⁻¹ * ‖a‖ : mul_le_mul_of_nonneg_right (hz.trans (min_le_left _ _)) (norm_nonneg _) ... < δ : by { conv { rw mul_assoc, to_rhs, rw (mul_one δ).symm }, exact mul_lt_mul_of_pos_left ((inv_mul_lt_iff ha₁).mpr ((mul_one (‖a‖ + 1)).symm ▸ (lt_add_one _))) δ_pos } }, rw [←inv_smul_smul z (resolvent a (z : 𝕜)), units_smul_resolvent_self, resolvent, algebra.algebra_map_eq_smul_one, one_smul, units.smul_def, norm_smul, units.coe_inv, norm_inv], calc _ ≤ ε * c⁻¹ * c : mul_le_mul (hz.trans (min_le_right _ _)) (hδ (mem_ball_zero_iff.mpr lt_δ)) (norm_nonneg _) (mul_pos hε (inv_pos.mpr c_pos)).le ... = _ : inv_mul_cancel_right₀ c_pos.ne.symm ε, end end resolvent section one_sub_smul open continuous_multilinear_map ennreal formal_multilinear_series open_locale nnreal ennreal variables [nontrivially_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] variable (𝕜) /-- In a Banach algebra `A` over a nontrivially normed field `𝕜`, for any `a : A` the power series with coefficients `a ^ n` represents the function `(1 - z • a)⁻¹` in a disk of radius `‖a‖₊⁻¹`. -/ lemma has_fpower_series_on_ball_inverse_one_sub_smul [complete_space A] (a : A) : has_fpower_series_on_ball (λ z : 𝕜, ring.inverse (1 - z • a)) (λ n, continuous_multilinear_map.mk_pi_field 𝕜 (fin n) (a ^ n)) 0 (‖a‖₊)⁻¹ := { r_le := begin refine le_of_forall_nnreal_lt (λ r hr, le_radius_of_bound_nnreal _ (max 1 ‖(1 : A)‖₊) (λ n, _)), rw [←norm_to_nnreal, norm_mk_pi_field, norm_to_nnreal], cases n, { simp only [le_refl, mul_one, or_true, le_max_iff, pow_zero] }, { refine le_trans (le_trans (mul_le_mul_right' (nnnorm_pow_le' a n.succ_pos) (r ^ n.succ)) _) (le_max_left _ _), { by_cases ‖a‖₊ = 0, { simp only [h, zero_mul, zero_le', pow_succ], }, { rw [←coe_inv h, coe_lt_coe, nnreal.lt_inv_iff_mul_lt h] at hr, simpa only [←mul_pow, mul_comm] using pow_le_one' hr.le n.succ } } } end, r_pos := ennreal.inv_pos.mpr coe_ne_top, has_sum := λ y hy, begin have norm_lt : ‖y • a‖ < 1, { by_cases h : ‖a‖₊ = 0, { simp only [nnnorm_eq_zero.mp h, norm_zero, zero_lt_one, smul_zero] }, { have nnnorm_lt : ‖y‖₊ < ‖a‖₊⁻¹, by simpa only [←coe_inv h, mem_ball_zero_iff, metric.emetric_ball_nnreal] using hy, rwa [←coe_nnnorm, ←real.lt_to_nnreal_iff_coe_lt, real.to_nnreal_one, nnnorm_smul, ←nnreal.lt_inv_iff_mul_lt h] } }, simpa [←smul_pow, (normed_ring.summable_geometric_of_norm_lt_1 _ norm_lt).has_sum_iff] using (normed_ring.inverse_one_sub _ norm_lt).symm, end } variable {𝕜} lemma is_unit_one_sub_smul_of_lt_inv_radius {a : A} {z : 𝕜} (h : ↑‖z‖₊ < (spectral_radius 𝕜 a)⁻¹) : is_unit (1 - z • a) := begin by_cases hz : z = 0, { simp only [hz, is_unit_one, sub_zero, zero_smul] }, { let u := units.mk0 z hz, suffices hu : is_unit (u⁻¹ • 1 - a), { rwa [is_unit.smul_sub_iff_sub_inv_smul, inv_inv u] at hu }, { rw [units.smul_def, ←algebra.algebra_map_eq_smul_one, ←mem_resolvent_set_iff], refine mem_resolvent_set_of_spectral_radius_lt _, rwa [units.coe_inv, nnnorm_inv, coe_inv (nnnorm_ne_zero_iff.mpr (units.coe_mk0 hz ▸ hz : (u : 𝕜) ≠ 0)), lt_inv_iff_lt_inv] } } end /-- In a Banach algebra `A` over `𝕜`, for `a : A` the function `λ z, (1 - z • a)⁻¹` is differentiable on any closed ball centered at zero of radius `r < (spectral_radius 𝕜 a)⁻¹`. -/ theorem differentiable_on_inverse_one_sub_smul [complete_space A] {a : A} {r : ℝ≥0} (hr : (r : ℝ≥0∞) < (spectral_radius 𝕜 a)⁻¹) : differentiable_on 𝕜 (λ z : 𝕜, ring.inverse (1 - z • a)) (metric.closed_ball 0 r) := begin intros z z_mem, apply differentiable_at.differentiable_within_at, have hu : is_unit (1 - z • a), { refine is_unit_one_sub_smul_of_lt_inv_radius (lt_of_le_of_lt (coe_mono _) hr), simpa only [norm_to_nnreal, real.to_nnreal_coe] using real.to_nnreal_mono (mem_closed_ball_zero_iff.mp z_mem) }, have H₁ : differentiable 𝕜 (λ w : 𝕜, 1 - w • a) := (differentiable_id.smul_const a).const_sub 1, exact differentiable_at.comp z (differentiable_at_inverse hu.unit) (H₁.differentiable_at), end end one_sub_smul section gelfand_formula open filter ennreal continuous_multilinear_map open_locale topological_space variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] /-- The `limsup` relationship for the spectral radius used to prove `spectrum.gelfand_formula`. -/ lemma limsup_pow_nnnorm_pow_one_div_le_spectral_radius (a : A) : limsup (λ n : ℕ, ↑‖a ^ n‖₊ ^ (1 / n : ℝ)) at_top ≤ spectral_radius ℂ a := begin refine ennreal.inv_le_inv.mp (le_of_forall_pos_nnreal_lt (λ r r_pos r_lt, _)), simp_rw [inv_limsup, ←one_div], let p : formal_multilinear_series ℂ ℂ A := λ n, continuous_multilinear_map.mk_pi_field ℂ (fin n) (a ^ n), suffices h : (r : ℝ≥0∞) ≤ p.radius, { convert h, simp only [p.radius_eq_liminf, ←norm_to_nnreal, norm_mk_pi_field], congr, ext n, rw [norm_to_nnreal, ennreal.coe_rpow_def (‖a ^ n‖₊) (1 / n : ℝ), if_neg], exact λ ha, by linarith [ha.2, (one_div_nonneg.mpr n.cast_nonneg : 0 ≤ (1 / n : ℝ))], }, { have H₁ := (differentiable_on_inverse_one_sub_smul r_lt).has_fpower_series_on_ball r_pos, exact ((has_fpower_series_on_ball_inverse_one_sub_smul ℂ a).exchange_radius H₁).r_le, } end /-- **Gelfand's formula**: Given an element `a : A` of a complex Banach algebra, the `spectral_radius` of `a` is the limit of the sequence `‖a ^ n‖₊ ^ (1 / n)` -/ theorem pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a : A) : tendsto (λ n : ℕ, ((‖a ^ n‖₊ ^ (1 / n : ℝ)) : ℝ≥0∞)) at_top (𝓝 (spectral_radius ℂ a)) := tendsto_of_le_liminf_of_limsup_le (spectral_radius_le_liminf_pow_nnnorm_pow_one_div ℂ a) (limsup_pow_nnnorm_pow_one_div_le_spectral_radius a) /- This is the same as `pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius` but for `norm` instead of `nnnorm`. -/ /-- **Gelfand's formula**: Given an element `a : A` of a complex Banach algebra, the `spectral_radius` of `a` is the limit of the sequence `‖a ^ n‖₊ ^ (1 / n)` -/ theorem pow_norm_pow_one_div_tendsto_nhds_spectral_radius (a : A) : tendsto (λ n : ℕ, ennreal.of_real (‖a ^ n‖ ^ (1 / n : ℝ))) at_top (𝓝 (spectral_radius ℂ a)) := begin convert pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius a, ext1, rw [←of_real_rpow_of_nonneg (norm_nonneg _) _, ←coe_nnnorm, coe_nnreal_eq], exact one_div_nonneg.mpr (by exact_mod_cast zero_le _), end end gelfand_formula section nonempty_spectrum variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] [nontrivial A] (a : A) /-- In a (nontrivial) complex Banach algebra, every element has nonempty spectrum. -/ protected theorem nonempty : (spectrum ℂ a).nonempty := begin /- Suppose `σ a = ∅`, then resolvent set is `ℂ`, any `(z • 1 - a)` is a unit, and `resolvent` is differentiable on `ℂ`. -/ rw set.nonempty_iff_ne_empty, by_contra h, have H₀ : resolvent_set ℂ a = set.univ, by rwa [spectrum, set.compl_empty_iff] at h, have H₁ : differentiable ℂ (λ z : ℂ, resolvent a z), from λ z, (has_deriv_at_resolvent (H₀.symm ▸ set.mem_univ z : z ∈ resolvent_set ℂ a)).differentiable_at, /- The norm of the resolvent is small for all sufficently large `z`, and by compactness and continuity it is bounded on the complement of a large ball, thus uniformly bounded on `ℂ`. By Liouville's theorem `λ z, resolvent a z` is constant -/ have H₂ := norm_resolvent_le_forall a, have H₃ : ∀ z : ℂ, resolvent a z = resolvent a (0 : ℂ), { refine λ z, H₁.apply_eq_apply_of_bounded (bounded_iff_forall_norm_le.mpr _) z 0, rcases H₂ 1 zero_lt_one with ⟨R, R_pos, hR⟩, rcases (proper_space.is_compact_closed_ball (0 : ℂ) R).exists_bound_of_continuous_on H₁.continuous.continuous_on with ⟨C, hC⟩, use max C 1, rintros _ ⟨w, rfl⟩, refine or.elim (em (‖w‖ ≤ R)) (λ hw, _) (λ hw, _), { exact (hC w (mem_closed_ball_zero_iff.mpr hw)).trans (le_max_left _ _) }, { exact (hR w (not_le.mp hw).le).trans (le_max_right _ _), }, }, /- `resolvent a 0 = 0`, which is a contradition because it isn't a unit. -/ have H₅ : resolvent a (0 : ℂ) = 0, { refine norm_eq_zero.mp (le_antisymm (le_of_forall_pos_le_add (λ ε hε, _)) (norm_nonneg _)), rcases H₂ ε hε with ⟨R, R_pos, hR⟩, simpa only [H₃ R] using (zero_add ε).symm.subst (hR R (by exact_mod_cast (real.norm_of_nonneg R_pos.lt.le).symm.le)), }, /- `not_is_unit_zero` is where we need `nontrivial A`, it is unavoidable. -/ exact not_is_unit_zero (H₅.subst (is_unit_resolvent.mp (mem_resolvent_set_iff.mp (H₀.symm ▸ set.mem_univ 0)))), end /-- In a complex Banach algebra, the spectral radius is always attained by some element of the spectrum. -/ lemma exists_nnnorm_eq_spectral_radius : ∃ z ∈ spectrum ℂ a, (‖z‖₊ : ℝ≥0∞) = spectral_radius ℂ a := exists_nnnorm_eq_spectral_radius_of_nonempty (spectrum.nonempty a) /-- In a complex Banach algebra, if every element of the spectrum has norm strictly less than `r : ℝ≥0`, then the spectral radius is also strictly less than `r`. -/ lemma spectral_radius_lt_of_forall_lt {r : ℝ≥0} (hr : ∀ z ∈ spectrum ℂ a, ‖z‖₊ < r) : spectral_radius ℂ a < r := spectral_radius_lt_of_forall_lt_of_nonempty (spectrum.nonempty a) hr open_locale polynomial open polynomial /-- The **spectral mapping theorem** for polynomials in a Banach algebra over `ℂ`. -/ lemma map_polynomial_aeval (p : ℂ[X]) : spectrum ℂ (aeval a p) = (λ k, eval k p) '' (spectrum ℂ a) := map_polynomial_aeval_of_nonempty a p (spectrum.nonempty a) /-- A specialization of the spectral mapping theorem for polynomials in a Banach algebra over `ℂ` to monic monomials. -/ protected lemma map_pow (n : ℕ) : spectrum ℂ (a ^ n) = (λ x, x ^ n) '' (spectrum ℂ a) := by simpa only [aeval_X_pow, eval_pow, eval_X] using map_polynomial_aeval a (X ^ n) end nonempty_spectrum section gelfand_mazur_isomorphism variables [normed_ring A] [normed_algebra ℂ A] (hA : ∀ {a : A}, is_unit a ↔ a ≠ 0) include hA local notation `σ` := spectrum ℂ lemma algebra_map_eq_of_mem {a : A} {z : ℂ} (h : z ∈ σ a) : algebra_map ℂ A z = a := by rwa [mem_iff, hA, not_not, sub_eq_zero] at h /-- **Gelfand-Mazur theorem**: For a complex Banach division algebra, the natural `algebra_map ℂ A` is an algebra isomorphism whose inverse is given by selecting the (unique) element of `spectrum ℂ a`. In addition, `algebra_map_isometry` guarantees this map is an isometry. Note: because `normed_division_ring` requires the field `norm_mul' : ∀ a b, ‖a * b‖ = ‖a‖ * ‖b‖`, we don't use this type class and instead opt for a `normed_ring` in which the nonzero elements are precisely the units. This allows for the application of this isomorphism in broader contexts, e.g., to the quotient of a complex Banach algebra by a maximal ideal. In the case when `A` is actually a `normed_division_ring`, one may fill in the argument `hA` with the lemma `is_unit_iff_ne_zero`. -/ @[simps] noncomputable def _root_.normed_ring.alg_equiv_complex_of_complete [complete_space A] : ℂ ≃ₐ[ℂ] A := let nt : nontrivial A := ⟨⟨1, 0, hA.mp ⟨⟨1, 1, mul_one _, mul_one _⟩, rfl⟩⟩⟩ in { to_fun := algebra_map ℂ A, inv_fun := λ a, (@spectrum.nonempty _ _ _ _ nt a).some, left_inv := λ z, by simpa only [@scalar_eq _ _ _ _ _ nt _] using (@spectrum.nonempty _ _ _ _ nt $ algebra_map ℂ A z).some_mem, right_inv := λ a, algebra_map_eq_of_mem @hA (@spectrum.nonempty _ _ _ _ nt a).some_mem, ..algebra.of_id ℂ A } end gelfand_mazur_isomorphism section exp_mapping local notation `↑ₐ` := algebra_map 𝕜 A /-- For `𝕜 = ℝ` or `𝕜 = ℂ`, `exp 𝕜` maps the spectrum of `a` into the spectrum of `exp 𝕜 a`. -/ theorem exp_mem_exp [is_R_or_C 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] (a : A) {z : 𝕜} (hz : z ∈ spectrum 𝕜 a) : exp 𝕜 z ∈ spectrum 𝕜 (exp 𝕜 a) := begin have hexpmul : exp 𝕜 a = exp 𝕜 (a - ↑ₐ z) * ↑ₐ (exp 𝕜 z), { rw [algebra_map_exp_comm z, ←exp_add_of_commute (algebra.commutes z (a - ↑ₐz)).symm, sub_add_cancel] }, let b := ∑' n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ n, have hb : summable (λ n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ n), { refine summable_of_norm_bounded_eventually _ (real.summable_pow_div_factorial ‖a - ↑ₐz‖) _, filter_upwards [filter.eventually_cofinite_ne 0] with n hn, rw [norm_smul, mul_comm, norm_inv, is_R_or_C.norm_eq_abs, is_R_or_C.abs_cast_nat, ←div_eq_mul_inv], exact div_le_div (pow_nonneg (norm_nonneg _) n) (norm_pow_le' (a - ↑ₐz) (zero_lt_iff.mpr hn)) (by exact_mod_cast nat.factorial_pos n) (by exact_mod_cast nat.factorial_le (lt_add_one n).le) }, have h₀ : ∑' n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ (n + 1) = (a - ↑ₐz) * b, { simpa only [mul_smul_comm, pow_succ] using hb.tsum_mul_left (a - ↑ₐz) }, have h₁ : ∑' n : ℕ, ((n + 1).factorial⁻¹ : 𝕜) • (a - ↑ₐz) ^ (n + 1) = b * (a - ↑ₐz), { simpa only [pow_succ', algebra.smul_mul_assoc] using hb.tsum_mul_right (a - ↑ₐz) }, have h₃ : exp 𝕜 (a - ↑ₐz) = 1 + (a - ↑ₐz) * b, { rw exp_eq_tsum, convert tsum_eq_zero_add (exp_series_summable' (a - ↑ₐz)), simp only [nat.factorial_zero, nat.cast_one, inv_one, pow_zero, one_smul], exact h₀.symm }, rw [spectrum.mem_iff, is_unit.sub_iff, ←one_mul (↑ₐ(exp 𝕜 z)), hexpmul, ←_root_.sub_mul, commute.is_unit_mul_iff (algebra.commutes (exp 𝕜 z) (exp 𝕜 (a - ↑ₐz) - 1)).symm, sub_eq_iff_eq_add'.mpr h₃, commute.is_unit_mul_iff (h₀ ▸ h₁ : (a - ↑ₐz) * b = b * (a - ↑ₐz))], exact not_and_of_not_left _ (not_and_of_not_left _ ((not_iff_not.mpr is_unit.sub_iff).mp hz)), end end exp_mapping end spectrum namespace alg_hom section normed_field variables {F : Type*} [normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] local notation `↑ₐ` := algebra_map 𝕜 A /-- An algebra homomorphism into the base field, as a continuous linear map (since it is automatically bounded). See note [lower instance priority] -/ @[priority 100] instance [alg_hom_class F 𝕜 A 𝕜] : continuous_linear_map_class F 𝕜 A 𝕜 := { map_continuous := λ φ, add_monoid_hom_class.continuous_of_bound φ ‖(1 : A)‖ $ λ a, (mul_comm ‖a‖ ‖(1 : A)‖) ▸ spectrum.norm_le_norm_mul_of_mem (apply_mem_spectrum φ _), .. alg_hom_class.linear_map_class } /-- An algebra homomorphism into the base field, as a continuous linear map (since it is automatically bounded). -/ def to_continuous_linear_map (φ : A →ₐ[𝕜] 𝕜) : A →L[𝕜] 𝕜 := { cont := map_continuous φ, .. φ.to_linear_map } @[simp] lemma coe_to_continuous_linear_map (φ : A →ₐ[𝕜] 𝕜) : ⇑φ.to_continuous_linear_map = φ := rfl lemma norm_apply_le_self_mul_norm_one [alg_hom_class F 𝕜 A 𝕜] (f : F) (a : A) : ‖f a‖ ≤ ‖a‖ * ‖(1 : A)‖ := spectrum.norm_le_norm_mul_of_mem (apply_mem_spectrum f _) lemma norm_apply_le_self [norm_one_class A] [alg_hom_class F 𝕜 A 𝕜] (f : F) (a : A) : ‖f a‖ ≤ ‖a‖ := spectrum.norm_le_norm_of_mem (apply_mem_spectrum f _) end normed_field section nontrivially_normed_field variables [nontrivially_normed_field 𝕜] [normed_ring A] [normed_algebra 𝕜 A] [complete_space A] local notation `↑ₐ` := algebra_map 𝕜 A @[simp] lemma to_continuous_linear_map_norm [norm_one_class A] (φ : A →ₐ[𝕜] 𝕜) : ‖φ.to_continuous_linear_map‖ = 1 := continuous_linear_map.op_norm_eq_of_bounds zero_le_one (λ a, (one_mul ‖a‖).symm ▸ spectrum.norm_le_norm_of_mem (apply_mem_spectrum φ _)) (λ _ _ h, by simpa only [coe_to_continuous_linear_map, map_one, norm_one, mul_one] using h 1) end nontrivially_normed_field end alg_hom namespace weak_dual namespace character_space variables [nontrivially_normed_field 𝕜] [normed_ring A] [complete_space A] variables [normed_algebra 𝕜 A] /-- The equivalence between characters and algebra homomorphisms into the base field. -/ def equiv_alg_hom : (character_space 𝕜 A) ≃ (A →ₐ[𝕜] 𝕜) := { to_fun := to_alg_hom, inv_fun := λ f, { val := f.to_continuous_linear_map, property := by { rw eq_set_map_one_map_mul, exact ⟨map_one f, map_mul f⟩ } }, left_inv := λ f, subtype.ext $ continuous_linear_map.ext $ λ x, rfl, right_inv := λ f, alg_hom.ext $ λ x, rfl } @[simp] lemma equiv_alg_hom_coe (f : character_space 𝕜 A) : ⇑(equiv_alg_hom f) = f := rfl @[simp] lemma equiv_alg_hom_symm_coe (f : A →ₐ[𝕜] 𝕜) : ⇑(equiv_alg_hom.symm f) = f := rfl end character_space end weak_dual
4550177a68b924fd02c9969947f1528e32489726
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1207.lean
01957fa371a49fe496bb8e1f9ed0d017071bcf5a
[ "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
468
lean
example : true := begin have H : true := (by trivial), exact H end example : true := begin have H : true := (by tactic.triv), exact H end meta example (h : tactic unit) : true := begin h, -- ERROR h should not be visible here trivial end example : false := begin have H : true := (by foo), -- ERROR exact sorry end constant P : Prop example (p : P) : true := begin have H : P := by do { p ← tactic.get_local `p, tactic.exact p }, trivial end
52b86d32f30f23d0367d512818ac015778867ad6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/ulift.lean
1524014a1e53bfb7a33905feb091e3624ad9f7e6
[]
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,784
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Jannis Limperg Facts about `ulift` and `plift`. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort universes u v u_1 u_2 u_3 namespace Mathlib namespace plift /-- Functorial action. -/ @[simp] protected def map {α : Sort u} {β : Sort v} (f : α → β) : plift α → plift β := sorry /-- Embedding of pure values. -/ @[simp] protected def pure {α : Sort u} : α → plift α := up /-- Applicative sequencing. -/ @[simp] protected def seq {α : Sort u} {β : Sort v} : plift (α → β) → plift α → plift β := sorry /-- Monadic bind. -/ @[simp] protected def bind {α : Sort u} {β : Sort v} : plift α → (α → plift β) → plift β := sorry protected instance monad : Monad plift := { toApplicative := { toFunctor := { map := plift.map, mapConst := fun (α β : Type u_1) => plift.map ∘ function.const β }, toPure := { pure := plift.pure }, toSeq := { seq := plift.seq }, toSeqLeft := { seqLeft := fun (α β : Type u_1) (a : plift α) (b : plift β) => plift.seq (plift.map (function.const β) a) b }, toSeqRight := { seqRight := fun (α β : Type u_1) (a : plift α) (b : plift β) => plift.seq (plift.map (function.const α id) a) b } }, toBind := { bind := plift.bind } } protected instance is_lawful_functor : is_lawful_functor plift := is_lawful_functor.mk (fun (α : Type u_1) (_x : plift α) => sorry) fun (α β γ : Type u_1) (g : α → β) (h : β → γ) (_x : plift α) => sorry protected instance is_lawful_applicative : is_lawful_applicative plift := is_lawful_applicative.mk (fun (α β : Type u_1) (g : α → β) (_x : plift α) => sorry) (fun (α β : Type u_1) (g : α → β) (x : α) => rfl) (fun (α β : Type u_1) (_x : plift (α → β)) => sorry) fun (α β γ : Type u_1) (_x : plift α) => sorry protected instance is_lawful_monad : is_lawful_monad plift := is_lawful_monad.mk (fun (α β : Type u_1) (x : α) (f : α → plift β) => rfl) fun (α β γ : Type u_1) (_x : plift α) => sorry @[simp] theorem rec.constant {α : Sort u} {β : Type v} (b : β) : (plift.rec fun (_x : α) => b) = fun (_x : plift α) => b := funext fun (x : plift α) => cases_on x fun (a : α) => Eq.refl (plift.rec (fun (_x : α) => b) (up a)) end plift namespace ulift /-- Functorial action. -/ @[simp] protected def map {α : Type u} {β : Type v} (f : α → β) : ulift α → ulift β := sorry /-- Embedding of pure values. -/ @[simp] protected def pure {α : Type u} : α → ulift α := up /-- Applicative sequencing. -/ @[simp] protected def seq {α : Type u} {β : Type v} : ulift (α → β) → ulift α → ulift β := sorry /-- Monadic bind. -/ @[simp] protected def bind {α : Type u} {β : Type v} : ulift α → (α → ulift β) → ulift β := sorry -- The `up ∘ down` gives us more universe polymorphism than simply `f a`. protected instance monad : Monad ulift := { toApplicative := { toFunctor := { map := ulift.map, mapConst := fun (α β : Type u_1) => ulift.map ∘ function.const β }, toPure := { pure := ulift.pure }, toSeq := { seq := ulift.seq }, toSeqLeft := { seqLeft := fun (α β : Type u_1) (a : ulift α) (b : ulift β) => ulift.seq (ulift.map (function.const β) a) b }, toSeqRight := { seqRight := fun (α β : Type u_1) (a : ulift α) (b : ulift β) => ulift.seq (ulift.map (function.const α id) a) b } }, toBind := { bind := ulift.bind } } protected instance is_lawful_functor : is_lawful_functor ulift := is_lawful_functor.mk (fun (α : Type u_1) (_x : ulift α) => sorry) fun (α β γ : Type u_1) (g : α → β) (h : β → γ) (_x : ulift α) => sorry protected instance is_lawful_applicative : is_lawful_applicative ulift := is_lawful_applicative.mk (fun (α β : Type u_1) (g : α → β) (_x : ulift α) => sorry) (fun (α β : Type u_1) (g : α → β) (x : α) => rfl) (fun (α β : Type u_1) (_x : ulift (α → β)) => sorry) fun (α β γ : Type u_1) (_x : ulift α) => sorry protected instance is_lawful_monad : is_lawful_monad ulift := is_lawful_monad.mk (fun (α β : Type u_1) (x : α) (f : α → ulift β) => id (cases_on (f x) fun (down : β) => Eq.refl (up (down (up down))))) fun (α β γ : Type u_1) (_x : ulift α) => sorry @[simp] theorem rec.constant {α : Type u} {β : Sort v} (b : β) : (ulift.rec fun (_x : α) => b) = fun (_x : ulift α) => b := funext fun (x : ulift α) => cases_on x fun (a : α) => Eq.refl (ulift.rec (fun (_x : α) => b) (up a))
683f1fa2b9aca2b7441f61f56968cf41e3822ee9
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/polynomial/vieta.lean
89f365ece15ab973f85385d92325e5d2d771c0d1
[ "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
4,360
lean
/- Copyright (c) 2020 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import ring_theory.polynomial.basic import ring_theory.polynomial.symmetric /-! # Vieta's Formula The main result is `vieta.prod_X_add_C_eq_sum_esymm`, which shows that the product of linear terms `λ + X i` is equal to a linear combination of the symmetric polynomials `esymm σ R j`. ## Implementation Notes: We first take the viewpoint where the "roots" `X i` are variables. This means we work over `polynomial (mv_polynomial σ R)`, which enables us to talk about linear combinations of `esymm σ R j`. We then derive Vieta's formula in `polynomial R` by giving a valuation from each `X i` to `r i`. -/ open_locale big_operators polynomial open finset polynomial fintype namespace mv_polynomial variables {R : Type*} [comm_semiring R] variables (σ : Type*) [fintype σ] /-- A sum version of Vieta's formula. Viewing `X i` as variables, the product of linear terms `λ + X i` is equal to a linear combination of the symmetric polynomials `esymm σ R j`. -/ lemma prod_X_add_C_eq_sum_esymm : (∏ i : σ, (polynomial.C (X i) + polynomial.X) : polynomial (mv_polynomial σ R) )= ∑ j in range (card σ + 1), (polynomial.C (esymm σ R j) * polynomial.X ^ (card σ - j)) := begin classical, rw [prod_add, sum_powerset], refine sum_congr begin congr end (λ j hj, _), rw [esymm, map_sum, sum_mul], refine sum_congr rfl (λ t ht, _), have h : (univ \ t).card = card σ - j := by { rw card_sdiff (mem_powerset_len.mp ht).1, congr, exact (mem_powerset_len.mp ht).2 }, rw [map_prod, prod_const, ← h], end /-- A fully expanded sum version of Vieta's formula, evaluated at the roots. The product of linear terms `X + r i` is equal to `∑ j in range (n + 1), e_j * X ^ (n - j)`, where `e_j` is the `j`th symmetric polynomial of the constant terms `r i`. -/ lemma prod_X_add_C_eval (r : σ → R) : ∏ i : σ, (polynomial.C (r i) + polynomial.X) = ∑ i in range (card σ + 1), (∑ t in powerset_len i (univ : finset σ), ∏ i in t, polynomial.C (r i)) * polynomial.X ^ (card σ - i) := begin classical, have h := @prod_X_add_C_eq_sum_esymm _ _ σ _, apply_fun (polynomial.map (eval r)) at h, rw [polynomial.map_prod, polynomial.map_sum] at h, convert h, simp only [eval_X, polynomial.map_add, polynomial.map_C, polynomial.map_X, eq_self_iff_true], funext, simp only [function.funext_iff, esymm, polynomial.map_C, polynomial.map_sum, map_sum, polynomial.map_C, polynomial.map_pow, polynomial.map_X, polynomial.map_mul], congr, funext, simp only [eval_prod, eval_X, map_prod], end lemma esymm_to_sum (r : σ → R) (j : ℕ) : polynomial.C (eval r (esymm σ R j)) = ∑ t in powerset_len j (univ : finset σ), ∏ i in t, polynomial.C (r i) := by simp only [esymm, eval_sum, eval_prod, eval_X, map_sum, map_prod] /-- Vieta's formula for the coefficients of the product of linear terms `X + r i`, The `k`th coefficient is `∑ t in powerset_len (card σ - k) (univ : finset σ), ∏ i in t, r i`, i.e. the symmetric polynomial `esymm σ R (card σ - k)` of the constant terms `r i`. -/ lemma prod_X_add_C_coeff (r : σ → R) (k : ℕ) (h : k ≤ card σ): polynomial.coeff (∏ i : σ, (polynomial.C (r i) + polynomial.X)) k = ∑ t in powerset_len (card σ - k) (univ : finset σ), ∏ i in t, r i := begin have hk : filter (λ (x : ℕ), k = card σ - x) (range (card σ + 1)) = {card σ - k} := begin refine finset.ext (λ a, ⟨λ ha, _, λ ha, _ ⟩), rw mem_singleton, have hσ := (tsub_eq_iff_eq_add_of_le (mem_range_succ_iff.mp (mem_filter.mp ha).1)).mp ((mem_filter.mp ha).2).symm, symmetry, rwa [(tsub_eq_iff_eq_add_of_le h), add_comm], rw mem_filter, have haσ : a ∈ range (card σ + 1) := by { rw mem_singleton.mp ha, exact mem_range_succ_iff.mpr (@tsub_le_self _ _ _ _ _ k) }, refine ⟨haσ, eq.symm _⟩, rw tsub_eq_iff_eq_add_of_le (mem_range_succ_iff.mp haσ), have hσ := (tsub_eq_iff_eq_add_of_le h).mp (mem_singleton.mp ha).symm, rwa add_comm, end, simp only [prod_X_add_C_eval, ← esymm_to_sum, finset_sum_coeff, coeff_C_mul_X_pow, sum_ite, hk, sum_singleton, esymm, eval_sum, eval_prod, eval_X, add_zero, sum_const_zero], end end mv_polynomial
da176a774cbf9c0f8ce3193304979aeaa7617435
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world02/level01.lean
e42ca4631eb616be408456921381e763667f0e2d
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
162
lean
import mynat.definition import mynat.add lemma zero_add (n : mynat) : 0 + n = n := begin induction n with d hd, rw add_zero, refl, rw add_succ, rw hd, refl, end
e8ff569ece7441faf9fbfe4b22ea5ff9493bb64f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Control/Lawful.lean
633f24e23f6c5b7a78027cbb0a4904f589d4a081
[ "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
14,335
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.SimpLemmas import Init.Control.Except import Init.Control.StateRef open Function @[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x := rfl class LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β id_map (x : f α) : id <$> x = x comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x export LawfulFunctor (map_const id_map comp_map) attribute [simp] id_map @[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x := id_map x class LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x) seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x comp_map g h x := (by repeat rw [← pure_seq] simp [seq_assoc, map_pure, seq_pure]) export LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc) attribute [simp] map_pure seq_pure @[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by simp [pure_seq] class LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where bind_pure_comp (f : α → β) (x : m α) : x >>= (fun a => pure (f a)) = f <$> x bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x pure_bind (x : α) (f : α → m β) : pure x >>= f = f x bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g map_pure g x := (by rw [← bind_pure_comp, pure_bind]) seq_pure g x := (by rw [← bind_map]; simp [map_pure, bind_pure_comp]) seq_assoc x g h := (by simp [← bind_pure_comp, ← bind_map, bind_assoc, pure_bind]) export LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc) attribute [simp] pure_bind bind_assoc @[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by show x >>= (fun a => pure (id a)) = x rw [bind_pure_comp, id_map] theorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by rw [← bind_pure_comp] theorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by rw [← bind_map] theorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by simp [funext h] @[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by rw [bind_pure] theorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by simp [funext h] theorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by rw [bind_map] theorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by rw [seqRight_eq] simp [map_eq_pure_bind, seq_eq_bind_map, const] theorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map] /-! # Id -/ namespace Id @[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl @[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl @[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl instance : LawfulMonad Id := by refine' { .. } <;> intros <;> rfl end Id /-! # ExceptT -/ namespace ExceptT theorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by simp [run] at h assumption @[simp] theorem run_pure [Monad m] (x : α) : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl @[simp] theorem run_lift [Monad.{u, v} m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl @[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl @[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind] @[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk] theorem run_bind [Monad m] (x : ExceptT ε m α) : run (x >>= f : ExceptT ε m β) = run x >>= fun | Except.ok x => run (f x) | Except.error e => pure (Except.error e) := rfl @[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by simp [ExceptT.lift, pure, ExceptT.pure] @[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : (f <$> x).run = Except.map f <$> x.run := by simp [Functor.map, ExceptT.map, map_eq_pure_bind] apply bind_congr intro a; cases a <;> simp [Except.map] protected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x := rfl protected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by intros; rfl protected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y rw [← ExceptT.bind_pure_comp] apply ext simp [run_bind] apply bind_congr intro | Except.error _ => simp | Except.ok _ => simp [map_eq_pure_bind]; apply bind_congr; intro b; cases b <;> simp [comp, Except.map, const] protected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y rw [← ExceptT.bind_pure_comp] apply ext simp [run_bind] apply bind_congr intro a; cases a <;> simp instance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where id_map := by intros; apply ext; simp map_const := by intros; rfl seqLeft_eq := ExceptT.seqLeft_eq seqRight_eq := ExceptT.seqRight_eq pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind] bind_pure_comp := ExceptT.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; simp [run_bind] bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp end ExceptT /-! # ReaderT -/ namespace ReaderT theorem ext {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by simp [run] at h exact funext h @[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl @[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ) : (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl @[simp] theorem run_mapConst [Monad m] (a : α) (x : ReaderT ρ m β) (ctx : ρ) : (Functor.mapConst a x).run ctx = Functor.mapConst a (x.run ctx) := rfl @[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ) : (f <$> x).run ctx = f <$> x.run ctx := rfl @[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ) : (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl @[simp] theorem run_monadMap [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ) : (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl @[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl @[simp] theorem run_seq {α β : Type u} [Monad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ) : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := rfl @[simp] theorem run_seqRight [Monad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x *> y).run ctx = (x.run ctx *> y.run ctx) := rfl @[simp] theorem run_seqLeft [Monad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x <* y).run ctx = (x.run ctx <* y.run ctx) := rfl instance [Monad m] [LawfulFunctor m] : LawfulFunctor (ReaderT ρ m) where id_map := by intros; apply ext; simp map_const := by intros; funext a b; apply ext; intros; simp [map_const] comp_map := by intros; apply ext; intros; simp [comp_map] instance [Monad m] [LawfulApplicative m] : LawfulApplicative (ReaderT ρ m) where seqLeft_eq := by intros; apply ext; intros; simp [seqLeft_eq] seqRight_eq := by intros; apply ext; intros; simp [seqRight_eq] pure_seq := by intros; apply ext; intros; simp [pure_seq] map_pure := by intros; apply ext; intros; simp [map_pure] seq_pure := by intros; apply ext; intros; simp [seq_pure] seq_assoc := by intros; apply ext; intros; simp [seq_assoc] instance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where bind_pure_comp := by intros; apply ext; intros; simp [LawfulMonad.bind_pure_comp] bind_map := by intros; apply ext; intros; simp [bind_map] pure_bind := by intros; apply ext; intros; simp bind_assoc := by intros; apply ext; intros; simp end ReaderT /-! # StateRefT -/ instance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) := inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m)) /-! # StateT -/ namespace StateT theorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y := funext h @[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s := rfl @[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl @[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ) : (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by simp [bind, StateT.bind, run] @[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by simp [Functor.map, StateT.map, run, map_eq_pure_bind] @[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl @[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl @[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl @[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run] @[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl @[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by simp [StateT.lift, StateT.run, bind, StateT.bind] @[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl @[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ) : (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl @[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by show (f >>= fun g => g <$> x).run s = _ simp @[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by show (x >>= fun _ => y).run s = _ simp @[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by show (x >>= fun a => y >>= fun _ => pure a).run s = _ simp theorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by apply ext; intro s simp [map_eq_pure_bind, const] apply bind_congr; intro p; cases p simp [Prod.eta] theorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by apply ext; intro s simp [map_eq_pure_bind] instance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where id_map := by intros; apply ext; intros; simp[Prod.eta] map_const := by intros; rfl seqLeft_eq := seqLeft_eq seqRight_eq := seqRight_eq pure_seq := by intros; apply ext; intros; simp bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; intros; simp bind_assoc := by intros; apply ext; intros; simp end StateT
f72da53f92fb66d1b0a579d942279443f61d2ef7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/group_theory/perm/support.lean
b779f3197931fe851b29a26e98dedf1251179ff8
[ "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
20,738
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Aaron Anderson, Yakov Pechersky -/ import data.finset.card import data.fintype.basic import group_theory.perm.basic /-! # Support of a permutation ## Main definitions In the following, `f g : equiv.perm α`. * `equiv.perm.disjoint`: two permutations `f` and `g` are `disjoint` if every element is fixed either by `f`, or by `g`. Equivalently, `f` and `g` are `disjoint` iff their `support` are disjoint. * `equiv.perm.is_swap`: `f = swap x y` for `x ≠ y`. * `equiv.perm.support`: the elements `x : α` that are not fixed by `f`. -/ open equiv finset namespace equiv.perm variables {α : Type*} section disjoint /-- Two permutations `f` and `g` are `disjoint` if their supports are disjoint, i.e., every element is fixed either by `f`, or by `g`. -/ def disjoint (f g : perm α) := ∀ x, f x = x ∨ g x = x variables {f g h : perm α} @[symm] lemma disjoint.symm : disjoint f g → disjoint g f := by simp only [disjoint, or.comm, imp_self] lemma disjoint.symmetric : symmetric (@disjoint α) := λ _ _, disjoint.symm instance : is_symm (perm α) disjoint := ⟨disjoint.symmetric⟩ lemma disjoint_comm : disjoint f g ↔ disjoint g f := ⟨disjoint.symm, disjoint.symm⟩ lemma disjoint.commute (h : disjoint f g) : commute f g := equiv.ext $ λ x, (h x).elim (λ hf, (h (g x)).elim (λ hg, by simp [mul_apply, hf, hg]) (λ hg, by simp [mul_apply, hf, g.injective hg])) (λ hg, (h (f x)).elim (λ hf, by simp [mul_apply, f.injective hf, hg]) (λ hf, by simp [mul_apply, hf, hg])) @[simp] lemma disjoint_one_left (f : perm α) : disjoint 1 f := λ _, or.inl rfl @[simp] lemma disjoint_one_right (f : perm α) : disjoint f 1 := λ _, or.inr rfl lemma disjoint_iff_eq_or_eq : disjoint f g ↔ ∀ (x : α), f x = x ∨ g x = x := iff.rfl @[simp] lemma disjoint_refl_iff : disjoint f f ↔ f = 1 := begin refine ⟨λ h, _, λ h, h.symm ▸ disjoint_one_left 1⟩, ext x, cases h x with hx hx; simp [hx] end lemma disjoint.inv_left (h : disjoint f g) : disjoint f⁻¹ g := begin intro x, rw [inv_eq_iff_eq, eq_comm], exact h x end lemma disjoint.inv_right (h : disjoint f g) : disjoint f g⁻¹ := h.symm.inv_left.symm @[simp] lemma disjoint_inv_left_iff : disjoint f⁻¹ g ↔ disjoint f g := begin refine ⟨λ h, _, disjoint.inv_left⟩, convert h.inv_left, exact (inv_inv _).symm end @[simp] lemma disjoint_inv_right_iff : disjoint f g⁻¹ ↔ disjoint f g := by rw [disjoint_comm, disjoint_inv_left_iff, disjoint_comm] lemma disjoint.mul_left (H1 : disjoint f h) (H2 : disjoint g h) : disjoint (f * g) h := λ x, by cases H1 x; cases H2 x; simp * lemma disjoint.mul_right (H1 : disjoint f g) (H2 : disjoint f h) : disjoint f (g * h) := by { rw disjoint_comm, exact H1.symm.mul_left H2.symm } lemma disjoint_prod_right (l : list (perm α)) (h : ∀ g ∈ l, disjoint f g) : disjoint f l.prod := begin induction l with g l ih, { exact disjoint_one_right _ }, { rw list.prod_cons, exact (h _ (list.mem_cons_self _ _)).mul_right (ih (λ g hg, h g (list.mem_cons_of_mem _ hg))) } end lemma disjoint_prod_perm {l₁ l₂ : list (perm α)} (hl : l₁.pairwise disjoint) (hp : l₁ ~ l₂) : l₁.prod = l₂.prod := hp.prod_eq' $ hl.imp $ λ f g, disjoint.commute lemma nodup_of_pairwise_disjoint {l : list (perm α)} (h1 : (1 : perm α) ∉ l) (h2 : l.pairwise disjoint) : l.nodup := begin refine list.pairwise.imp_of_mem _ h2, rintros σ - h_mem - h_disjoint rfl, suffices : σ = 1, { rw this at h_mem, exact h1 h_mem }, exact ext (λ a, (or_self _).mp (h_disjoint a)), end lemma pow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℕ, (f ^ n) x = x | 0 := rfl | (n+1) := by rw [pow_succ', mul_apply, hfx, pow_apply_eq_self_of_apply_eq_self] lemma zpow_apply_eq_self_of_apply_eq_self {x : α} (hfx : f x = x) : ∀ n : ℤ, (f ^ n) x = x | (n : ℕ) := pow_apply_eq_self_of_apply_eq_self hfx n | -[1+ n] := by rw [zpow_neg_succ_of_nat, inv_eq_iff_eq, pow_apply_eq_self_of_apply_eq_self hfx] lemma pow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ n : ℕ, (f ^ n) x = x ∨ (f ^ n) x = f x | 0 := or.inl rfl | (n+1) := (pow_apply_eq_of_apply_apply_eq_self n).elim (λ h, or.inr (by rw [pow_succ, mul_apply, h])) (λ h, or.inl (by rw [pow_succ, mul_apply, h, hffx])) lemma zpow_apply_eq_of_apply_apply_eq_self {x : α} (hffx : f (f x) = x) : ∀ i : ℤ, (f ^ i) x = x ∨ (f ^ i) x = f x | (n : ℕ) := pow_apply_eq_of_apply_apply_eq_self hffx n | -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_eq_iff_eq, ← f.injective.eq_iff, ← mul_apply, ← pow_succ, eq_comm, inv_eq_iff_eq, ← mul_apply, ← pow_succ', @eq_comm _ x, or.comm], exact pow_apply_eq_of_apply_apply_eq_self hffx _ } lemma disjoint.mul_apply_eq_iff {σ τ : perm α} (hστ : disjoint σ τ) {a : α} : (σ * τ) a = a ↔ σ a = a ∧ τ a = a := begin refine ⟨λ h, _, λ h, by rw [mul_apply, h.2, h.1]⟩, cases hστ a with hσ hτ, { exact ⟨hσ, σ.injective (h.trans hσ.symm)⟩ }, { exact ⟨(congr_arg σ hτ).symm.trans h, hτ⟩ }, end lemma disjoint.mul_eq_one_iff {σ τ : perm α} (hστ : disjoint σ τ) : σ * τ = 1 ↔ σ = 1 ∧ τ = 1 := by simp_rw [ext_iff, one_apply, hστ.mul_apply_eq_iff, forall_and_distrib] lemma disjoint.zpow_disjoint_zpow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℤ) : disjoint (σ ^ m) (τ ^ n) := λ x, or.imp (λ h, zpow_apply_eq_self_of_apply_eq_self h m) (λ h, zpow_apply_eq_self_of_apply_eq_self h n) (hστ x) lemma disjoint.pow_disjoint_pow {σ τ : perm α} (hστ : disjoint σ τ) (m n : ℕ) : disjoint (σ ^ m) (τ ^ n) := hστ.zpow_disjoint_zpow m n end disjoint section is_swap variable [decidable_eq α] /-- `f.is_swap` indicates that the permutation `f` is a transposition of two elements. -/ def is_swap (f : perm α) : Prop := ∃ x y, x ≠ y ∧ f = swap x y @[simp] lemma of_subtype_swap_eq {p : α → Prop} [decidable_pred p] (x y : subtype p) : (equiv.swap x y).of_subtype = equiv.swap ↑x ↑y := equiv.ext $ λ z, begin by_cases hz : p z, { rw [swap_apply_def, of_subtype_apply_of_mem _ hz], split_ifs with hzx hzy, { simp_rw [hzx, subtype.coe_eta, swap_apply_left], }, { simp_rw [hzy, subtype.coe_eta, swap_apply_right], }, { rw swap_apply_of_ne_of_ne, refl, intro h, apply hzx, rw ← h, refl, intro h, apply hzy, rw ← h, refl, } }, { rw [of_subtype_apply_of_not_mem _ hz, swap_apply_of_ne_of_ne], intro h, apply hz, rw h, exact subtype.prop x, intro h, apply hz, rw h, exact subtype.prop y, } end lemma is_swap.of_subtype_is_swap {p : α → Prop} [decidable_pred p] {f : perm (subtype p)} (h : f.is_swap) : (of_subtype f).is_swap := let ⟨⟨x, hx⟩, ⟨y, hy⟩, hxy⟩ := h in ⟨x, y, by { simp only [ne.def] at hxy, exact hxy.1 }, by { simp only [hxy.2, of_subtype_swap_eq], refl, }⟩ lemma ne_and_ne_of_swap_mul_apply_ne_self {f : perm α} {x y : α} (hy : (swap x (f x) * f) y ≠ y) : f y ≠ y ∧ y ≠ x := begin simp only [swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end end is_swap section support section set variables (p q : perm α) lemma set_support_inv_eq : {x | p⁻¹ x ≠ x} = {x | p x ≠ x} := begin ext x, simp only [set.mem_set_of_eq, ne.def], rw [inv_def, symm_apply_eq, eq_comm] end lemma set_support_apply_mem {p : perm α} {a : α} : p a ∈ {x | p x ≠ x} ↔ a ∈ {x | p x ≠ x} := by simp lemma set_support_zpow_subset (n : ℤ) : {x | (p ^ n) x ≠ x} ⊆ {x | p x ≠ x} := begin intros x, simp only [set.mem_set_of_eq, ne.def], intros hx H, simpa [zpow_apply_eq_self_of_apply_eq_self H] using hx end lemma set_support_mul_subset : {x | (p * q) x ≠ x} ⊆ {x | p x ≠ x} ∪ {x | q x ≠ x} := begin intro x, simp only [perm.coe_mul, function.comp_app, ne.def, set.mem_union, set.mem_set_of_eq], by_cases hq : q x = x; simp [hq] end end set variables [decidable_eq α] [fintype α] {f g : perm α} /-- The `finset` of nonfixed points of a permutation. -/ def support (f : perm α) : finset α := univ.filter (λ x, f x ≠ x) @[simp] lemma mem_support {x : α} : x ∈ f.support ↔ f x ≠ x := by rw [support, mem_filter, and_iff_right (mem_univ x)] lemma not_mem_support {x : α} : x ∉ f.support ↔ f x = x := by simp lemma coe_support_eq_set_support (f : perm α) : (f.support : set α) = {x | f x ≠ x} := by { ext, simp } @[simp] lemma support_eq_empty_iff {σ : perm α} : σ.support = ∅ ↔ σ = 1 := by simp_rw [finset.ext_iff, mem_support, finset.not_mem_empty, iff_false, not_not, equiv.perm.ext_iff, one_apply] @[simp] lemma support_one : (1 : perm α).support = ∅ := by rw support_eq_empty_iff @[simp] lemma support_refl : support (equiv.refl α) = ∅ := support_one lemma support_congr (h : f.support ⊆ g.support) (h' : ∀ x ∈ g.support, f x = g x) : f = g := begin ext x, by_cases hx : x ∈ g.support, { exact h' x hx }, { rw [not_mem_support.mp hx, ←not_mem_support], exact λ H, hx (h H) } end lemma support_mul_le (f g : perm α) : (f * g).support ≤ f.support ⊔ g.support := λ x, begin rw [sup_eq_union, mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], rintro ⟨hf, hg⟩, rw [hg, hf] end lemma exists_mem_support_of_mem_support_prod {l : list (perm α)} {x : α} (hx : x ∈ l.prod.support) : ∃ f : perm α, f ∈ l ∧ x ∈ f.support := begin contrapose! hx, simp_rw [mem_support, not_not] at hx ⊢, induction l with f l ih generalizing hx, { refl }, { rw [list.prod_cons, mul_apply, ih (λ g hg, hx g (or.inr hg)), hx f (or.inl rfl)] }, end lemma support_pow_le (σ : perm α) (n : ℕ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (pow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_inv (σ : perm α) : support (σ⁻¹) = σ.support := by simp_rw [finset.ext_iff, mem_support, not_iff_not, (inv_eq_iff_eq).trans eq_comm, iff_self, imp_true_iff] @[simp] lemma apply_mem_support {x : α} : f x ∈ f.support ↔ x ∈ f.support := by rw [mem_support, mem_support, ne.def, ne.def, not_iff_not, apply_eq_iff_eq] @[simp] lemma pow_apply_mem_support {n : ℕ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin induction n with n ih, { refl }, rw [pow_succ, perm.mul_apply, apply_mem_support, ih] end @[simp] lemma zpow_apply_mem_support {n : ℤ} {x : α} : (f ^ n) x ∈ f.support ↔ x ∈ f.support := begin cases n, { rw [int.of_nat_eq_coe, zpow_coe_nat, pow_apply_mem_support] }, { rw [zpow_neg_succ_of_nat, ← support_inv, ← inv_pow, pow_apply_mem_support] } end lemma pow_eq_on_of_mem_support (h : ∀ (x ∈ f.support ∩ g.support), f x = g x) (k : ℕ) : ∀ (x ∈ f.support ∩ g.support), (f ^ k) x = (g ^ k) x := begin induction k with k hk, { simp }, { intros x hx, rw [pow_succ', mul_apply, pow_succ', mul_apply, h _ hx, hk], rwa [mem_inter, apply_mem_support, ←h _ hx, apply_mem_support, ←mem_inter] } end lemma disjoint_iff_disjoint_support : disjoint f g ↔ _root_.disjoint f.support g.support := by simp [disjoint_iff_eq_or_eq, disjoint_iff, finset.ext_iff, not_and_distrib] lemma disjoint.disjoint_support (h : disjoint f g) : _root_.disjoint f.support g.support := disjoint_iff_disjoint_support.1 h lemma disjoint.support_mul (h : disjoint f g) : (f * g).support = f.support ∪ g.support := begin refine le_antisymm (support_mul_le _ _) (λ a, _), rw [mem_union, mem_support, mem_support, mem_support, mul_apply, ←not_and_distrib, not_imp_not], exact (h a).elim (λ hf h, ⟨hf, f.apply_eq_iff_eq.mp (h.trans hf.symm)⟩) (λ hg h, ⟨(congr_arg f hg).symm.trans h, hg⟩), end lemma support_prod_of_pairwise_disjoint (l : list (perm α)) (h : l.pairwise disjoint) : l.prod.support = (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.pairwise_cons] at h, have : disjoint hd tl.prod := disjoint_prod_right _ h.left, simp [this.support_mul, hl h.right] } end lemma support_prod_le (l : list (perm α)) : l.prod.support ≤ (l.map support).foldr (⊔) ⊥ := begin induction l with hd tl hl, { simp }, { rw [list.prod_cons, list.map_cons, list.foldr_cons], refine (support_mul_le hd tl.prod).trans _, exact sup_le_sup le_rfl hl } end lemma support_zpow_le (σ : perm α) (n : ℤ) : (σ ^ n).support ≤ σ.support := λ x h1, mem_support.mpr (λ h2, mem_support.mp h1 (zpow_apply_eq_self_of_apply_eq_self h2 n)) @[simp] lemma support_swap {x y : α} (h : x ≠ y) : support (swap x y) = {x, y} := begin ext z, by_cases hx : z = x, any_goals { simpa [hx] using h.symm }, by_cases hy : z = y; { simp [swap_apply_of_ne_of_ne, hx, hy]; cc } end lemma support_swap_iff (x y : α) : support (swap x y) = {x, y} ↔ x ≠ y := begin refine ⟨λ h H, _, support_swap⟩, subst H, simp only [swap_self, support_refl, pair_eq_singleton] at h, have : x ∈ ∅, { rw h, exact mem_singleton.mpr rfl }, simpa end lemma support_swap_mul_swap {x y z : α} (h : list.nodup [x, y, z]) : support (swap x y * swap y z) = {x, y, z} := begin simp only [list.not_mem_nil, and_true, list.mem_cons_iff, not_false_iff, list.nodup_cons, list.mem_singleton, and_self, list.nodup_nil] at h, push_neg at h, apply le_antisymm, { convert support_mul_le _ _, rw [support_swap h.left.left, support_swap h.right], ext, simp [or.comm, or.left_comm] }, { intro, simp only [mem_insert, mem_singleton], rintro (rfl | rfl | rfl | _); simp [swap_apply_of_ne_of_ne, h.left.left, h.left.left.symm, h.left.right, h.left.right.symm, h.right.symm] } end lemma support_swap_mul_ge_support_diff (f : perm α) (x y : α) : f.support \ {x, y} ≤ (swap x y * f).support := begin intro, simp only [and_imp, perm.coe_mul, function.comp_app, ne.def, mem_support, mem_insert, mem_sdiff, mem_singleton], push_neg, rintro ha ⟨hx, hy⟩ H, rw [swap_apply_eq_iff, swap_apply_of_ne_of_ne hx hy] at H, exact ha H end lemma support_swap_mul_eq (f : perm α) (x : α) (h : f (f x) ≠ x) : (swap x (f x) * f).support = f.support \ {x} := begin by_cases hx : f x = x, { simp [hx, sdiff_singleton_eq_erase, not_mem_support.mpr hx, erase_eq_of_not_mem] }, ext z, by_cases hzx : z = x, { simp [hzx] }, by_cases hzf : z = f x, { simp [hzf, hx, h, swap_apply_of_ne_of_ne], }, by_cases hzfx : f z = x, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx] }, { simp [ne.symm hzx, hzx, ne.symm hzf, hzfx, f.injective.ne hzx, swap_apply_of_ne_of_ne] } end lemma mem_support_swap_mul_imp_mem_support_ne {x y : α} (hy : y ∈ support (swap x (f x) * f)) : y ∈ support f ∧ y ≠ x := begin simp only [mem_support, swap_apply_def, mul_apply, f.injective.eq_iff] at *, by_cases h : f y = x, { split; intro; simp only [*, if_true, eq_self_iff_true, not_true, ne.def] at * }, { split_ifs at hy; cc } end lemma disjoint.mem_imp (h : disjoint f g) {x : α} (hx : x ∈ f.support) : x ∉ g.support := disjoint_left.mp h.disjoint_support hx lemma eq_on_support_mem_disjoint {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : ∀ (x ∈ f.support), f x = l.prod x := begin induction l with hd tl IH, { simpa using h }, { intros x hx, rw list.pairwise_cons at hl, rw list.mem_cons_iff at h, rcases h with rfl|h, { rw [list.prod_cons, mul_apply, not_mem_support.mp ((disjoint_prod_right tl hl.left).mem_imp hx)] }, { rw [list.prod_cons, mul_apply, ←IH h hl.right _ hx, eq_comm, ←not_mem_support], refine (hl.left _ h).symm.mem_imp _, simpa using hx } } end lemma disjoint.mono {x y : perm α} (h : disjoint f g) (hf : x.support ≤ f.support) (hg : y.support ≤ g.support) : disjoint x y := begin rw disjoint_iff_disjoint_support at h ⊢, exact h.mono hf hg, end lemma support_le_prod_of_mem {l : list (perm α)} (h : f ∈ l) (hl : l.pairwise disjoint) : f.support ≤ l.prod.support := begin intros x hx, rwa [mem_support, ←eq_on_support_mem_disjoint h hl _ hx, ←mem_support], end section extend_domain variables {β : Type*} [decidable_eq β] [fintype β] {p : β → Prop} [decidable_pred p] @[simp] lemma support_extend_domain (f : α ≃ subtype p) {g : perm α} : support (g.extend_domain f) = g.support.map f.as_embedding := begin ext b, simp only [exists_prop, function.embedding.coe_fn_mk, to_embedding_apply, mem_map, ne.def, function.embedding.trans_apply, mem_support], by_cases pb : p b, { rw [extend_domain_apply_subtype _ _ pb], split, { rintro h, refine ⟨f.symm ⟨b, pb⟩, _, by simp⟩, contrapose! h, simp [h] }, { rintro ⟨a, ha, hb⟩, contrapose! ha, obtain rfl : a = f.symm ⟨b, pb⟩, { rw eq_symm_apply, exact subtype.coe_injective hb }, rw eq_symm_apply, exact subtype.coe_injective ha } }, { rw [extend_domain_apply_not_subtype _ _ pb], simp only [not_exists, false_iff, not_and, eq_self_iff_true, not_true], rintros a ha rfl, exact pb (subtype.prop _) } end lemma card_support_extend_domain (f : α ≃ subtype p) {g : perm α} : (g.extend_domain f).support.card = g.support.card := by simp end extend_domain section card @[simp] lemma card_support_eq_zero {f : perm α} : f.support.card = 0 ↔ f = 1 := by rw [finset.card_eq_zero, support_eq_empty_iff] lemma one_lt_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 1 < f.support.card := begin simp_rw [one_lt_card_iff, mem_support, ←not_or_distrib], contrapose! h, ext a, specialize h (f a) a, rwa [apply_eq_iff_eq, or_self, or_self] at h, end lemma card_support_ne_one (f : perm α) : f.support.card ≠ 1 := begin by_cases h : f = 1, { exact ne_of_eq_of_ne (card_support_eq_zero.mpr h) zero_ne_one }, { exact ne_of_gt (one_lt_card_support_of_ne_one h) }, end @[simp] lemma card_support_le_one {f : perm α} : f.support.card ≤ 1 ↔ f = 1 := by rw [le_iff_lt_or_eq, nat.lt_succ_iff, le_zero_iff, card_support_eq_zero, or_iff_not_imp_right, imp_iff_right f.card_support_ne_one] lemma two_le_card_support_of_ne_one {f : perm α} (h : f ≠ 1) : 2 ≤ f.support.card := one_lt_card_support_of_ne_one h lemma card_support_swap_mul {f : perm α} {x : α} (hx : f x ≠ x) : (swap x (f x) * f).support.card < f.support.card := finset.card_lt_card ⟨λ z hz, (mem_support_swap_mul_imp_mem_support_ne hz).left, λ h, absurd (h (mem_support.2 hx)) (mt mem_support.1 (by simp))⟩ lemma card_support_swap {x y : α} (hxy : x ≠ y) : (swap x y).support.card = 2 := show (swap x y).support.card = finset.card ⟨x ::ₘ y ::ₘ 0, by simp [hxy]⟩, from congr_arg card $ by simp [support_swap hxy, *, finset.ext_iff] @[simp] lemma card_support_eq_two {f : perm α} : f.support.card = 2 ↔ is_swap f := begin split; intro h, { obtain ⟨x, t, hmem, hins, ht⟩ := card_eq_succ.1 h, obtain ⟨y, rfl⟩ := card_eq_one.1 ht, rw mem_singleton at hmem, refine ⟨x, y, hmem, _⟩, ext a, have key : ∀ b, f b ≠ b ↔ _ := λ b, by rw [←mem_support, ←hins, mem_insert, mem_singleton], by_cases ha : f a = a, { have ha' := not_or_distrib.mp (mt (key a).mpr (not_not.mpr ha)), rw [ha, swap_apply_of_ne_of_ne ha'.1 ha'.2] }, { have ha' := (key (f a)).mp (mt f.apply_eq_iff_eq.mp ha), obtain rfl | rfl := ((key a).mp ha), { rw [or.resolve_left ha' ha, swap_apply_left] }, { rw [or.resolve_right ha' ha, swap_apply_right] } } }, { obtain ⟨x, y, hxy, rfl⟩ := h, exact card_support_swap hxy } end lemma disjoint.card_support_mul (h : disjoint f g) : (f * g).support.card = f.support.card + g.support.card := begin rw ←finset.card_disjoint_union, { congr, ext, simp [h.support_mul] }, { simpa using h.disjoint_support } end lemma card_support_prod_list_of_pairwise_disjoint {l : list (perm α)} (h : l.pairwise disjoint) : l.prod.support.card = (l.map (finset.card ∘ support)).sum := begin induction l with a t ih, { exact card_support_eq_zero.mpr rfl, }, { obtain ⟨ha, ht⟩ := list.pairwise_cons.1 h, rw [list.prod_cons, list.map_cons, list.sum_cons, ←ih ht], exact (disjoint_prod_right _ ha).card_support_mul } end end card end support end equiv.perm
639f6b2075b6098c52acdd4b2ee403dc5603b01c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/match_convoy.lean
112101a42623f3920af48b9a0afbb6f8d3749d92
[ "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
2,737
lean
definition foo (a b : bool) : bool := match a, b with | tt, ff := tt | tt, tt := tt | ff, tt := tt | ff, ff := ff end example : foo tt tt = tt := rfl example : foo tt ff = tt := rfl example : foo ff tt = tt := rfl example : foo ff ff = ff := rfl inductive vec (A : Type) : nat → Type | nil {} : vec nat.zero | cons : ∀ {n}, A → vec n → vec (nat.succ n) open vec definition boo (n : nat) (v : vec bool n) : vec bool n := match n, v : ∀ (n : _), vec bool n → _ with | 0, nil := nil | n+1, cons a v := cons (bnot a) v end constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid noncomputable definition bag (A : Type) : Type := quotient (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quotient.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) noncomputable definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix (name := subbag) ⊆ := subbag attribute [instance] noncomputable definition decidable_subbag {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end) attribute [instance] noncomputable definition decidable_subbag2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match psigma.mk (subcount l₁ l₂) rfl : (Σ' (b : _), subcount l₁ l₂ = b) → _ with | psigma.mk tt H := is_true (all_of_subcount_eq_tt H) | psigma.mk ff H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end) local notation ⟦ a , b ⟧ := psigma.mk a b attribute [instance] noncomputable definition decidable_subbag3 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match ⟦subcount l₁ l₂, rfl⟧ : (Σ' (b : _), subcount l₁ l₂ = b) → _ with | ⟦tt, H⟧ := is_true (all_of_subcount_eq_tt H) | ⟦ff, H⟧ := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end)
37c714503a9504bf83994744dacd26a874f72608
d531288a798ba153485c54976a6d77d1c10fed24
/src/humanproof.lean
c700ef8c2b29d271e92ae5fcba8e83eaacf44295
[]
no_license
EdAyers/lean-humanproof
f757f6d40bd57ce44f5e92f89b1c1994afb0ad05
7fa4cc5a95c1bd4d7dc309bb8c132a6ca500fe8e
refs/heads/master
1,585,168,875,076
1,533,927,266,000
1,533,927,266,000
144,141,041
5
0
null
null
null
null
UTF-8
Lean
false
false
5,211
lean
-- The *moves* as explained in the G&G paper. -- -- --Deletion -- deleteDone, -- done by Lean. -- deleteDoneDisjunct, -- done by Lean. -- deleteDangling, -- need to detect this, then use `clear`. -- deleteUnmatchable, -- need to detect this, then use `clear`. -- --Tidying -- peelAndSplitUniversalConditionalTarget, -- this would be `intros`, or do we need something more specialised? -- It's intros applied only when has form `∀(a:α), (∀(a:α), | (P->)) Q` and it does them all in one go. -- splitDisjunctiveHypothesis, -- this would be `cases`, but again that might be too general. -- Yep it's a specialisation of cases (E) -- splitConjunctiveTarget, -- there is a general purpose tactic called `split`. It might be to aggressive. See Remark (1) below. -- will need to read up on split (E) -- splitDisjunctiveTarget, -- in Lean you can't have two goals (=boxes) joined by `∨`. Need to thing about the tagging. -- We can do this by `try {refine (inj _), ...rest_of_tactic}` or similar. -- peelBareUniversalTarget, -- this would also be `intros`. So a couple lines up we need something specialised. Also see Remark (2). -- removeTarget, -- this is a class of moves. No direct equivalent in Lean. -- I'll have to look at the source to remind myself what this does. -- collapseSubboxTarget, -- probably done by Lean. -- --Applying -- forwardsReasoning, -- `have h₃ : X := h₁ h₂, ` where h₁ h₂ are in context -- forwardsLibraryReasoning, -- `have h₃ : X := l h₂, ` where h₁ in context and l is found through a search procedure. -- expandPreExistentialHypothesis, -- no direct equivalent in Lean. This seems to be a conditional `unfold` followed by `cases`. -- elementaryExpansionOfHypothesis, -- would this be something like `unfold * at *` or `dsimp at *`? Currently `at *` also effects the goal. -- backwardsReasoning, -- this is something like; `apply assumption`. -- backwardsLibraryReasoning, -- search through the library and find results whose conclusion can be `apply`ed. We can use an algorithm like SInE to search sensibly. -- elementaryExpansionOfTarget, -- some sort of `unfold *`. Maybe `dsimp`. -- expandPreUniversalTarget, -- this would also be `intros`. So a couple lines up we need something specialised. -- solveBullets, -- synthesize placeholders. -- automaticRewrite, -- no direct equivalent in Lean. See Remark (3). -- will be overhauled (E) -- --Suspension -- unlockExistentialUniversalConditionalTarget, -- this is making a placeholder `_` to fill in later, so kind of reminds me of `refine` but not really. -- unlockExistentialTarget, -- see above ^ -- expandPreExistentialTarget, -- this seems to be a conditional `unfold`. -- convertDiamondToBullet, -- no direct equivalent in Lean.-- tag identifiers in some way -- --EqualitySubstitution -- rewriteVariableVariableEquality, -- no direct equivalent in Lean. See Remark (3). -- Me and Tim want to overhaul these anyway so let's not worry about them too much. (E) -- rewriteVariableTermEquality -- no direct equivalent in Lean. See Remark (3). -- In the original GG implementation they just had a library of carefully chosen rewrite rules, so I don't think these will scale anyway (E) /- Remark (1). We will have to think about types. In the G&G setting there is no such thing as a type. I guess humans have a pretty intuitive way of thinking about inductive types. And maybe the `split` tactic is exactly what we need. Remark (2). In the G&G paper, during the explanation of `peelBareUniversalTarget` there is some discussion about "background information". There is no natural analogue of this in Lean. Indeed, it seems quite a psychological notion. Maybe this can be dealt with using some sort of tagging. Remark (3). Scott has a tactic called `rewrite_search`. It uses an edit-distance heuristic to look for a chain of rewrites that will discharge goals of the form A = B. (i) One could imagine a non-finishing version of this tactic. That will rewrite the goal into something like A' = B' with an improved edit-distance. (ii) A student of Scott is currently writing an improved version of this tactic. It will use machine learning to find the chain of rewrites. There is a tactic `rewrite` but it doesn't do any reasoning or automation. It has to be told explicitly what the use for the rewrite. Remark (4). For the suspension moves we might be able to use Lean's metavariables. On the other hand, I have bad experiences with using metavariables before specifying their value. -/
cd8a38a0da4cd345bab8b7b8501582e103c00ee3
94e33a31faa76775069b071adea97e86e218a8ee
/archive/imo/imo2008_q3.lean
9cf6d16121cbd1708c8ce84d4d326d231ebdf2b3
[ "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
3,831
lean
/- Copyright (c) 2021 Manuel Candales. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Manuel Candales -/ import data.real.basic import data.real.sqrt import data.nat.prime import number_theory.primes_congruent_one import number_theory.legendre_symbol.quadratic_reciprocity import tactic.linear_combination /-! # IMO 2008 Q3 Prove that there exist infinitely many positive integers `n` such that `n^2 + 1` has a prime divisor which is greater than `2n + √(2n)`. # Solution We first prove the following lemma: for every prime `p > 20`, satisfying `p ≡ 1 [MOD 4]`, there exists `n ∈ ℕ` such that `p ∣ n^2 + 1` and `p > 2n + √(2n)`. Then the statement of the problem follows from the fact that there exist infinitely many primes `p ≡ 1 [MOD 4]`. To prove the lemma, notice that `p ≡ 1 [MOD 4]` implies `∃ n ∈ ℕ` such that `n^2 ≡ -1 [MOD p]` and we can take this `n` such that `n ≤ p/2`. Let `k = p - 2n ≥ 0`. Then we have: `k^2 + 4 = (p - 2n)^2 + 4 ≣ 4n^2 + 4 ≡ 0 [MOD p]`. Then `k^2 + 4 ≥ p` and so `k ≥ √(p - 4) > 4`. Then `p = 2n + k ≥ 2n + √(p - 4) = 2n + √(2n + k - 4) > √(2n)` and we are done. -/ open real lemma p_lemma (p : ℕ) (hpp : nat.prime p) (hp_mod_4_eq_1 : p ≡ 1 [MOD 4]) (hp_gt_20 : p > 20) : ∃ n : ℕ, p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt(2 * n) := begin haveI := fact.mk hpp, have hp_mod_4_ne_3 : p % 4 ≠ 3, { linarith [(show p % 4 = 1, by exact hp_mod_4_eq_1)] }, obtain ⟨y, hy⟩ := (zmod.exists_sq_eq_neg_one_iff p).mpr hp_mod_4_ne_3, let m := zmod.val_min_abs y, let n := int.nat_abs m, have hnat₁ : p ∣ n ^ 2 + 1, { refine int.coe_nat_dvd.mp _, simp only [int.nat_abs_sq, int.coe_nat_pow, int.coe_nat_succ, int.coe_nat_dvd.mp], refine (zmod.int_coe_zmod_eq_zero_iff_dvd (m ^ 2 + 1) p).mp _, simp only [int.cast_pow, int.cast_add, int.cast_one, zmod.coe_val_min_abs], rw [pow_two, ← hy], exact add_left_neg 1 }, have hnat₂ : n ≤ p / 2 := zmod.nat_abs_val_min_abs_le y, have hnat₃ : p ≥ 2 * n, { linarith [nat.div_mul_le_self p 2] }, set k : ℕ := p - 2 * n with hnat₄, have hnat₅ : p ∣ k ^ 2 + 4, { cases hnat₁ with x hx, have : (p:ℤ) ∣ k ^ 2 + 4, { use (p:ℤ) - 4 * n + 4 * x, have hcast₁ : (k:ℤ) = p - 2 * n, { assumption_mod_cast }, have hcast₂ : (n:ℤ) ^ 2 + 1 = p * x, { assumption_mod_cast }, linear_combination ((k:ℤ) + p - 2 * n)*hcast₁ + 4*hcast₂ }, assumption_mod_cast }, have hnat₆ : k ^ 2 + 4 ≥ p := nat.le_of_dvd (k ^ 2 + 3).succ_pos hnat₅, have hreal₁ : (k:ℝ) = p - 2 * n, { assumption_mod_cast }, have hreal₂ : (p:ℝ) > 20, { assumption_mod_cast }, have hreal₃ : (k:ℝ) ^ 2 + 4 ≥ p, { assumption_mod_cast }, have hreal₅ : (k:ℝ) > 4, { apply lt_of_pow_lt_pow 2 k.cast_nonneg, linarith only [hreal₂, hreal₃] }, have hreal₆ : (k:ℝ) > sqrt (2 * n), { apply lt_of_pow_lt_pow 2 k.cast_nonneg, rw sq_sqrt (mul_nonneg zero_le_two n.cast_nonneg), linarith only [hreal₁, hreal₃, hreal₅] }, exact ⟨n, hnat₁, by linarith only [hreal₆, hreal₁]⟩, end theorem imo2008_q3 : ∀ N : ℕ, ∃ n : ℕ, n ≥ N ∧ ∃ p : ℕ, nat.prime p ∧ p ∣ n ^ 2 + 1 ∧ (p : ℝ) > 2 * n + sqrt(2 * n) := begin intro N, obtain ⟨p, hpp, hineq₁, hpmod4⟩ := nat.exists_prime_ge_modeq_one (N ^ 2 + 21) zero_lt_four, obtain ⟨n, hnat, hreal⟩ := p_lemma p hpp hpmod4 (by linarith [hineq₁, nat.zero_le (N ^ 2)]), have hineq₂ : n ^ 2 + 1 ≥ p := nat.le_of_dvd (n ^ 2).succ_pos hnat, have hineq₃ : n * n ≥ N * N, { linarith [hineq₁, hineq₂] }, have hn_ge_N : n ≥ N := nat.mul_self_le_mul_self_iff.mpr hineq₃, exact ⟨n, hn_ge_N, p, hpp, hnat, hreal⟩, end
92e273f01e37ad0d9be871f9ad74fe593399df91
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/new_frontend2.lean
b913ad8f5586f7a615013b7f8b54fb66dc222723
[ "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
753
lean
new_frontend declare_syntax_cat foo variable {m : Type → Type} variable [s : Functor m] #check @Nat.rec #check s.map /- The following doesn't work because ``` variable [r : Monad m] #check r.map ``` because `Monad.to* methods have bad binder annotations -/ theorem aux (a b c : Nat) (h₁ : a = b) (h₂ : c = b) : a = c := by let! aux := h₂.symm subst aux subst h₁ exact rfl def ex1 : {α : Type} → {a b c : α} → a = b → b = c → a = c := @(by intro α a b c h₁ h₂ exact Eq.trans h₁ h₂) def f1 (x : Nat) : Nat := by apply (· + ?hole) exact 1 case hole => exact x theorem ex2 (x : Nat) : f1 x = 1 + x := rfl def f2 (x : Nat) : Nat := by apply Nat.add _ exact 1 exact x theorem ex3 (x : Nat) : f2 x = x + 1 := rfl
ac4a110560628e011c5e492d6cfa20ad557efaff
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/adjunction/limits.lean
76373aadf58544a94f313b5768c66726392b8ec1
[]
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
14,346
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.adjunction.basic import Mathlib.category_theory.limits.creates import Mathlib.PostPort universes u₁ u₂ v namespace Mathlib namespace category_theory.adjunction /-- The right adjoint of `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`. Auxiliary definition for `functoriality_is_left_adjoint`. -/ def functoriality_right_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ C) : limits.cocone (K ⋙ F) ⥤ limits.cocone K := limits.cocones.functoriality (K ⋙ F) G ⋙ limits.cocones.precompose (iso.inv (functor.right_unitor K) ≫ whisker_left K (unit adj) ≫ iso.inv (functor.associator K F G)) /-- The unit for the adjunction for `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`. Auxiliary definition for `functoriality_is_left_adjoint`. -/ def functoriality_unit {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ C) : 𝟭 ⟶ limits.cocones.functoriality K F ⋙ functoriality_right_adjoint adj K := nat_trans.mk fun (c : limits.cocone K) => limits.cocone_morphism.mk (nat_trans.app (unit adj) (limits.cocone.X c)) /-- The counit for the adjunction for `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)`. Auxiliary definition for `functoriality_is_left_adjoint`. -/ def functoriality_counit {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ C) : functoriality_right_adjoint adj K ⋙ limits.cocones.functoriality K F ⟶ 𝟭 := nat_trans.mk fun (c : limits.cocone (K ⋙ F)) => limits.cocone_morphism.mk (nat_trans.app (counit adj) (limits.cocone.X c)) /-- The functor `cocones.functoriality K F : cocone K ⥤ cocone (K ⋙ F)` is a left adjoint. -/ def functoriality_is_left_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ C) : is_left_adjoint (limits.cocones.functoriality K F) := is_left_adjoint.mk (functoriality_right_adjoint adj K) (mk_of_unit_counit (core_unit_counit.mk (functoriality_unit adj K) (functoriality_counit adj K))) /-- A left adjoint preserves colimits. See https://stacks.math.columbia.edu/tag/0038. -/ def left_adjoint_preserves_colimits {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) : limits.preserves_colimits F := limits.preserves_colimits.mk fun (J : Type v) (𝒥 : small_category J) => limits.preserves_colimits_of_shape.mk fun (F_1 : J ⥤ C) => limits.preserves_colimit.mk fun (c : limits.cocone F_1) (hc : limits.is_colimit c) => iso.inv limits.is_colimit.iso_unique_cocone_morphism fun (s : limits.cocone (F_1 ⋙ F)) => equiv.unique (hom_equiv is_left_adjoint.adj c s) protected instance is_equivalence_preserves_colimits {C : Type u₁} [category C] {D : Type u₂} [category D] (E : C ⥤ D) [is_equivalence E] : limits.preserves_colimits E := left_adjoint_preserves_colimits (functor.adjunction E) protected instance is_equivalence_reflects_colimits {C : Type u₁} [category C] {D : Type u₂} [category D] (E : D ⥤ C) [is_equivalence E] : limits.reflects_colimits E := limits.reflects_colimits.mk fun (J : Type v) (𝒥 : small_category J) => limits.reflects_colimits_of_shape.mk fun (K : J ⥤ D) => limits.reflects_colimit.mk fun (c : limits.cocone K) (t : limits.is_colimit (functor.map_cocone E c)) => limits.is_colimit.of_iso_colimit (coe_fn (equiv.symm (limits.is_colimit.precompose_inv_equiv (functor.right_unitor K) (functor.map_cocone 𝟭 c))) (limits.is_colimit.map_cocone_equiv (functor.fun_inv_id E) (limits.is_colimit_of_preserves (functor.inv E) t))) (limits.cocones.ext sorry sorry) protected instance is_equivalence_creates_colimits {C : Type u₁} [category C] {D : Type u₂} [category D] (H : D ⥤ C) [is_equivalence H] : creates_colimits H := creates_colimits.mk fun (J : Type v) (𝒥 : small_category J) => creates_colimits_of_shape.mk fun (F : J ⥤ D) => creates_colimit.mk fun (c : limits.cocone (F ⋙ H)) (t : limits.is_colimit c) => liftable_cocone.mk (functor.map_cocone_inv H c) (functor.map_cocone_map_cocone_inv H c) -- verify the preserve_colimits instance works as expected: protected instance has_colimit_comp_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {J : Type v} [small_category J] (K : J ⥤ C) (E : C ⥤ D) [is_equivalence E] [limits.has_colimit K] : limits.has_colimit (K ⋙ E) := limits.has_colimit.mk (limits.colimit_cocone.mk (functor.map_cocone E (limits.colimit.cocone K)) (limits.preserves_colimit.preserves (limits.colimit.is_colimit K))) theorem has_colimit_of_comp_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {J : Type v} [small_category J] (K : J ⥤ C) (E : C ⥤ D) [is_equivalence E] [limits.has_colimit (K ⋙ E)] : limits.has_colimit K := limits.has_colimit_of_iso (iso.symm (functor.right_unitor K) ≪≫ iso.symm (iso_whisker_left K (functor.fun_inv_id E))) /-- The left adjoint of `cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`. Auxiliary definition for `functoriality_is_right_adjoint`. -/ def functoriality_left_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ D) : limits.cone (K ⋙ G) ⥤ limits.cone K := limits.cones.functoriality (K ⋙ G) F ⋙ limits.cones.postcompose (iso.hom (functor.associator K G F) ≫ whisker_left K (counit adj) ≫ iso.hom (functor.right_unitor K)) /-- The unit for the adjunction for`cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`. Auxiliary definition for `functoriality_is_right_adjoint`. -/ @[simp] theorem functoriality_unit'_app_hom {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ D) (c : limits.cone (K ⋙ G)) : limits.cone_morphism.hom (nat_trans.app (functoriality_unit' adj K) c) = nat_trans.app (unit adj) (limits.cone.X c) := Eq.refl (limits.cone_morphism.hom (nat_trans.app (functoriality_unit' adj K) c)) /-- The counit for the adjunction for`cones.functoriality K G : cone K ⥤ cone (K ⋙ G)`. Auxiliary definition for `functoriality_is_right_adjoint`. -/ @[simp] theorem functoriality_counit'_app_hom {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ D) (c : limits.cone K) : limits.cone_morphism.hom (nat_trans.app (functoriality_counit' adj K) c) = nat_trans.app (counit adj) (limits.cone.X c) := Eq.refl (limits.cone_morphism.hom (nat_trans.app (functoriality_counit' adj K) c)) /-- The functor `cones.functoriality K G : cone K ⥤ cone (K ⋙ G)` is a right adjoint. -/ def functoriality_is_right_adjoint {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] (K : J ⥤ D) : is_right_adjoint (limits.cones.functoriality K G) := is_right_adjoint.mk (functoriality_left_adjoint adj K) (mk_of_unit_counit (core_unit_counit.mk (functoriality_unit' adj K) (functoriality_counit' adj K))) /-- A right adjoint preserves limits. See https://stacks.math.columbia.edu/tag/0038. -/ def right_adjoint_preserves_limits {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) : limits.preserves_limits G := limits.preserves_limits.mk fun (J : Type v) (𝒥 : small_category J) => limits.preserves_limits_of_shape.mk fun (K : J ⥤ D) => limits.preserves_limit.mk fun (c : limits.cone K) (hc : limits.is_limit c) => iso.inv limits.is_limit.iso_unique_cone_morphism fun (s : limits.cone (K ⋙ G)) => equiv.unique (equiv.symm (hom_equiv is_right_adjoint.adj s c)) protected instance is_equivalence_preserves_limits {C : Type u₁} [category C] {D : Type u₂} [category D] (E : D ⥤ C) [is_equivalence E] : limits.preserves_limits E := right_adjoint_preserves_limits (functor.adjunction (functor.inv E)) protected instance is_equivalence_reflects_limits {C : Type u₁} [category C] {D : Type u₂} [category D] (E : D ⥤ C) [is_equivalence E] : limits.reflects_limits E := limits.reflects_limits.mk fun (J : Type v) (𝒥 : small_category J) => limits.reflects_limits_of_shape.mk fun (K : J ⥤ D) => limits.reflects_limit.mk fun (c : limits.cone K) (t : limits.is_limit (functor.map_cone E c)) => limits.is_limit.of_iso_limit (coe_fn (equiv.symm (limits.is_limit.postcompose_hom_equiv (functor.left_unitor K) (functor.map_cone 𝟭 c))) (limits.is_limit.map_cone_equiv (functor.fun_inv_id E) (limits.is_limit_of_preserves (functor.inv E) t))) (limits.cones.ext sorry sorry) protected instance is_equivalence_creates_limits {C : Type u₁} [category C] {D : Type u₂} [category D] (H : D ⥤ C) [is_equivalence H] : creates_limits H := creates_limits.mk fun (J : Type v) (𝒥 : small_category J) => creates_limits_of_shape.mk fun (F : J ⥤ D) => creates_limit.mk fun (c : limits.cone (F ⋙ H)) (t : limits.is_limit c) => liftable_cone.mk (functor.map_cone_inv H c) (functor.map_cone_map_cone_inv H c) -- verify the preserve_limits instance works as expected: protected instance has_limit_comp_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {J : Type v} [small_category J] (K : J ⥤ D) (E : D ⥤ C) [is_equivalence E] [limits.has_limit K] : limits.has_limit (K ⋙ E) := limits.has_limit.mk (limits.limit_cone.mk (functor.map_cone E (limits.limit.cone K)) (limits.preserves_limit.preserves (limits.limit.is_limit K))) theorem has_limit_of_comp_equivalence {C : Type u₁} [category C] {D : Type u₂} [category D] {J : Type v} [small_category J] (K : J ⥤ D) (E : D ⥤ C) [is_equivalence E] [limits.has_limit (K ⋙ E)] : limits.has_limit K := limits.has_limit_of_iso (iso_whisker_left K (functor.fun_inv_id E) ≪≫ functor.right_unitor K) /-- auxiliary construction for `cocones_iso` -/ @[simp] theorem cocones_iso_component_hom_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : functor.obj (functor.obj (cocones J D) (opposite.op (K ⋙ F))) Y) (j : J) : nat_trans.app (cocones_iso_component_hom adj Y t) j = coe_fn (hom_equiv adj (functor.obj K j) Y) (nat_trans.app t j) := Eq.refl (nat_trans.app (cocones_iso_component_hom adj Y t) j) /-- auxiliary construction for `cocones_iso` -/ def cocones_iso_component_inv {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : functor.obj (G ⋙ functor.obj (cocones J C) (opposite.op K)) Y) : functor.obj (functor.obj (cocones J D) (opposite.op (K ⋙ F))) Y := nat_trans.mk fun (j : J) => coe_fn (equiv.symm (hom_equiv adj (functor.obj K j) Y)) (nat_trans.app t j) /-- When `F ⊣ G`, the functor associating to each `Y` the cocones over `K ⋙ F` with cone point `Y` is naturally isomorphic to the functor associating to each `Y` the cocones over `K` with cone point `G.obj Y`. -/ -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] {K : J ⥤ C} : functor.obj (cocones J D) (opposite.op (K ⋙ F)) ≅ G ⋙ functor.obj (cocones J C) (opposite.op K) := nat_iso.of_components (fun (Y : D) => iso.mk (cocones_iso_component_hom adj Y) (cocones_iso_component_inv adj Y)) sorry /-- auxiliary construction for `cones_iso` -/ @[simp] theorem cones_iso_component_hom_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : functor.obj (functor.op F ⋙ functor.obj (cones J D) K) X) (j : J) : nat_trans.app (cones_iso_component_hom adj X t) j = coe_fn (hom_equiv adj (opposite.unop X) (functor.obj K j)) (nat_trans.app t j) := Eq.refl (nat_trans.app (cones_iso_component_hom adj X t) j) /-- auxiliary construction for `cones_iso` -/ @[simp] theorem cones_iso_component_inv_app {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : functor.obj (functor.obj (cones J C) (K ⋙ G)) X) (j : J) : nat_trans.app (cones_iso_component_inv adj X t) j = coe_fn (equiv.symm (hom_equiv adj (opposite.unop X) (functor.obj K j))) (nat_trans.app t j) := Eq.refl (nat_trans.app (cones_iso_component_inv adj X t) j) -- Note: this is natural in K, but we do not yet have the tools to formulate that. /-- When `F ⊣ G`, the functor associating to each `X` the cones over `K` with cone point `F.op.obj X` is naturally isomorphic to the functor associating to each `X` the cones over `K ⋙ G` with cone point `X`. -/ def cones_iso {C : Type u₁} [category C] {D : Type u₂} [category D] {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) {J : Type v} [small_category J] {K : J ⥤ D} : functor.op F ⋙ functor.obj (cones J D) K ≅ functor.obj (cones J C) (K ⋙ G) := nat_iso.of_components (fun (X : Cᵒᵖ) => iso.mk (cones_iso_component_hom adj X) (cones_iso_component_inv adj X)) sorry
c73d31da8581d45d5f6e8097eb319f62b2afacf1
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/analysis/asymptotics.lean
cbcbe5d9de65bfd21b6e98f4d6fad421caa2f60f
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
51,154
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov -/ import analysis.normed_space.basic import topology.local_homeomorph /-! # Asymptotics We introduce these relations: * `is_O_with c f g l` : "f is big O of g along l with constant c"; * `is_O f g l` : "f is big O of g along l"; * `is_o f g l` : "f is little o of g along l". Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. The relation `is_O_with c` is introduced to factor out common algebraic arguments in the proofs of similar properties of `is_O` and `is_o`. Usually proofs outside of this file should use `is_O` instead. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter set open_locale topological_space big_operators classical namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] [normed_group E'] [normed_group F'] [normed_group G'] [normed_ring R] [normed_ring R'] [normed_field 𝕜] [normed_field 𝕜'] {c c' : ℝ} {f : α → E} {g : α → F} {k : α → G} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l l' : filter α} section defs /-! ### Definitions -/ /-- This version of the Landau notation `is_O_with C f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by `C * ∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded by `C`, modulo division by zero issues that are avoided by this definition. Probably you want to use `is_O` instead of this relation. -/ def is_O_with (c : ℝ) (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ /-- Definition of `is_O_with`. We record it in a lemma as we will set `is_O_with` to be irreducible at the end of this file. -/ lemma is_O_with_iff {c : ℝ} {f : α → E} {g : α → F} {l : filter α} : is_O_with c f g l ↔ ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := iff.rfl lemma is_O_with.of_bound {c : ℝ} {f : α → E} {g : α → F} {l : filter α} (h : ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥) : is_O_with c f g l := h /-- The Landau notation `is_O f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by a constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ def is_O (f : α → E) (g : α → F) (l : filter α) : Prop := ∃ c : ℝ, is_O_with c f g l /-- Definition of `is_O` in terms of `is_O_with`. We record it in a lemma as we will set `is_O` to be irreducible at the end of this file. -/ lemma is_O_iff_is_O_with {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ c : ℝ, is_O_with c f g l := iff.rfl /-- Definition of `is_O` in terms of filters. We record it in a lemma as we will set `is_O` to be irreducible at the end of this file. -/ lemma is_O_iff {f : α → E} {g : α → F} {l : filter α} : is_O f g l ↔ ∃ c : ℝ, ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := iff.rfl lemma is_O.of_bound (c : ℝ) {f : α → E} {g : α → F} {l : filter α} (h : ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥) : is_O f g l := ⟨c, h⟩ /-- The Landau notation `is_o f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by an arbitrarily small constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ def is_o (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c f g l /-- Definition of `is_o` in terms of `is_O_with`. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff_forall_is_O_with {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c f g l := iff.rfl /-- Definition of `is_o` in terms of filters. We record it in a lemma as we will set `is_o` to be irreducible at the end of this file. -/ lemma is_o_iff {f : α → E} {g : α → F} {l : filter α} : is_o f g l ↔ ∀ ⦃c : ℝ⦄, 0 < c → ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := iff.rfl lemma is_o.def {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ := h hc lemma is_o.def' {f : α → E} {g : α → F} {l : filter α} (h : is_o f g l) {c : ℝ} (hc : 0 < c) : is_O_with c f g l := h hc end defs /-! ### Conversions -/ theorem is_O_with.is_O (h : is_O_with c f g l) : is_O f g l := ⟨c, h⟩ theorem is_o.is_O_with (hgf : is_o f g l) : is_O_with 1 f g l := hgf zero_lt_one theorem is_o.is_O (hgf : is_o f g l) : is_O f g l := hgf.is_O_with.is_O theorem is_O_with.weaken (h : is_O_with c f g' l) (hc : c ≤ c') : is_O_with c' f g' l := mem_sets_of_superset h $ λ x hx, calc ∥f x∥ ≤ c * ∥g' x∥ : hx ... ≤ _ : mul_le_mul_of_nonneg_right hc (norm_nonneg _) theorem is_O_with.exists_pos (h : is_O_with c f g' l) : ∃ c' (H : 0 < c'), is_O_with c' f g' l := ⟨max c 1, lt_of_lt_of_le zero_lt_one (le_max_right c 1), h.weaken $ le_max_left c 1⟩ theorem is_O.exists_pos (h : is_O f g' l) : ∃ c (H : 0 < c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_pos theorem is_O_with.exists_nonneg (h : is_O_with c f g' l) : ∃ c' (H : 0 ≤ c'), is_O_with c' f g' l := let ⟨c, cpos, hc⟩ := h.exists_pos in ⟨c, le_of_lt cpos, hc⟩ theorem is_O.exists_nonneg (h : is_O f g' l) : ∃ c (H : 0 ≤ c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_nonneg /-! ### Subsingleton -/ @[nontriviality] lemma is_o_of_subsingleton [subsingleton E'] : is_o f' g' l := λ c hc, is_O_with.of_bound $ by simp [subsingleton.elim (f' _) 0, mul_nonneg hc.le] @[nontriviality] lemma is_O_of_subsingleton [subsingleton E'] : is_O f' g' l := is_o_of_subsingleton.is_O /-! ### Congruence -/ theorem is_O_with_congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₁ f₁ g₁ l ↔ is_O_with c₂ f₂ g₂ l := begin subst c₂, apply filter.congr_sets, filter_upwards [hf, hg], assume x e₁ e₂, rw [e₁, e₂] end theorem is_O_with.congr' {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := (is_O_with_congr hc hf hg).mp theorem is_O_with.congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := λ h, h.congr' hc (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O_with.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O_with c f₁ g l → is_O_with c f₂ g l := is_O_with.congr rfl hf (λ _, rfl) theorem is_O_with.congr_right {g₁ g₂ : α → F} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O_with c f g₁ l → is_O_with c f g₂ l := is_O_with.congr rfl (λ _, rfl) hg theorem is_O_with.congr_const {c₁ c₂} {l : filter α} (hc : c₁ = c₂) : is_O_with c₁ f g l → is_O_with c₂ f g l := is_O_with.congr hc (λ _, rfl) (λ _, rfl) theorem is_O_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := exists_congr $ λ c, is_O_with_congr rfl hf hg theorem is_O.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_O f₁ g₁ l → is_O f₂ g₂ l := (is_O_congr hf hg).mp theorem is_O.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf (λ _, rfl) theorem is_O.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (λ _, rfl) hg theorem is_o_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr (λ c hc, is_O_with_congr (eq.refl c) hf hg) theorem is_o.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : f₁ =ᶠ[l] f₂) (hg : g₁ =ᶠ[l] g₂) : is_o f₁ g₁ l → is_o f₂ g₂ l := (is_o_congr hf hg).mp theorem is_o.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_o.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf (λ _, rfl) theorem is_o.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (λ _, rfl) hg /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto (hcfg : is_O_with c f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l): is_O_with c (f ∘ k) (g ∘ k) l' := hk hcfg theorem is_O.comp_tendsto (hfg : is_O f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_O (f ∘ k) (g ∘ k) l' := hfg.imp (λ c h, h.comp_tendsto hk) theorem is_o.comp_tendsto (hfg : is_o f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_o (f ∘ k) (g ∘ k) l' := λ c cpos, (hfg cpos).comp_tendsto hk theorem is_O_with.mono (h : is_O_with c f g l') (hl : l ≤ l') : is_O_with c f g l := hl h theorem is_O.mono (h : is_O f g l') (hl : l ≤ l') : is_O f g l := h.imp (λ c h, h.mono hl) theorem is_o.mono (h : is_o f g l') (hl : l ≤ l') : is_o f g l := λ c cpos, (h cpos).mono hl theorem is_O_with.trans (hfg : is_O_with c f g l) (hgk : is_O_with c' g k l) (hc : 0 ≤ c) : is_O_with (c * c') f k l := begin filter_upwards [hfg, hgk], assume x hx hx', calc ∥f x∥ ≤ c * ∥g x∥ : hx ... ≤ c * (c' * ∥k x∥) : mul_le_mul_of_nonneg_left hx' hc ... = c * c' * ∥k x∥ : (mul_assoc _ _ _).symm end theorem is_O.trans (hfg : is_O f g' l) (hgk : is_O g' k l) : is_O f k l := let ⟨c, cnonneg, hc⟩ := hfg.exists_nonneg, ⟨c', hc'⟩ := hgk in (hc.trans hc' cnonneg).is_O theorem is_o.trans_is_O_with (hfg : is_o f g l) (hgk : is_O_with c g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact ((hfg this).trans hgk (le_of_lt this)).congr_const (div_mul_cancel _ (ne_of_gt hc)) end theorem is_o.trans_is_O (hfg : is_o f g l) (hgk : is_O g k' l) : is_o f k' l := let ⟨c, cpos, hc⟩ := hgk.exists_pos in hfg.trans_is_O_with hc cpos theorem is_O_with.trans_is_o (hfg : is_O_with c f g l) (hgk : is_o g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact (hfg.trans (hgk this) (le_of_lt hc)).congr_const (mul_div_cancel' _ (ne_of_gt hc)) end theorem is_O.trans_is_o (hfg : is_O f g' l) (hgk : is_o g' k l) : is_o f k l := let ⟨c, cpos, hc⟩ := hfg.exists_pos in hc.trans_is_o hgk cpos theorem is_o.trans (hfg : is_o f g l) (hgk : is_o g k' l) : is_o f k' l := hfg.trans_is_O hgk.is_O theorem is_o.trans' (hfg : is_o f g' l) (hgk : is_o g' k l) : is_o f k l := hfg.is_O.trans_is_o hgk section variable (l) theorem is_O_with_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O_with c f g l := univ_mem_sets' hfg theorem is_O_with_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O_with 1 f g l := is_O_with_of_le' l $ λ x, by { rw one_mul, exact hfg x } theorem is_O_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O f g l := (is_O_with_of_le' l hfg).is_O theorem is_O_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O f g l := (is_O_with_of_le l hfg).is_O end theorem is_O_with_refl (f : α → E) (l : filter α) : is_O_with 1 f f l := is_O_with_of_le l $ λ _, le_refl _ theorem is_O_refl (f : α → E) (l : filter α) : is_O f f l := (is_O_with_refl f l).is_O theorem is_O_with.trans_le (hfg : is_O_with c f g l) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) (hc : 0 ≤ c) : is_O_with c f k l := (hfg.trans (is_O_with_of_le l hgk) hc).congr_const $ mul_one c theorem is_O.trans_le (hfg : is_O f g' l) (hgk : ∀ x, ∥g' x∥ ≤ ∥k x∥) : is_O f k l := hfg.trans (is_O_of_le l hgk) theorem is_o.trans_le (hfg : is_o f g l) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) : is_o f k l := hfg.trans_is_O_with (is_O_with_of_le _ hgk) zero_lt_one section bot variables (c f g) theorem is_O_with_bot : is_O_with c f g ⊥ := trivial theorem is_O_bot : is_O f g ⊥ := (is_O_with_bot c f g).is_O theorem is_o_bot : is_o f g ⊥ := λ c _, is_O_with_bot c f g end bot theorem is_O_with.join (h : is_O_with c f g l) (h' : is_O_with c f g l') : is_O_with c f g (l ⊔ l') := mem_sup_sets.2 ⟨h, h'⟩ theorem is_O_with.join' (h : is_O_with c f g' l) (h' : is_O_with c' f g' l') : is_O_with (max c c') f g' (l ⊔ l') := mem_sup_sets.2 ⟨(h.weaken $ le_max_left c c'), (h'.weaken $ le_max_right c c')⟩ theorem is_O.join (h : is_O f g' l) (h' : is_O f g' l') : is_O f g' (l ⊔ l') := let ⟨c, hc⟩ := h, ⟨c', hc'⟩ := h' in (hc.join' hc').is_O theorem is_o.join (h : is_o f g l) (h' : is_o f g l') : is_o f g (l ⊔ l') := λ c cpos, (h cpos).join (h' cpos) /-! ### Simplification : norm -/ @[simp] theorem is_O_with_norm_right : is_O_with c f (λ x, ∥g' x∥) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_right ↔ asymptotics.is_O_with.of_norm_right asymptotics.is_O_with.norm_right @[simp] theorem is_O_norm_right : is_O f (λ x, ∥g' x∥) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_norm_right alias is_O_norm_right ↔ asymptotics.is_O.of_norm_right asymptotics.is_O.norm_right @[simp] theorem is_o_norm_right : is_o f (λ x, ∥g' x∥) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_right alias is_o_norm_right ↔ asymptotics.is_o.of_norm_right asymptotics.is_o.norm_right @[simp] theorem is_O_with_norm_left : is_O_with c (λ x, ∥f' x∥) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_left ↔ asymptotics.is_O_with.of_norm_left asymptotics.is_O_with.norm_left @[simp] theorem is_O_norm_left : is_O (λ x, ∥f' x∥) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_norm_left alias is_O_norm_left ↔ asymptotics.is_O.of_norm_left asymptotics.is_O.norm_left @[simp] theorem is_o_norm_left : is_o (λ x, ∥f' x∥) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_left alias is_o_norm_left ↔ asymptotics.is_o.of_norm_left asymptotics.is_o.norm_left theorem is_O_with_norm_norm : is_O_with c (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O_with c f' g' l := is_O_with_norm_left.trans is_O_with_norm_right alias is_O_with_norm_norm ↔ asymptotics.is_O_with.of_norm_norm asymptotics.is_O_with.norm_norm theorem is_O_norm_norm : is_O (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O f' g' l := is_O_norm_left.trans is_O_norm_right alias is_O_norm_norm ↔ asymptotics.is_O.of_norm_norm asymptotics.is_O.norm_norm theorem is_o_norm_norm : is_o (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_o f' g' l := is_o_norm_left.trans is_o_norm_right alias is_o_norm_norm ↔ asymptotics.is_o.of_norm_norm asymptotics.is_o.norm_norm /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right : is_O_with c f (λ x, -(g' x)) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_right ↔ asymptotics.is_O_with.of_neg_right asymptotics.is_O_with.neg_right @[simp] theorem is_O_neg_right : is_O f (λ x, -(g' x)) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_neg_right alias is_O_neg_right ↔ asymptotics.is_O.of_neg_right asymptotics.is_O.neg_right @[simp] theorem is_o_neg_right : is_o f (λ x, -(g' x)) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_right alias is_o_neg_right ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_right @[simp] theorem is_O_with_neg_left : is_O_with c (λ x, -(f' x)) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_left ↔ asymptotics.is_O_with.of_neg_left asymptotics.is_O_with.neg_left @[simp] theorem is_O_neg_left : is_O (λ x, -(f' x)) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_neg_left alias is_O_neg_left ↔ asymptotics.is_O.of_neg_left asymptotics.is_O.neg_left @[simp] theorem is_o_neg_left : is_o (λ x, -(f' x)) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_left alias is_o_neg_left ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_left /-! ### Product of functions (right) -/ lemma is_O_with_fst_prod : is_O_with 1 f' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_left _ _ lemma is_O_with_snd_prod : is_O_with 1 g' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_right _ _ lemma is_O_fst_prod : is_O f' (λ x, (f' x, g' x)) l := is_O_with_fst_prod.is_O lemma is_O_snd_prod : is_O g' (λ x, (f' x, g' x)) l := is_O_with_snd_prod.is_O lemma is_O_fst_prod' {f' : α → E' × F'} : is_O (λ x, (f' x).1) f' l := is_O_fst_prod lemma is_O_snd_prod' {f' : α → E' × F'} : is_O (λ x, (f' x).2) f' l := is_O_snd_prod section variables (f' k') lemma is_O_with.prod_rightl (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (g' x, k' x)) l := (h.trans is_O_with_fst_prod hc).congr_const (mul_one c) lemma is_O.prod_rightl (h : is_O f g' l) : is_O f (λx, (g' x, k' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightl k' cnonneg).is_O lemma is_o.prod_rightl (h : is_o f g' l) : is_o f (λ x, (g' x, k' x)) l := λ c cpos, (h cpos).prod_rightl k' (le_of_lt cpos) lemma is_O_with.prod_rightr (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (f' x, g' x)) l := (h.trans is_O_with_snd_prod hc).congr_const (mul_one c) lemma is_O.prod_rightr (h : is_O f g' l) : is_O f (λx, (f' x, g' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightr f' cnonneg).is_O lemma is_o.prod_rightr (h : is_o f g' l) : is_o f (λx, (f' x, g' x)) l := λ c cpos, (h cpos).prod_rightr f' (le_of_lt cpos) end lemma is_O_with.prod_left_same (hf : is_O_with c f' k' l) (hg : is_O_with c g' k' l) : is_O_with c (λ x, (f' x, g' x)) k' l := by filter_upwards [hf, hg] λ x, max_le lemma is_O_with.prod_left (hf : is_O_with c f' k' l) (hg : is_O_with c' g' k' l) : is_O_with (max c c') (λ x, (f' x, g' x)) k' l := (hf.weaken $ le_max_left c c').prod_left_same (hg.weaken $ le_max_right c c') lemma is_O_with.prod_left_fst (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c f' k' l := (is_O_with_fst_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with.prod_left_snd (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c g' k' l := (is_O_with_snd_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with_prod_left : is_O_with c (λ x, (f' x, g' x)) k' l ↔ is_O_with c f' k' l ∧ is_O_with c g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left_same h.2⟩ lemma is_O.prod_left (hf : is_O f' k' l) (hg : is_O g' k' l) : is_O (λ x, (f' x, g' x)) k' l := let ⟨c, hf⟩ := hf, ⟨c', hg⟩ := hg in (hf.prod_left hg).is_O lemma is_O.prod_left_fst (h : is_O (λ x, (f' x, g' x)) k' l) : is_O f' k' l := is_O_fst_prod.trans h lemma is_O.prod_left_snd (h : is_O (λ x, (f' x, g' x)) k' l) : is_O g' k' l := is_O_snd_prod.trans h @[simp] lemma is_O_prod_left : is_O (λ x, (f' x, g' x)) k' l ↔ is_O f' k' l ∧ is_O g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_o.prod_left (hf : is_o f' k' l) (hg : is_o g' k' l) : is_o (λ x, (f' x, g' x)) k' l := λ c hc, (hf hc).prod_left_same (hg hc) lemma is_o.prod_left_fst (h : is_o (λ x, (f' x, g' x)) k' l) : is_o f' k' l := is_O_fst_prod.trans_is_o h lemma is_o.prod_left_snd (h : is_o (λ x, (f' x, g' x)) k' l) : is_o g' k' l := is_O_snd_prod.trans_is_o h @[simp] lemma is_o_prod_left : is_o (λ x, (f' x, g' x)) k' l ↔ is_o f' k' l ∧ is_o g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ /-! ### Addition and subtraction -/ section add_sub variables {c₁ c₂ : ℝ} {f₁ f₂ : α → E'} theorem is_O_with.add (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x + f₂ x) g l := by filter_upwards [h₁, h₂] λ x hx₁ hx₂, calc ∥f₁ x + f₂ x∥ ≤ c₁ * ∥g x∥ + c₂ * ∥g x∥ : norm_add_le_of_le hx₁ hx₂ ... = (c₁ + c₂) * ∥g x∥ : (add_mul _ _ _).symm theorem is_O.add : is_O f₁ g l → is_O f₂ g l → is_O (λ x, f₁ x + f₂ x) g l | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := (hc₁.add hc₂).is_O theorem is_o.add (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x + f₂ x) g l := λ c cpos, ((h₁ $ half_pos cpos).add (h₂ $ half_pos cpos)).congr_const (add_halves c) theorem is_o.add_add {g₁ g₂ : α → F'} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x + f₂ x) (λ x, ∥g₁ x∥ + ∥g₂ x∥) l := by refine (h₁.trans_le $ λ x, _).add (h₂.trans_le _); simp [real.norm_eq_abs, abs_of_nonneg, add_nonneg] theorem is_O.add_is_o (h₁ : is_O f₁ g l) (h₂ : is_o f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.add h₂.is_O theorem is_o.add_is_O (h₁ : is_o f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.is_O.add h₂ theorem is_O_with.add_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₁.add (h₂ (sub_pos.2 hc))).congr_const (add_sub_cancel'_right _ _) theorem is_o.add_is_O_with (h₁ : is_o f₁ g l) (h₂ : is_O_with c₁ f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₂.add_is_o h₁ hc).congr_left $ λ _, add_comm _ _ theorem is_O_with.sub (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x - f₂ x) g l := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left theorem is_O_with.sub_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λ x, f₁ x - f₂ x) g l := by simpa only [sub_eq_add_neg] using h₁.add_is_o h₂.neg_left hc theorem is_O.sub (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x - f₂ x) g l := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left theorem is_o.sub (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x - f₂ x) g l := by simpa only [sub_eq_add_neg] using h₁.add h₂.neg_left end add_sub /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ section is_oO_as_rel variables {f₁ f₂ f₃ : α → E'} theorem is_O_with.symm (h : is_O_with c (λ x, f₁ x - f₂ x) g l) : is_O_with c (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_with_comm : is_O_with c (λ x, f₁ x - f₂ x) g l ↔ is_O_with c (λ x, f₂ x - f₁ x) g l := ⟨is_O_with.symm, is_O_with.symm⟩ theorem is_O.symm (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_comm : is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l := ⟨is_O.symm, is_O.symm⟩ theorem is_o.symm (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o (λ x, f₂ x - f₁ x) g l := by simpa only [neg_sub] using h.neg_left theorem is_o_comm : is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l := ⟨is_o.symm, is_o.symm⟩ theorem is_O_with.triangle (h₁ : is_O_with c (λ x, f₁ x - f₂ x) g l) (h₂ : is_O_with c' (λ x, f₂ x - f₃ x) g l) : is_O_with (c + c') (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.triangle (h₁ : is_O (λ x, f₁ x - f₂ x) g l) (h₂ : is_O (λ x, f₂ x - f₃ x) g l) : is_O (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_o.triangle (h₁ : is_o (λ x, f₁ x - f₂ x) g l) (h₂ : is_o (λ x, f₂ x - f₃ x) g l) : is_o (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.congr_of_sub (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o.congr_of_sub (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ end is_oO_as_rel /-! ### Zero, one, and other constants -/ section zero_const variables (g g' l) theorem is_o_zero : is_o (λ x, (0 : E')) g' l := λ c hc, univ_mem_sets' $ λ x, by simpa using mul_nonneg (le_of_lt hc) (norm_nonneg $ g' x) theorem is_O_with_zero (hc : 0 ≤ c) : is_O_with c (λ x, (0 : E')) g' l := univ_mem_sets' $ λ x, by simpa using mul_nonneg hc (norm_nonneg $ g' x) theorem is_O_with_zero' : is_O_with 0 (λ x, (0 : E')) g l := univ_mem_sets' $ λ x, by simp theorem is_O_zero : is_O (λ x, (0 : E')) g l := ⟨0, is_O_with_zero' _ _⟩ theorem is_O_refl_left : is_O (λ x, f' x - f' x) g' l := (is_O_zero g' l).congr_left $ λ x, (sub_self _).symm theorem is_o_refl_left : is_o (λ x, f' x - f' x) g' l := (is_o_zero g' l).congr_left $ λ x, (sub_self _).symm variables {g g' l} theorem is_O_with_zero_right_iff : is_O_with c f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := by simp only [is_O_with, exists_prop, true_and, norm_zero, mul_zero, norm_le_zero_iff] theorem is_O_zero_right_iff : is_O f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := ⟨λ h, let ⟨c, hc⟩ := h in (is_O_with_zero_right_iff).1 hc, λ h, (is_O_with_zero_right_iff.2 h : is_O_with 1 _ _ _).is_O⟩ theorem is_o_zero_right_iff : is_o f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := ⟨λ h, is_O_zero_right_iff.1 h.is_O, λ h c hc, is_O_with_zero_right_iff.2 h⟩ theorem is_O_with_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O_with (∥c∥ / ∥c'∥) (λ x : α, c) (λ x, c') l := begin apply univ_mem_sets', intro x, rw [mem_set_of_eq, div_mul_cancel], rwa [ne.def, norm_eq_zero] end theorem is_O_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O (λ x : α, c) (λ x, c') l := (is_O_with_const_const c hc' l).is_O end zero_const theorem is_O_with_const_one (c : E) (l : filter α) : is_O_with ∥c∥ (λ x : α, c) (λ x, (1 : 𝕜)) l := begin refine (is_O_with_const_const c _ l).congr_const _, { rw [norm_one, div_one] }, { exact one_ne_zero } end theorem is_O_const_one (c : E) (l : filter α) : is_O (λ x : α, c) (λ x, (1 : 𝕜)) l := (is_O_with_const_one c l).is_O section variable (𝕜) theorem is_o_const_iff_is_o_one {c : F'} (hc : c ≠ 0) : is_o f (λ x, c) l ↔ is_o f (λ x, (1:𝕜)) l := ⟨λ h, h.trans_is_O $ is_O_const_one c l, λ h, h.trans_is_O $ is_O_const_const _ hc _⟩ end theorem is_o_const_iff {c : F'} (hc : c ≠ 0) : is_o f' (λ x, c) l ↔ tendsto f' l (𝓝 0) := (is_o_const_iff_is_o_one ℝ hc).trans begin clear hc c, simp only [is_o, is_O_with, norm_one, mul_one, metric.nhds_basis_closed_ball.tendsto_right_iff, metric.mem_closed_ball, dist_zero_right] end lemma is_o_id_const {c : F'} (hc : c ≠ 0) : is_o (λ (x : E'), x) (λ x, c) (𝓝 0) := (is_o_const_iff hc).mpr (continuous_id.tendsto 0) theorem is_O_const_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) {c : F'} (hc : c ≠ 0) : is_O f' (λ x, c) l := begin refine is_O.trans _ (is_O_const_const (∥y∥ + 1) hc l), use 1, simp only [is_O_with, one_mul], have : tendsto (λx, ∥f' x∥) l (𝓝 ∥y∥), from (continuous_norm.tendsto _).comp h, have Iy : ∥y∥ < ∥∥y∥ + 1∥, from lt_of_lt_of_le (lt_add_one _) (le_abs_self _), exact this (ge_mem_nhds Iy) end section variable (𝕜) theorem is_o_one_iff : is_o f' (λ x, (1 : 𝕜)) l ↔ tendsto f' l (𝓝 0) := is_o_const_iff one_ne_zero theorem is_O_one_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) : is_O f' (λ x, (1:𝕜)) l := is_O_const_of_tendsto h one_ne_zero theorem is_O.trans_tendsto_nhds (hfg : is_O f g' l) {y : F'} (hg : tendsto g' l (𝓝 y)) : is_O f (λ x, (1:𝕜)) l := hfg.trans $ is_O_one_of_tendsto 𝕜 hg end theorem is_O.trans_tendsto (hfg : is_O f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := (is_o_one_iff ℝ).1 $ hfg.trans_is_o $ (is_o_one_iff ℝ).2 hg theorem is_o.trans_tendsto (hfg : is_o f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := hfg.is_O.trans_tendsto hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O_with ∥c∥ (λ x, c * f x) f l := is_O_with_of_le' _ $ λ x, norm_mul_le _ _ theorem is_O_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O (λ x, c * f x) f l := (is_O_with_const_mul_self c f l).is_O theorem is_O_with.const_mul_left {f : α → R} (h : is_O_with c f g l) (c' : R) : is_O_with (∥c'∥ * c) (λ x, c' * f x) g l := (is_O_with_const_mul_self c' f l).trans h (norm_nonneg c') theorem is_O.const_mul_left {f : α → R} (h : is_O f g l) (c' : R) : is_O (λ x, c' * f x) g l := let ⟨c, hc⟩ := h in (hc.const_mul_left c').is_O theorem is_O_with_self_const_mul' (u : units R) (f : α → R) (l : filter α) : is_O_with ∥(↑u⁻¹:R)∥ f (λ x, ↑u * f x) l := (is_O_with_const_mul_self ↑u⁻¹ _ l).congr_left $ λ x, u.inv_mul_cancel_left (f x) theorem is_O_with_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with ∥c∥⁻¹ f (λ x, c * f x) l := (is_O_with_self_const_mul' (units.mk0 c hc) f l).congr_const $ normed_field.norm_inv c theorem is_O_self_const_mul' {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : is_O f (λ x, c * f x) l := let ⟨u, hu⟩ := hc in hu ▸ (is_O_with_self_const_mul' u f l).is_O theorem is_O_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O f (λ x, c * f x) l := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_O (λ x, c * f x) g l ↔ is_O f g l := ⟨(is_O_self_const_mul' hc f l).trans, λ h, h.const_mul_left c⟩ theorem is_O_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c * f x) g l ↔ is_O f g l := is_O_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_o.const_mul_left {f : α → R} (h : is_o f g l) (c : R) : is_o (λ x, c * f x) g l := (is_O_const_mul_self c f l).trans_is_o h theorem is_o_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_o (λ x, c * f x) g l ↔ is_o f g l := ⟨(is_O_self_const_mul' hc f l).trans_is_o, λ h, h.const_mul_left c⟩ theorem is_o_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c * f x) g l ↔ is_o f g l := is_o_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_O_with.of_const_mul_right {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' f (λ x, c * g x) l) : is_O_with (c' * ∥c∥) f g l := h.trans (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {g : α → R} {c : R} (h : is_O f (λ x, c * g x) l) : is_O f g l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.of_const_mul_right cnonneg).is_O theorem is_O_with.const_mul_right' {g : α → R} {u : units R} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥(↑u⁻¹:R)∥) f (λ x, ↑u * g x) l := h.trans (is_O_with_self_const_mul' _ _ _) hc' theorem is_O_with.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥c∥⁻¹) f (λ x, c * g x) l := h.trans (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.trans (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_O_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_O f (λ x, c * g x) l ↔ is_O f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_O_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c * g x) l ↔ is_O f g l := is_O_const_mul_right_iff' $ is_unit.mk0 c hc theorem is_o.of_const_mul_right {g : α → R} {c : R} (h : is_o f (λ x, c * g x) l) : is_o f g l := h.trans_is_O (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.trans_is_O (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_o_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_o f (λ x, c * g x) l ↔ is_o f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_o_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c * g x) l ↔ is_o f g l := is_o_const_mul_right_iff' $ is_unit.mk0 c hc /-! ### Multiplication -/ theorem is_O_with.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} {c₁ c₂ : ℝ} (h₁ : is_O_with c₁ f₁ g₁ l) (h₂ : is_O_with c₂ f₂ g₂ l) : is_O_with (c₁ * c₂) (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin filter_upwards [h₁, h₂], intros x hx₁ hx₂, apply le_trans (norm_mul_le _ _), convert mul_le_mul hx₁ hx₂ (norm_nonneg _) (le_trans (norm_nonneg _) hx₁) using 1, rw normed_field.norm_mul, ac_refl end theorem is_O.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := let ⟨c, hc⟩ := h₁, ⟨c', hc'⟩ := h₂ in (hc.mul hc').is_O theorem is_O.mul_is_o {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₁.exists_pos with ⟨c', c'pos, hc'⟩, exact (hc'.mul (h₂ (div_pos cpos c'pos))).congr_const (mul_div_cancel' _ (ne_of_gt c'pos)) end theorem is_o.mul_is_O {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₂.exists_pos with ⟨c', c'pos, hc'⟩, exact ((h₁ (div_pos cpos c'pos)).mul hc').congr_const (div_mul_cancel _ (ne_of_gt c'pos)) end theorem is_o.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := h₁.mul_is_O h₂.is_O /-! ### Scalar multiplication -/ section smul_const variables [normed_space 𝕜 E'] theorem is_O_with.const_smul_left (h : is_O_with c f' g l) (c' : 𝕜) : is_O_with (∥c'∥ * c) (λ x, c' • f' x) g l := by refine ((h.norm_left.const_mul_left (∥c'∥)).congr _ _ (λ _, rfl)).of_norm_left; intros; simp only [norm_norm, norm_smul] theorem is_O_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c • f' x) g l ↔ is_O f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left], end theorem is_o_const_smul_left (h : is_o f' g l) (c : 𝕜) : is_o (λ x, c • f' x) g l := begin refine ((h.norm_left.const_mul_left (∥c∥)).congr_left _).of_norm_left, exact λ x, (norm_smul _ _).symm end theorem is_o_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c • f' x) g l ↔ is_o f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end theorem is_O_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c • f' x) l ↔ is_O f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c • f' x) l ↔ is_o f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right_iff cne0, is_o_norm_right] end end smul_const section smul variables [normed_space 𝕜 E'] [normed_space 𝕜 F'] theorem is_O_with.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O_with c k₁ k₂ l) (h₂ : is_O_with c' f' g' l) : is_O_with (c * c') (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr rfl _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_O f' g' l) : is_O (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul_is_o {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_o h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul_is_O {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_O f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_O h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] end smul /-! ### Sum -/ section sum variables {ι : Type*} {A : ι → α → E'} {C : ι → ℝ} {s : finset ι} theorem is_O_with.sum (h : ∀ i ∈ s, is_O_with (C i) (A i) g l) : is_O_with (∑ i in s, C i) (λ x, ∑ i in s, A i x) g l := begin induction s using finset.induction_on with i s is IH, { simp only [is_O_with_zero', finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end theorem is_O.sum (h : ∀ i ∈ s, is_O (A i) g l) : is_O (λ x, ∑ i in s, A i x) g l := begin induction s using finset.induction_on with i s is IH, { simp only [is_O_zero, finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end theorem is_o.sum (h : ∀ i ∈ s, is_o (A i) g' l) : is_o (λ x, ∑ i in s, A i x) g' l := begin induction s using finset.induction_on with i s is IH, { simp only [is_o_zero, finset.sum_empty, forall_true_iff] }, { simp only [is, finset.sum_insert, not_false_iff], exact (h _ (finset.mem_insert_self i s)).add (IH (λ j hj, h _ (finset.mem_insert_of_mem hj))) } end end sum /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_0 {f g : α → 𝕜} {l : filter α} (h : is_o f g l) : tendsto (λ x, f x / (g x)) l (𝓝 0) := have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l, from h.mul_is_O (is_O_refl _ _), have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : 𝕜)) l, from is_O_of_le _ (λ x, by by_cases h : ∥g x∥ = 0; simp [h, zero_le_one]), (is_o_one_iff 𝕜).mp (eq₁.trans_is_O eq₂) private theorem is_o_of_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) : is_o f g l := have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : 𝕜)) l, from (is_o_one_iff _).mpr h, have eq₂ : is_o (λ x, f x / g x * g x) g l, by convert eq₁.mul_is_O (is_O_refl _ _); simp, have eq₃ : is_O f (λ x, f x / g x * g x) l, begin refine is_O_of_le _ (λ x, _), by_cases H : g x = 0, { simp only [H, hgf _ H, mul_zero] }, { simp only [div_mul_cancel _ H] } end, eq₃.trans_is_o eq₂ private theorem is_o_of_tendsto' {f g : α → 𝕜} {l : filter α} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) : is_o f g l := let ⟨u, hu, himp⟩ := hgf.exists_mem in have key : u.indicator f =ᶠ[l] f, from eventually_eq_of_mem hu eq_on_indicator, have himp : ∀ x, g x = 0 → (u.indicator f) x = 0, from λ x hgx, begin by_cases h : x ∈ u, { exact (indicator_of_mem h f).symm ▸ himp x h hgx }, { exact indicator_of_not_mem h f } end, suffices h : is_o (u.indicator f) g l, from is_o.congr' key (by refl) h, is_o_of_tendsto himp (h.congr' (key.symm.div (by refl))) theorem is_o_iff_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := iff.intro is_o.tendsto_0 (is_o_of_tendsto hgf) theorem is_o_iff_tendsto' {f g : α → 𝕜} {l : filter α} (hgf : ∀ᶠ x in l, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := iff.intro is_o.tendsto_0 (is_o_of_tendsto' hgf) /-! ### Eventually (u / v) * v = u If `u` and `v` are linked by an `is_O_with` relation, then we eventually have `(u / v) * v = u`, even if `v` vanishes. -/ section eventually_mul_div_cancel variables {u v : α → 𝕜} lemma is_O_with.eventually_mul_div_cancel (h : is_O_with c u v l) : (u / v) * v =ᶠ[l] u := begin refine eventually.mono h (λ y hy, div_mul_cancel_of_imp $ λ hv, _), rw hv at *, simpa using hy end /-- If `u = O(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ lemma is_O.eventually_mul_div_cancel (h : is_O u v l) : (u / v) * v =ᶠ[l] u := let ⟨c, hc⟩ := h in hc.eventually_mul_div_cancel /-- If `u = o(v)` along `l`, then `(u / v) * v = u` eventually at `l`. -/ lemma is_o.eventually_mul_div_cancel (h : is_o u v l) : (u / v) * v =ᶠ[l] u := (h zero_lt_one).eventually_mul_div_cancel end eventually_mul_div_cancel /-! ### Equivalent definitions of the form `∃ φ, u =ᶠ[l] φ * v` in a `normed_field`. -/ section exists_mul_eq variables {u v : α → 𝕜} /-- If `∥φ∥` is eventually bounded by `c`, and `u =ᶠ[l] φ * v`, then we have `is_O_with c u v l`. This does not require any assumptions on `c`, which is why we keep this version along with `is_O_with_iff_exists_eq_mul`. -/ lemma is_O_with_of_eq_mul (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ∥φ x∥ ≤ c) (h : u =ᶠ[l] φ * v) : is_O_with c u v l := begin refine h.symm.rw (λ x a, ∥a∥ ≤ c * ∥v x∥) (hφ.mono $ λ x hx, _), simp only [normed_field.norm_mul, pi.mul_apply], exact mul_le_mul_of_nonneg_right hx (norm_nonneg _) end lemma is_O_with_iff_exists_eq_mul (hc : 0 ≤ c) : is_O_with c u v l ↔ ∃ (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ∥φ x∥ ≤ c), u =ᶠ[l] φ * v := begin split, { intro h, use (λ x, u x / v x), refine ⟨eventually.mono h (λ y hy, _), h.eventually_mul_div_cancel.symm⟩, simpa using div_le_iff_of_nonneg_of_le (norm_nonneg _) hc hy }, { rintros ⟨φ, hφ, h⟩, exact is_O_with_of_eq_mul φ hφ h } end lemma is_O_with.exists_eq_mul (h : is_O_with c u v l) (hc : 0 ≤ c) : ∃ (φ : α → 𝕜) (hφ : ∀ᶠ x in l, ∥φ x∥ ≤ c), u =ᶠ[l] φ * v := (is_O_with_iff_exists_eq_mul hc).mp h lemma is_O_iff_exists_eq_mul : is_O u v l ↔ ∃ (φ : α → 𝕜) (hφ : l.is_bounded_under (≤) (norm ∘ φ)), u =ᶠ[l] φ * v := begin split, { rintros h, rcases h.exists_nonneg with ⟨c, hnnc, hc⟩, rcases hc.exists_eq_mul hnnc with ⟨φ, hφ, huvφ⟩, exact ⟨φ, ⟨c, hφ⟩, huvφ⟩ }, { rintros ⟨φ, ⟨c, hφ⟩, huvφ⟩, exact ⟨c, is_O_with_of_eq_mul φ hφ huvφ⟩ } end alias is_O_iff_exists_eq_mul ↔ asymptotics.is_O.exists_eq_mul _ lemma is_o_iff_exists_eq_mul : is_o u v l ↔ ∃ (φ : α → 𝕜) (hφ : tendsto φ l (𝓝 0)), u =ᶠ[l] φ * v := begin split, { exact λ h, ⟨λ x, u x / v x, h.tendsto_0, h.eventually_mul_div_cancel.symm⟩ }, { rintros ⟨φ, hφ, huvφ⟩ c hpos, rw normed_group.tendsto_nhds_zero at hφ, exact is_O_with_of_eq_mul _ ((hφ c hpos).mono $ λ x, le_of_lt) huvφ } end alias is_o_iff_exists_eq_mul ↔ asymptotics.is_o.exists_eq_mul _ end exists_mul_eq /-! ### Miscellanous lemmas -/ theorem is_o_pow_pow {m n : ℕ} (h : m < n) : is_o (λ(x : 𝕜), x^n) (λx, x^m) (𝓝 0) := begin let p := n - m, have nmp : n = m + p := (nat.add_sub_cancel' (le_of_lt h)).symm, have : (λ(x : 𝕜), x^m) = (λx, x^m * 1), by simp only [mul_one], simp only [this, pow_add, nmp], refine is_O.mul_is_o (is_O_refl _ _) ((is_o_one_iff _).2 _), convert (continuous_pow p).tendsto (0 : 𝕜), exact (zero_pow (nat.sub_pos_of_lt h)).symm end theorem is_o_pow_id {n : ℕ} (h : 1 < n) : is_o (λ(x : 𝕜), x^n) (λx, x) (𝓝 0) := by { convert is_o_pow_pow h, simp only [pow_one] } theorem is_O_with.right_le_sub_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₂ x - f₁ x) l := mem_sets_of_superset h $ λ x hx, begin simp only [mem_set_of_eq] at hx ⊢, rw [mul_comm, one_div, ← div_eq_mul_inv, le_div_iff, mul_sub, mul_one, mul_comm], { exact le_trans (sub_le_sub_left hx _) (norm_sub_norm_le _ _) }, { exact sub_pos.2 hc } end theorem is_O_with.right_le_add_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₁ x + f₂ x) l := (h.neg_right.right_le_sub_of_lt_1 hc).neg_right.of_neg_left.congr rfl (λ x, rfl) (λ x, by rw [neg_sub, sub_neg_eq_add]) theorem is_o.right_is_O_sub {f₁ f₂ : α → E'} (h : is_o f₁ f₂ l) : is_O f₂ (λx, f₂ x - f₁ x) l := ((h.def' one_half_pos).right_le_sub_of_lt_1 one_half_lt_one).is_O theorem is_o.right_is_O_add {f₁ f₂ : α → E'} (h : is_o f₁ f₂ l) : is_O f₂ (λx, f₁ x + f₂ x) l := ((h.def' one_half_pos).right_le_add_of_lt_1 one_half_lt_one).is_O end asymptotics namespace local_homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `local_homeomorph`. -/ lemma is_O_with_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} {C : ℝ} : is_O_with C f g (𝓝 b) ↔ is_O_with C (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := ⟨λ h, h.comp_tendsto $ by { convert e.continuous_at (e.map_target hb), exact (e.right_inv hb).symm }, λ h, (h.comp_tendsto (e.continuous_at_symm hb)).congr' rfl ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg f hx) ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg g hx)⟩ /-- Transfer `is_O` over a `local_homeomorph`. -/ lemma is_O_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : is_O f g (𝓝 b) ↔ is_O (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := exists_congr $ λ C, e.is_O_with_congr hb /-- Transfer `is_o` over a `local_homeomorph`. -/ lemma is_o_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : is_o f g (𝓝 b) ↔ is_o (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := forall_congr $ λ c, forall_congr $ λ hc, e.is_O_with_congr hb end local_homeomorph namespace homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `homeomorph`. -/ lemma is_O_with_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} {C : ℝ} : is_O_with C f g (𝓝 b) ↔ is_O_with C (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := e.to_local_homeomorph.is_O_with_congr trivial /-- Transfer `is_O` over a `homeomorph`. -/ lemma is_O_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : is_O f g (𝓝 b) ↔ is_O (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := exists_congr $ λ C, e.is_O_with_congr /-- Transfer `is_o` over a `homeomorph`. -/ lemma is_o_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : is_o f g (𝓝 b) ↔ is_o (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := forall_congr $ λ c, forall_congr $ λ hc, e.is_O_with_congr end homeomorph attribute [irreducible] asymptotics.is_o asymptotics.is_O asymptotics.is_O_with
db41f41711036e52e8690eddb401b2a0942cfde5
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Parser/Extra.lean
a00944f6f648ee0c236f5593b24bc3a96a1a6ea4
[ "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
10,290
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, Sebastian Ullrich -/ import Lean.Parser.Extension -- necessary for auto-generation import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter namespace Lean namespace Parser -- synthesize pretty printers for parsers declared prior to `Lean.PrettyPrinter` -- (because `Parser.Extension` depends on them) attribute [run_builtin_parser_attribute_hooks] leadingNode termParser commandParser mkAntiquot nodeWithAntiquot sepBy sepBy1 unicodeSymbol nonReservedSymbol withCache withResetCache withPosition withPositionAfterLinebreak withoutPosition withForbidden withoutForbidden setExpected incQuotDepth decQuotDepth suppressInsideQuot evalInsideQuot withOpen withOpenDecl dbgTraceState @[run_builtin_parser_attribute_hooks] def optional (p : Parser) : Parser := optionalNoAntiquot (withAntiquotSpliceAndSuffix `optional p (symbol "?")) @[run_builtin_parser_attribute_hooks] def many (p : Parser) : Parser := manyNoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol "*")) @[run_builtin_parser_attribute_hooks] def many1 (p : Parser) : Parser := many1NoAntiquot (withAntiquotSpliceAndSuffix `many p (symbol "*")) @[run_builtin_parser_attribute_hooks] def ident : Parser := withAntiquot (mkAntiquot "ident" identKind) identNoAntiquot -- `ident` and `rawIdent` produce the same syntax tree, so we reuse the antiquotation kind name @[run_builtin_parser_attribute_hooks] def rawIdent : Parser := withAntiquot (mkAntiquot "ident" identKind) rawIdentNoAntiquot @[run_builtin_parser_attribute_hooks] def hygieneInfo : Parser := withAntiquot (mkAntiquot "hygieneInfo" hygieneInfoKind (anonymous := false)) hygieneInfoNoAntiquot @[run_builtin_parser_attribute_hooks] def numLit : Parser := withAntiquot (mkAntiquot "num" numLitKind) numLitNoAntiquot @[run_builtin_parser_attribute_hooks] def scientificLit : Parser := withAntiquot (mkAntiquot "scientific" scientificLitKind) scientificLitNoAntiquot @[run_builtin_parser_attribute_hooks] def strLit : Parser := withAntiquot (mkAntiquot "str" strLitKind) strLitNoAntiquot @[run_builtin_parser_attribute_hooks] def charLit : Parser := withAntiquot (mkAntiquot "char" charLitKind) charLitNoAntiquot @[run_builtin_parser_attribute_hooks] def nameLit : Parser := withAntiquot (mkAntiquot "name" nameLitKind) nameLitNoAntiquot @[run_builtin_parser_attribute_hooks, inline] def group (p : Parser) : Parser := node groupKind p @[run_builtin_parser_attribute_hooks, inline] def many1Indent (p : Parser) : Parser := withPosition $ many1 (checkColGe "irrelevant" >> p) @[run_builtin_parser_attribute_hooks, inline] def manyIndent (p : Parser) : Parser := withPosition $ many (checkColGe "irrelevant" >> p) @[inline] def sepByIndent (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := let p := withAntiquotSpliceAndSuffix `sepBy p (symbol "*") withPosition $ sepBy (checkColGe "irrelevant" >> p) sep (psep <|> checkColEq "irrelevant" >> checkLinebreakBefore >> pushNone) allowTrailingSep @[inline] def sepBy1Indent (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := let p := withAntiquotSpliceAndSuffix `sepBy p (symbol "*") withPosition $ sepBy1 (checkColGe "irrelevant" >> p) sep (psep <|> checkColEq "irrelevant" >> checkLinebreakBefore >> pushNone) allowTrailingSep open PrettyPrinter Syntax.MonadTraverser Formatter in @[combinator_formatter sepByIndent] def sepByIndent.formatter (p : Formatter) (_sep : String) (pSep : Formatter) : Formatter := do let stx ← getCur let hasNewlineSep := stx.getArgs.mapIdx (fun ⟨i, _⟩ n => i % 2 == 1 && n.matchesNull 0 && i != stx.getArgs.size - 1) |>.any id visitArgs do for i in (List.range stx.getArgs.size).reverse do if i % 2 == 0 then p else pSep <|> -- If the final separator is a newline, skip it. ((if i == stx.getArgs.size - 1 then pure () else pushWhitespace "\n") *> goLeft) -- If there is any newline separator, then we add an `align` at the start -- so that `withPosition` will pick up the right column. if hasNewlineSep then pushAlign (force := true) @[combinator_formatter sepBy1Indent] def sepBy1Indent.formatter := sepByIndent.formatter attribute [run_builtin_parser_attribute_hooks] sepByIndent sepBy1Indent @[run_builtin_parser_attribute_hooks] abbrev notSymbol (s : String) : Parser := notFollowedBy (symbol s) s /-- No-op parser combinator that annotates subtrees to be ignored in syntax patterns. -/ @[inline, run_builtin_parser_attribute_hooks] def patternIgnore : Parser → Parser := node `patternIgnore /-- No-op parser that advises the pretty printer to emit a non-breaking space. -/ @[inline] def ppHardSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a space/soft line break. -/ @[inline] def ppSpace : Parser := skip /-- No-op parser that advises the pretty printer to emit a hard line break. -/ @[inline] def ppLine : Parser := skip /-- No-op parser combinator that advises the pretty printer to emit a `Format.fill` node. -/ @[inline] def ppRealFill : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to emit a `Format.group` node. -/ @[inline] def ppRealGroup : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to indent the given syntax without grouping it. -/ @[inline] def ppIndent : Parser → Parser := id /-- No-op parser combinator that advises the pretty printer to group and indent the given syntax. By default, only syntax categories are grouped. -/ @[inline] def ppGroup (p : Parser) : Parser := ppRealFill (ppIndent p) /-- No-op parser combinator that advises the pretty printer to dedent the given syntax. Dedenting can in particular be used to counteract automatic indentation. -/ @[inline] def ppDedent : Parser → Parser := id /-- No-op parser combinator that allows the pretty printer to omit the group and indent operation in the enclosing category parser. ``` syntax ppAllowUngrouped "by " tacticSeq : term -- allows a `by` after `:=` without linebreak in between: theorem foo : True := by trivial ``` -/ @[inline] def ppAllowUngrouped : Parser := skip /-- No-op parser combinator that advises the pretty printer to dedent the given syntax, if it was grouped by the category parser. Dedenting can in particular be used to counteract automatic indentation. -/ @[inline] def ppDedentIfGrouped : Parser → Parser := id /-- No-op parser combinator that prints a line break. The line break is soft if the combinator is followed by an ungrouped parser (see ppAllowUngrouped), otherwise hard. -/ @[inline] def ppHardLineUnlessUngrouped : Parser := skip end Parser section open PrettyPrinter Parser @[combinator_formatter ppHardSpace] def ppHardSpace.formatter : Formatter := Formatter.pushWhitespace " " @[combinator_formatter ppSpace] def ppSpace.formatter : Formatter := Formatter.pushLine @[combinator_formatter ppLine] def ppLine.formatter : Formatter := Formatter.pushWhitespace "\n" @[combinator_formatter ppRealFill] def ppRealFill.formatter (p : Formatter) : Formatter := Formatter.fill p @[combinator_formatter ppRealGroup] def ppRealGroup.formatter (p : Formatter) : Formatter := Formatter.group p @[combinator_formatter ppIndent] def ppIndent.formatter (p : Formatter) : Formatter := Formatter.indent p @[combinator_formatter ppDedent] def ppDedent.formatter (p : Formatter) : Formatter := do let opts ← getOptions Formatter.indent p (some ((0:Int) - Std.Format.getIndent opts)) @[combinator_formatter ppAllowUngrouped] def ppAllowUngrouped.formatter : Formatter := do modify ({ · with mustBeGrouped := false }) @[combinator_formatter ppDedentIfGrouped] def ppDedentIfGrouped.formatter (p : Formatter) : Formatter := do Formatter.concat p let indent := Std.Format.getIndent (← getOptions) unless (← get).isUngrouped do modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (·.nest (0 - indent)) } @[combinator_formatter ppHardLineUnlessUngrouped] def ppHardLineUnlessUngrouped.formatter : Formatter := do if (← get).isUngrouped then Formatter.pushLine else ppLine.formatter end namespace Parser -- now synthesize parenthesizers attribute [run_builtin_parser_attribute_hooks] ppHardSpace ppSpace ppLine ppGroup ppRealGroup ppRealFill ppIndent ppDedent ppAllowUngrouped ppDedentIfGrouped ppHardLineUnlessUngrouped syntax "register_parser_alias " group("(" &"kind" " := " term ") ")? (strLit ppSpace)? ident (ppSpace colGt term)? : term macro_rules | `(register_parser_alias $[(kind := $kind?)]? $(aliasName?)? $declName $(info?)?) => do let [(fullDeclName, [])] ← Macro.resolveGlobalName declName.getId | Macro.throwError "expected non-overloaded constant name" let aliasName := aliasName?.getD (Syntax.mkStrLit declName.getId.toString) `(do Parser.registerAlias $aliasName ``$declName $declName $(info?.getD (Unhygienic.run `({}))) (kind? := some $(kind?.getD (quote fullDeclName))) PrettyPrinter.Formatter.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `formatter)) PrettyPrinter.Parenthesizer.registerAlias $aliasName $(mkIdentFrom declName (declName.getId ++ `parenthesizer))) builtin_initialize register_parser_alias patternIgnore { autoGroupArgs := false } register_parser_alias group { autoGroupArgs := false } register_parser_alias ppHardSpace { stackSz? := some 0 } register_parser_alias ppSpace { stackSz? := some 0 } register_parser_alias ppLine { stackSz? := some 0 } register_parser_alias ppGroup { stackSz? := none } register_parser_alias ppRealGroup { stackSz? := none } register_parser_alias ppRealFill { stackSz? := none } register_parser_alias ppIndent { stackSz? := none } register_parser_alias ppDedent { stackSz? := none } register_parser_alias ppDedentIfGrouped { stackSz? := none } register_parser_alias ppAllowUngrouped { stackSz? := some 0 } register_parser_alias ppHardLineUnlessUngrouped { stackSz? := some 0 } end Parser end Lean
def6908ea61d407d0292a06531883651808c5f5f
947b78d97130d56365ae2ec264df196ce769371a
/src/Std/Data/PersistentHashMap.lean
1ff2a2468e2fd359af36b2734726fe8ff6e84e46
[ "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
13,312
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 -/ namespace Std universes u v w w' namespace PersistentHashMap inductive Entry (α : Type u) (β : Type v) (σ : Type w) | entry (key : α) (val : β) : Entry | ref (node : σ) : Entry | null : Entry instance Entry.inhabited {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩ inductive Node (α : Type u) (β : Type v) : Type (max u v) | entries (es : Array (Entry α β Node)) : Node | collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node instance Node.inhabited {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩ abbrev shift : USize := 5 abbrev branching : USize := USize.ofNat (2 ^ shift.toNat) abbrev maxDepth : USize := 7 abbrev maxCollisions : Nat := 4 def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) := (Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null) end PersistentHashMap structure PersistentHashMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] := (root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray) (size : Nat := 0) abbrev PHashMap (α : Type u) (β : Type v) [HasBeq α] [Hashable α] := PersistentHashMap α β namespace PersistentHashMap variables {α : Type u} {β : Type v} def empty [HasBeq α] [Hashable α] : PersistentHashMap α β := {} def isEmpty [HasBeq α] [Hashable α] (m : PersistentHashMap α β) : Bool := m.size == 0 instance [HasBeq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩ def mkEmptyEntries {α β} : Node α β := Node.entries mkEmptyEntriesArray abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1) inductive IsCollisionNode : Node α β → Prop | mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h) abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n } inductive IsEntriesNode : Node α β → Prop | mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries) abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n } private theorem setSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β) : (ks.set i k).size = (vs.set j v).size := have h₁ : (ks.set i k).size = ks.size from Array.szFSetEq _ _ _; have h₂ : (vs.set j v).size = vs.size from Array.szFSetEq _ _ _; (h₁.trans h).trans h₂.symm private theorem pushSizeEq {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := have h₁ : (ks.push k).size = ks.size + 1 from Array.szPushEq _ _; have h₂ : (vs.push v).size = vs.size + 1 from Array.szPushEq _ _; have h₃ : ks.size + 1 = vs.size + 1 from h ▸ rfl; (h₁.trans h₃).trans h₂.symm partial def insertAtCollisionNodeAux [HasBeq α] : CollisionNode α β → Nat → α → β → CollisionNode α β | n@⟨Node.collision keys vals heq, _⟩, i, k, v => if h : i < keys.size then let idx : Fin keys.size := ⟨i, h⟩; let k' := keys.get idx; if k == k' then let j : Fin vals.size := ⟨i, heq ▸ h⟩; ⟨Node.collision (keys.set idx k) (vals.set j v) (setSizeEq heq idx j k v), IsCollisionNode.mk _ _ _⟩ else insertAtCollisionNodeAux n (i+1) k v else ⟨Node.collision (keys.push k) (vals.push v) (pushSizeEq heq k v), IsCollisionNode.mk _ _ _⟩ | ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h) def insertAtCollisionNode [HasBeq α] : CollisionNode α β → α → β → CollisionNode α β := fun n k v => insertAtCollisionNodeAux n 0 k v def getCollisionNodeSize : CollisionNode α β → Nat | ⟨Node.collision keys _ _, _⟩ => keys.size | ⟨Node.entries _, h⟩ => False.elim (nomatch h) def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β := let ks : Array α := Array.mkEmpty maxCollisions; let ks := (ks.push k₁).push k₂; let vs : Array β := Array.mkEmpty maxCollisions; let vs := (vs.push v₁).push v₂; Node.collision ks vs rfl partial def insertAux [HasBeq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β | Node.collision keys vals heq, _, depth, k, v => let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v; if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val else match newNode with | ⟨Node.entries _, h⟩ => False.elim (nomatch h) | ⟨Node.collision keys vals heq, _⟩ => let entries : Node α β := mkEmptyEntries; keys.iterate entries $ fun i k entries => let v := vals.get ⟨i.val, heq ▸ i.isLt⟩; let h := hash k; -- dbgTrace ("toCollision " ++ toString i ++ ", h: " ++ toString h ++ ", depth: " ++ toString depth ++ ", h': " ++ -- toString (div2Shift h (shift * (depth - 1)))) $ fun _ => let h := div2Shift h (shift * (depth - 1)); insertAux entries h depth k v | Node.entries entries, h, depth, k, v => let j := (mod2Shift h shift).toNat; Node.entries $ entries.modify j $ fun entry => match entry with | Entry.null => Entry.entry k v | Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v | Entry.entry k' v' => if k == k' then Entry.entry k v else Entry.ref $ mkCollisionNode k' v' k v def insert [HasBeq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β | { root := n, size := sz }, k, v => { root := insertAux n (hash k) 1 k v, size := sz + 1 } partial def findAtAux [HasBeq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) : Nat → α → Option β | i, k => if h : i < keys.size then let k' := keys.get ⟨i, h⟩; if k == k' then some (vals.get ⟨i, heq ▸ h⟩) else findAtAux (i+1) k else none partial def findAux [HasBeq α] : Node α β → USize → α → Option β | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat; match entries.get! j with | Entry.null => none | Entry.ref node => findAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some v else none | Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k def find? [HasBeq α] [Hashable α] : PersistentHashMap α β → α → Option β | { root := n, .. }, k => findAux n (hash k) k @[inline] def getOp [HasBeq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β := self.find? idx @[inline] def findD [HasBeq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β := (m.find? a).getD b₀ @[inline] def find! [HasBeq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β := match m.find? a with | some b => b | none => panic! "key is not in the map" partial def findEntryAtAux [HasBeq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) : Nat → α → Option (α × β) | i, k => if h : i < keys.size then let k' := keys.get ⟨i, h⟩; if k == k' then some (k', vals.get ⟨i, heq ▸ h⟩) else findEntryAtAux (i+1) k else none partial def findEntryAux [HasBeq α] : Node α β → USize → α → Option (α × β) | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat; match entries.get! j with | Entry.null => none | Entry.ref node => findEntryAux node (div2Shift h shift) k | Entry.entry k' v => if k == k' then some (k', v) else none | Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k def findEntry? [HasBeq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β) | { root := n, .. }, k => findEntryAux n (hash k) k partial def containsAtAux [HasBeq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) : Nat → α → Bool | i, k => if h : i < keys.size then let k' := keys.get ⟨i, h⟩; if k == k' then true else containsAtAux (i+1) k else false partial def containsAux [HasBeq α] : Node α β → USize → α → Bool | Node.entries entries, h, k => let j := (mod2Shift h shift).toNat; match entries.get! j with | Entry.null => false | Entry.ref node => containsAux node (div2Shift h shift) k | Entry.entry k' v => k == k' | Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k def contains [HasBeq α] [Hashable α] : PersistentHashMap α β → α → Bool | { root := n, .. }, k => containsAux n (hash k) k partial def isUnaryEntries (a : Array (Entry α β (Node α β))) : Nat → Option (α × β) → Option (α × β) | i, acc => if h : i < a.size then match a.get ⟨i, h⟩ with | Entry.null => isUnaryEntries (i+1) acc | Entry.ref _ => none | Entry.entry k v => match acc with | none => isUnaryEntries (i+1) (some (k, v)) | some _ => none else acc def isUnaryNode : Node α β → Option (α × β) | Node.entries entries => isUnaryEntries entries 0 none | Node.collision keys vals heq => if h : 1 = keys.size then have 0 < keys.size from h ▸ (Nat.zeroLtSucc _); some (keys.get ⟨0, this⟩, vals.get ⟨0, heq ▸ this⟩) else none partial def eraseAux [HasBeq α] : Node α β → USize → α → Node α β × Bool | n@(Node.collision keys vals heq), _, k => match keys.indexOf? k with | some idx => let ⟨keys', keq⟩ := keys.eraseIdx' idx; let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.rec idx heq); have keys.size - 1 = vals.size - 1 from heq ▸ rfl; (Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true) | none => (n, false) | n@(Node.entries entries), h, k => let j := (mod2Shift h shift).toNat; let entry := entries.get! j; match entry with | Entry.null => (n, false) | Entry.entry k' v => if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false) | Entry.ref node => let entries := entries.set! j Entry.null; let (newNode, deleted) := eraseAux node (div2Shift h shift) k; if !deleted then (n, false) else match isUnaryNode newNode with | none => (Node.entries (entries.set! j (Entry.ref newNode)), true) | some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true) def erase [HasBeq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β | { root := n, size := sz }, k => let h := hash k; let (n, del) := eraseAux n h k; { root := n, size := if del then sz - 1 else sz } section variables {m : Type w → Type w'} [Monad m] variables {σ : Type w} @[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ | Node.collision keys vals heq, acc => keys.iterateM acc $ fun i k acc => f acc k (vals.get ⟨i.val, heq ▸ i.isLt⟩) | Node.entries entries, acc => entries.foldlM (fun acc entry => match entry with | Entry.null => pure acc | Entry.entry k v => f acc k v | Entry.ref node => foldlMAux node acc) acc @[specialize] def foldlM [HasBeq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (acc : σ) : m σ := foldlMAux f map.root acc @[specialize] def forM [HasBeq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit := map.foldlM (fun _ => f) ⟨⟩ @[specialize] def foldl [HasBeq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (acc : σ) : σ := Id.run $ map.foldlM f acc end def toList [HasBeq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) := m.foldl (fun ps k v => (k, v) :: ps) [] structure Stats := (numNodes : Nat := 0) (numNull : Nat := 0) (numCollisions : Nat := 0) (maxDepth : Nat := 0) partial def collectStats : Node α β → Stats → Nat → Stats | Node.collision keys _ _, stats, depth => { stats with numNodes := stats.numNodes + 1, numCollisions := stats.numCollisions + keys.size - 1, maxDepth := Nat.max stats.maxDepth depth } | Node.entries entries, stats, depth => let stats := { stats with numNodes := stats.numNodes + 1, maxDepth := Nat.max stats.maxDepth depth }; entries.foldl (fun stats entry => match entry with | Entry.null => { stats with numNull := stats.numNull + 1 } | Entry.ref node => collectStats node stats (depth + 1) | Entry.entry _ _ => stats) stats def stats [HasBeq α] [Hashable α] (m : PersistentHashMap α β) : Stats := collectStats m.root {} 1 def Stats.toString (s : Stats) : String := "{ nodes := " ++ toString s.numNodes ++ ", null := " ++ toString s.numNull ++ ", collisions := " ++ toString s.numCollisions ++ ", depth := " ++ toString s.maxDepth ++ "}" instance : HasToString Stats := ⟨Stats.toString⟩ end PersistentHashMap end Std
6236327e48d59e29855893dd513881026aeeefca
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/ns.lean
c5edac337e7ed393e99f3e41d69c4fa21c56bd61
[ "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
274
lean
prelude constant nat : Type.{1} constant f : nat → nat namespace foo constant int : Type.{1} constant f : int → int constant a : nat constant i : int check _root_.f a check f i end foo open foo constants a : nat constants i : int check f a check f i
b5f6713c790af7cbb18e34247a56dd2fc06546f6
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/ind_ns.lean
d1aa1734fab73f4945a3d207452ac62e56dac456
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
120
lean
inductive day := monday, tuesday, wednesday, thursday, friday, saturday, sunday check day.monday open day check monday
a9e51fda21cfcbd2c090b70ce18a2f08f7a6af9b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/number_theory/lucas_lehmer.lean
c10103c2d381dc854fcd975068c554472c0013c8
[ "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
17,304
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison, Ainsley Pahljina -/ import tactic.ring_exp import tactic.interval_cases import data.nat.parity import data.zmod.basic import group_theory.order_of_element import ring_theory.fintype /-! # The Lucas-Lehmer test for Mersenne primes. We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`. We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic required to calculate the residue, and enables us to prove ``` example : prime (mersenne 127) := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test) ``` ## TODO - Show reverse implication. - Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`. - Find some bigger primes! ## History This development began as a student project by Ainsley Pahljina, and was then cleaned up for mathlib by Scott Morrison. The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro. -/ /-- The Mersenne numbers, 2^p - 1. -/ def mersenne (p : ℕ) : ℕ := 2^p - 1 lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p := begin dsimp [mersenne], calc 0 < 2^1 - 1 : by norm_num ... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h) end @[simp] lemma succ_mersenne (k : ℕ) : mersenne k + 1 = 2 ^ k := begin rw [mersenne, nat.sub_add_cancel], exact one_le_pow_of_one_le (by norm_num) k end namespace lucas_lehmer open nat /-! We now define three(!) different versions of the recurrence `s (i+1) = (s i)^2 - 2`. These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or in `ℤ` but applying `% (2^p - 1)` at each step. They are each useful at different points in the proof, so we take a moment setting up the lemmas relating them. -/ /-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/ def s : ℕ → ℤ | 0 := 4 | (i+1) := (s i)^2 - 2 /-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/ def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1) | 0 := 4 | (i+1) := (s_zmod i)^2 - 2 /-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/ def s_mod (p : ℕ) : ℕ → ℤ | 0 := 4 % (2^p - 1) | (i+1) := ((s_mod i)^2 - 2) % (2^p - 1) lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 := begin apply ne_of_gt, simp only [gt_iff_lt, sub_pos], exact_mod_cast nat.one_lt_two_pow p w, end lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i := begin cases i; dsimp [s_mod], { exact sup_eq_left.mp rfl }, { apply int.mod_nonneg, exact mersenne_int_ne_zero p w }, end lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i := by cases i; simp [s_mod] lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 := begin rw ←s_mod_mod, convert int.mod_lt _ _, { refine (abs_of_nonneg _).symm, simp only [sub_nonneg, ge_iff_le], exact_mod_cast nat.one_le_two_pow p, }, { exact mersenne_int_ne_zero p w, }, end lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):= begin induction i with i ih, { dsimp [s, s_zmod], norm_num, }, { push_cast [s, s_zmod, ih] }, end -- These next two don't make good `norm_cast` lemmas. lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) := begin have : 1 ≤ b^p := nat.one_le_pow p b w, push_cast [this], end lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) := int.coe_nat_pow_pred 2 p dec_trivial lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) := by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *] /-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/ def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2) lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) : lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 := begin dsimp [lucas_lehmer_residue], rw s_zmod_eq_s_mod p, split, { -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1` -- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`. intro h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h, apply s_mod_nonneg _ (nat.lt_of_succ_lt w), convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2), push_cast [nat.one_le_two_pow p], refl, }, { intro h, rw h, simp, }, end /-- A Mersenne number `2^p-1` is prime if and only if the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero. -/ @[derive decidable_pred] def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0 /-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/ def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩ local attribute [instance] lemma fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := ⟨q.2⟩ /-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/ -- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3), -- obtaining the ring structure for free, -- but that seems to be more trouble than it's worth; -- if it were easy to make the definition, -- cardinality calculations would be somewhat more involved, too. @[derive [add_comm_group, decidable_eq, fintype, inhabited]] def X (q : ℕ+) : Type := (zmod q) × (zmod q) namespace X variable {q : ℕ+} @[ext] lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := begin cases x, cases y, congr; assumption end @[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl @[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl @[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl @[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl instance : has_mul (X q) := { mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) } @[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl @[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl instance : has_one (X q) := { one := ⟨1,0⟩ } @[simp] lemma one_fst : (1 : X q).1 = 1 := rfl @[simp] lemma one_snd : (1 : X q).2 = 0 := rfl @[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl @[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl @[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl @[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, } instance : monoid (X q) := { mul_assoc := λ x y z, by { ext; { dsimp, ring }, }, one := ⟨1,0⟩, one_mul := λ x, by { ext; simp, }, mul_one := λ x, by { ext; simp, }, ..(infer_instance : has_mul (X q)) } lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z := by { ext; { dsimp, ring }, } lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z := by { ext; { dsimp, ring }, } instance : ring (X q) := { left_distrib := left_distrib, right_distrib := right_distrib, ..(infer_instance : add_comm_group (X q)), ..(infer_instance : monoid (X q)) } instance : comm_ring (X q) := { mul_comm := λ x y, by { ext; { dsimp, ring }, }, ..(infer_instance : ring (X q))} instance [fact (1 < (q : ℕ))] : nontrivial (X q) := ⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩ @[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_left_inj], exact n_ih, } end @[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_zero], exact n_ih, } end @[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := by { induction n; simp, } @[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := by { induction n; simp, } @[norm_cast] lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) := by { ext; simp; ring } @[norm_cast] lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) := by { ext; simp, } /-- The cardinality of `X` is `q^2`. -/ lemma X_card : fintype.card (X q) = q^2 := begin dsimp [X], rw [fintype.card_prod, zmod.card q], ring, end /-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/ lemma units_card (w : 1 < q) : fintype.card (units (X q)) < q^2 := begin haveI : fact (1 < (q:ℕ)) := ⟨w⟩, convert card_units_lt (X q), rw X_card, end /-- We define `ω = 2 + √3`. -/ def ω : X q := (2, 1) /-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/ def ωb : X q := (2, -1) lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 := begin dsimp [ω, ωb], ext; simp; ring, end lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 := begin dsimp [ω, ωb], ext; simp; ring, end /-- A closed form for the recurrence relation. -/ lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) := begin induction i with i ih, { dsimp [s, ω, ωb], ext; { simp; refl, }, }, { calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl ... = ((s i : X q)^2 - 2) : by push_cast ... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih ... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring ... = (ω^(2^i))^2 + (ωb^(2^i))^2 : by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel] ... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] } end end X open X /-! Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`. -/ /-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/ lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin by_contradiction H, simp at H, interval_cases q (p'+2); clear H, { -- If q = 1, we get a contradiction from 2^p = 2 dsimp [q] at h, injection h with h', clear h, simp [mersenne] at h', exact lt_irrefl 2 (calc 2 ≤ p'+2 : nat.le_add_left _ _ ... < 2^(p'+2) : nat.lt_two_pow _ ... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), }, { -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1 dsimp [q] at h, injection h with h', clear h, rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h', exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', } end theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : ∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) = k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 := begin dsimp [lucas_lehmer_residue] at h, rw s_zmod_eq_s p' at h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, cases h with k h, use k, replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q dsimp at h, rw closed_form at h, replace h := congr_arg (λ x, ω^2^p' * x) h, dsimp at h, have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp, rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h, rw [mul_comm, coe_mul] at h, rw [mul_comm _ (k : X (q (p'+2)))] at h, replace h := eq_sub_of_add_eq h, exact_mod_cast h, end /-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/ theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 := begin ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd, -pow_pos], apply nat.min_fac_dvd, end theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+1)) = -1 := begin cases ω_pow_formula p' h with k w, rw [mersenne_coe_X] at w, simpa using w, end theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+2)) = 1 := calc (ω : X (q (p'+2)))^2^(p'+2) = (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ'] ... = (-1)^2 : by rw ω_pow_eq_neg_one p' h ... = 1 : by simp /-- `ω` as an element of the group of units. -/ def ω_unit (p : ℕ) : units (X (q p)) := { val := ω, inv := ωb, val_inv := by simp [ω_mul_ωb], inv_val := by simp [ωb_mul_ω], } @[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl /-- The order of `ω` in the unit group is exactly `2^p`. -/ theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : order_of (ω_unit (p'+2)) = 2^(p'+2) := begin apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p { norm_num, }, { intro o, have ω_pow := order_of_dvd_iff_pow_eq_one.1 o, replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) : units (X (q (p'+2))) → X (q (p'+2))) ω_pow, simp at ω_pow, have h : (1 : zmod (q (p'+2))) = -1 := congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)), haveI : fact (2 < (q (p'+2) : ℕ)) := ⟨two_lt_q _⟩, apply zmod.neg_one_ne_one h.symm, }, { apply order_of_dvd_iff_pow_eq_one.2, apply units.ext, push_cast, exact ω_pow_eq_one p' h, } end lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 := calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm ... ≤ fintype.card (units (X _)) : order_of_le_card_univ ... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _)) end lucas_lehmer export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue) open lucas_lehmer theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime := begin let p' := p - 2, have z : p = p' + 2 := (nat.sub_eq_iff_eq_add w).mp rfl, have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl), contrapose, intros a t, rw z at a, rw z at t, have h₁ := order_ineq p' t, have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a, have h := lt_of_lt_of_le h₁ h₂, exact not_lt_of_ge (nat.sub_le _ _) h, end -- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better. example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial -- Next we use `norm_num` to calculate each `s p i`. namespace lucas_lehmer open tactic meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ lemma s_mod_succ {p a i b c} (h1 : (2^p - 1 : ℤ) = a) (h2 : s_mod p i = b) (h3 : (b * b - 2) % a = c) : s_mod p (i+1) = c := by { dsimp [s_mod, mersenne], rw [h1, h2, sq, h3] } /-- Given a goal of the form `lucas_lehmer_test p`, attempt to do the calculation using `norm_num` to certify each step. -/ meta def run_test : tactic unit := do `(lucas_lehmer_test %%p) ← target, `[dsimp [lucas_lehmer_test]], `[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num], p ← eval_expr ℕ p, -- Calculate the candidate Mersenne prime let M : ℤ := 2^p - 1, t ← to_expr ``(2^%%p - 1 = %%M), v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M), w ← assertv `w t v, -- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`. -- We could make a better `has_to_pexpr ℤ` instance, or just: `[simp only [int.coe_nat_zero, int.coe_nat_succ, int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w], -- base case t ← to_expr ``(s_mod %%p 0 = 4), v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4), h ← assertv `h t v, -- step case, repeated p-2 times iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })], -- now close the goal h ← get_local `h, exact h end lucas_lehmer /-- We verify that the tactic works to prove `127.prime`. -/ example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test). /-! This implementation works successfully to prove `(2^127 - 1).prime`, and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean]. `(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!), and unfortunately the next Mersenne prime `(2^521 - 1)`, which was the first "computer era" prime, is out of reach with the current implementation. There's still low hanging fruit available to do faster computations based on the formula n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1] and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation. Someone should do this, too! -/ lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] := -- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446 begin conv in k { rw ← nat.div_add_mod k (2^n) }, refine nat.modeq.modeq_add _ (by refl), conv { congr, skip, skip, rw ← one_mul (k/2^n) }, refine nat.modeq.modeq_mul _ (by refl), symmetry, rw [nat.modeq.modeq_iff_dvd, int.coe_nat_sub], exact pow_pos (show 0 < 2, from dec_trivial) _ end -- It's hard to know what the limiting factor for large Mersenne primes would be. -- In the purely computational world, I think it's the squaring operation in `s`.
89d7a51f8c6b21acb91942adc2c0d8225b7b1839
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/digits.lean
1c3c071d19ebf212881b6fee25be2956fc0a0258
[ "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
21,745
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Shing Tak Lam, Mario Carneiro -/ import data.int.modeq import data.list.indexes import tactic.interval_cases import tactic.linarith /-! # Digits of a natural number This provides a basic API for extracting the digits of a natural number in a given base, and reconstructing numbers from their digits. We also prove some divisibility tests based on digits, in particular completing Theorem #85 from https://www.cs.ru.nl/~freek/100/. A basic `norm_digits` tactic is also provided for proving goals of the form `nat.digits a b = l` where `a` and `b` are numerals. -/ namespace nat /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_0 : ℕ → list ℕ | 0 := [] | (n+1) := [n+1] /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux_1 (n : ℕ) : list ℕ := list.repeat 1 n /-- (Impl.) An auxiliary definition for `digits`, to help get the desired definitional unfolding. -/ def digits_aux (b : ℕ) (h : 2 ≤ b) : ℕ → list ℕ | 0 := [] | (n+1) := have (n+1)/b < n+1 := nat.div_lt_self (nat.succ_pos _) h, (n+1) % b :: digits_aux ((n+1)/b) @[simp] lemma digits_aux_zero (b : ℕ) (h : 2 ≤ b) : digits_aux b h 0 = [] := by rw digits_aux lemma digits_aux_def (b : ℕ) (h : 2 ≤ b) (n : ℕ) (w : 0 < n) : digits_aux b h n = n % b :: digits_aux b h (n/b) := begin cases n, { cases w, }, { rw [digits_aux], } end /-- `digits b n` gives the digits, in little-endian order, of a natural number `n` in a specified base `b`. In any base, we have `of_digits b L = L.foldr (λ x y, x + b * y) 0`. * For any `2 ≤ b`, we have `l < b` for any `l ∈ digits b n`, and the last digit is not zero. This uniquely specifies the behaviour of `digits b`. * For `b = 1`, we define `digits 1 n = list.repeat 1 n`. * For `b = 0`, we define `digits 0 n = [n]`, except `digits 0 0 = []`. Note this differs from the existing `nat.to_digits` in core, which is used for printing numerals. In particular, `nat.to_digits b 0 = [0]`, while `digits b 0 = []`. -/ def digits : ℕ → ℕ → list ℕ | 0 := digits_aux_0 | 1 := digits_aux_1 | (b+2) := digits_aux (b+2) (by norm_num) @[simp] lemma digits_zero (b : ℕ) : digits b 0 = [] := by rcases b with _|⟨_|⟨_⟩⟩; simp [digits, digits_aux_0, digits_aux_1] @[simp] lemma digits_zero_zero : digits 0 0 = [] := rfl @[simp] lemma digits_zero_succ (n : ℕ) : digits 0 (n.succ) = [n+1] := rfl theorem digits_zero_succ' : ∀ {n : ℕ} (w : 0 < n), digits 0 n = [n] | 0 h := absurd h dec_trivial | (n+1) _ := rfl @[simp] lemma digits_one (n : ℕ) : digits 1 n = list.repeat 1 n := rfl @[simp] lemma digits_one_succ (n : ℕ) : digits 1 (n + 1) = 1 :: digits 1 n := rfl @[simp] lemma digits_add_two_add_one (b n : ℕ) : digits (b+2) (n+1) = (((n+1) % (b+2)) :: digits (b+2) ((n+1) / (b+2))) := by { rw [digits, digits_aux_def], exact succ_pos n } theorem digits_def' : ∀ {b : ℕ} (h : 2 ≤ b) {n : ℕ} (w : 0 < n), digits b n = n % b :: digits b (n/b) | 0 h := absurd h dec_trivial | 1 h := absurd h dec_trivial | (b+2) h := digits_aux_def _ _ @[simp] lemma digits_of_lt (b x : ℕ) (w₁ : 0 < x) (w₂ : x < b) : digits b x = [x] := begin cases b, { cases w₂ }, { cases b, { interval_cases x, }, { cases x, { cases w₁, }, { rw [digits_add_two_add_one, nat.div_eq_of_lt w₂, digits_zero, nat.mod_eq_of_lt w₂] } } } end lemma digits_add (b : ℕ) (h : 2 ≤ b) (x y : ℕ) (w : x < b) (w' : 0 < x ∨ 0 < y) : digits b (x + b * y) = x :: digits b y := begin cases b, { cases h, }, { cases b, { norm_num at h, }, { cases y, { norm_num at w', simp [w, w'], }, dsimp [digits], rw digits_aux_def, { congr, { simp [nat.add_mod, nat.mod_eq_of_lt w], }, { simp [mul_comm (b+2), nat.add_mul_div_right, nat.div_eq_of_lt w], } }, { apply nat.succ_pos, }, }, }, end /-- `of_digits b L` takes a list `L` of natural numbers, and interprets them as a number in semiring, as the little-endian digits in base `b`. -/ -- If we had a function converting a list into a polynomial, -- and appropriate lemmas about that function, -- we could rewrite this in terms of that. def of_digits {α : Type*} [semiring α] (b : α) : list ℕ → α | [] := 0 | (h :: t) := h + b * of_digits t lemma of_digits_eq_foldr {α : Type*} [semiring α] (b : α) (L : list ℕ) : of_digits b L = L.foldr (λ x y, x + b * y) 0 := begin induction L with d L ih, { refl, }, { dsimp [of_digits], rw ih, }, end lemma of_digits_eq_sum_map_with_index_aux (b : ℕ) (l : list ℕ) : ((list.range l.length).zip_with ((λ (i a : ℕ), a * b ^ i) ∘ succ) l).sum = b * ((list.range l.length).zip_with (λ i a, a * b ^ i) l).sum := begin suffices : (list.range l.length).zip_with (((λ (i a : ℕ), a * b ^ i) ∘ succ)) l = (list.range l.length).zip_with (λ i a, b * (a * b ^ i)) l, { simp [this] }, congr, ext, simp [pow_succ], ring end lemma of_digits_eq_sum_map_with_index (b : ℕ) (L : list ℕ): of_digits b L = (L.map_with_index (λ i a, a * b ^ i)).sum := begin rw [list.map_with_index_eq_enum_map, list.enum_eq_zip_range, list.map_uncurry_zip_eq_zip_with, of_digits_eq_foldr], induction L with hd tl hl, { simp }, { simpa [list.range_succ_eq_map, list.zip_with_map_left, of_digits_eq_sum_map_with_index_aux] using or.inl hl } end @[simp] lemma of_digits_singleton {b n : ℕ} : of_digits b [n] = n := by simp [of_digits] @[simp] lemma of_digits_one_cons {α : Type*} [semiring α] (h : ℕ) (L : list ℕ) : of_digits (1 : α) (h :: L) = h + of_digits 1 L := by simp [of_digits] lemma of_digits_append {b : ℕ} {l1 l2 : list ℕ} : of_digits b (l1 ++ l2) = of_digits b l1 + b^(l1.length) * of_digits b l2 := begin induction l1 with hd tl IH, { simp [of_digits] }, { rw [of_digits, list.cons_append, of_digits, IH, list.length_cons, pow_succ'], ring } end @[norm_cast] lemma coe_of_digits (α : Type*) [semiring α] (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : α) = of_digits (b : α) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end @[norm_cast] lemma coe_int_of_digits (b : ℕ) (L : list ℕ) : ((of_digits b L : ℕ) : ℤ) = of_digits (b : ℤ) L := begin induction L with d L ih, { refl, }, { dsimp [of_digits], push_cast, rw ih, } end lemma digits_zero_of_eq_zero {b : ℕ} (h : 1 ≤ b) {L : list ℕ} (w : of_digits b L = 0) : ∀ l ∈ L, l = 0 := begin induction L with d L ih, { intros l m, cases m, }, { intros l m, dsimp [of_digits] at w, rcases m with ⟨rfl⟩, { convert nat.eq_zero_of_add_eq_zero_right w, simp, }, { exact ih ((nat.mul_right_inj h).mp (nat.eq_zero_of_add_eq_zero_left w)) _ m, }, } end lemma digits_of_digits (b : ℕ) (h : 2 ≤ b) (L : list ℕ) (w₁ : ∀ l ∈ L, l < b) (w₂ : ∀ (h : L ≠ []), L.last h ≠ 0) : digits b (of_digits b L) = L := begin induction L with d L ih, { dsimp [of_digits], simp }, { dsimp [of_digits], replace w₂ := w₂ (by simp), rw digits_add b h, { rw ih, { simp, }, { intros l m, apply w₁, exact list.mem_cons_of_mem _ m, }, { intro h, { rw [list.last_cons _ h] at w₂, convert w₂, }}}, { convert w₁ d (list.mem_cons_self _ _), simp, }, { by_cases h' : L = [], { rcases h' with rfl, simp at w₂, left, apply nat.pos_of_ne_zero, convert w₂, simp, }, { right, apply nat.pos_of_ne_zero, contrapose! w₂, apply digits_zero_of_eq_zero _ w₂, { rw list.last_cons _ h', exact list.last_mem h', }, { exact le_of_lt h, }, }, }, }, end lemma of_digits_digits (b n : ℕ) : of_digits b (digits b n) = n := begin cases b with b, { cases n with n, { refl, }, { change of_digits 0 [n+1] = n+1, dsimp [of_digits], simp, } }, { cases b with b, { induction n with n ih, { refl, }, { simp only [ih, add_comm 1, of_digits_one_cons, nat.cast_id, digits_one_succ], } }, { apply nat.strong_induction_on n _, clear n, intros n h, cases n, { rw digits_zero, refl, }, { simp only [nat.succ_eq_add_one, digits_add_two_add_one], dsimp [of_digits], rw h _ (nat.div_lt_self' n b), rw [nat.cast_id, nat.mod_add_div], }, }, }, end lemma of_digits_one (L : list ℕ) : of_digits 1 L = L.sum := begin induction L with d L ih, { refl, }, { simp [of_digits, list.sum_cons, ih], } end /-! ### Properties This section contains various lemmas of properties relating to `digits` and `of_digits`. -/ lemma digits_eq_nil_iff_eq_zero {b n : ℕ} : digits b n = [] ↔ n = 0 := begin split, { intro h, have : of_digits b (digits b n) = of_digits b [], by rw h, convert this, rw of_digits_digits }, { rintro rfl, simp } end lemma digits_ne_nil_iff_ne_zero {b n : ℕ} : digits b n ≠ [] ↔ n ≠ 0 := not_congr digits_eq_nil_iff_eq_zero private lemma digits_last_aux {b n : ℕ} (h : 2 ≤ b) (w : 0 < n) : digits b n = ((n % b) :: digits b (n / b)) := begin rcases b with _|_|b, { finish }, { norm_num at h }, rcases n with _|n, { norm_num at w }, simp, end lemma digits_last {b m : ℕ} (h : 2 ≤ b) (hm : 0 < m) (p q) : (digits b m).last p = (digits b (m/b)).last q := by { simp only [digits_last_aux h hm], rw list.last_cons } lemma digits.injective (b : ℕ) : function.injective b.digits := function.left_inverse.injective (of_digits_digits b) @[simp] lemma digits_inj_iff {b n m : ℕ} : b.digits n = b.digits m ↔ n = m := (digits.injective b).eq_iff lemma last_digit_ne_zero (b : ℕ) {m : ℕ} (hm : m ≠ 0) : (digits b m).last (digits_ne_nil_iff_ne_zero.mpr hm) ≠ 0 := begin rcases b with _|_|b, { cases m; finish }, { cases m, { finish }, simp_rw [digits_one, list.last_repeat_succ 1 m], norm_num }, revert hm, apply nat.strong_induction_on m, intros n IH hn, have hnpos : 0 < n := nat.pos_of_ne_zero hn, by_cases hnb : n < b + 2, { simp_rw [digits_of_lt b.succ.succ n hnpos hnb], exact pos_iff_ne_zero.mp hnpos }, { rw digits_last (show 2 ≤ b + 2, from dec_trivial) hnpos, refine IH _ (nat.div_lt_self hnpos dec_trivial) _, { rw ←pos_iff_ne_zero, exact nat.div_pos (le_of_not_lt hnb) dec_trivial } }, end /-- The digits in the base b+2 expansion of n are all less than b+2 -/ lemma digits_lt_base' {b m : ℕ} : ∀ {d}, d ∈ digits (b+2) m → d < b+2 := begin apply nat.strong_induction_on m, intros n IH d hd, cases n with n, { rw digits_zero at hd, cases hd }, -- base b+2 expansion of 0 has no digits rw digits_add_two_add_one at hd, cases hd, { rw hd, exact n.succ.mod_lt (by linarith) }, { exact IH _ (nat.div_lt_self (nat.succ_pos _) (by linarith)) hd } end /-- The digits in the base b expansion of n are all less than b, if b ≥ 2 -/ lemma digits_lt_base {b m d : ℕ} (hb : 2 ≤ b) (hd : d ∈ digits b m) : d < b := begin rcases b with _ | _ | b; try {linarith}, exact digits_lt_base' hd, end /-- an n-digit number in base b + 2 is less than (b + 2)^n -/ lemma of_digits_lt_base_pow_length' {b : ℕ} {l : list ℕ} (hl : ∀ x ∈ l, x < b+2) : of_digits (b+2) l < (b+2)^(l.length) := begin induction l with hd tl IH, { simp [of_digits], }, { rw [of_digits, list.length_cons, pow_succ], have : (of_digits (b + 2) tl + 1) * (b+2) ≤ (b + 2) ^ tl.length * (b+2) := mul_le_mul (IH (λ x hx, hl _ (list.mem_cons_of_mem _ hx))) (by refl) dec_trivial (nat.zero_le _), suffices : ↑hd < b + 2, { linarith }, norm_cast, exact hl hd (list.mem_cons_self _ _) } end /-- an n-digit number in base b is less than b^n if b ≥ 2 -/ lemma of_digits_lt_base_pow_length {b : ℕ} {l : list ℕ} (hb : 2 ≤ b) (hl : ∀ x ∈ l, x < b) : of_digits b l < b^l.length := begin rcases b with _ | _ | b; try { linarith }, exact of_digits_lt_base_pow_length' hl, end /-- Any number m is less than (b+2)^(number of digits in the base b + 2 representation of m) -/ lemma lt_base_pow_length_digits' {b m : ℕ} : m < (b + 2) ^ (digits (b + 2) m).length := begin convert of_digits_lt_base_pow_length' (λ _, digits_lt_base'), rw of_digits_digits (b+2) m, end /-- Any number m is less than b^(number of digits in the base b representation of m) -/ lemma lt_base_pow_length_digits {b m : ℕ} (hb : 2 ≤ b) : m < b^(digits b m).length := begin rcases b with _ | _ | b; try { linarith }, exact lt_base_pow_length_digits', end lemma of_digits_digits_append_digits {b m n : ℕ} : of_digits b (digits b n ++ digits b m) = n + b ^ (digits b n).length * m:= by rw [of_digits_append, of_digits_digits, of_digits_digits] lemma digits_len_le_digits_len_succ (b n : ℕ) : (digits b n).length ≤ (digits b (n + 1)).length := begin cases b, { -- base 0 cases n; simp }, { cases b, { -- base 1 simp }, { -- base >= 2 apply nat.strong_induction_on n, clear n, intros n IH, cases n, { simp }, { rw [digits_add_two_add_one, digits_add_two_add_one], by_cases hdvd : (b.succ.succ) ∣ (n.succ+1), { rw [nat.succ_div_of_dvd hdvd, list.length_cons, list.length_cons, nat.succ_le_succ_iff], apply IH, exact nat.div_lt_self (by linarith) (by linarith) }, { rw nat.succ_div_of_not_dvd hdvd, refl } } } } end lemma le_digits_len_le (b n m : ℕ) (h : n ≤ m) : (digits b n).length ≤ (digits b m).length := monotone_nat_of_le_succ (digits_len_le_digits_len_succ b) h lemma pow_length_le_mul_of_digits {b : ℕ} {l : list ℕ} (hl : l ≠ []) (hl2 : l.last hl ≠ 0): (b + 2) ^ l.length ≤ (b + 2) * of_digits (b+2) l := begin rw [←list.init_append_last hl], simp only [list.length_append, list.length, zero_add, list.length_init, of_digits_append, list.length_init, of_digits_singleton, add_comm (l.length - 1), pow_add, pow_one], apply nat.mul_le_mul_left, refine le_trans _ (nat.le_add_left _ _), have : 0 < l.last hl, { rwa [pos_iff_ne_zero] }, convert nat.mul_le_mul_left _ this, rw [mul_one] end /-- Any non-zero natural number `m` is greater than (b+2)^((number of digits in the base (b+2) representation of m) - 1) -/ lemma base_pow_length_digits_le' (b m : ℕ) (hm : m ≠ 0) : (b + 2) ^ ((digits (b + 2) m).length) ≤ (b + 2) * m := begin have : digits (b + 2) m ≠ [], from digits_ne_nil_iff_ne_zero.mpr hm, convert pow_length_le_mul_of_digits this (last_digit_ne_zero _ hm), rwa of_digits_digits, end /-- Any non-zero natural number `m` is greater than b^((number of digits in the base b representation of m) - 1) -/ lemma base_pow_length_digits_le (b m : ℕ) (hb : 2 ≤ b): m ≠ 0 → b ^ ((digits b m).length) ≤ b * m := begin rcases b with _ | _ | b; try { linarith }, exact base_pow_length_digits_le' b m, end /-! ### Modular Arithmetic -/ -- This is really a theorem about polynomials. lemma dvd_of_digits_sub_of_digits {α : Type*} [comm_ring α] {a b k : α} (h : k ∣ a - b) (L : list ℕ) : k ∣ of_digits a L - of_digits b L := begin induction L with d L ih, { change k ∣ 0 - 0, simp, }, { simp only [of_digits, add_sub_add_left_eq_sub], exact dvd_mul_sub_mul h ih, } end lemma of_digits_modeq' (b b' : ℕ) (k : ℕ) (h : b ≡ b' [MOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [MOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [nat.modeq] at *, conv_lhs { rw [nat.add_mod, nat.mul_mod, h, ih], }, conv_rhs { rw [nat.add_mod, nat.mul_mod], }, } end lemma of_digits_modeq (b k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [MOD k] := of_digits_modeq' b (b % k) k (b.mod_modeq k).symm L lemma of_digits_mod (b k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_modeq b k L lemma of_digits_zmodeq' (b b' : ℤ) (k : ℕ) (h : b ≡ b' [ZMOD k]) (L : list ℕ) : of_digits b L ≡ of_digits b' L [ZMOD k] := begin induction L with d L ih, { refl, }, { dsimp [of_digits], dsimp [int.modeq] at *, conv_lhs { rw [int.add_mod, int.mul_mod, h, ih], }, conv_rhs { rw [int.add_mod, int.mul_mod], }, } end lemma of_digits_zmodeq (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L ≡ of_digits (b % k) L [ZMOD k] := of_digits_zmodeq' b (b % k) k (b.mod_modeq ↑k).symm L lemma of_digits_zmod (b : ℤ) (k : ℕ) (L : list ℕ) : of_digits b L % k = of_digits (b % k) L % k := of_digits_zmodeq b k L lemma modeq_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : n ≡ (digits b' n).sum [MOD b] := begin rw ←of_digits_one, conv { congr, skip, rw ←(of_digits_digits b' n) }, convert of_digits_modeq _ _ _, exact h.symm, end lemma modeq_three_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 3] := modeq_digits_sum 3 10 (by norm_num) n lemma modeq_nine_digits_sum (n : ℕ) : n ≡ (digits 10 n).sum [MOD 9] := modeq_digits_sum 9 10 (by norm_num) n lemma zmodeq_of_digits_digits (b b' : ℕ) (c : ℤ) (h : b' ≡ c [ZMOD b]) (n : ℕ) : n ≡ of_digits c (digits b' n) [ZMOD b] := begin conv { congr, skip, rw ←(of_digits_digits b' n) }, rw coe_int_of_digits, apply of_digits_zmodeq' _ _ _ h, end lemma of_digits_neg_one : Π (L : list ℕ), of_digits (-1 : ℤ) L = (L.map (λ n : ℕ, (n : ℤ))).alternating_sum | [] := rfl | [n] := by simp [of_digits, list.alternating_sum] | (a :: b :: t) := begin simp only [of_digits, list.alternating_sum, list.map_cons, of_digits_neg_one t], push_cast, ring, end lemma modeq_eleven_digits_sum (n : ℕ) : n ≡ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum [ZMOD 11] := begin have t := zmodeq_of_digits_digits 11 10 (-1 : ℤ) (by unfold int.modeq; norm_num) n, rwa of_digits_neg_one at t end /-! ## Divisibility -/ lemma dvd_iff_dvd_digits_sum (b b' : ℕ) (h : b' % b = 1) (n : ℕ) : b ∣ n ↔ b ∣ (digits b' n).sum := begin rw ←of_digits_one, conv_lhs { rw ←(of_digits_digits b' n) }, rw [nat.dvd_iff_mod_eq_zero, nat.dvd_iff_mod_eq_zero, of_digits_mod, h], end /-- **Divisibility by 3 Rule** -/ lemma three_dvd_iff (n : ℕ) : 3 ∣ n ↔ 3 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 3 10 (by norm_num) n lemma nine_dvd_iff (n : ℕ) : 9 ∣ n ↔ 9 ∣ (digits 10 n).sum := dvd_iff_dvd_digits_sum 9 10 (by norm_num) n lemma dvd_iff_dvd_of_digits (b b' : ℕ) (c : ℤ) (h : (b : ℤ) ∣ (b' : ℤ) - c) (n : ℕ) : b ∣ n ↔ (b : ℤ) ∣ of_digits c (digits b' n) := begin rw ←int.coe_nat_dvd, exact dvd_iff_dvd_of_dvd_sub (zmodeq_of_digits_digits b b' c (int.modeq_iff_dvd.2 h).symm _).symm.dvd, end lemma eleven_dvd_iff (n : ℕ) : 11 ∣ n ↔ (11 : ℤ) ∣ ((digits 10 n).map (λ n : ℕ, (n : ℤ))).alternating_sum := begin have t := dvd_iff_dvd_of_digits 11 10 (-1 : ℤ) (by norm_num) n, rw of_digits_neg_one at t, exact t, end /-! ### `norm_digits` tactic -/ namespace norm_digits theorem digits_succ (b n m r l) (e : r + b * m = n) (hr : r < b) (h : nat.digits b m = l ∧ 2 ≤ b ∧ 0 < m) : nat.digits b n = r :: l ∧ 2 ≤ b ∧ 0 < n := begin rcases h with ⟨h, b2, m0⟩, have b0 : 0 < b := by linarith, have n0 : 0 < n := by linarith [mul_pos b0 m0], refine ⟨_, b2, n0⟩, obtain ⟨rfl, rfl⟩ := (nat.div_mod_unique b0).2 ⟨e, hr⟩, subst h, exact nat.digits_def' b2 n0, end theorem digits_one (b n) (n0 : 0 < n) (nb : n < b) : nat.digits b n = [n] ∧ 2 ≤ b ∧ 0 < n := begin have b2 : 2 ≤ b := by linarith, refine ⟨_, b2, n0⟩, rw [nat.digits_def' b2 n0, nat.mod_eq_of_lt nb, (nat.div_eq_zero_iff (by linarith : 0 < b)).2 nb, nat.digits_zero], end open tactic /-- Helper function for the `norm_digits` tactic. -/ meta def eval_aux (eb : expr) (b : ℕ) : expr → ℕ → instance_cache → tactic (instance_cache × expr × expr) | en n ic := do let m := n / b, let r := n % b, (ic, er) ← ic.of_nat r, (ic, pr) ← norm_num.prove_lt_nat ic er eb, if m = 0 then do (_, pn0) ← norm_num.prove_pos ic en, return (ic, `([%%en] : list nat), `(digits_one %%eb %%en %%pn0 %%pr)) else do em ← expr.of_nat `(ℕ) m, (_, pe) ← norm_num.derive `(%%er + %%eb * %%em : ℕ), (ic, el, p) ← eval_aux em m ic, return (ic, `(@list.cons ℕ %%er %%el), `(digits_succ %%eb %%en %%em %%er %%el %%pe %%pr %%p)) /-- A tactic for normalizing expressions of the form `nat.digits a b = l` where `a` and `b` are numerals. ``` example : nat.digits 10 123 = [3,2,1] := by norm_num ``` -/ @[norm_num] meta def eval : expr → tactic (expr × expr) | `(nat.digits %%eb %%en) := do b ← expr.to_nat eb, n ← expr.to_nat en, if n = 0 then return (`([] : list ℕ), `(nat.digits_zero %%eb)) else if b = 0 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, return (`([%%en] : list ℕ), `(@nat.digits_zero_succ' %%en %%pn0)) else if b = 1 then do ic ← mk_instance_cache `(ℕ), (_, pn0) ← norm_num.prove_pos ic en, s ← simp_lemmas.add_simp simp_lemmas.mk `list.repeat, (rhs, p2, _) ← simplify s [] `(list.repeat 1 %%en), p ← mk_eq_trans `(nat.digits_one %%en) p2, return (rhs, p) else do ic ← mk_instance_cache `(ℕ), (_, l, p) ← eval_aux eb b en n ic, p ← mk_app ``and.left [p], return (l, p) | _ := failed end norm_digits end nat
b764794555e7dec5135ac9eecb0eb55f42a63086
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/algebra/group/commute.lean
dbc94d32402d1bf0367714507a08bc2c00dc14c4
[ "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
7,314
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland, Yury Kudryashov -/ import algebra.group.semiconj /-! # Commuting pairs of elements in monoids We define the predicate `commute a b := a * b = b * a` and provide some operations on terms `(h : commute a b)`. E.g., if `a`, `b`, and c are elements of a semiring, and that `hb : commute a b` and `hc : commute a c`. Then `hb.pow_left 5` proves `commute (a ^ 5) b` and `(hb.pow_right 2).add_right (hb.mul_right hc)` proves `commute a (b ^ 2 + b * c)`. Lean does not immediately recognise these terms as equations, so for rewriting we need syntax like `rw [(hb.pow_left 5).eq]` rather than just `rw [hb.pow_left 5]`. This file defines only a few operations (`mul_left`, `inv_right`, etc). Other operations (`pow_right`, field inverse etc) are in the files that define corresponding notions. ## Implementation details Most of the proofs come from the properties of `semiconj_by`. -/ /-- Two elements commute if `a * b = b * a`. -/ @[to_additive add_commute "Two elements additively commute if `a + b = b + a`"] def commute {S : Type*} [has_mul S] (a b : S) : Prop := semiconj_by a b b namespace commute section has_mul variables {S : Type*} [has_mul S] /-- Equality behind `commute a b`; useful for rewriting. -/ @[to_additive] protected theorem eq {a b : S} (h : commute a b) : a * b = b * a := h /-- Any element commutes with itself. -/ @[refl, simp, to_additive] protected theorem refl (a : S) : commute a a := eq.refl (a * a) /-- If `a` commutes with `b`, then `b` commutes with `a`. -/ @[symm, to_additive] protected theorem symm {a b : S} (h : commute a b) : commute b a := eq.symm h @[to_additive] protected theorem semiconj_by {a b : S} (h : commute a b) : semiconj_by a b b := h @[to_additive] protected theorem symm_iff {a b : S} : commute a b ↔ commute b a := ⟨commute.symm, commute.symm⟩ end has_mul section semigroup variables {S : Type*} [semigroup S] {a b c : S} /-- If `a` commutes with both `b` and `c`, then it commutes with their product. -/ @[simp, to_additive] theorem mul_right (hab : commute a b) (hac : commute a c) : commute a (b * c) := hab.mul_right hac /-- If both `a` and `b` commute with `c`, then their product commutes with `c`. -/ @[simp, to_additive] theorem mul_left (hac : commute a c) (hbc : commute b c) : commute (a * b) c := hac.mul_left hbc @[to_additive] protected lemma right_comm (h : commute b c) (a : S) : a * b * c = a * c * b := by simp only [mul_assoc, h.eq] @[to_additive] protected lemma left_comm (h : commute a b) (c) : a * (b * c) = b * (a * c) := by simp only [← mul_assoc, h.eq] end semigroup @[to_additive] protected theorem all {S : Type*} [comm_semigroup S] (a b : S) : commute a b := mul_comm a b section mul_one_class variables {M : Type*} [mul_one_class M] @[simp, to_additive] theorem one_right (a : M) : commute a 1 := semiconj_by.one_right a @[simp, to_additive] theorem one_left (a : M) : commute 1 a := semiconj_by.one_left a end mul_one_class section monoid variables {M : Type*} [monoid M] {a b : M} {u u₁ u₂ : units M} @[simp, to_additive] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp, to_additive] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp, to_additive] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp, to_additive] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp, to_additive] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp, to_additive] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) := (commute.refl a).pow_pow m n @[to_additive succ_nsmul'] theorem _root_.pow_succ' (a : M) (n : ℕ) : a ^ (n + 1) = a ^ n * a := (pow_succ a n).trans (self_pow _ _) @[to_additive] theorem units_inv_right : commute a u → commute a ↑u⁻¹ := semiconj_by.units_inv_right @[simp, to_additive] theorem units_inv_right_iff : commute a ↑u⁻¹ ↔ commute a u := semiconj_by.units_inv_right_iff @[to_additive] theorem units_inv_left : commute ↑u a → commute ↑u⁻¹ a := semiconj_by.units_inv_symm_left @[simp, to_additive] theorem units_inv_left_iff: commute ↑u⁻¹ a ↔ commute ↑u a := semiconj_by.units_inv_symm_left_iff @[to_additive] theorem units_coe : commute u₁ u₂ → commute (u₁ : M) u₂ := semiconj_by.units_coe @[to_additive] theorem units_of_coe : commute (u₁ : M) u₂ → commute u₁ u₂ := semiconj_by.units_of_coe @[simp, to_additive] theorem units_coe_iff : commute (u₁ : M) u₂ ↔ commute u₁ u₂ := semiconj_by.units_coe_iff @[to_additive] lemma is_unit_mul_iff (h : commute a b) : is_unit (a * b) ↔ is_unit a ∧ is_unit b := begin refine ⟨_, λ H, H.1.mul H.2⟩, rintro ⟨u, hu⟩, have : b * ↑u⁻¹ * a = 1, { have : commute a u := hu.symm ▸ (commute.refl _).mul_right h, rw [← this.units_inv_right.right_comm, ← h.eq, ← hu, u.mul_inv] }, split, { refine ⟨⟨a, b * ↑u⁻¹, _, this⟩, rfl⟩, rw [← mul_assoc, ← hu, u.mul_inv] }, { rw mul_assoc at this, refine ⟨⟨b, ↑u⁻¹ * a, this, _⟩, rfl⟩, rw [mul_assoc, ← hu, u.inv_mul] } end @[simp, to_additive] lemma _root_.is_unit_mul_self_iff : is_unit (a * a) ↔ is_unit a := (commute.refl a).is_unit_mul_iff.trans (and_self _) end monoid section group variables {G : Type*} [group G] {a b : G} @[to_additive] theorem inv_right : commute a b → commute a b⁻¹ := semiconj_by.inv_right @[simp, to_additive] theorem inv_right_iff : commute a b⁻¹ ↔ commute a b := semiconj_by.inv_right_iff @[to_additive] theorem inv_left : commute a b → commute a⁻¹ b := semiconj_by.inv_symm_left @[simp, to_additive] theorem inv_left_iff : commute a⁻¹ b ↔ commute a b := semiconj_by.inv_symm_left_iff @[to_additive] theorem inv_inv : commute a b → commute a⁻¹ b⁻¹ := semiconj_by.inv_inv_symm @[simp, to_additive] theorem inv_inv_iff : commute a⁻¹ b⁻¹ ↔ commute a b := semiconj_by.inv_inv_symm_iff @[to_additive] protected theorem inv_mul_cancel (h : commute a b) : a⁻¹ * b * a = b := by rw [h.inv_left.eq, inv_mul_cancel_right] @[to_additive] theorem inv_mul_cancel_assoc (h : commute a b) : a⁻¹ * (b * a) = b := by rw [← mul_assoc, h.inv_mul_cancel] @[to_additive] protected theorem mul_inv_cancel (h : commute a b) : a * b * a⁻¹ = b := by rw [h.eq, mul_inv_cancel_right] @[to_additive] theorem mul_inv_cancel_assoc (h : commute a b) : a * (b * a⁻¹) = b := by rw [← mul_assoc, h.mul_inv_cancel] end group end commute section comm_group variables {G : Type*} [comm_group G] (a b : G) @[simp, to_additive] lemma mul_inv_cancel_comm : a * b * a⁻¹ = b := (commute.all a b).mul_inv_cancel @[simp, to_additive] lemma mul_inv_cancel_comm_assoc : a * (b * a⁻¹) = b := (commute.all a b).mul_inv_cancel_assoc @[simp, to_additive] lemma inv_mul_cancel_comm : a⁻¹ * b * a = b := (commute.all a b).inv_mul_cancel @[simp, to_additive] lemma inv_mul_cancel_comm_assoc : a⁻¹ * (b * a) = b := (commute.all a b).inv_mul_cancel_assoc end comm_group
6fcb5034bcdf7fef2ffaf04aecceb7e05e7dd1fb
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/big_operators/basic.lean
13446fadb00c1237e6d957708a107a17ef0075a5
[ "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
79,594
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 -/ import algebra.group.pi import algebra.hom.equiv import algebra.ring.opposite import data.finset.fold import data.fintype.basic import data.set.pairwise /-! # Big operators In this file we define products and sums indexed by finite sets (specifically, `finset`). ## Notation We introduce the following notation, localized in `big_operators`. To enable the notation, use `open_locale big_operators`. Let `s` be a `finset α`, and `f : α → β` a function. * `∏ x in s, f x` is notation for `finset.prod s f` (assuming `β` is a `comm_monoid`) * `∑ x in s, f x` is notation for `finset.sum s f` (assuming `β` is an `add_comm_monoid`) * `∏ x, f x` is notation for `finset.prod finset.univ f` (assuming `α` is a `fintype` and `β` is a `comm_monoid`) * `∑ x, f x` is notation for `finset.sum finset.univ f` (assuming `α` is a `fintype` and `β` is an `add_comm_monoid`) ## Implementation Notes The first arguments in all definitions and lemmas is the codomain of the function of the big operator. This is necessary for the heuristic in `@[to_additive]`. See the documentation of `to_additive.attr` for more information. -/ universes u v w variables {ι : Type*} {β : Type u} {α : Type v} {γ : Type w} open fin namespace finset /-- `∏ x in s, f x` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive "`∑ x in s, f x` is the sum of `f x` as `x` ranges over the elements of the finite set `s`."] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod @[simp, to_additive] lemma prod_mk [comm_monoid β] (s : multiset α) (hs : s.nodup) (f : α → β) : (⟨s, hs⟩ : finset α).prod f = (s.map f).prod := rfl @[simp, to_additive] lemma prod_val [comm_monoid α] (s : finset α) : s.1.prod = s.prod id := by rw [finset.prod, multiset.map_id] end finset /-- There is no established mathematical convention for the operator precedence of big operators like `∏` and `∑`. We will have to make a choice. Online discussions, such as https://math.stackexchange.com/q/185538/30839 seem to suggest that `∏` and `∑` should have the same precedence, and that this should be somewhere between `*` and `+`. The latter have precedence levels `70` and `65` respectively, and we therefore choose the level `67`. In practice, this means that parentheses should be placed as follows: ```lean ∑ k in K, (a k + b k) = ∑ k in K, a k + ∑ k in K, b k → ∏ k in K, a k * b k = (∏ k in K, a k) * (∏ k in K, b k) ``` (Example taken from page 490 of Knuth's *Concrete Mathematics*.) -/ library_note "operator precedence of big operators" localized "notation (name := finset.sum_univ) `∑` binders `, ` r:(scoped:67 f, finset.sum finset.univ f) := r" in big_operators localized "notation (name := finset.prod_univ) `∏` binders `, ` r:(scoped:67 f, finset.prod finset.univ f) := r" in big_operators localized "notation (name := finset.sum) `∑` binders ` in ` s `, ` r:(scoped:67 f, finset.sum s f) := r" in big_operators localized "notation (name := finset.prod) `∏` binders ` in ` s `, ` r:(scoped:67 f, finset.prod s f) := r" in big_operators open_locale big_operators namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} @[to_additive] lemma prod_eq_multiset_prod [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = (s.1.map f).prod := rfl @[to_additive] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : ∏ x in s, f x = s.fold (*) 1 f := rfl @[simp] lemma sum_multiset_singleton (s : finset α) : s.sum (λ x, {x}) = s.val := by simp only [sum_eq_multiset_sum, multiset.sum_map_singleton] end finset @[to_additive] lemma map_prod [comm_monoid β] [comm_monoid γ] {G : Type*} [monoid_hom_class G β γ] (g : G) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := by simp only [finset.prod_eq_multiset_prod, map_multiset_prod, multiset.map_map] section deprecated /-- Deprecated: use `_root_.map_prod` instead. -/ @[to_additive "Deprecated: use `_root_.map_sum` instead."] protected lemma monoid_hom.map_prod [comm_monoid β] [comm_monoid γ] (g : β →* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := map_prod g f s /-- Deprecated: use `_root_.map_prod` instead. -/ @[to_additive "Deprecated: use `_root_.map_sum` instead."] protected lemma mul_equiv.map_prod [comm_monoid β] [comm_monoid γ] (g : β ≃* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := map_prod g f s /-- Deprecated: use `_root_.map_list_prod` instead. -/ protected lemma ring_hom.map_list_prod [semiring β] [semiring γ] (f : β →+* γ) (l : list β) : f l.prod = (l.map f).prod := map_list_prod f l /-- Deprecated: use `_root_.map_list_sum` instead. -/ protected lemma ring_hom.map_list_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (l : list β) : f l.sum = (l.map f).sum := map_list_sum f l /-- A morphism into the opposite ring acts on the product by acting on the reversed elements. Deprecated: use `_root_.unop_map_list_prod` instead. -/ protected lemma ring_hom.unop_map_list_prod [semiring β] [semiring γ] (f : β →+* γᵐᵒᵖ) (l : list β) : mul_opposite.unop (f l.prod) = (l.map (mul_opposite.unop ∘ f)).reverse.prod := unop_map_list_prod f l /-- Deprecated: use `_root_.map_multiset_prod` instead. -/ protected lemma ring_hom.map_multiset_prod [comm_semiring β] [comm_semiring γ] (f : β →+* γ) (s : multiset β) : f s.prod = (s.map f).prod := map_multiset_prod f s /-- Deprecated: use `_root_.map_multiset_sum` instead. -/ protected lemma ring_hom.map_multiset_sum [non_assoc_semiring β] [non_assoc_semiring γ] (f : β →+* γ) (s : multiset β) : f s.sum = (s.map f).sum := map_multiset_sum f s /-- Deprecated: use `_root_.map_prod` instead. -/ protected lemma ring_hom.map_prod [comm_semiring β] [comm_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∏ x in s, f x) = ∏ x in s, g (f x) := map_prod g f s /-- Deprecated: use `_root_.map_sum` instead. -/ protected lemma ring_hom.map_sum [non_assoc_semiring β] [non_assoc_semiring γ] (g : β →+* γ) (f : α → β) (s : finset α) : g (∑ x in s, f x) = ∑ x in s, g (f x) := map_sum g f s end deprecated @[to_additive] lemma monoid_hom.coe_finset_prod [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) : ⇑(∏ x in s, f x) = ∏ x in s, f x := (monoid_hom.coe_fn β γ).map_prod _ _ -- See also `finset.prod_apply`, with the same conclusion -- but with the weaker hypothesis `f : α → β → γ`. @[simp, to_additive] lemma monoid_hom.finset_prod_apply [mul_one_class β] [comm_monoid γ] (f : α → β →* γ) (s : finset α) (b : β) : (∏ x in s, f x) b = ∏ x in s, f x b := (monoid_hom.eval b).map_prod _ _ variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} namespace finset section comm_monoid variables [comm_monoid β] @[simp, to_additive] lemma prod_empty : ∏ x in ∅, f x = 1 := rfl @[to_additive] lemma prod_of_empty [is_empty α] : ∏ i, f i = 1 := by rw [univ_eq_empty, prod_empty] @[simp, to_additive] lemma prod_cons (h : a ∉ s) : (∏ x in (cons a s h), f x) = f a * ∏ x in s, f x := fold_cons h @[simp, to_additive] lemma prod_insert [decidable_eq α] : a ∉ s → (∏ x in (insert a s), f x) = f a * ∏ x in s, f x := fold_insert /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `a` is in `s` or `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `a` is in `s` or `f a = 0`."] lemma prod_insert_of_eq_one_if_not_mem [decidable_eq α] (h : a ∉ s → f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := begin by_cases hm : a ∈ s, { simp_rw insert_eq_of_mem hm }, { rw [prod_insert hm, h hm, one_mul] }, end /-- The product of `f` over `insert a s` is the same as the product over `s`, as long as `f a = 1`. -/ @[simp, to_additive "The sum of `f` over `insert a s` is the same as the sum over `s`, as long as `f a = 0`."] lemma prod_insert_one [decidable_eq α] (h : f a = 1) : ∏ x in insert a s, f x = ∏ x in s, f x := prod_insert_of_eq_one_if_not_mem (λ _, h) @[simp, to_additive] lemma prod_singleton : (∏ x in (singleton a), f x) = f a := eq.trans fold_singleton $ mul_one _ @[to_additive] lemma prod_pair [decidable_eq α] {a b : α} (h : a ≠ b) : (∏ x in ({a, b} : finset α), f x) = f a * f b := by rw [prod_insert (not_mem_singleton.2 h), prod_singleton] @[simp, priority 1100, to_additive] lemma prod_const_one : (∏ x in s, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp, to_additive] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀ x ∈ s, ∀ y ∈ s, g x = g y → x = y) → (∏ x in (s.image g), f x) = ∏ x in s, f (g x) := fold_image @[simp, to_additive] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (∏ x in (s.map e), f x) = ∏ x in s, f (e x) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive] lemma prod_congr (h : s₁ = s₂) : (∀ x ∈ s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive] lemma prod_disj_union (h) : ∏ x in s₁.disj_union s₂ h, f x = (∏ x in s₁, f x) * ∏ x in s₂, f x := by { refine eq.trans _ (fold_disj_union h), rw one_mul, refl } @[to_additive] lemma prod_union_inter [decidable_eq α] : (∏ x in (s₁ ∪ s₂), f x) * (∏ x in (s₁ ∩ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := fold_union_inter @[to_additive] lemma prod_union [decidable_eq α] (h : disjoint s₁ s₂) : (∏ x in (s₁ ∪ s₂), f x) = (∏ x in s₁, f x) * (∏ x in s₂, f x) := by rw [←prod_union_inter, (disjoint_iff_inter_eq_empty.mp h)]; exact (mul_one _).symm @[to_additive] lemma prod_filter_mul_prod_filter_not (s : finset α) (p : α → Prop) [decidable_pred p] [decidable_pred (λ x, ¬p x)] (f : α → β) : (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬p x), f x) = ∏ x in s, f x := begin haveI := classical.dec_eq α, rw [← prod_union (filter_inter_filter_neg_eq p s).le, filter_union_filter_neg_eq] end section to_list @[simp, to_additive] lemma prod_to_list (s : finset α) (f : α → β) : (s.to_list.map f).prod = s.prod f := by rw [finset.prod, ← multiset.coe_prod, ← multiset.coe_map, finset.coe_to_list] end to_list @[to_additive] lemma _root_.equiv.perm.prod_comp (σ : equiv.perm α) (s : finset α) (f : α → β) (hs : {a | σ a ≠ a} ⊆ s) : (∏ x in s, f (σ x)) = ∏ x in s, f x := by { convert (prod_map _ σ.to_embedding _).symm, exact (map_perm hs).symm } @[to_additive] lemma _root_.equiv.perm.prod_comp' (σ : equiv.perm α) (s : finset α) (f : α → α → β) (hs : {a | σ a ≠ a} ⊆ s) : (∏ x in s, f (σ x) x) = ∏ x in s, f x (σ.symm x) := by { convert σ.prod_comp s (λ x, f x (σ.symm x)) hs, ext, rw equiv.symm_apply_apply } end comm_monoid end finset section open finset variables [fintype α] [decidable_eq α] [comm_monoid β] @[to_additive] lemma is_compl.prod_mul_prod {s t : finset α} (h : is_compl s t) (f : α → β) : (∏ i in s, f i) * (∏ i in t, f i) = ∏ i, f i := (finset.prod_union h.disjoint).symm.trans $ by rw [← finset.sup_eq_union, h.sup_eq_top]; refl end namespace finset section comm_monoid variables [comm_monoid β] /-- Multiplying the products of a function over `s` and over `sᶜ` gives the whole product. For a version expressed with subtypes, see `fintype.prod_subtype_mul_prod_subtype`. -/ @[to_additive "Adding the sums of a function over `s` and over `sᶜ` gives the whole sum. For a version expressed with subtypes, see `fintype.sum_subtype_add_sum_subtype`. "] lemma prod_mul_prod_compl [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in s, f i) * (∏ i in sᶜ, f i) = ∏ i, f i := is_compl.prod_mul_prod is_compl_compl f @[to_additive] lemma prod_compl_mul_prod [fintype α] [decidable_eq α] (s : finset α) (f : α → β) : (∏ i in sᶜ, f i) * (∏ i in s, f i) = ∏ i, f i := (@is_compl_compl _ s _).symm.prod_mul_prod f @[to_additive] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) * (∏ x in s₁, f x) = (∏ x in s₂, f x) := by rw [←prod_union sdiff_disjoint, sdiff_union_of_subset h] @[simp, to_additive] lemma prod_sum_elim [decidable_eq (α ⊕ γ)] (s : finset α) (t : finset γ) (f : α → β) (g : γ → β) : ∏ x in s.map function.embedding.inl ∪ t.map function.embedding.inr, sum.elim f g x = (∏ x in s, f x) * (∏ x in t, g x) := begin rw [prod_union, prod_map, prod_map], { simp only [sum.elim_inl, function.embedding.inl_apply, function.embedding.inr_apply, sum.elim_inr] }, { simp only [disjoint_left, finset.mem_map, finset.mem_map], rintros _ ⟨i, hi, rfl⟩ ⟨j, hj, H⟩, cases H } end @[simp, to_additive] lemma prod_on_sum [fintype α] [fintype γ] (f : α ⊕ γ → β) : ∏ (x : α ⊕ γ), f x = (∏ (x : α), f (sum.inl x)) * (∏ (x : γ), f (sum.inr x)) := begin haveI := classical.dec_eq (α ⊕ γ), convert prod_sum_elim univ univ (λ x, f (sum.inl x)) (λ x, f (sum.inr x)), { ext a, split, { intro x, cases a, { simp only [mem_union, mem_map, mem_univ, function.embedding.inl_apply, or_false, exists_true_left, exists_apply_eq_apply, function.embedding.inr_apply, exists_false], }, { simp only [mem_union, mem_map, mem_univ, function.embedding.inl_apply, false_or, exists_true_left, exists_false, function.embedding.inr_apply, exists_apply_eq_apply], }, }, { simp only [mem_univ, implies_true_iff], }, }, { simp only [sum.elim_comp_inl_inr], }, end @[to_additive] lemma prod_bUnion [decidable_eq α] {s : finset γ} {t : γ → finset α} (hs : set.pairwise_disjoint ↑s t) : (∏ x in (s.bUnion t), f x) = ∏ x in s, ∏ i in t x, f i := begin haveI := classical.dec_eq γ, induction s using finset.induction_on with x s hxs ih hd, { simp_rw [bUnion_empty, prod_empty] }, { simp_rw [coe_insert, set.pairwise_disjoint_insert, mem_coe] at hs, have : disjoint (t x) (finset.bUnion s t), { exact (disjoint_bUnion_right _ _ _).mpr (λ y hy, hs.2 y hy $ λ H, hxs $ H.substr hy) }, rw [bUnion_insert, prod_insert hxs, prod_union this, ih hs.1] } end /-- Product over a sigma type equals the product of fiberwise products. For rewriting in the reverse direction, use `finset.prod_sigma'`. -/ @[to_additive "Sum over a sigma type equals the sum of fiberwise sums. For rewriting in the reverse direction, use `finset.sum_sigma'`"] lemma prod_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : sigma σ → β) : (∏ x in s.sigma t, f x) = ∏ a in s, ∏ s in (t a), f ⟨a, s⟩ := by classical; calc (∏ x in s.sigma t, f x) = ∏ x in s.bUnion (λ a, (t a).map (function.embedding.sigma_mk a)), f x : by rw sigma_eq_bUnion ... = ∏ a in s, ∏ x in (t a).map (function.embedding.sigma_mk a), f x : prod_bUnion $ assume a₁ ha a₂ ha₂ h x hx, by { simp only [inf_eq_inter, mem_inter, mem_map, function.embedding.sigma_mk_apply] at hx, rcases hx with ⟨⟨y, hy, rfl⟩, ⟨z, hz, hz'⟩⟩, cc } ... = ∏ a in s, ∏ s in t a, f ⟨a, s⟩ : prod_congr rfl $ λ _ _, prod_map _ _ _ @[to_additive] lemma prod_sigma' {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) (f : Π a, σ a → β) : (∏ a in s, ∏ s in (t a), f a s) = ∏ x in s.sigma t, f x.1 x.2 := eq.symm $ prod_sigma s t (λ x, f x.1 x.2) /-- Reorder a product. The difference with `prod_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. -/ @[to_additive " Reorder a sum. The difference with `sum_bij'` is that the bijection is specified as a surjective injection, rather than by an inverse function. "] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (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) : (∏ x in s, f x) = (∏ x in t, g x) := congr_arg multiset.prod (multiset.map_eq_map_of_bij_of_nodup f g s.2 t.2 i hi h i_inj i_surj) /-- Reorder a product. The difference with `prod_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. -/ @[to_additive " Reorder a sum. The difference with `sum_bij` is that the bijection is specified with an inverse, rather than as a surjective injection. "] lemma prod_bij' {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, γ) (hi : ∀ a ha, i a ha ∈ t) (h : ∀ a ha, f a = g (i a ha)) (j : Π a ∈ t, α) (hj : ∀ a ha, j a ha ∈ s) (left_inv : ∀ a ha, j (i a ha) (hi a ha) = a) (right_inv : ∀ a ha, i (j a ha) (hj a ha) = a) : (∏ x in s, f x) = (∏ x in t, g x) := begin refine prod_bij i hi h _ _, {intros a1 a2 h1 h2 eq, rw [←left_inv a1 h1, ←left_inv a2 h2], cc,}, {intros b hb, use j b hb, use hj b hb, exact (right_inv b hb).symm,}, end @[to_additive] lemma prod_finset_product (r : finset (γ × α)) (s : finset γ) (t : γ → finset α) (h : ∀ p : γ × α, p ∈ r ↔ p.1 ∈ s ∧ p.2 ∈ t p.1) {f : γ × α → β} : ∏ p in r, f p = ∏ c in s, ∏ a in t c, f (c, a) := begin refine eq.trans _ (prod_sigma s t (λ p, f (p.1, p.2))), exact prod_bij' (λ p hp, ⟨p.1, p.2⟩) (λ p, mem_sigma.mpr ∘ (h p).mp) (λ p hp, congr_arg f prod.mk.eta.symm) (λ p hp, (p.1, p.2)) (λ p, (h (p.1, p.2)).mpr ∘ mem_sigma.mp) (λ p hp, prod.mk.eta) (λ p hp, p.eta), end @[to_additive] lemma prod_finset_product' (r : finset (γ × α)) (s : finset γ) (t : γ → finset α) (h : ∀ p : γ × α, p ∈ r ↔ p.1 ∈ s ∧ p.2 ∈ t p.1) {f : γ → α → β} : ∏ p in r, f p.1 p.2 = ∏ c in s, ∏ a in t c, f c a := prod_finset_product r s t h @[to_additive] lemma prod_finset_product_right (r : finset (α × γ)) (s : finset γ) (t : γ → finset α) (h : ∀ p : α × γ, p ∈ r ↔ p.2 ∈ s ∧ p.1 ∈ t p.2) {f : α × γ → β} : ∏ p in r, f p = ∏ c in s, ∏ a in t c, f (a, c) := begin refine eq.trans _ (prod_sigma s t (λ p, f (p.2, p.1))), exact prod_bij' (λ p hp, ⟨p.2, p.1⟩) (λ p, mem_sigma.mpr ∘ (h p).mp) (λ p hp, congr_arg f prod.mk.eta.symm) (λ p hp, (p.2, p.1)) (λ p, (h (p.2, p.1)).mpr ∘ mem_sigma.mp) (λ p hp, prod.mk.eta) (λ p hp, p.eta), end @[to_additive] lemma prod_finset_product_right' (r : finset (α × γ)) (s : finset γ) (t : γ → finset α) (h : ∀ p : α × γ, p ∈ r ↔ p.2 ∈ s ∧ p.1 ∈ t p.2) {f : α → γ → β} : ∏ p in r, f p.1 p.2 = ∏ c in s, ∏ a in t c, f a c := prod_finset_product_right r s t h @[to_additive] lemma prod_fiberwise_of_maps_to [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} (h : ∀ x ∈ s, g x ∈ t) (f : α → β) : (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) = ∏ x in s, f x := begin letI := classical.dec_eq α, rw [← bUnion_filter_eq_of_maps_to h] {occs := occurrences.pos [2]}, refine (prod_bUnion $ λ x' hx y' hy hne, _).symm, rw [function.on_fun, disjoint_filter], rintros x hx rfl, exact hne end @[to_additive] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀ c ∈ s, f (g c) = ∏ x in s.filter (λ c', g c' = g c), h x) : (∏ x in s.image g, f x) = ∏ x in s, h x := calc (∏ x in s.image g, f x) = ∏ x in s.image g, ∏ x in s.filter (λ c', g c' = x), h x : prod_congr rfl $ λ x hx, let ⟨c, hcs, hc⟩ := mem_image.1 hx in hc ▸ (eq c hcs) ... = ∏ x in s, h x : prod_fiberwise_of_maps_to (λ x, mem_image_of_mem g) _ @[to_additive] lemma prod_mul_distrib : ∏ x in s, (f x * g x) = (∏ x in s, f x) * (∏ x in s, g x) := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s ×ˢ t, f x) = ∏ x in s, ∏ y in t, f (x, y) := prod_finset_product (s ×ˢ t) s (λ a, t) (λ p, mem_product) /-- An uncurried version of `finset.prod_product`. -/ @[to_additive "An uncurried version of `finset.sum_product`"] lemma prod_product' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s ×ˢ t, f x.1 x.2) = ∏ x in s, ∏ y in t, f x y := prod_product @[to_additive] lemma prod_product_right {s : finset γ} {t : finset α} {f : γ×α → β} : (∏ x in s ×ˢ t, f x) = ∏ y in t, ∏ x in s, f (x, y) := prod_finset_product_right (s ×ˢ t) t (λ a, s) (λ p, mem_product.trans and.comm) /-- An uncurried version of `finset.prod_product_right`. -/ @[to_additive "An uncurried version of `finset.prod_product_right`"] lemma prod_product_right' {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s ×ˢ t, f x.1 x.2) = ∏ y in t, ∏ x in s, f x y := prod_product_right /-- Generalization of `finset.prod_comm` to the case when the inner `finset`s depend on the outer variable. -/ @[to_additive "Generalization of `finset.sum_comm` to the case when the inner `finset`s depend on the outer variable."] lemma prod_comm' {s : finset γ} {t : γ → finset α} {t' : finset α} {s' : α → finset γ} (h : ∀ x y, x ∈ s ∧ y ∈ t x ↔ x ∈ s' y ∧ y ∈ t') {f : γ → α → β} : (∏ x in s, ∏ y in t x, f x y) = (∏ y in t', ∏ x in s' y, f x y) := begin classical, have : ∀ z : γ × α, z ∈ s.bUnion (λ x, (t x).map $ function.embedding.sectr x _) ↔ z.1 ∈ s ∧ z.2 ∈ t z.1, { rintro ⟨x, y⟩, simp }, exact (prod_finset_product' _ _ _ this).symm.trans (prod_finset_product_right' _ _ _ $ λ ⟨x, y⟩, (this _).trans ((h x y).trans and.comm)) end @[to_additive] lemma prod_comm {s : finset γ} {t : finset α} {f : γ → α → β} : (∏ x in s, ∏ y in t, f x y) = (∏ y in t, ∏ x in s, f x y) := prod_comm' $ λ _ _, iff.rfl @[to_additive] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀ a b c, r b c → r (f a * b) (g a * c)) : r (∏ x in s, f x) (∏ x in s, g x) := by { delta finset.prod, apply multiset.prod_hom_rel; assumption } @[to_additive] lemma prod_eq_one {f : α → β} {s : finset α} (h : ∀ x ∈ s, f x = 1) : (∏ x in s, f x) = 1 := calc (∏ x in s, f x) = ∏ x in s, 1 : finset.prod_congr rfl h ... = 1 : finset.prod_const_one @[to_additive] lemma prod_subset_one_on_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) (hg : ∀ x ∈ (s₂ \ s₁), g x = 1) (hfg : ∀ x ∈ s₁, f x = g x) : ∏ i in s₁, f i = ∏ i in s₂, g i := begin rw [← prod_sdiff h, prod_eq_one hg, one_mul], exact prod_congr rfl hfg end @[to_additive] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀ x ∈ s₂, x ∉ s₁ → f x = 1) : (∏ x in s₁, f x) = ∏ x in s₂, f x := by haveI := classical.dec_eq α; exact prod_subset_one_on_sdiff h (by simpa) (λ _ _, rfl) @[to_additive] lemma prod_filter_of_ne {p : α → Prop} [decidable_pred p] (hp : ∀ x ∈ s, f x ≠ 1 → p x) : (∏ x in (s.filter p), f x) = (∏ x in s, f x) := prod_subset (filter_subset _ _) $ λ x, by { classical, rw [not_imp_comm, mem_filter], exact λ h₁ h₂, ⟨h₁, hp _ h₁ h₂⟩ } -- If we use `[decidable_eq β]` here, some rewrites fail because they find a wrong `decidable` -- instance first; `{∀ x, decidable (f x ≠ 1)}` doesn't work with `rw ← prod_filter_ne_one` @[to_additive] lemma prod_filter_ne_one [∀ x, decidable (f x ≠ 1)] : (∏ x in (s.filter $ λ x, f x ≠ 1), f x) = (∏ x in s, f x) := prod_filter_of_ne $ λ _ _, id @[to_additive] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (∏ a in s.filter p, f a) = (∏ a in s, if p a then f a else 1) := calc (∏ a in s.filter p, f a) = ∏ a in s.filter p, if p a then f a else 1 : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = ∏ a in s, if p a then f a else 1 : begin refine prod_subset (filter_subset _ s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive] lemma prod_eq_single_of_mem {s : finset α} {f : α → β} (a : α) (h : a ∈ s) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) : (∏ x in s, f x) = f a := begin haveI := classical.dec_eq α, calc (∏ x in s, f x) = ∏ x in {a}, f x : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton end @[to_additive] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀ b ∈ s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : (∏ x in s, f x) = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, prod_eq_single_of_mem a this h₀) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive] lemma prod_eq_mul_of_mem {s : finset α} {f : α → β} (a b : α) (ha : a ∈ s) (hb : b ∈ s) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; let s' := ({a, b} : finset α), have hu : s' ⊆ s, { refine insert_subset.mpr _, apply and.intro ha, apply singleton_subset_iff.mpr hb }, have hf : ∀ c ∈ s, c ∉ s' → f c = 1, { intros c hc hcs, apply h₀ c hc, apply not_or_distrib.mp, intro hab, apply hcs, apply mem_insert.mpr, rw mem_singleton, exact hab }, rw ←prod_subset hu hf, exact finset.prod_pair hn end @[to_additive] lemma prod_eq_mul {s : finset α} {f : α → β} (a b : α) (hn : a ≠ b) (h₀ : ∀ c ∈ s, c ≠ a ∧ c ≠ b → f c = 1) (ha : a ∉ s → f a = 1) (hb : b ∉ s → f b = 1) : (∏ x in s, f x) = (f a) * (f b) := begin haveI := classical.dec_eq α; by_cases h₁ : a ∈ s; by_cases h₂ : b ∈ s, { exact prod_eq_mul_of_mem a b h₁ h₂ hn h₀ }, { rw [hb h₂, mul_one], apply prod_eq_single_of_mem a h₁, exact λ c hc hca, h₀ c hc ⟨hca, ne_of_mem_of_not_mem hc h₂⟩ }, { rw [ha h₁, one_mul], apply prod_eq_single_of_mem b h₂, exact λ c hc hcb, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, hcb⟩ }, { rw [ha h₁, hb h₂, mul_one], exact trans (prod_congr rfl (λ c hc, h₀ c hc ⟨ne_of_mem_of_not_mem hc h₁, ne_of_mem_of_not_mem hc h₂⟩)) prod_const_one } end @[to_additive] lemma prod_attach {f : α → β} : (∏ x in s.attach, f x) = (∏ x in s, f x) := by haveI := classical.dec_eq α; exact calc (∏ x in s.attach, f x.val) = (∏ x in (s.attach).image subtype.val, f x) : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] /-- A product over `s.subtype p` equals one over `s.filter p`. -/ @[simp, to_additive "A sum over `s.subtype p` equals one over `s.filter p`."] lemma prod_subtype_eq_prod_filter (f : α → β) {p : α → Prop} [decidable_pred p] : ∏ x in s.subtype p, f x = ∏ x in s.filter p, f x := begin conv_lhs { erw ←prod_map (s.subtype p) (function.embedding.subtype _) f }, exact prod_congr (subtype_map _) (λ x hx, rfl) end /-- If all elements of a `finset` satisfy the predicate `p`, a product over `s.subtype p` equals that product over `s`. -/ @[to_additive "If all elements of a `finset` satisfy the predicate `p`, a sum over `s.subtype p` equals that sum over `s`."] lemma prod_subtype_of_mem (f : α → β) {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : ∏ x in s.subtype p, f x = ∏ x in s, f x := by simp_rw [prod_subtype_eq_prod_filter, filter_true_of_mem h] /-- A product of a function over a `finset` in a subtype equals a product in the main type of a function that agrees with the first function on that `finset`. -/ @[to_additive "A sum of a function over a `finset` in a subtype equals a sum in the main type of a function that agrees with the first function on that `finset`."] lemma prod_subtype_map_embedding {p : α → Prop} {s : finset {x // p x}} {f : {x // p x} → β} {g : α → β} (h : ∀ x : {x // p x}, x ∈ s → g x = f x) : ∏ x in s.map (function.embedding.subtype _), g x = ∏ x in s, f x := begin rw finset.prod_map, exact finset.prod_congr rfl h end variables (f s) @[to_additive] lemma prod_coe_sort_eq_attach (f : s → β) : ∏ (i : s), f i = ∏ i in s.attach, f i := rfl @[to_additive] lemma prod_coe_sort : ∏ (i : s), f i = ∏ i in s, f i := prod_attach @[to_additive] lemma prod_finset_coe (f : α → β) (s : finset α) : ∏ (i : (s : set α)), f i = ∏ i in s, f i := prod_coe_sort s f variables {f s} @[to_additive] lemma prod_subtype {p : α → Prop} {F : fintype (subtype p)} (s : finset α) (h : ∀ x, x ∈ s ↔ p x) (f : α → β) : ∏ a in s, f a = ∏ a : subtype p, f a := have (∈ s) = p, from set.ext h, by { substI p, rw ← prod_coe_sort, congr } /-- The product of a function `g` defined only on a set `s` is equal to the product of a function `f` defined everywhere, as long as `f` and `g` agree on `s`, and `f = 1` off `s`. -/ @[to_additive "The sum of a function `g` defined only on a set `s` is equal to the sum of a function `f` defined everywhere, as long as `f` and `g` agree on `s`, and `f = 0` off `s`."] lemma prod_congr_set {α : Type*} [comm_monoid α] {β : Type*} [fintype β] (s : set β) [decidable_pred (∈s)] (f : β → α) (g : s → α) (w : ∀ (x : β) (h : x ∈ s), f x = g ⟨x, h⟩) (w' : ∀ (x : β), x ∉ s → f x = 1) : finset.univ.prod f = finset.univ.prod g := begin rw ←@finset.prod_subset _ _ s.to_finset finset.univ f _ (by simp), { rw finset.prod_subtype, { apply finset.prod_congr rfl, exact λ ⟨x, h⟩ _, w x h, }, { simp, }, }, { rintro x _ h, exact w' x (by simpa using h), }, end @[to_additive] lemma prod_apply_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} [decidable_pred (λ x, ¬ p x)] (f : Π (x : α), p x → γ) (g : Π (x : α), ¬p x → γ) (h : γ → β) : (∏ x in s, h (if hx : p x then f x hx else g x hx)) = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) := calc ∏ x in s, h (if hx : p x then f x hx else g x hx) = (∏ x in s.filter p, h (if hx : p x then f x hx else g x hx)) * (∏ x in s.filter (λ x, ¬ p x), h (if hx : p x then f x hx else g x hx)) : (prod_filter_mul_prod_filter_not s p _).symm ... = (∏ x in (s.filter p).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (if hx : p x.1 then f x.1 hx else g x.1 hx)) : congr_arg2 _ prod_attach.symm prod_attach.symm ... = (∏ x in (s.filter p).attach, h (f x.1 (mem_filter.mp x.2).2)) * (∏ x in (s.filter (λ x, ¬ p x)).attach, h (g x.1 (mem_filter.mp x.2).2)) : congr_arg2 _ (prod_congr rfl (λ x hx, congr_arg h (dif_pos (mem_filter.mp x.2).2))) (prod_congr rfl (λ x hx, congr_arg h (dif_neg (mem_filter.mp x.2).2))) @[to_additive] lemma prod_apply_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (h : γ → β) : (∏ x in s, h (if p x then f x else g x)) = (∏ x in s.filter p, h (f x)) * (∏ x in s.filter (λ x, ¬ p x), h (g x)) := trans (prod_apply_dite _ _ _) (congr_arg2 _ (@prod_attach _ _ _ _ (h ∘ f)) (@prod_attach _ _ _ _ (h ∘ g))) @[to_additive] lemma prod_dite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = (∏ x in (s.filter p).attach, f x.1 (mem_filter.mp x.2).2) * (∏ x in (s.filter (λ x, ¬ p x)).attach, g x.1 (mem_filter.mp x.2).2) := by simp [prod_apply_dite _ _ (λ x, x)] @[to_additive] lemma prod_ite {s : finset α} {p : α → Prop} {hp : decidable_pred p} (f g : α → β) : (∏ x in s, if p x then f x else g x) = (∏ x in s.filter p, f x) * (∏ x in s.filter (λ x, ¬ p x), g x) := by simp [prod_apply_ite _ _ (λ x, x)] @[to_additive] lemma prod_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, g x) := by { rw prod_ite, simp [filter_false_of_mem h, filter_true_of_mem h] } @[to_additive] lemma prod_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → β) (h : ∀ x ∈ s, p x) : (∏ x in s, if p x then f x else g x) = (∏ x in s, f x) := by { simp_rw ←(ite_not (p _)), apply prod_ite_of_false, simpa } @[to_additive] lemma prod_apply_ite_of_false {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, ¬p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (g x)) := by { simp_rw apply_ite k, exact prod_ite_of_false _ _ h } @[to_additive] lemma prod_apply_ite_of_true {p : α → Prop} {hp : decidable_pred p} (f g : α → γ) (k : γ → β) (h : ∀ x ∈ s, p x) : (∏ x in s, k (if p x then f x else g x)) = (∏ x in s, k (f x)) := by { simp_rw apply_ite k, exact prod_ite_of_true _ _ h } @[to_additive] lemma prod_extend_by_one [decidable_eq α] (s : finset α) (f : α → β) : ∏ i in s, (if i ∈ s then f i else 1) = ∏ i in s, f i := prod_congr rfl $ λ i hi, if_pos hi @[simp, to_additive] lemma prod_dite_eq [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, a = x → β) : (∏ x in s, (if h : a = x then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_dite_eq' [decidable_eq α] (s : finset α) (a : α) (b : Π x : α, x = a → β) : (∏ x in s, (if h : x = a then b x h else 1)) = ite (a ∈ s) (b a rfl) 1 := begin split_ifs with h, { rw [finset.prod_eq_single a, dif_pos rfl], { intros, rw dif_neg, cc }, { cc } }, { rw finset.prod_eq_one, intros, rw dif_neg, intro, cc } end @[simp, to_additive] lemma prod_ite_eq [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (a = x) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq s a (λ x _, b x) /-- A product taken over a conditional whose condition is an equality test on the index and whose alternative is `1` has value either the term at that index or `1`. The difference with `finset.prod_ite_eq` is that the arguments to `eq` are swapped. -/ @[simp, to_additive "A sum taken over a conditional whose condition is an equality test on the index and whose alternative is `0` has value either the term at that index or `0`. The difference with `finset.sum_ite_eq` is that the arguments to `eq` are swapped."] lemma prod_ite_eq' [decidable_eq α] (s : finset α) (a : α) (b : α → β) : (∏ x in s, (ite (x = a) (b x) 1)) = ite (a ∈ s) (b a) 1 := prod_dite_eq' s a (λ x _, b x) @[to_additive] lemma prod_ite_index (p : Prop) [decidable p] (s t : finset α) (f : α → β) : (∏ x in if p then s else t, f x) = if p then ∏ x in s, f x else ∏ x in t, f x := apply_ite (λ s, ∏ x in s, f x) _ _ _ @[simp, to_additive] lemma prod_ite_irrel (p : Prop) [decidable p] (s : finset α) (f g : α → β) : (∏ x in s, if p then f x else g x) = if p then ∏ x in s, f x else ∏ x in s, g x := by { split_ifs with h; refl } @[simp, to_additive] lemma prod_dite_irrel (p : Prop) [decidable p] (s : finset α) (f : p → α → β) (g : ¬p → α → β) : (∏ x in s, if h : p then f h x else g h x) = if h : p then ∏ x in s, f h x else ∏ x in s, g h x := by { split_ifs with h; refl } @[simp] lemma sum_pi_single' {ι M : Type*} [decidable_eq ι] [add_comm_monoid M] (i : ι) (x : M) (s : finset ι) : ∑ j in s, pi.single i x j = if i ∈ s then x else 0 := sum_dite_eq' _ _ _ @[simp] lemma sum_pi_single {ι : Type*} {M : ι → Type*} [decidable_eq ι] [Π i, add_comm_monoid (M i)] (i : ι) (f : Π i, M i) (s : finset ι) : ∑ j in s, pi.single j (f j) i = if i ∈ s then f i else 0 := sum_dite_eq _ _ _ @[to_additive] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Π a ∈ s, f a ≠ 1 → γ) (hi : ∀ a h₁ h₂, i a h₁ h₂ ∈ t) (i_inj : ∀ a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (i_surj : ∀ b ∈ t, g b ≠ 1 → ∃ a h₁ h₂, b = i a h₁ h₂) (h : ∀ a h₁ h₂, f a = g (i a h₁ h₂)) : (∏ x in s, f x) = (∏ x in t, g x) := by classical; exact calc (∏ x in s, f x) = ∏ x in (s.filter $ λ x, f x ≠ 1), f x : prod_filter_ne_one.symm ... = ∏ x in (t.filter $ λ x, g x ≠ 1), g x : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λ h₁ h₂, mem_filter.mpr ⟨hi a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λ ha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λ ha₂₁ ha₂₂, i_inj a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λ h₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := i_surj b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = (∏ x in t, g x) : prod_filter_ne_one @[to_additive] lemma prod_dite_of_false {p : α → Prop} {hp : decidable_pred p} (h : ∀ x ∈ s, ¬ p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = ∏ (x : s), g x.val (h x.val x.property) := prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_neg }) (λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩) @[to_additive] lemma prod_dite_of_true {p : α → Prop} {hp : decidable_pred p} (h : ∀ x ∈ s, p x) (f : Π (x : α), p x → β) (g : Π (x : α), ¬p x → β) : (∏ x in s, if hx : p x then f x hx else g x hx) = ∏ (x : s), f x.val (h x.val x.property) := prod_bij (λ x hx, ⟨x,hx⟩) (λ x hx, by simp) (λ a ha, by { dsimp, rw dif_pos }) (λ a₁ a₂ h₁ h₂ hh, congr_arg coe hh) (λ b hb, ⟨b.1, b.2, by simp⟩) @[to_additive] lemma nonempty_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : s.nonempty := s.eq_empty_or_nonempty.elim (λ H, false.elim $ h $ H.symm ▸ prod_empty) id @[to_additive] lemma exists_ne_one_of_prod_ne_one (h : (∏ x in s, f x) ≠ 1) : ∃ a ∈ s, f a ≠ 1 := begin classical, rw ← prod_filter_ne_one at h, rcases nonempty_of_prod_ne_one h with ⟨x, hx⟩, exact ⟨x, (mem_filter.1 hx).1, (mem_filter.1 hx).2⟩ end @[to_additive] lemma prod_range_succ_comm (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = f n * ∏ x in range n, f x := by rw [range_succ, prod_insert not_mem_range_self] @[to_additive] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : ∏ x in range (n + 1), f x = (∏ x in range n, f x) * f n := by simp only [mul_comm, prod_range_succ_comm] @[to_additive] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (∏ k in range (n + 1), f k) = (∏ k in range n, f (k+1)) * f 0 | 0 := prod_range_succ _ _ | (n + 1) := by rw [prod_range_succ _ n, mul_right_comm, ← prod_range_succ', prod_range_succ] @[to_additive] lemma eventually_constant_prod {u : ℕ → β} {N : ℕ} (hu : ∀ n ≥ N, u n = 1) {n : ℕ} (hn : N ≤ n) : ∏ k in range (n + 1), u k = ∏ k in range (N + 1), u k := begin obtain ⟨m, rfl : n = N + m⟩ := le_iff_exists_add.mp hn, clear hn, induction m with m hm, { simp }, erw [prod_range_succ, hm], simp [hu, @zero_le' ℕ], end @[to_additive] lemma prod_range_add (f : ℕ → β) (n m : ℕ) : ∏ x in range (n + m), f x = (∏ x in range n, f x) * (∏ x in range m, f (n + x)) := begin induction m with m hm, { simp }, { rw [nat.add_succ, prod_range_succ, hm, prod_range_succ, mul_assoc], }, end @[to_additive] lemma prod_range_add_div_prod_range {α : Type*} [comm_group α] (f : ℕ → α) (n m : ℕ) : (∏ k in range (n + m), f k) / (∏ k in range n, f k) = ∏ k in finset.range m, f (n + k) := div_eq_of_eq_mul' (prod_range_add f n m) @[to_additive] lemma prod_range_zero (f : ℕ → β) : ∏ k in range 0, f k = 1 := by rw [range_zero, prod_empty] @[to_additive sum_range_one] lemma prod_range_one (f : ℕ → β) : ∏ k in range 1, f k = f 0 := by { rw [range_one], apply @prod_singleton β ℕ 0 f } open list @[to_additive] lemma prod_list_map_count [decidable_eq α] (l : list α) {M : Type*} [comm_monoid M] (f : α → M) : (l.map f).prod = ∏ m in l.to_finset, (f m) ^ (l.count m) := begin induction l with a s IH, { simp only [map_nil, prod_nil, count_nil, pow_zero, prod_const_one] }, simp only [list.map, list.prod_cons, to_finset_cons, IH], by_cases has : a ∈ s.to_finset, { rw [insert_eq_of_mem has, ← insert_erase has, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _), ← mul_assoc, count_cons_self, pow_succ], congr' 1, refine prod_congr rfl (λ x hx, _), rw [count_cons_of_ne (ne_of_mem_erase hx)] }, rw [prod_insert has, count_cons_self, count_eq_zero_of_not_mem (mt mem_to_finset.2 has), pow_one], congr' 1, refine prod_congr rfl (λ x hx, _), rw count_cons_of_ne, rintro rfl, exact has hx, end @[to_additive] lemma prod_list_count [decidable_eq α] [comm_monoid α] (s : list α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by simpa using prod_list_map_count s id @[to_additive] lemma prod_list_count_of_subset [decidable_eq α] [comm_monoid α] (m : list α) (s : finset α) (hs : m.to_finset ⊆ s) : m.prod = ∏ i in s, i ^ (m.count i) := begin rw prod_list_count, refine prod_subset hs (λ x _ hx, _), rw [mem_to_finset] at hx, rw [count_eq_zero_of_not_mem hx, pow_zero], end lemma sum_filter_count_eq_countp [decidable_eq α] (p : α → Prop) [decidable_pred p] (l : list α) : ∑ x in l.to_finset.filter p, l.count x = l.countp p := by simp [finset.sum, sum_map_count_dedup_filter_eq_countp p l] open multiset @[to_additive] lemma prod_multiset_map_count [decidable_eq α] (s : multiset α) {M : Type*} [comm_monoid M] (f : α → M) : (s.map f).prod = ∏ m in s.to_finset, (f m) ^ (s.count m) := by { refine quot.induction_on s (λ l, _), simp [prod_list_map_count l f] } @[to_additive] lemma prod_multiset_count [decidable_eq α] [comm_monoid α] (s : multiset α) : s.prod = ∏ m in s.to_finset, m ^ (s.count m) := by { convert prod_multiset_map_count s id, rw multiset.map_id } @[to_additive] lemma prod_multiset_count_of_subset [decidable_eq α] [comm_monoid α] (m : multiset α) (s : finset α) (hs : m.to_finset ⊆ s) : m.prod = ∏ i in s, i ^ (m.count i) := begin revert hs, refine quot.induction_on m (λ l, _), simp only [quot_mk_to_coe'', coe_prod, coe_count], apply prod_list_count_of_subset l s end @[to_additive] lemma prod_mem_multiset [decidable_eq α] (m : multiset α) (f : {x // x ∈ m} → β) (g : α → β) (hfg : ∀ x, f x = g x) : ∏ (x : {x // x ∈ m}), f x = ∏ x in m.to_finset, g x := prod_bij (λ x _, x.1) (λ x _, multiset.mem_to_finset.mpr x.2) (λ _ _, hfg _) (λ _ _ _ _ h, by { ext, assumption }) (λ y hy, ⟨⟨y, multiset.mem_to_finset.mp hy⟩, finset.mem_univ _, rfl⟩) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (p_one : p 1) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction _ _ p_mul p_one (multiset.forall_mem_map_iff.mpr p_s) /-- To prove a property of a product, it suffices to prove that the property is multiplicative and holds on factors. -/ @[to_additive "To prove a property of a sum, it suffices to prove that the property is additive and holds on summands."] lemma prod_induction_nonempty {M : Type*} [comm_monoid M] (f : α → M) (p : M → Prop) (p_mul : ∀ a b, p a → p b → p (a * b)) (hs_nonempty : s.nonempty) (p_s : ∀ x ∈ s, p $ f x) : p $ ∏ x in s, f x := multiset.prod_induction_nonempty p p_mul (by simp [nonempty_iff_ne_empty.mp hs_nonempty]) (multiset.forall_mem_map_iff.mpr p_s) /-- For any product along `{0, ..., n - 1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking ratios of adjacent terms. This is a multiplicative discrete analogue of the fundamental theorem of calculus. -/ @[to_additive "For any sum along `{0, ..., n - 1}` of a commutative-monoid-valued function, we can verify that it's equal to a different function just by checking differences of adjacent terms. This is a discrete analogue of the fundamental theorem of calculus."] lemma prod_range_induction (f s : ℕ → β) (h0 : s 0 = 1) (h : ∀ n, s (n + 1) = s n * f n) (n : ℕ) : ∏ k in finset.range n, f k = s n := begin induction n with k hk, { simp only [h0, finset.prod_range_zero] }, { simp only [hk, finset.prod_range_succ, h, mul_comm] } end /-- A telescoping product along `{0, ..., n - 1}` of a commutative group valued function reduces to the ratio of the last and first factors. -/ @[to_additive "A telescoping sum along `{0, ..., n - 1}` of an additive commutative group valued function reduces to the difference of the last and first terms."] lemma prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f (i + 1) / f i) = f n / f 0 := by apply prod_range_induction; simp @[to_additive] lemma prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : ∏ i in range n, (f i / f (i + 1)) = f 0 / f n := by apply prod_range_induction; simp @[to_additive] lemma eq_prod_range_div {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : f n = f 0 * ∏ i in range n, (f (i + 1) / f i) := by rw [prod_range_div, mul_div_cancel'_right] @[to_additive] lemma eq_prod_range_div' {M : Type*} [comm_group M] (f : ℕ → M) (n : ℕ) : f n = ∏ i in range (n + 1), if i = 0 then f 0 else f i / f (i - 1) := by { conv_lhs { rw [finset.eq_prod_range_div f] }, simp [finset.prod_range_succ', mul_comm] } /-- A telescoping sum along `{0, ..., n-1}` of an `ℕ`-valued function reduces to the difference of the last and first terms when the function we are summing is monotone. -/ lemma sum_range_tsub [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] [contravariant_class α α (+) (≤)] {f : ℕ → α} (h : monotone f) (n : ℕ) : ∑ i in range n, (f (i+1) - f i) = f n - f 0 := begin refine sum_range_induction _ _ (tsub_self _) (λ n, _) _, have h₁ : f n ≤ f (n+1) := h (nat.le_succ _), have h₂ : f 0 ≤ f n := h (nat.zero_le _), rw [tsub_add_eq_add_tsub h₂, add_tsub_cancel_of_le h₁], end @[simp, to_additive] lemma prod_const (b : β) : (∏ x in s, b) = b ^ s.card := (congr_arg _ $ s.val.map_const b).trans $ multiset.prod_repeat b s.card @[to_additive] lemma pow_eq_prod_const (b : β) : ∀ n, b ^ n = ∏ k in range n, b := by simp @[to_additive] lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : ∏ x in s, f x ^ n = (∏ x in s, f x) ^ n := multiset.prod_map_pow @[to_additive] lemma prod_flip {n : ℕ} (f : ℕ → β) : ∏ r in range (n + 1), f (n - r) = ∏ k in range (n + 1), f k := begin induction n with n ih, { rw [prod_range_one, prod_range_one] }, { rw [prod_range_succ', prod_range_succ _ (nat.succ n)], simp [← ih] } end @[to_additive] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h : ∀ a ha, f a * f (g a ha) = 1) (g_ne : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (g_mem : ∀ a ha, g a ha ∈ s) (g_inv : ∀ a ha, g (g a ha) (g_mem a ha) = a), (∏ x in s, f x) = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h g_ne g_mem g_inv, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ rfl) (λ ⟨x, hx⟩, have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← g_inv x hx, ← g_inv y hy]; simp [h], have ih': ∏ y in erase (erase s x) (g x hx), f y = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (g_mem x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h y (hmem y hy)) (λ y hy, g_ne y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from g_inv y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, g_mem y (hmem y hy)⟩⟩) (λ y hy, g_inv y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simpa [hy, not_and_distrib, or_comm] using hy₁, this.elim (λ hy, hy.symm ▸ hx1) (λ hy, h x hx ▸ hy ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨g_ne x hx hx1, g_mem x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h x hx])) /-- The product of the composition of functions `f` and `g`, is the product over `b ∈ s.image g` of `f b` to the power of the cardinality of the fibre of `b`. See also `finset.prod_image`. -/ @[to_additive "The sum of the composition of functions `f` and `g`, is the sum over `b ∈ s.image g` of `f b` times of the cardinality of the fibre of `b`. See also `finset.sum_image`."] lemma prod_comp [decidable_eq γ] (f : γ → β) (g : α → γ) : ∏ a in s, f (g a) = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card := calc ∏ a in s, f (g a) = ∏ x in (s.image g).sigma (λ b : γ, s.filter (λ a, g a = b)), f (g x.2) : prod_bij (λ a ha, ⟨g a, a⟩) (by simp; tauto) (λ _ _, rfl) (by simp) -- `(by finish)` closes this (by { rintro ⟨b_fst, b_snd⟩ H, simp only [mem_image, exists_prop, mem_filter, mem_sigma] at H, tauto }) ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f (g a) : prod_sigma _ _ _ ... = ∏ b in s.image g, ∏ a in s.filter (λ a, g a = b), f b : prod_congr rfl (λ b hb, prod_congr rfl (by simp {contextual := tt})) ... = ∏ b in s.image g, f b ^ (s.filter (λ a, g a = b)).card : prod_congr rfl (λ _ _, prod_const _) @[to_additive] lemma prod_piecewise [decidable_eq α] (s t : finset α) (f g : α → β) : (∏ x in s, (t.piecewise f g) x) = (∏ x in s ∩ t, f x) * (∏ x in s \ t, g x) := by { rw [piecewise, prod_ite, filter_mem_eq_inter, ← sdiff_eq_filter], } @[to_additive] lemma prod_inter_mul_prod_diff [decidable_eq α] (s t : finset α) (f : α → β) : (∏ x in s ∩ t, f x) * (∏ x in s \ t, f x) = (∏ x in s, f x) := by { convert (s.prod_piecewise t f f).symm, simp [finset.piecewise] } @[to_additive] lemma prod_eq_mul_prod_diff_singleton [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = f i * ∏ x in s \ {i}, f x := by { convert (s.prod_inter_mul_prod_diff {i} f).symm, simp [h] } @[to_additive] lemma prod_eq_prod_diff_singleton_mul [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) : ∏ x in s, f x = (∏ x in s \ {i}, f x) * f i := by { rw [prod_eq_mul_prod_diff_singleton h, mul_comm] } @[to_additive] lemma _root_.fintype.prod_eq_mul_prod_compl [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (f a) * ∏ i in {a}ᶜ, f i := prod_eq_mul_prod_diff_singleton (mem_univ a) f @[to_additive] lemma _root_.fintype.prod_eq_prod_compl_mul [decidable_eq α] [fintype α] (a : α) (f : α → β) : ∏ i, f i = (∏ i in {a}ᶜ, f i) * f a := prod_eq_prod_diff_singleton_mul (mem_univ a) f lemma dvd_prod_of_mem (f : α → β) {a : α} {s : finset α} (ha : a ∈ s) : f a ∣ ∏ i in s, f i := begin classical, rw finset.prod_eq_mul_prod_diff_singleton ha, exact dvd_mul_right _ _, end /-- A product can be partitioned into a product of products, each equivalent under a setoid. -/ @[to_additive "A sum can be partitioned into a sum of sums, each equivalent under a setoid."] lemma prod_partition (R : setoid α) [decidable_rel R.r] : (∏ x in s, f x) = ∏ xbar in s.image quotient.mk, ∏ y in s.filter (λ y, ⟦y⟧ = xbar), f y := begin refine (finset.prod_image' f (λ x hx, _)).symm, refl, end /-- If we can partition a product into subsets that cancel out, then the whole product cancels. -/ @[to_additive "If we can partition a sum into subsets that cancel out, then the whole sum cancels."] lemma prod_cancels_of_partition_cancels (R : setoid α) [decidable_rel R.r] (h : ∀ x ∈ s, (∏ a in s.filter (λ y, y ≈ x), f a) = 1) : (∏ x in s, f x) = 1 := begin rw [prod_partition R, ←finset.prod_eq_one], intros xbar xbar_in_s, obtain ⟨x, x_in_s, xbar_eq_x⟩ := mem_image.mp xbar_in_s, rw [←xbar_eq_x, filter_congr (λ y _, @quotient.eq _ R y x)], apply h x x_in_s, end @[to_additive] lemma prod_update_of_not_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∉ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = (∏ x in s, f x) := begin apply prod_congr rfl (λ j hj, _), have : j ≠ i, by { assume eq, rw eq at hj, exact h hj }, simp [this] end @[to_additive] lemma prod_update_of_mem [decidable_eq α] {s : finset α} {i : α} (h : i ∈ s) (f : α → β) (b : β) : (∏ x in s, function.update f i b x) = b * (∏ x in s \ (singleton i), f x) := by { rw [update_eq_piecewise, prod_piecewise], simp [h] } /-- If a product of a `finset` of size at most 1 has a given value, so do the terms in that product. -/ @[to_additive eq_of_card_le_one_of_sum_eq "If a sum of a `finset` of size at most 1 has a given value, so do the terms in that sum."] lemma eq_of_card_le_one_of_prod_eq {s : finset α} (hc : s.card ≤ 1) {f : α → β} {b : β} (h : ∏ x in s, f x = b) : ∀ x ∈ s, f x = b := begin intros x hx, by_cases hc0 : s.card = 0, { exact false.elim (card_ne_zero_of_mem hx hc0) }, { have h1 : s.card = 1 := le_antisymm hc (nat.one_le_of_lt (nat.pos_of_ne_zero hc0)), rw card_eq_one at h1, cases h1 with x2 hx2, rw [hx2, mem_singleton] at hx, simp_rw hx2 at h, rw hx, rw prod_singleton at h, exact h } end /-- Taking a product over `s : finset α` is the same as multiplying the value on a single element `f a` by the product of `s.erase a`. See `multiset.prod_map_erase` for the `multiset` version. -/ @[to_additive "Taking a sum over `s : finset α` is the same as adding the value on a single element `f a` to the sum over `s.erase a`. See `multiset.sum_map_erase` for the `multiset` version."] lemma mul_prod_erase [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : f a * (∏ x in s.erase a, f x) = ∏ x in s, f x := by rw [← prod_insert (not_mem_erase a s), insert_erase h] /-- A variant of `finset.mul_prod_erase` with the multiplication swapped. -/ @[to_additive "A variant of `finset.add_sum_erase` with the addition swapped."] lemma prod_erase_mul [decidable_eq α] (s : finset α) (f : α → β) {a : α} (h : a ∈ s) : (∏ x in s.erase a, f x) * f a = ∏ x in s, f x := by rw [mul_comm, mul_prod_erase s f h] /-- If a function applied at a point is 1, a product is unchanged by removing that point, if present, from a `finset`. -/ @[to_additive "If a function applied at a point is 0, a sum is unchanged by removing that point, if present, from a `finset`."] lemma prod_erase [decidable_eq α] (s : finset α) {f : α → β} {a : α} (h : f a = 1) : ∏ x in s.erase a, f x = ∏ x in s, f x := begin rw ←sdiff_singleton_eq_erase, refine prod_subset (sdiff_subset _ _) (λ x hx hnx, _), rw sdiff_singleton_eq_erase at hnx, rwa eq_of_mem_of_not_mem_erase hx hnx end lemma sum_erase_lt_of_pos {γ : Type*} [decidable_eq α] [ordered_add_comm_monoid γ] [covariant_class γ γ (+) (<)] {s : finset α} {d : α} (hd : d ∈ s) {f : α → γ} (hdf : 0 < f d) : ∑ (m : α) in s.erase d, f m < ∑ (m : α) in s, f m := begin nth_rewrite_rhs 0 ←finset.insert_erase hd, rw finset.sum_insert (finset.not_mem_erase d s), exact lt_add_of_pos_left _ hdf, end /-- If a product is 1 and the function is 1 except possibly at one point, it is 1 everywhere on the `finset`. -/ @[to_additive "If a sum is 0 and the function is 0 except possibly at one point, it is 0 everywhere on the `finset`."] lemma eq_one_of_prod_eq_one {s : finset α} {f : α → β} {a : α} (hp : ∏ x in s, f x = 1) (h1 : ∀ x ∈ s, x ≠ a → f x = 1) : ∀ x ∈ s, f x = 1 := begin intros x hx, classical, by_cases h : x = a, { rw h, rw h at hx, rw [←prod_subset (singleton_subset_iff.2 hx) (λ t ht ha, h1 t ht (not_mem_singleton.1 ha)), prod_singleton] at hp, exact hp }, { exact h1 x hx h } end lemma prod_pow_boole [decidable_eq α] (s : finset α) (f : α → β) (a : α) : (∏ x in s, (f x)^(ite (a = x) 1 0)) = ite (a ∈ s) (f a) 1 := by simp lemma prod_dvd_prod_of_dvd {S : finset α} (g1 g2 : α → β) (h : ∀ a ∈ S, g1 a ∣ g2 a) : S.prod g1 ∣ S.prod g2 := begin classical, apply finset.induction_on' S, { simp }, intros a T haS _ haT IH, repeat {rw finset.prod_insert haT}, exact mul_dvd_mul (h a haS) IH, end lemma prod_dvd_prod_of_subset {ι M : Type*} [comm_monoid M] (s t : finset ι) (f : ι → M) (h : s ⊆ t) : ∏ i in s, f i ∣ ∏ i in t, f i := multiset.prod_dvd_prod_of_le $ multiset.map_le_map $ by simpa end comm_monoid /-- If `f = g = h` everywhere but at `i`, where `f i = g i + h i`, then the product of `f` over `s` is the sum of the products of `g` and `h`. -/ lemma prod_add_prod_eq [comm_semiring β] {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h1 : g i + h i = f i) (h2 : ∀ j ∈ s, j ≠ i → g j = f j) (h3 : ∀ j ∈ s, j ≠ i → h j = f j) : ∏ i in s, g i + ∏ i in s, h i = ∏ i in s, f i := by { classical, simp_rw [prod_eq_mul_prod_diff_singleton hi, ← h1, right_distrib], congr' 2; apply prod_congr rfl; simpa } lemma card_eq_sum_ones (s : finset α) : s.card = ∑ _ in s, 1 := by simp lemma sum_const_nat {m : ℕ} {f : α → ℕ} (h₁ : ∀ x ∈ s, f x = m) : (∑ x in s, f x) = card s * m := begin rw [← nat.nsmul_eq_mul, ← sum_const], apply sum_congr rfl h₁ end @[simp] lemma sum_boole {s : finset α} {p : α → Prop} [non_assoc_semiring β] {hp : decidable_pred p} : (∑ x in s, if p x then (1 : β) else (0 : β)) = (s.filter p).card := by simp [sum_ite] lemma _root_.commute.sum_right [non_unital_non_assoc_semiring β] (s : finset α) (f : α → β) (b : β) (h : ∀ i ∈ s, commute b (f i)) : commute b (∑ i in s, f i) := commute.multiset_sum_right _ _ $ λ b hb, begin obtain ⟨i, hi, rfl⟩ := multiset.mem_map.mp hb, exact h _ hi end lemma _root_.commute.sum_left [non_unital_non_assoc_semiring β] (s : finset α) (f : α → β) (b : β) (h : ∀ i ∈ s, commute (f i) b) : commute (∑ i in s, f i) b := (commute.sum_right _ _ _ $ λ i hi, (h _ hi).symm).symm section opposite open mul_opposite /-- Moving to the opposite additive commutative monoid commutes with summing. -/ @[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) : op (∑ x in s, f x) = ∑ x in s, op (f x) := (op_add_equiv : β ≃+ βᵐᵒᵖ).map_sum _ _ @[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵐᵒᵖ) : unop (∑ x in s, f x) = ∑ x in s, unop (f x) := (op_add_equiv : β ≃+ βᵐᵒᵖ).symm.map_sum _ _ end opposite section division_comm_monoid variables [division_comm_monoid β] @[simp, to_additive] lemma prod_inv_distrib : (∏ x in s, (f x)⁻¹) = (∏ x in s, f x)⁻¹ := multiset.prod_map_inv @[simp, to_additive] lemma prod_div_distrib : (∏ x in s, f x / g x) = (∏ x in s, f x) / ∏ x in s, g x := multiset.prod_map_div @[to_additive] lemma prod_zpow (f : α → β) (s : finset α) (n : ℤ) : ∏ a in s, (f a) ^ n = (∏ a in s, f a) ^ n := multiset.prod_map_zpow end division_comm_monoid section comm_group variables [comm_group β] [decidable_eq α] @[simp, to_additive] lemma prod_sdiff_eq_div (h : s₁ ⊆ s₂) : (∏ x in (s₂ \ s₁), f x) = (∏ x in s₂, f x) / (∏ x in s₁, f x) := by rw [eq_div_iff_mul_eq', prod_sdiff h] @[to_additive] lemma prod_sdiff_div_prod_sdiff : (∏ x in s₂ \ s₁, f x) / (∏ x in s₁ \ s₂, f x) = (∏ x in s₂, f x) / (∏ x in s₁, f x) := by simp [← finset.prod_sdiff (@inf_le_left _ _ s₁ s₂), ← finset.prod_sdiff (@inf_le_right _ _ s₁ s₂)] @[simp, to_additive] lemma prod_erase_eq_div {a : α} (h : a ∈ s) : (∏ x in s.erase a, f x) = (∏ x in s, f x) / f a := by rw [eq_div_iff_mul_eq', prod_erase_mul _ _ h] end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = ∑ a in s, card (t a) := multiset.card_sigma _ _ lemma card_bUnion [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → disjoint (t x) (t y)) : (s.bUnion t).card = ∑ u in s, card (t u) := calc (s.bUnion t).card = ∑ i in s.bUnion t, 1 : by simp ... = ∑ a in s, ∑ i in t a, 1 : finset.sum_bUnion h ... = ∑ u in s, card (t u) : by simp lemma card_bUnion_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bUnion t).card ≤ ∑ a in s, (t a).card := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bUnion t).card ≤ (t a).card + (s.bUnion t).card : by rw bUnion_insert; exact finset.card_union_le _ _ ... ≤ ∑ a in insert a s, card (t a) : by rw sum_insert has; exact add_le_add_left ih _) theorem card_eq_sum_card_fiberwise [decidable_eq β] {f : α → β} {s : finset α} {t : finset β} (H : ∀ x ∈ s, f x ∈ t) : s.card = ∑ a in t, (s.filter (λ x, f x = a)).card := by simp only [card_eq_sum_ones, sum_fiberwise_of_maps_to H] theorem card_eq_sum_card_image [decidable_eq β] (f : α → β) (s : finset α) : s.card = ∑ a in s.image f, (s.filter (λ x, f x = a)).card := card_eq_sum_card_fiberwise (λ _, mem_image_of_mem _) lemma mem_sum {f : α → multiset β} (s : finset α) (b : β) : b ∈ ∑ x in s, f x ↔ ∃ a ∈ s, b ∈ f a := begin classical, refine s.induction_on (by simp) _, { intros a t hi ih, simp [sum_insert hi, ih, or_and_distrib_right, exists_or_distrib] } end section prod_eq_zero variables [comm_monoid_with_zero β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : (∏ x in s, f x) = 0 := by { haveI := classical.dec_eq α, rw [←prod_erase_mul _ _ ha, h, mul_zero] } lemma prod_boole {s : finset α} {p : α → Prop} [decidable_pred p] : ∏ i in s, ite (p i) (1 : β) (0 : β) = ite (∀ i ∈ s, p i) 1 0 := begin split_ifs, { apply prod_eq_one, intros i hi, rw if_pos (h i hi) }, { push_neg at h, rcases h with ⟨i, hi, hq⟩, apply prod_eq_zero hi, rw [if_neg hq] }, end variables [nontrivial β] [no_zero_divisors β] lemma prod_eq_zero_iff : (∏ x in s, f x) = 0 ↔ (∃ a ∈ s, f a = 0) := begin classical, apply finset.induction_on s, exact ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩, assume a s ha ih, rw [prod_insert ha, mul_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end theorem prod_ne_zero_iff : (∏ x in s, f x) ≠ 0 ↔ (∀ a ∈ s, f a ≠ 0) := by { rw [ne, prod_eq_zero_iff], push_neg } end prod_eq_zero @[to_additive] lemma prod_unique_nonempty {α β : Type*} [comm_monoid β] [unique α] (s : finset α) (f : α → β) (h : s.nonempty) : (∏ x in s, f x) = f default := by rw [h.eq_singleton_default, finset.prod_singleton] end finset namespace fintype open finset /-- `fintype.prod_bijective` is a variant of `finset.prod_bij` that accepts `function.bijective`. See `function.bijective.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a variant of `finset.sum_bij` that accepts `function.bijective`. See `function.bijective.sum_comp` for a version without `h`. "] lemma prod_bijective {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α → β) (he : function.bijective e) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bij (λ x _, e x) (λ x _, mem_univ (e x)) (λ x _, h x) (λ x x' _ _ h, he.injective h) (λ y _, (he.surjective y).imp $ λ a h, ⟨mem_univ _, h.symm⟩) /-- `fintype.prod_equiv` is a specialization of `finset.prod_bij` that automatically fills in most arguments. See `equiv.prod_comp` for a version without `h`. -/ @[to_additive "`fintype.sum_equiv` is a specialization of `finset.sum_bij` that automatically fills in most arguments. See `equiv.sum_comp` for a version without `h`. "] lemma prod_equiv {α β M : Type*} [fintype α] [fintype β] [comm_monoid M] (e : α ≃ β) (f : α → M) (g : β → M) (h : ∀ x, f x = g (e x)) : ∏ x : α, f x = ∏ x : β, g x := prod_bijective e e.bijective f g h variables {f s} @[to_additive] lemma prod_unique {α β : Type*} [comm_monoid β] [unique α] (f : α → β) : (∏ x : α, f x) = f default := by rw [univ_unique, prod_singleton] @[to_additive] lemma prod_empty {α β : Type*} [comm_monoid β] [is_empty α] (f : α → β) : (∏ x : α, f x) = 1 := by rw [eq_empty_of_is_empty (univ : finset α), finset.prod_empty] @[to_additive] lemma prod_subsingleton {α β : Type*} [comm_monoid β] [subsingleton α] [fintype α] (f : α → β) (a : α) : (∏ x : α, f x) = f a := begin haveI : unique α := unique_of_subsingleton a, convert prod_unique f end @[to_additive] lemma prod_subtype_mul_prod_subtype {α β : Type*} [fintype α] [comm_monoid β] (p : α → Prop) (f : α → β) [decidable_pred p] : (∏ (i : {x // p x}), f i) * (∏ i : {x // ¬ p x}, f i) = ∏ i, f i := begin classical, let s := {x | p x}.to_finset, rw [← finset.prod_subtype s, ← finset.prod_subtype sᶜ], { exact finset.prod_mul_prod_compl _ _ }, { simp }, { simp } end end fintype namespace list @[to_additive] lemma prod_to_finset {M : Type*} [decidable_eq α] [comm_monoid M] (f : α → M) : ∀ {l : list α} (hl : l.nodup), l.to_finset.prod f = (l.map f).prod | [] _ := by simp | (a :: l) hl := let ⟨not_mem, hl⟩ := list.nodup_cons.mp hl in by simp [finset.prod_insert (mt list.mem_to_finset.mp not_mem), prod_to_finset hl] end list namespace multiset lemma disjoint_list_sum_left {a : multiset α} {l : list (multiset α)} : multiset.disjoint l.sum a ↔ ∀ b ∈ l, multiset.disjoint b a := begin induction l with b bs ih, { simp only [zero_disjoint, list.not_mem_nil, is_empty.forall_iff, forall_const, list.sum_nil], }, { simp_rw [list.sum_cons, disjoint_add_left, list.mem_cons_iff, forall_eq_or_imp], simp [and.congr_left_iff, iff_self, ih], }, end lemma disjoint_list_sum_right {a : multiset α} {l : list (multiset α)} : multiset.disjoint a l.sum ↔ ∀ b ∈ l, multiset.disjoint a b := by simpa only [disjoint_comm] using disjoint_list_sum_left lemma disjoint_sum_left {a : multiset α} {i : multiset (multiset α)} : multiset.disjoint i.sum a ↔ ∀ b ∈ i, multiset.disjoint b a := quotient.induction_on i $ λ l, begin rw [quot_mk_to_coe, multiset.coe_sum], exact disjoint_list_sum_left, end lemma disjoint_sum_right {a : multiset α} {i : multiset (multiset α)} : multiset.disjoint a i.sum ↔ ∀ b ∈ i, multiset.disjoint a b := by simpa only [disjoint_comm] using disjoint_sum_left lemma disjoint_finset_sum_left {β : Type*} {i : finset β} {f : β → multiset α} {a : multiset α} : multiset.disjoint (i.sum f) a ↔ ∀ b ∈ i, multiset.disjoint (f b) a := begin convert (@disjoint_sum_left _ a) (map f i.val), simp [finset.mem_def, and.congr_left_iff, iff_self], end lemma disjoint_finset_sum_right {β : Type*} {i : finset β} {f : β → multiset α} {a : multiset α} : multiset.disjoint a (i.sum f) ↔ ∀ b ∈ i, multiset.disjoint a (f b) := by simpa only [disjoint_comm] using disjoint_finset_sum_left variables [decidable_eq α] lemma add_eq_union_left_of_le {x y z : multiset α} (h : y ≤ x) : z + x = z ∪ y ↔ z.disjoint x ∧ x = y := begin rw ←add_eq_union_iff_disjoint, split, { intro h0, rw and_iff_right_of_imp, { exact (le_of_add_le_add_left $ h0.trans_le $ union_le_add z y).antisymm h, }, { rintro rfl, exact h0, } }, { rintro ⟨h0, rfl⟩, exact h0, } end lemma add_eq_union_right_of_le {x y z : multiset α} (h : z ≤ y) : x + y = x ∪ z ↔ y = z ∧ x.disjoint y := by simpa only [and_comm] using add_eq_union_left_of_le h lemma finset_sum_eq_sup_iff_disjoint {β : Type*} {i : finset β} {f : β → multiset α} : i.sum f = i.sup f ↔ ∀ x y ∈ i, x ≠ y → multiset.disjoint (f x) (f y) := begin induction i using finset.cons_induction_on with z i hz hr, { simp only [finset.not_mem_empty, is_empty.forall_iff, implies_true_iff, finset.sum_empty, finset.sup_empty, bot_eq_zero, eq_self_iff_true], }, { simp_rw [finset.sum_cons hz, finset.sup_cons, finset.mem_cons, multiset.sup_eq_union, forall_eq_or_imp, ne.def, eq_self_iff_true, not_true, is_empty.forall_iff, true_and, imp_and_distrib, forall_and_distrib, ←hr, @eq_comm _ z], have := λ x ∈ i, ne_of_mem_of_not_mem H hz, simp only [this, not_false_iff, true_implies_iff] {contextual := tt}, simp_rw [←disjoint_finset_sum_left, ←disjoint_finset_sum_right, disjoint_comm, ←and_assoc, and_self], exact add_eq_union_left_of_le (finset.sup_le (λ x hx, le_sum_of_mem (mem_map_of_mem f hx))), }, end lemma sup_powerset_len {α : Type*} [decidable_eq α] (x : multiset α) : finset.sup (finset.range (x.card + 1)) (λ k, x.powerset_len k) = x.powerset := begin convert bind_powerset_len x, rw [multiset.bind, multiset.join, ←finset.range_coe, ←finset.sum_eq_multiset_sum], exact eq.symm (finset_sum_eq_sup_iff_disjoint.mpr (λ _ _ _ _ h, disjoint_powerset_len x h)), end @[simp] lemma to_finset_sum_count_eq (s : multiset α) : (∑ a in s.to_finset, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (∑ x in to_finset (a ::ₘ s), count x (a ::ₘ s)) = ∑ x in to_finset (a ::ₘ s), ((if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a ::ₘ s) : begin by_cases a ∈ s.to_finset, { have : ∑ x in s.to_finset, ite (x = a) 1 0 = ∑ x in {a}, ite (x = a) 1 0, { rw [finset.sum_ite_eq', if_pos h, finset.sum_singleton, if_pos rfl], }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : ∑ x in to_finset s, ite (x = a) 1 0 = ∑ x in to_finset s, 0, from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) lemma count_sum' {s : finset β} {a : α} {f : β → multiset α} : count a (∑ x in s, f x) = ∑ x in s, count a (f x) := by { dunfold finset.sum, rw count_sum } @[simp] lemma to_finset_sum_count_nsmul_eq (s : multiset α) : (∑ a in s.to_finset, s.count a • {a}) = s := begin apply ext', intro b, rw count_sum', have h : count b s = count b (count b s • {b}), { rw [count_nsmul, count_singleton_self, mul_one] }, rw h, clear h, apply finset.sum_eq_single b, { intros c h hcb, rw count_nsmul, convert mul_zero (count c s), apply count_eq_zero.mpr, exact finset.not_mem_singleton.mpr (ne.symm hcb) }, { intro hb, rw [count_eq_zero_of_not_mem (mt mem_to_finset.2 hb), count_nsmul, zero_mul]} end theorem exists_smul_of_dvd_count (s : multiset α) {k : ℕ} (h : ∀ (a : α), a ∈ s → k ∣ multiset.count a s) : ∃ (u : multiset α), s = k • u := begin use ∑ a in s.to_finset, (s.count a / k) • {a}, have h₂ : ∑ (x : α) in s.to_finset, k • (count x s / k) • ({x} : multiset α) = ∑ (x : α) in s.to_finset, count x s • {x}, { apply finset.sum_congr rfl, intros x hx, rw [← mul_nsmul, nat.mul_div_cancel' (h x (mem_to_finset.mp hx))] }, rw [← finset.sum_nsmul, h₂, to_finset_sum_count_nsmul_eq] end lemma to_finset_prod_dvd_prod [comm_monoid α] (S : multiset α) : S.to_finset.prod id ∣ S.prod := begin rw finset.prod_eq_multiset_prod, refine multiset.prod_dvd_prod_of_le _, simp [multiset.dedup_le S], end @[to_additive] lemma prod_sum {α : Type*} {ι : Type*} [comm_monoid α] (f : ι → multiset α) (s : finset ι) : (∑ x in s, f x).prod = ∏ x in s, (f x).prod := begin classical, induction s using finset.induction_on with a t hat ih, { rw [finset.sum_empty, finset.prod_empty, multiset.prod_zero] }, { rw [finset.sum_insert hat, finset.prod_insert hat, multiset.prod_add, ih] } end end multiset namespace nat @[simp, norm_cast] lemma cast_list_sum [add_monoid_with_one β] (s : list ℕ) : (↑(s.sum) : β) = (s.map coe).sum := map_list_sum (cast_add_monoid_hom β) _ @[simp, norm_cast] lemma cast_list_prod [semiring β] (s : list ℕ) : (↑(s.prod) : β) = (s.map coe).prod := map_list_prod (cast_ring_hom β) _ @[simp, norm_cast] lemma cast_multiset_sum [add_comm_monoid_with_one β] (s : multiset ℕ) : (↑(s.sum) : β) = (s.map coe).sum := map_multiset_sum (cast_add_monoid_hom β) _ @[simp, norm_cast] lemma cast_multiset_prod [comm_semiring β] (s : multiset ℕ) : (↑(s.prod) : β) = (s.map coe).prod := map_multiset_prod (cast_ring_hom β) _ @[simp, norm_cast] lemma cast_sum [add_comm_monoid_with_one β] (s : finset α) (f : α → ℕ) : ↑(∑ x in s, f x : ℕ) = (∑ x in s, (f x : β)) := map_sum (cast_add_monoid_hom β) _ _ @[simp, norm_cast] lemma cast_prod [comm_semiring β] (f : α → ℕ) (s : finset α) : (↑∏ i in s, f i : β) = ∏ i in s, f i := map_prod (cast_ring_hom β) _ _ end nat namespace int @[simp, norm_cast] lemma cast_list_sum [add_group_with_one β] (s : list ℤ) : (↑(s.sum) : β) = (s.map coe).sum := map_list_sum (cast_add_hom β) _ @[simp, norm_cast] lemma cast_list_prod [ring β] (s : list ℤ) : (↑(s.prod) : β) = (s.map coe).prod := map_list_prod (cast_ring_hom β) _ @[simp, norm_cast] lemma cast_multiset_sum [add_comm_group_with_one β] (s : multiset ℤ) : (↑(s.sum) : β) = (s.map coe).sum := map_multiset_sum (cast_add_hom β) _ @[simp, norm_cast] lemma cast_multiset_prod {R : Type*} [comm_ring R] (s : multiset ℤ) : (↑(s.prod) : R) = (s.map coe).prod := map_multiset_prod (cast_ring_hom R) _ @[simp, norm_cast] lemma cast_sum [add_comm_group_with_one β] (s : finset α) (f : α → ℤ) : ↑(∑ x in s, f x : ℤ) = (∑ x in s, (f x : β)) := map_sum (cast_add_hom β) _ _ @[simp, norm_cast] lemma cast_prod {R : Type*} [comm_ring R] (f : α → ℤ) (s : finset α) : (↑∏ i in s, f i : R) = ∏ i in s, f i := (int.cast_ring_hom R).map_prod _ _ end int @[simp, norm_cast] lemma units.coe_prod {M : Type*} [comm_monoid M] (f : α → Mˣ) (s : finset α) : (↑∏ i in s, f i : M) = ∏ i in s, f i := (units.coe_hom M).map_prod _ _ lemma units.mk0_prod [comm_group_with_zero β] (s : finset α) (f : α → β) (h) : units.mk0 (∏ b in s, f b) h = ∏ b in s.attach, units.mk0 (f b) (λ hh, h (finset.prod_eq_zero b.2 hh)) := by { classical, induction s using finset.induction_on; simp* } lemma nat_abs_sum_le {ι : Type*} (s : finset ι) (f : ι → ℤ) : (∑ i in s, f i).nat_abs ≤ ∑ i in s, (f i).nat_abs := begin classical, apply finset.induction_on s, { simp only [finset.sum_empty, int.nat_abs_zero] }, { intros i s his IH, simp only [his, finset.sum_insert, not_false_iff], exact (int.nat_abs_add_le _ _).trans (add_le_add le_rfl IH) } end /-! ### `additive`, `multiplicative` -/ open additive multiplicative section monoid variables [monoid α] @[simp] lemma of_mul_list_prod (s : list α) : of_mul s.prod = (s.map of_mul).sum := by simpa [of_mul] @[simp] lemma to_mul_list_sum (s : list (additive α)) : to_mul s.sum = (s.map to_mul).prod := by simpa [to_mul, of_mul] end monoid section add_monoid variables [add_monoid α] @[simp] lemma of_add_list_prod (s : list α) : of_add s.sum = (s.map of_add).prod := by simpa [of_add] @[simp] lemma to_add_list_sum (s : list (multiplicative α)) : to_add s.prod = (s.map to_add).sum := by simpa [to_add, of_add] end add_monoid section comm_monoid variables [comm_monoid α] @[simp] lemma of_mul_multiset_prod (s : multiset α) : of_mul s.prod = (s.map of_mul).sum := by simpa [of_mul] @[simp] lemma to_mul_multiset_sum (s : multiset (additive α)) : to_mul s.sum = (s.map to_mul).prod := by simpa [to_mul, of_mul] @[simp] lemma of_mul_prod (s : finset ι) (f : ι → α) : of_mul (∏ i in s, f i) = ∑ i in s, of_mul (f i) := rfl @[simp] lemma to_mul_sum (s : finset ι) (f : ι → additive α) : to_mul (∑ i in s, f i) = ∏ i in s, to_mul (f i) := rfl end comm_monoid section add_comm_monoid variables [add_comm_monoid α] @[simp] lemma of_add_multiset_prod (s : multiset α) : of_add s.sum = (s.map of_add).prod := by simpa [of_add] @[simp] lemma to_add_multiset_sum (s : multiset (multiplicative α)) : to_add s.prod = (s.map to_add).sum := by simpa [to_add, of_add] @[simp] lemma of_add_sum (s : finset ι) (f : ι → α) : of_add (∑ i in s, f i) = ∏ i in s, of_add (f i) := rfl @[simp] lemma to_add_prod (s : finset ι) (f : ι → multiplicative α) : to_add (∏ i in s, f i) = ∑ i in s, to_add (f i) := rfl end add_comm_monoid
6cf5e26771617fc9c8d43a81ead310631c4592ae
0403d75087eccd9fdec22713ec7cff4d40c93610
/lean/love05_inductive_predicates_demo.lean
99eebb6151f8b445549252bd88e8684aac9e835c
[]
no_license
5l1v3r1/logical_verification_2020
9660ae5a83915be2103183490cae279b888be83c
000aa1fe212813b8458bf26c16b8a97597b7417e
refs/heads/master
1,621,861,800,557
1,586,181,042,000
1,586,181,042,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,903
lean
import .love03_forward_proofs_demo import .love04_functional_programming_demo /-! # LoVe Demo 5: Inductive Predicates __Inductive predicates__, or inductively defined propositions, are a convenient way to specify functions of type `⋯ → Prop`. They are reminiscent of formal systems and of the the Horn clauses of Prolog, the logic programming language par excellence. A possible view of Lean: Lean = typed functional programming + logic programming + more logic -/ set_option pp.beta true namespace LoVe /-! ## Introductory Examples ### Even Numbers Mathematicians often define sets as the smallest that meets some criteria. For example: The set `E` of even natural numbers is defined as the smallest set closed under the following rules: (1) `0 ∈ E` and (2) for every `k ∈ ℕ`, if `k ∈ E`, then `k + 2 ∈ E`. In Lean, we can define the corresponding "is even" predicate as follows: -/ inductive even : ℕ → Prop | zero : even 0 | add_two : ∀k : ℕ, even k → even (k + 2) /-! This should look familiar. We have used the same syntax, except with `Type` instead of `Prop`, for inductive types. The above command introduces a new unary predicate `even` as well as two constructors, `even.zero` and `even.add_two`, which can be used to build proof terms. Thanks to the "no junk" guarantee of inductive definitions, `even.zero` and `even.add_two` are the only two ways to construct proofs of `even`. By the Curry–Howard correspondence, `even` can be seen as a data type, the values being the proof terms. -/ lemma even_4 : even 4 := have even_0 : even 0 := even.zero, have even_2 : even 2 := even.add_two _ even_0, show even 4, from even.add_two _ even_2 /-! Why cannot we simply define `even` recursively? Indeed, why not? -/ def even₂ : ℕ → bool | 0 := tt | 1 := ff | (k + 2) := even₂ k /-! There are advantages and disadvantages to both styles. The recursive version requires us to specify a false case (1), and it requires us to worry about termination. On the other hand, because it is computational, it works well with `refl`, `simp`, `#reduce`, and `#eval`. The inductive version is often considered more abstract and elegant. Each rule is stated independently of the others. Yet another way to define `even` is as a nonrecursive definition: -/ def even₃ (k : ℕ) : bool := k % 2 = 0 /-! Mathematicians would probably find this the most satisfactory definition. But the inductive version is a convenient, intuitive example that is typical of many realistic inductive definitions. ### Tennis Games Transition systems consists of transition rules, which together specify a binary predicate connecting a "before" and an "after" state. As a simple specimen of a transition system, we consider the possible transitions, in a game of tennis, starting from 0–0. -/ inductive score : Type | vs : ℕ → ℕ → score | adv_srv : score | adv_rcv : score | game_srv : score | game_rcv : score infixr ` – ` : 10 := score.vs inductive step : score → score → Prop | srv_0_15 : ∀n, step (0–n) (15–n) | srv_15_30 : ∀n, step (15–n) (30–n) | srv_30_40 : ∀n, step (30–n) (40–n) | srv_40_game : ∀n, n < 40 → step (40–n) score.game_srv | srv_40_adv : step (40–40) score.adv_srv | rcv_0_15 : ∀n, step (n–0) (n–15) | rcv_15_30 : ∀n, step (n–15) (n–30) | rcv_30_40 : ∀n, step (n–30) (n–40) | rcv_40_game : ∀n, n < 40 → step (n–40) score.game_rcv | rcv_40_adv : step (40–40) score.adv_rcv infixr ` ⇒ ` := step /-! We can ask—and formally answer—questions such as: Is this transition system confluent? Does it always terminate? Can the score 65–15 be reached from 0–0? ### Reflexive Transitive Closure Our last introductory example is the reflexive transitive closure of a relation `r`, modeled as a binary predicate `star r`. -/ inductive star {α : Type} (r : α → α → Prop) : α → α → Prop | base (a b : α) : r a b → star a b | refl (a : α) : star a a | trans (a b c : α) : star a b → star b c → star a c /-! The first rule embeds `r` into `star r`. The second rule achieves the reflexive closure. The third rule achieves the transitive closure. The definition is truly elegant. If you doubt this, try implementing `star` as a recursive function: -/ def star₂ {α : Type} (r : α → α → Prop) : α → α → Prop := sorry /-! ### A Nonexample Not all inductive definitions admit a least solution. -/ -- fails inductive illegal : Prop | intro : ¬ illegal → illegal /-! ## Logical Symbols The truth values `false` and `true`, the connectives `∧` and `∨`, the `∃`-quantifier, and the equality predicate `=` are all defined as inductive propositions or predicates. In contrast, `∀` (= `Π`) and `→` are built into the logic. Syntactic sugar: `∃x : α, p` := `Exists (λx : α, p)` `x = y` := `eq x y` -/ namespace logical_symbols inductive and (a b : Prop) : Prop | intro : a → b → and inductive or (a b : Prop) : Prop | intro_left : a → or | intro_right : b → or inductive iff (a b : Prop) : Prop | intro : (a → b) → (b → a) → iff inductive Exists {α : Type} (p : α → Prop) : Prop | intro : ∀a : α, p a → Exists inductive true : Prop | intro : true inductive false : Prop inductive eq {α : Type} : α → α → Prop | refl : ∀a : α, eq a a end logical_symbols #print and #print or #print iff #print Exists #print true #print false #print eq /-! ## Rule Induction Just as we can perform induction on a term, we can perform induction on a proof term. This is called __rule induction__, because the induction is on the introduction rules (i.e., the constructors of the proof term). Thanks to the Curry–Howard correspondence, this works as expected. -/ lemma mod_two_eq_zero_of_even (n : ℕ) (h : even n) : n % 2 = 0 := begin induction h, case even.zero { refl }, case even.add_two : k hk ih { simp [ih] } end lemma star_star_iff_star {α : Type} (r : α → α → Prop) (a b : α) : star (star r) a b ↔ star r a b := begin apply iff.intro, { intro h, induction h, case star.base : a b hab { exact hab }, case star.refl : a { apply star.refl }, case star.trans : a b c hab hbc ihab ihbc { apply star.trans a b, { exact ihab }, { exact ihbc } } }, { intro h, apply star.base, exact h } end @[simp] lemma star_star_eq_star {α : Type} (r : α → α → Prop) : star (star r) = star r := begin apply funext, intro a, apply funext, intro b, apply propext, apply star_star_iff_star end #check funext #check propext /-! ## Rule Induction Pitfalls Inductive predicates often have arguments that evolve through the induction. Some care is necessary. -/ lemma p_of_even (p : ℕ → Prop) (n : ℕ) : even n → p n := begin intro h, induction h, case even.zero { sorry }, -- looks reasonable case even.add_two { sorry } -- looks reasonable end lemma not_even_2_mul_add_1_sorry (n : ℕ) : ¬ even (2 * n + 1) := begin intro h, induction h, case even.zero { sorry }, -- unprovable case even.add_two : k hk ih { exact ih } end lemma not_even_2_mul_add_1_sorry₂ (n : ℕ) : ¬ even (2 * n + 1) := begin generalize hx : 2 * n + 1 = x, intro h, induction h, case even.zero { cases hx }, case even.add_two : k hk ih { apply ih, rewrite hx, sorry } -- unprovable end lemma not_even_2_mul_add_1 (n : ℕ) : ¬ even (2 * n + 1) := begin generalize hx : 2 * n + 1 = x, intro h, induction h generalizing n, case even.zero { cases hx }, case even.add_two : k hk ih { apply ih (n - 1), cases n, case nat.zero { linarith }, case nat.succ : m { simp [nat.succ_eq_add_one] at *, linarith } } end /-! `linarith` proves goals involving linear arithmetic equalities or inequalities. "Linear" means it works only with `+` and `-`, not `*` and `/` (but multiplication by a constant is supported). -/ lemma linarith_example (i : ℤ) (hi : i > 5) : 2 * i + 3 > 11 := by linarith /-! ## Elimination Given an inductive predicate `p`, its introduction rules typically have the form `∀…, ⋯ → p …` and can be used to prove goals of the form `⊢ p …`. Elimination works the other way around: It extracts information from a lemma or hypothesis of the form `p …`. Elimination takes various forms: pattern matching, the `cases` and `induction` tactics, and custom elimination rules (e.g., `and.elim_left`). * `cases` works roughly like `induction` but without induction hypothesis. * `match` is available as well, but it corresponds to dependently typed pattern matching (cf. `vector` in lecture 4). Now we can finally analyze how `cases h`, where `h : l = r`, and how `cases classical.em h` work. -/ #print eq lemma cases_eq_example {α : Type} (l r : α) (h : l = r) (p : α → α → Prop) : p l r := begin cases h, sorry end #check classical.em #print or lemma cases_classical_em_example {α : Type} (a : α) (p q : α → Prop) : q a := begin have h : p a ∨ ¬ p a := classical.em (p a), cases h, case or.inl { sorry }, case or.inr { sorry } end /-! Often it is convenient to rewrite concrete terms of the form `p (c …)`, where `c` is typically a constructor. We can state and prove an __inversion rule__ to support such eliminative reasoning. Typical inversion rule: `∀x y, p (c x y) → (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)` It can be useful to combine introduction and elimination into a single lemma, which can be used for rewriting both the hypotheses and conclusions of goals: `∀x y, p (c x y) ↔ (∃…, ⋯ ∧ ⋯) ∨ ⋯ ∨ (∃…, ⋯ ∧ ⋯)` -/ lemma even_iff (n : ℕ) : even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) := begin apply iff.intro, { intro hn, cases hn, case even.zero { simp }, case even.add_two : k hk { apply or.intro_right, apply exists.intro k, simp [hk] } }, { intro hor, cases hor, case or.inl : heq { simp [heq, even.zero] }, case or.inr : hex { cases hex with k hand, cases hand with heq hk, simp [heq, even.add_two _ hk] } } end lemma even_iff₂ (n : ℕ) : even n ↔ n = 0 ∨ (∃m : ℕ, n = m + 2 ∧ even m) := iff.intro (assume hn : even n, match n, hn with | _, even.zero := show 0 = 0 ∨ _, from by simp | _, even.add_two k hk := show _ ∨ (∃m, k + 2 = m + 2 ∧ even m), from or.intro_right _ (exists.intro k (by simp [*])) end) (assume hor : n = 0 ∨ (∃m, n = m + 2 ∧ even m), match hor with | or.intro_left _ heq := show even n, from by simp [heq, even.zero] | or.intro_right _ hex := match hex with | Exists.intro m hand := match hand with | and.intro heq hm := show even n, from by simp [heq, even.add_two _ hm] end end end) /-! ## Further Examples ### Sorted Lists -/ inductive sorted : list ℕ → Prop | nil : sorted [] | single {x : ℕ} : sorted [x] | two_or_more {x y : ℕ} {zs : list ℕ} (hle : x ≤ y) (hsorted : sorted (y :: zs)) : sorted (x :: y :: zs) lemma sorted_nil : sorted [] := sorted.nil lemma sorted_2 : sorted [2] := sorted.single lemma sorted_3_5 : sorted [3, 5] := begin apply sorted.two_or_more, { exact dec_trivial }, { exact sorted.single } end lemma sorted_3_5₂ : sorted [3, 5] := sorted.two_or_more dec_trivial sorted.single lemma sorted_7_9_9_11 : sorted [7, 9, 9, 11] := sorted.two_or_more dec_trivial (sorted.two_or_more dec_trivial (sorted.two_or_more dec_trivial sorted.single)) lemma not_sorted_17_13 : ¬ sorted [17, 13] := assume h : sorted [17, 13], have 17 ≤ 13 := match h with | sorted.two_or_more hle _ := hle end, have ¬ 17 ≤ 13 := dec_trivial, show false, from by cc /-! ### Palindromes -/ inductive palindrome {α : Type} : list α → Prop | nil : palindrome [] | single (x : α) : palindrome [x] | sandwich (x : α) (xs : list α) (hxs : palindrome xs) : palindrome ([x] ++ xs ++ [x]) -- fails def palindrome₂ {α : Type} : list α → Prop | [] := true | [_] := true | ([x] ++ xs ++ [x]) := palindrome₂ xs | _ := false lemma palindrome_aa {α : Type} (a : α) : palindrome [a, a] := palindrome.sandwich a _ palindrome.nil lemma palindrome_aba {α : Type} (a b : α) : palindrome [a, b, a] := palindrome.sandwich a _ (palindrome.single b) lemma reverse_palindrome {α : Type} (xs : list α) (hxs : palindrome xs) : palindrome (reverse xs) := begin induction hxs, case palindrome.nil { exact palindrome.nil }, case palindrome.single : x { exact palindrome.single x }, case palindrome.sandwich : x xs hxs ih { simp [reverse, reverse_append], exact palindrome.sandwich _ _ ih } end /-! ### Full Binary Trees -/ #check btree inductive is_full {α : Type} : btree α → Prop | empty : is_full btree.empty | node (a : α) (l r : btree α) (hl : is_full l) (hr : is_full r) (hiff : l = btree.empty ↔ r = btree.empty) : is_full (btree.node a l r) lemma is_full_singleton {α : Type} (a : α) : is_full (btree.node a btree.empty btree.empty) := begin apply is_full.node, { exact is_full.empty }, { exact is_full.empty }, { refl } end lemma is_full_mirror {α : Type} (t : btree α) (ht : is_full t) : is_full (mirror t) := begin induction ht, case is_full.empty { exact is_full.empty }, case is_full.node : a l r hl hr hiff ih_l ih_r { rewrite mirror, apply is_full.node, { exact ih_r }, { exact ih_l }, { simp [mirror_eq_empty_iff, *] } } end lemma is_full_mirror₂ {α : Type} : ∀t : btree α, is_full t → is_full (mirror t) | btree.empty := begin intro ht, exact ht end | (btree.node a l r) := begin intro ht, cases ht with _ _ _ hl hr hiff, rewrite mirror, apply is_full.node, { exact is_full_mirror₂ _ hr }, { apply is_full_mirror₂ _ hl }, { simp [mirror_eq_empty_iff, *] } end /-! ### First-Order Terms -/ inductive term (α β : Type) : Type | var {} : β → term | fn : α → list term → term inductive well_formed {α β : Type} (arity : α → ℕ) : term α β → Prop | var (x : β) : well_formed (term.var x) | fn (f : α) (ts : list (term α β)) (hargs : ∀t ∈ ts, well_formed t) (hlen : list.length ts = arity f) : well_formed (term.fn f ts) inductive variable_free {α β : Type} : term α β → Prop | fn (f : α) (ts : list (term α β)) (hargs : ∀t ∈ ts, variable_free t) : variable_free (term.fn f ts) end LoVe
d413b821b7d1340a2c2ec9b24c6fa9a84aaaeca0
9a0b1b3a653ea926b03d1495fef64da1d14b3174
/tidy/lib/tactic.lean
4ca5798aa2a60750d40bd189a119574f29f97e48
[ "Apache-2.0" ]
permissive
khoek/mathlib-tidy
8623b27b4e04e7d598164e7eaf248610d58f768b
866afa6ab597c47f1b72e8fe2b82b97fff5b980f
refs/heads/master
1,585,598,975,772
1,538,659,544,000
1,538,659,544,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,772
lean
import .pretty_print universe u namespace tactic meta def is_eq_after_binders : expr → bool | (expr.pi n bi d b) := is_eq_after_binders b | `(%%a = %%b) := tt | _ := ff meta def is_iff_after_binders : expr → bool | (expr.pi n bi d b) := is_iff_after_binders b | `(%%a ↔ %%b) := tt | _ := ff meta def is_eq_or_iff_after_binders : expr → bool | (expr.pi n bi d b) := is_eq_or_iff_after_binders b | `(%%a = %%b) := tt | `(%%a ↔ %%b) := tt | _ := ff meta def get_binder_types : expr → list expr | (expr.pi n bi d b) := d :: get_binder_types b | _ := [] -- TODO is there any way to replace `type : expr` with an honest `α : Type`? -- Maybe at least a `type : name`? In this case probably just need to read about -- name resolution. meta def assert_type (type : expr) (n : name) : tactic unit := do t ← infer_type (expr.const n []), guard $ t = type meta def type_cast (α : Type u) [reflected α] (n : name) : tactic α := eval_expr α (expr.const n []) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end -- FIXME doesn't `unify` do exactly this?? meta def attempt_refl (lhs rhs : expr) : tactic expr := lock_tactic_state $ do gs ← get_goals, m ← to_expr ``(%%lhs = %%rhs) >>= mk_meta_var, set_goals [m], refl ← mk_const `eq.refl, tactic.apply_core refl {new_goals := new_goals.non_dep_only}, instantiate_mvars m -- TODO Am I even good? Do I work? Do I slow us down too much? meta def simp_expr (t : expr) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) (cfg : simp_config := {}) (discharger : tactic unit := failed) : tactic (expr × expr) := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, simplify s to_unfold t cfg `eq discharger meta def dsimp_expr (t : expr) (no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) (cfg : dsimp_config := {}) (discharger : tactic unit := failed) : tactic expr := do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs, s.dsimplify to_unfold t cfg meta def mk_app_aux : expr → expr → expr → tactic expr | f (expr.pi n binder_info.default d b) arg := do infer_type arg >>= unify d, return $ f arg | f (expr.pi n binder_info.inst_implicit d b) arg := do infer_type arg >>= unify d, return $ f arg -- TODO use typeclass inference? | f (expr.pi n _ d b) arg := do v ← mk_meta_var d, t ← whnf (b.instantiate_var v), mk_app_aux (f v) t arg | e _ _ := failed -- TODO check if just the first will suffice meta def mk_app' (f arg : expr) : tactic expr := lock_tactic_state $ do r ← to_expr ``(%%f %%arg) /- FIXME too expensive -/ <|> (do infer_type f >>= whnf >>= λ t, mk_app_aux f t arg), instantiate_mvars r /-- Given an expression `e` and list of expressions `F`, builds all applications of `e` to elements of `F`. `mk_apps` returns a list of all pairs ``(`(%%e %%f), f)`` which typecheck, for `f` in the list `F`. -/ meta def mk_apps (e : expr) (F : list expr) : tactic (list (expr × expr)) := do l ← F.mmap $ λ f, (do r ← try_core (mk_app' e f >>= λ m, return (m, f)), return r.to_list), return l.join meta def if_not_done {α : Type} (t₁ : tactic α) (t₂ : tactic α) : tactic α := do ret ← t₁, (done >> return ret <|> t₂) end tactic
3dc1fdf5beb9a2dbb0da9779d1839a746f301220
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/topology/algebra/group_completion.lean
9f475ed14e1ba9b2f5242d5fe4e8b98545a24204
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
5,550
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl Completion of topological groups: -/ import topology.uniform_space.completion topology.algebra.uniform_group noncomputable theory section group open uniform_space Cauchy filter set variables {α : Type*} [uniform_space α] instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩ instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩ instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩ lemma coe_zero [has_zero α] : ((0 : α) : completion α) = 0 := rfl end group namespace uniform_space.completion section uniform_add_group open uniform_space uniform_space.completion variables {α : Type*} [uniform_space α] [add_group α] [uniform_add_group α] lemma coe_neg (a : α) : ((- a : α) : completion α) = - a := (map_coe uniform_continuous_neg' a).symm lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b := (map₂_coe_coe a b (+) uniform_continuous_add').symm instance : add_group (completion α) := { zero_add := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id) (assume a, show 0 + (a : completion α) = a, by rw [← coe_zero, ← coe_add, zero_add]), add_zero := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id) (assume a, show (a : completion α) + 0 = a, by rw [← coe_zero, ← coe_add, add_zero]), add_left_neg := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const) (assume a, show - (a : completion α) + a = 0, by rw [← coe_neg, ← coe_add, add_left_neg, coe_zero]), add_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_map₂ (continuous_map₂ continuous_fst (continuous_snd.comp continuous_fst)) (continuous_snd.comp continuous_snd)) (continuous_map₂ continuous_fst (continuous_map₂ (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd)))) (assume a b c, show (a : completion α) + b + c = a + (b + c), by repeat { rw [← coe_add] }; rw [add_assoc]), .. completion.has_zero, .. completion.has_neg, ..completion.has_add } instance : uniform_add_group (completion α) := ⟨ (uniform_continuous.prod_mk uniform_continuous_fst (uniform_continuous_snd.comp uniform_continuous_map)).comp (uniform_continuous_map₂' (+)) ⟩ instance is_add_group_hom_coe : is_add_group_hom (coe : α → completion α) := ⟨ coe_add ⟩ variables {β : Type*} [uniform_space β] [add_group β] [uniform_add_group β] lemma is_add_group_hom_extension [complete_space β] [separated β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.extension f) := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, ⟨assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_add'.comp continuous_extension) (continuous_add (continuous_fst.comp continuous_extension) (continuous_snd.comp continuous_extension))) (assume a b, by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf, is_add_group_hom.add f])⟩ lemma is_add_group_hom_map [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (hf : continuous f) : is_add_group_hom (completion.map f) := is_add_group_hom_extension (hf.comp (continuous_coe _)) section instance_max_depth -- TODO: continuous_add requires some long proofs through -- uniform_add_group / topological_add_group w.r.t prod / completion etc set_option class.instance_max_depth 52 lemma is_add_group_hom_prod [add_group β] [uniform_add_group β] : is_add_group_hom (@completion.prod α β _ _) := ⟨assume ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, begin refine completion.induction_on₄ a₁ a₂ b₁ b₂ (is_closed_eq _ _) _, { refine continuous.comp _ uniform_continuous_prod.continuous, refine continuous_add _ _, exact continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd), exact continuous.prod_mk (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd) }, { refine continuous_add _ _, refine continuous.comp _ uniform_continuous_prod.continuous, exact continuous.prod_mk (continuous_fst.comp continuous_fst) (continuous_fst.comp continuous_snd), refine continuous.comp _ uniform_continuous_prod.continuous, exact continuous.prod_mk (continuous_snd.comp continuous_fst) (continuous_snd.comp continuous_snd) }, { assume a b c d, show completion.prod (↑a + ↑c, ↑b + ↑d) = completion.prod (↑a, ↑b) + completion.prod (↑c, ↑d), rw [← coe_add, ← coe_add, prod_coe_coe, prod_coe_coe, prod_coe_coe, ← coe_add], refl } end⟩ end instance_max_depth instance {α : Type*} [uniform_space α] [add_comm_group α] [uniform_add_group α] : add_comm_group (completion α) := { add_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_snd continuous_fst)) (assume x y, by { change ↑x + ↑y = ↑y + ↑x, rw [← coe_add, ← coe_add, add_comm]}), .. completion.add_group } end uniform_add_group end uniform_space.completion
0cb71f0758c29f40ca081251d58094c55a2b02d0
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/smt/interactive.lean
dede8a147bb064fbe1b2ba690a61ac794868b0fe
[ "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
10,125
lean
/- Copyright (c) 2017 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.smt.smt_tactic init.meta.interactive_base import init.meta.smt.rsimp namespace smt_tactic meta def save_info (p : pos) : smt_tactic unit := do (ss, ts) ← smt_tactic.read, tactic.save_info_thunk p (λ _, smt_state.to_format ss ts) meta def skip : smt_tactic unit := return () meta def solve_goals : smt_tactic unit := iterate close meta def step {α : Type} (tac : smt_tactic α) : smt_tactic unit := tac >> solve_goals meta def istep {α : Type} (line0 col0 line col ast : nat) (tac : smt_tactic α) : smt_tactic unit := ⟨λ ss ts, (@scope_trace _ line col (λ _, tactic.with_ast ast ((tac >> solve_goals).run ss) ts)).clamp_pos line0 line col⟩ meta def execute (tac : smt_tactic unit) : tactic unit := using_smt tac meta def execute_with (cfg : smt_config) (tac : smt_tactic unit) : tactic unit := using_smt tac cfg meta instance : interactive.executor smt_tactic := { config_type := smt_config, inhabited := ⟨{}⟩, execute_with := λ cfg tac, using_smt tac cfg, } namespace interactive open lean.parser open _root_.interactive open interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many meta def itactic : Type := smt_tactic unit meta def intros : parse ident* → smt_tactic unit | [] := smt_tactic.intros | hs := smt_tactic.intro_lst hs /-- Try to close main goal by using equalities implied by the congruence closure module. -/ meta def close : smt_tactic unit := smt_tactic.close /-- Produce new facts using heuristic lemma instantiation based on E-matching. This tactic tries to match patterns from lemmas in the main goal with terms in the main goal. The set of lemmas is populated with theorems tagged with the attribute specified at smt_config.em_attr, and lemmas added using tactics such as `smt_tactic.add_lemmas`. The current set of lemmas can be retrieved using the tactic `smt_tactic.get_lemmas`. -/ meta def ematch : smt_tactic unit := smt_tactic.ematch meta def apply (q : parse texpr) : smt_tactic unit := tactic.interactive.apply q meta def fapply (q : parse texpr) : smt_tactic unit := tactic.interactive.fapply q meta def apply_instance : smt_tactic unit := tactic.apply_instance meta def change (q : parse texpr) : smt_tactic unit := tactic.interactive.change q none (loc.ns [none]) meta def exact (q : parse texpr) : smt_tactic unit := tactic.interactive.exact q meta def «from» := exact meta def «assume» := tactic.interactive.assume meta def «have» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : smt_tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← tactic.to_expr e, v ← tactic.to_expr ``(%%p : %%t), smt_tactic.assertv h t v | none, some p := do p ← tactic.to_expr p, smt_tactic.note h none p | some e, none := tactic.to_expr e >>= smt_tactic.assert h | none, none := do u ← tactic.mk_meta_univ, e ← tactic.mk_meta_var (expr.sort u), smt_tactic.assert h e end >> return () meta def «let» (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : smt_tactic unit := let h := h.get_or_else `this in match q₁, q₂ with | some e, some p := do t ← tactic.to_expr e, v ← tactic.to_expr ``(%%p : %%t), smt_tactic.definev h t v | none, some p := do p ← tactic.to_expr p, smt_tactic.pose h none p | some e, none := tactic.to_expr e >>= smt_tactic.define h | none, none := do u ← tactic.mk_meta_univ, e ← tactic.mk_meta_var (expr.sort u), smt_tactic.define h e end >> return () meta def add_fact (q : parse texpr) : smt_tactic unit := do h ← tactic.get_unused_name `h none, p ← tactic.to_expr_strict q, smt_tactic.note h none p meta def trace_state : smt_tactic unit := smt_tactic.trace_state meta def trace {α : Type} [has_to_tactic_format α] (a : α) : smt_tactic unit := tactic.trace a meta def destruct (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.destruct p meta def by_cases (q : parse texpr) : smt_tactic unit := do p ← tactic.to_expr_strict q, smt_tactic.by_cases p meta def by_contradiction : smt_tactic unit := smt_tactic.by_contradiction meta def by_contra : smt_tactic unit := smt_tactic.by_contradiction open tactic (resolve_name transparency to_expr) private meta def report_invalid_em_lemma {α : Type} (n : name) : smt_tactic α := fail format!"invalid ematch lemma '{n}'" private meta def add_lemma_name (md : transparency) (lhs_lemma : bool) (n : name) (ref : pexpr) : smt_tactic unit := do p ← resolve_name n, match p with | expr.const n _ := (add_ematch_lemma_from_decl_core md lhs_lemma n >> tactic.save_const_type_info n ref) <|> report_invalid_em_lemma n | _ := (do e ← to_expr p, add_ematch_lemma_core md lhs_lemma e >> try (tactic.save_type_info e ref)) <|> report_invalid_em_lemma n end private meta def add_lemma_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) : smt_tactic unit := match p with | (expr.const c []) := add_lemma_name md lhs_lemma c p | (expr.local_const c _ _ _) := add_lemma_name md lhs_lemma c p | _ := do new_e ← to_expr p, add_ematch_lemma_core md lhs_lemma new_e end private meta def add_lemma_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr → smt_tactic unit | [] := return () | (p::ps) := add_lemma_pexpr md lhs_lemma p >> add_lemma_pexprs ps meta def add_lemma (l : parse pexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible ff l meta def add_lhs_lemma (l : parse pexpr_list_or_texpr) : smt_tactic unit := add_lemma_pexprs reducible tt l private meta def add_eqn_lemmas_for_core (md : transparency) : list name → smt_tactic unit | [] := return () | (c::cs) := do p ← resolve_name c, match p with | expr.const n _ := add_ematch_eqn_lemmas_for_core md n >> add_eqn_lemmas_for_core cs | _ := fail format!"'{c}' is not a constant" end meta def add_eqn_lemmas_for (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for_core reducible ids meta def add_eqn_lemmas (ids : parse ident*) : smt_tactic unit := add_eqn_lemmas_for ids private meta def add_hinst_lemma_from_name (md : transparency) (lhs_lemma : bool) (n : name) (hs : hinst_lemmas) (ref : pexpr) : smt_tactic hinst_lemmas := do p ← resolve_name n, match p with | expr.const n _ := (do h ← hinst_lemma.mk_from_decl_core md n lhs_lemma, tactic.save_const_type_info n ref, return $ hs.add h) <|> (do hs₁ ← mk_ematch_eqn_lemmas_for_core md n, tactic.save_const_type_info n ref, return $ hs.merge hs₁) <|> report_invalid_em_lemma n | _ := (do e ← to_expr p, h ← hinst_lemma.mk_core md e lhs_lemma, try (tactic.save_type_info e ref), return $ hs.add h) <|> report_invalid_em_lemma n end private meta def add_hinst_lemma_from_pexpr (md : transparency) (lhs_lemma : bool) (p : pexpr) (hs : hinst_lemmas) : smt_tactic hinst_lemmas := match p with | (expr.const c []) := add_hinst_lemma_from_name md lhs_lemma c hs p | (expr.local_const c _ _ _) := add_hinst_lemma_from_name md lhs_lemma c hs p | _ := do new_e ← to_expr p, h ← hinst_lemma.mk_core md new_e lhs_lemma, return $ hs.add h end private meta def add_hinst_lemmas_from_pexprs (md : transparency) (lhs_lemma : bool) : list pexpr → hinst_lemmas → smt_tactic hinst_lemmas | [] hs := return hs | (p::ps) hs := do hs₁ ← add_hinst_lemma_from_pexpr md lhs_lemma p hs, add_hinst_lemmas_from_pexprs ps hs₁ meta def ematch_using (l : parse pexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.ematch_using hs /-- Try the given tactic, and do nothing if it fails. -/ meta def try (t : itactic) : smt_tactic unit := smt_tactic.try t /-- Keep applying the given tactic until it fails. -/ meta def iterate (t : itactic) : smt_tactic unit := smt_tactic.iterate t /-- Apply the given tactic to all remaining goals. -/ meta def all_goals (t : itactic) : smt_tactic unit := smt_tactic.all_goals t meta def induction (p : parse tactic.interactive.cases_arg_p) (rec_name : parse using_ident) (ids : parse with_ident_list) (revert : parse $ (tk "generalizing" *> ident*)?) : smt_tactic unit := slift (tactic.interactive.induction p rec_name ids revert) open tactic /-- Simplify the target type of the main goal. -/ meta def simp (use_iota_eqn : parse $ (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (cfg : simp_config_ext := {}) : smt_tactic unit := tactic.interactive.simp use_iota_eqn none no_dflt hs attr_names (loc.ns [none]) cfg meta def dsimp (no_dflt : parse only_flag) (es : parse simp_arg_list) (attr_names : parse with_ident_list) : smt_tactic unit := tactic.interactive.dsimp no_dflt es attr_names (loc.ns [none]) meta def rsimp : smt_tactic unit := do ccs ← to_cc_state, _root_.rsimp.rsimplify_goal ccs meta def add_simp_lemmas : smt_tactic unit := get_hinst_lemmas_for_attr `rsimp_attr >>= add_lemmas /-- Keep applying heuristic instantiation until the current goal is solved, or it fails. -/ meta def eblast : smt_tactic unit := smt_tactic.eblast /-- Keep applying heuristic instantiation using the given lemmas until the current goal is solved, or it fails. -/ meta def eblast_using (l : parse pexpr_list_or_texpr) : smt_tactic unit := do hs ← add_hinst_lemmas_from_pexprs reducible ff l hinst_lemmas.mk, smt_tactic.iterate (smt_tactic.ematch_using hs >> smt_tactic.try smt_tactic.close) meta def guard_expr_eq (t : expr) (p : parse $ tk ":=" *> texpr) : smt_tactic unit := do e ← to_expr p, guard (expr.alpha_eqv t e) meta def guard_target (p : parse texpr) : smt_tactic unit := do t ← target, guard_expr_eq t p end interactive end smt_tactic
c9075b468f95c20f1e0f7e2dbb9a146c77b95071
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/holor_auto.lean
59d23dababd55ccfb3c690c27a905e1e44cbcc0e
[]
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
14,008
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.module.pi import Mathlib.algebra.big_operators.basic import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : List ℕ) := Subtype fun (is : List ℕ) => list.forall₂ Less is ds namespace holor_index def take {ds₂ : List ℕ} {ds₁ : List ℕ} : holor_index (ds₁ ++ ds₂) → holor_index ds₁ := sorry def drop {ds₂ : List ℕ} {ds₁ : List ℕ} : holor_index (ds₁ ++ ds₂) → holor_index ds₂ := sorry theorem cast_type {ds₁ : List ℕ} {ds₂ : List ℕ} (is : List ℕ) (eq : ds₁ = ds₂) (h : list.forall₂ Less is ds₁) : subtype.val (cast (congr_arg holor_index eq) { val := is, property := h }) = is := eq.drec (Eq.refl (subtype.val (cast (congr_arg holor_index (Eq.refl ds₁)) { val := is, property := h }))) eq def assoc_right {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast sorry def assoc_left {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast sorry theorem take_take {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : take (assoc_right t) = take (take t) := sorry theorem drop_take {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : take (drop (assoc_right t)) = drop (take t) := sorry theorem drop_drop {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} (t : holor_index (ds₁ ++ ds₂ ++ ds₃)) : drop (drop (assoc_right t)) = drop t := sorry end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds : List ℕ) := holor_index ds → α namespace holor protected instance inhabited {α : Type} {ds : List ℕ} [Inhabited α] : Inhabited (holor α ds) := { default := fun (t : holor_index ds) => Inhabited.default } protected instance has_zero {α : Type} {ds : List ℕ} [HasZero α] : HasZero (holor α ds) := { zero := fun (t : holor_index ds) => 0 } protected instance has_add {α : Type} {ds : List ℕ} [Add α] : Add (holor α ds) := { add := fun (x y : holor α ds) (t : holor_index ds) => x t + y t } protected instance has_neg {α : Type} {ds : List ℕ} [Neg α] : Neg (holor α ds) := { neg := fun (a : holor α ds) (t : holor_index ds) => -a t } protected instance add_semigroup {α : Type} {ds : List ℕ} [add_semigroup α] : add_semigroup (holor α ds) := add_semigroup.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_semigroup.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry protected instance add_comm_semigroup {α : Type} {ds : List ℕ} [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := add_comm_semigroup.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_semigroup.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry sorry protected instance add_monoid {α : Type} {ds : List ℕ} [add_monoid α] : add_monoid (holor α ds) := add_monoid.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_monoid.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_monoid.zero) sorry sorry protected instance add_comm_monoid {α : Type} {ds : List ℕ} [add_comm_monoid α] : add_comm_monoid (holor α ds) := add_comm_monoid.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_monoid.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_comm_monoid.zero) sorry sorry sorry protected instance add_group {α : Type} {ds : List ℕ} [add_group α] : add_group (holor α ds) := add_group.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_group.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_group.zero) sorry sorry (fun (ᾰ : holor α ds) => id fun (ᾰ_1 : holor_index ds) => add_group.neg (ᾰ ᾰ_1)) (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_group.sub (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry protected instance add_comm_group {α : Type} {ds : List ℕ} [add_comm_group α] : add_comm_group (holor α ds) := add_comm_group.mk (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_group.add (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry (id fun (ᾰ : holor_index ds) => add_comm_group.zero) sorry sorry (fun (ᾰ : holor α ds) => id fun (ᾰ_1 : holor_index ds) => add_comm_group.neg (ᾰ ᾰ_1)) (fun (ᾰ ᾰ_1 : holor α ds) => id fun (ᾰ_2 : holor_index ds) => add_comm_group.sub (ᾰ ᾰ_2) (ᾰ_1 ᾰ_2)) sorry sorry /- scalar product -/ protected instance has_scalar {α : Type} {ds : List ℕ} [Mul α] : has_scalar α (holor α ds) := has_scalar.mk fun (a : α) (x : holor α ds) (t : holor_index ds) => a * x t protected instance semimodule {α : Type} {ds : List ℕ} [semiring α] : semimodule α (holor α ds) := pi.semimodule (holor_index ds) (fun (ᾰ : holor_index ds) => α) α /-- The tensor product of two holors. -/ def mul {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [s : Mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := fun (t : holor_index (ds₁ ++ ds₂)) => x (holor_index.take t) * y (holor_index.drop t) theorem cast_type {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = fun (t : holor_index ds₂) => a (cast (congr_arg holor_index (Eq.symm eq)) t) := eq.drec (Eq.refl (cast (congr_arg (holor α) (Eq.refl ds₁)) a)) eq def assoc_right {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast sorry def assoc_left {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast sorry theorem mul_assoc0 {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z = assoc_left (mul x (mul y z)) := sorry theorem mul_assoc {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} {ds₃ : List ℕ} [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == mul x (mul y z) := sorry theorem mul_left_distrib {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : mul x (y + z) = mul x y + mul x z := funext fun (t : holor_index (ds₁ ++ ds₂)) => left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t)) theorem mul_right_distrib {α : Type} {ds₁ : List ℕ} {ds₂ : List ℕ} [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : mul (x + y) z = mul x z + mul y z := funext fun (t : holor_index (ds₁ ++ ds₂)) => right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t)) @[simp] theorem zero_mul {ds₁ : List ℕ} {ds₂ : List ℕ} {α : Type} [ring α] (x : holor α ds₂) : mul 0 x = 0 := funext fun (t : holor_index (ds₁ ++ ds₂)) => zero_mul (x (holor_index.drop t)) @[simp] theorem mul_zero {ds₁ : List ℕ} {ds₂ : List ℕ} {α : Type} [ring α] (x : holor α ds₁) : mul x 0 = 0 := funext fun (t : holor_index (ds₁ ++ ds₂)) => mul_zero (x (holor_index.take t)) theorem mul_scalar_mul {α : Type} {ds : List ℕ} [monoid α] (x : holor α []) (y : holor α ds) : mul x y = x { val := [], property := list.forall₂.nil } • y := sorry /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice {α : Type} {d : ℕ} {ds : List ℕ} (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := fun (is : holor_index ds) => x { val := i :: subtype.val is, property := sorry } /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec {α : Type} [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := fun (ti : holor_index [d]) => ite (subtype.val ti = [j]) 1 0 theorem holor_index_cons_decomp {d : ℕ} {ds : List ℕ} (p : holor_index (d :: ds) → Prop) (t : holor_index (d :: ds)) : (∀ (i : ℕ) (is : List ℕ) (h : subtype.val t = i :: is), p { val := i :: is, property := eq.mpr (id (Eq._oldrec (Eq.refl (list.forall₂ Less (i :: is) (d :: ds))) (Eq.symm h))) (subtype.property t) }) → p t := sorry /-- Two holors are equal if all their slices are equal. -/ theorem slice_eq {α : Type} {d : ℕ} {ds : List ℕ} (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := sorry theorem slice_unit_vec_mul {α : Type} {d : ℕ} {ds : List ℕ} [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (mul (unit_vec d j) x) i hid = ite (i = j) x 0 := sorry theorem slice_add {α : Type} {d : ℕ} {ds : List ℕ} [Add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := sorry theorem slice_zero {α : Type} {d : ℕ} {ds : List ℕ} [HasZero α] (i : ℕ) (hid : i < d) : slice 0 i hid = 0 := rfl theorem slice_sum {α : Type} {d : ℕ} {ds : List ℕ} [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : (finset.sum s fun (x : β) => slice (f x) i hid) = slice (finset.sum s fun (x : β) => f x) i hid := sorry /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] theorem sum_unit_vec_mul_slice {α : Type} {d : ℕ} {ds : List ℕ} [ring α] (x : holor α (d :: ds)) : (finset.sum (finset.attach (finset.range d)) fun (i : Subtype fun (x : ℕ) => x ∈ finset.range d) => mul (unit_vec d ↑i) (slice x (↑i) (nat.succ_le_of_lt (iff.mp finset.mem_range (subtype.prop i))))) = x := sorry /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 {α : Type} [Mul α] : {ds : List ℕ} → holor α ds → Prop where | nil : ∀ (x : holor α []), cprank_max1 x | cons : ∀ {d : ℕ} {ds : List ℕ} (x : holor α [d]) (y : holor α ds), cprank_max1 y → cprank_max1 (mul x y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max {α : Type} [Mul α] [add_monoid α] : ℕ → {ds : List ℕ} → holor α ds → Prop where | zero : ∀ {ds : List ℕ}, cprank_max 0 0 | succ : ∀ (n : ℕ) {ds : List ℕ} (x y : holor α ds), cprank_max1 x → cprank_max n y → cprank_max (n + 1) (x + y) theorem cprank_max_nil {α : Type} [monoid α] [add_monoid α] (x : holor α []) : cprank_max 1 x := sorry theorem cprank_max_1 {α : Type} {ds : List ℕ} [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := sorry theorem cprank_max_add {α : Type} {ds : List ℕ} [monoid α] [add_monoid α] {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds} : cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) := sorry theorem cprank_max_mul {α : Type} {d : ℕ} {ds : List ℕ} [ring α] (n : ℕ) (x : holor α [d]) (y : holor α ds) : cprank_max n y → cprank_max n (mul x y) := sorry theorem cprank_max_sum {α : Type} {ds : List ℕ} [ring α] {β : Type u_1} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ (x : β), x ∈ s → cprank_max n (f x)) → cprank_max (finset.card s * n) (finset.sum s fun (x : β) => f x) := sorry theorem cprank_max_upper_bound {α : Type} [ring α] {ds : List ℕ} (x : holor α ds) : cprank_max (list.prod ds) x := sorry /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ def cprank {α : Type} {ds : List ℕ} [ring α] (x : holor α ds) : ℕ := nat.find sorry theorem cprank_upper_bound {α : Type} [ring α] {ds : List ℕ} (x : holor α ds) : cprank x ≤ list.prod ds := nat.find_min' (Exists.intro (list.prod ds) ((fun (this : cprank_max (list.prod ds) x) => this) (cprank_max_upper_bound x))) (cprank_max_upper_bound x) end Mathlib
9597ada23435ebbd05de9df0ec70247e32aa2ce0
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/new_obtain4.lean
66a6aedd1d7b7ea13f397e6e92e8f2edaa1ab73d
[ "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
441
lean
import data.set open set function eq.ops variables {X Y Z : Type} lemma image_comp (f : Y → X) (g : X → Y) (a : set X) : (f ∘ g) ' a = f ' (g ' a) := ext (take z, iff.intro (assume Hz, obtain x Hx₁ Hx₂, from Hz, by repeat (apply mem_image | assumption | reflexivity)) (assume Hz, obtain y [x Hz₁ Hz₂] Hy₂, from Hz, by repeat (apply mem_image | assumption | esimp [comp] | rewrite Hz₂)))
84a7809fa6188cca31115fbfd2ec4196b8f7f568
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/fiber_bundle/is_homeomorphic_trivial_bundle.lean
bd2502ee9930defd3aa114150e406955a593e8f4
[ "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,052
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 topology.homeomorph /-! # Maps equivariantly-homeomorphic to projection in a product This file contains the definition `is_homeomorphic_trivial_fiber_bundle F p`, a Prop saying that a map `p : Z → B` between topological spaces is a "trivial fiber bundle" in the sense that there exists a homeomorphism `h : Z ≃ₜ B × F` such that `proj x = (h x).1`. This is an abstraction which is occasionally convenient in showing that a map is open, a quotient map, etc. This material was formerly linked to the main definition of fibre bundles, but after a series of refactors, there is no longer a direct connection. -/ variables {B : Type*} (F : Type*) {Z : Type*} [topological_space B] [topological_space F] [topological_space Z] /-- A trivial fiber bundle with fiber `F` over a base `B` is a space `Z` projecting on `B` for which there exists a homeomorphism to `B × F` that sends `proj` to `prod.fst`. -/ def is_homeomorphic_trivial_fiber_bundle (proj : Z → B) : Prop := ∃ e : Z ≃ₜ (B × F), ∀ x, (e x).1 = proj x namespace is_homeomorphic_trivial_fiber_bundle variables {F} {proj : Z → B} protected lemma proj_eq (h : is_homeomorphic_trivial_fiber_bundle F proj) : ∃ e : Z ≃ₜ (B × F), proj = prod.fst ∘ e := ⟨h.some, (funext h.some_spec).symm⟩ /-- The projection from a trivial fiber bundle to its base is surjective. -/ protected lemma surjective_proj [nonempty F] (h : is_homeomorphic_trivial_fiber_bundle F proj) : function.surjective proj := begin obtain ⟨e, rfl⟩ := h.proj_eq, exact prod.fst_surjective.comp e.surjective, end /-- The projection from a trivial fiber bundle to its base is continuous. -/ protected lemma continuous_proj (h : is_homeomorphic_trivial_fiber_bundle F proj) : continuous proj := begin obtain ⟨e, rfl⟩ := h.proj_eq, exact continuous_fst.comp e.continuous, end /-- The projection from a trivial fiber bundle to its base is open. -/ protected lemma is_open_map_proj (h : is_homeomorphic_trivial_fiber_bundle F proj) : is_open_map proj := begin obtain ⟨e, rfl⟩ := h.proj_eq, exact is_open_map_fst.comp e.is_open_map, end /-- The projection from a trivial fiber bundle to its base is open. -/ protected lemma quotient_map_proj [nonempty F] (h : is_homeomorphic_trivial_fiber_bundle F proj) : quotient_map proj := h.is_open_map_proj.to_quotient_map h.continuous_proj h.surjective_proj end is_homeomorphic_trivial_fiber_bundle /-- The first projection in a product is a trivial fiber bundle. -/ lemma is_homeomorphic_trivial_fiber_bundle_fst : is_homeomorphic_trivial_fiber_bundle F (prod.fst : B × F → B) := ⟨homeomorph.refl _, λ x, rfl⟩ /-- The second projection in a product is a trivial fiber bundle. -/ lemma is_homeomorphic_trivial_fiber_bundle_snd : is_homeomorphic_trivial_fiber_bundle F (prod.snd : F × B → B) := ⟨homeomorph.prod_comm _ _, λ x, rfl⟩
9d2290986091968dac6bcc8f440db33e9a7116a8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/analysis/calculus/deriv.lean
07003596a705b5e2341826fc172446247982725d
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
54,717
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. -/ universes u v w noncomputable theory open_locale classical topological_space open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) set_option class.instance_max_depth 100 variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (nhds_within x s) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := by simp [has_deriv_within_at, has_deriv_at_filter, has_fderiv_within_at] /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := by simp [has_deriv_at, has_deriv_at_filter, has_fderiv_at] /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ principal (-{x})) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), rw mem_inf_principal, refine univ_mem_sets' (λ z hz, _), have : z ≠ x, by simpa [function.comp] using hz, simp only [mem_set_of_eq], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 this), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (-{x})) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } section congr /-! ### Congruence properties of derivatives -/ theorem has_deriv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁]) lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa has_deriv_at_filter_congr_of_mem_sets hx hL rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_mem_nhds_within (h : has_deriv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_mem_sets h h₁ hx lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma deriv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : deriv f₁ x = deriv f x := by { unfold deriv, rwa fderiv_congr_of_mem_nhds } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (is_o_zero _ _).congr_left $ by simp theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := by { unfold deriv_within, rw fderiv_within_id, simp, assumption } end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (is_o_zero _ _).congr_left $ λ _, by simp [continuous_linear_map.zero_apply, sub_self] theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := by { rw (differentiable_at_const _).deriv_within hxs, apply deriv_const } end const section is_linear_map /-! ### Derivative of linear maps -/ variables (s x L) [is_linear_map 𝕜 f] lemma is_linear_map.has_deriv_at_filter : has_deriv_at_filter f (f 1) x L := (is_o_zero _ _).congr_left begin intro y, simp [sub_smul], rw ← is_linear_map.smul f x, rw ← is_linear_map.smul f y, simp end lemma is_linear_map.has_deriv_within_at : has_deriv_within_at f (f 1) s x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.has_deriv_at : has_deriv_at f (f 1) x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.differentiable_at : differentiable_at 𝕜 f x := (is_linear_map.has_deriv_at _).differentiable_at lemma is_linear_map.differentiable_within_at : differentiable_within_at 𝕜 f s x := (is_linear_map.differentiable_at _).differentiable_within_at @[simp] lemma is_linear_map.deriv : deriv f x = f 1 := has_deriv_at.deriv (is_linear_map.has_deriv_at _) lemma is_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f 1 := begin rw differentiable_at.deriv_within (is_linear_map.differentiable_at _) hxs, apply is_linear_map.deriv, assumption end lemma is_linear_map.differentiable : differentiable 𝕜 f := λ x, is_linear_map.differentiable_at _ lemma is_linear_map.differentiable_on : differentiable_on 𝕜 f s := is_linear_map.differentiable.differentiable_on end is_linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ by simp [add_smul, smul_add] theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := begin show has_fderiv_within_at _ _ _ _, convert has_fderiv_within_at.smul hc hf, ext, simp [smul_add, (mul_smul _ _ _).symm, mul_comm] end theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := h.neg.congr (by simp) (by simp) theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv_neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv_neg end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := has_fderiv_at_filter.tendsto_nhds hL h theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector valued function and a scalar function -/ variables {h : 𝕜 → 𝕜} {h' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.comp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := have (smul_right 1 g' : 𝕜 →L[𝕜] _).comp (smul_right 1 h' : 𝕜 →L[𝕜] _) = smul_right 1 (h' • g'), by { ext, simp [mul_smul] }, begin unfold has_deriv_at_filter, rw ← this, exact has_fderiv_at_filter.comp x hg hh, end theorem has_deriv_within_at.comp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.comp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.comp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).comp x hh theorem has_deriv_at.comp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.comp x hg hh subset_preimage_univ end lemma deriv_within.comp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.comp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hg.has_deriv_at hh.has_deriv_at end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ lemma has_deriv_at_inv_one : has_deriv_at (λx, x⁻¹) (-1) (1 : 𝕜) := begin rw has_deriv_at_iff_is_o_nhds_zero, have : is_o (λ (h : 𝕜), h^2 * (1 + h)⁻¹) (λ (h : 𝕜), h * 1) (𝓝 0), { have : tendsto (λ (h : 𝕜), (1 + h)⁻¹) (𝓝 0) (𝓝 (1 + 0)⁻¹) := ((tendsto_const_nhds).add tendsto_id).inv' (by norm_num), exact is_o.mul_is_O (is_o_pow_id one_lt_two) (is_O_one_of_tendsto _ this) }, apply this.congr' _ _, { have : metric.ball (0 : 𝕜) 1 ∈ 𝓝 (0 : 𝕜), from metric.ball_mem_nhds 0 zero_lt_one, filter_upwards [this], assume h hx, have : 0 < ∥1 + h∥ := calc 0 < ∥(1:𝕜)∥ - ∥-h∥ : by rwa [norm_neg, sub_pos, ← dist_zero_right h, normed_field.norm_one] ... ≤ ∥1 - -h∥ : norm_sub_norm_le _ _ ... = ∥1 + h∥ : by simp, have : 1 + h ≠ 0 := norm_pos_iff.mp this, simp, rw ← eq_div_iff_mul_eq _ _ (inv_ne_zero this), field_simp, simp [right_distrib, sub_mul, (show (1 + h)⁻¹ * (1 + h) = 1, by rw mul_comm; exact field.mul_inv_cancel this)], ring }, { exact univ_mem_sets' mul_one } end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := begin have A : has_deriv_at (λy, y⁻¹) (-1) (x⁻¹ * x : 𝕜), by { simp only [inv_mul_cancel x_ne_zero, has_deriv_at_inv_one] }, have B : has_deriv_at (λy, x⁻¹ * y) (x⁻¹) x, by simpa only [mul_one] using (has_deriv_at_id x).const_mul x⁻¹, convert (A.comp x B : _).const_mul x⁻¹, { ext y, rw [function.comp_apply, mul_inv', inv_inv', mul_comm, mul_assoc, mul_inv_cancel x_ne_zero, mul_one] }, { rw [pow_two, mul_inv', smul_eq_mul, mul_neg_one, neg_mul_eq_mul_neg] } end theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul, pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv end division end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} variable {n : ℕ } lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C 1 * (polynomial.X)^n).has_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, nat.sub_zero, nat.cast_one] }, { simp only [nat.iterate_succ', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_of_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_deriv_at_inv _).comp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_deriv_at_const] }, { exact this m hm } end theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = ((finset.range k).prod (λ i, m - i):ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [nat.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], apply deriv_congr_of_mem_nhds, apply eventually.mono _ @ihk, exact mem_nhds_sets (is_open_neg $ is_closed_eq continuous_id continuous_const) hx } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently (nhds_within_Ioi_self_ne_bot x) end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently (nhds_within_Ioi_self_ne_bot x) /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently (nhds_within_Ioi_self_ne_bot x), refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
1d13efd92608d09d3509f910eff6ececeb1e3a38
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/tests/lean/hott/notation_with_nested_tactics.hlean
d33eb3257f04137f154f118c1b3807b28a99fef7
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
354
hlean
open is_equiv constants (A B : Type) (f : A → B) definition H : is_equiv f := sorry definition loop [instance] [h : is_equiv f] : is_equiv f := h notation `noinstances` t:max := by+ with_options [elaborator.ignore_instances true] (exact t) example (a : A) : let H' : is_equiv f := H in @(is_equiv.inv f) H' (f a) = a := noinstances (left_inv f a)
0def78f356fd65f404740a06d08ef6a24f27338d
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/topology/bases.lean
44c214414a832893102fbd5e36366ce70e7ba217
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
38,876
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.constructions import topology.continuous_on /-! # Bases of topologies. Countability axioms. A topological basis on a topological space `t` is a collection of sets, such that all open sets can be generated as unions of these sets, without the need to take finite intersections of them. This file introduces a framework for dealing with these collections, and also what more we can say under certain countability conditions on bases, which are referred to as first- and second-countable. We also briefly cover the theory of separable spaces, which are those with a countable, dense subset. If a space is second-countable, and also has a countably generated uniformity filter (for example, if `t` is a metric space), it will automatically be separable (and indeed, these conditions are equivalent in this case). ## Main definitions * `is_topological_basis s`: The topological space `t` has basis `s`. * `separable_space α`: The topological space `t` has a countable, dense subset. * `is_separable s`: The set `s` is contained in the closure of a countable set. * `first_countable_topology α`: A topology in which `𝓝 x` is countably generated for every `x`. * `second_countable_topology α`: A topology which has a topological basis which is countable. ## Main results * `first_countable_topology.tendsto_subseq`: In a first-countable space, cluster points are limits of subsequences. * `second_countable_topology.is_open_Union_countable`: In a second-countable space, the union of arbitrarily-many open sets is equal to a sub-union of only countably many of these sets. * `second_countable_topology.countable_cover_nhds`: Consider `f : α → set α` with the property that `f x ∈ 𝓝 x` for all `x`. Then there is some countable set `s` whose image covers the space. ## Implementation Notes For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. ### TODO: More fine grained instances for `first_countable_topology`, `separable_space`, `t2_space`, and more (see the comment below `subtype.second_countable_topology`.) -/ open set filter function open_locale topological_space filter noncomputable theory namespace topological_space universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ structure is_topological_basis (s : set (set α)) : Prop := (exists_subset_inter : ∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) (sUnion_eq : (⋃₀ s) = univ) (eq_generate_from : t = generate_from s) /-- If a family of sets `s` generates the topology, then nonempty intersections of finite subcollections of `s` form a topological basis. -/ lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λ f, ⋂₀ f) '' {f : set (set α) | f.finite ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) := begin refine ⟨_, _, _⟩, { rintro _ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, rfl⟩ _ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, rfl⟩ x h, have : ⋂₀ (t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂ := sInter_union t₁ t₂, exact ⟨_, ⟨t₁ ∪ t₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b, this.symm ▸ ⟨x, h⟩⟩, this⟩, h, subset.rfl⟩ }, { rw [sUnion_image, Union₂_eq_univ_iff], intro x, have : x ∈ ⋂₀ ∅, { rw sInter_empty, exact mem_univ x }, exact ⟨∅, ⟨finite_empty, empty_subset _, x, this⟩, this⟩ }, { rw hs, apply le_antisymm; apply le_generate_from, { rintro _ ⟨t, ⟨hft, htb, ht⟩, rfl⟩, exact @is_open_sInter _ (generate_from s) _ hft (λ s hs, generate_open.basic _ $ htb hs) }, { intros t ht, rcases t.eq_empty_or_nonempty with rfl|hne, { apply @is_open_empty _ _ }, rw ← sInter_singleton t at hne ⊢, exact generate_open.basic _ ⟨{t}, ⟨finite_singleton t, singleton_subset_iff.2 ht, hne⟩, rfl⟩ } } end /-- If a family of open sets `s` is such that every open neighbourhood contains some member of `s`, then `s` is a topological basis. -/ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := begin refine ⟨λ t₁ ht₁ t₂ ht₂ x hx, h_nhds _ _ hx (is_open.inter (h_open _ ht₁) (h_open _ ht₂)), _, _⟩, { refine sUnion_eq_univ_iff.2 (λ a, _), rcases h_nhds a univ trivial is_open_univ with ⟨u, h₁, h₂, -⟩, exact ⟨u, h₁, h₂⟩ }, { refine (le_generate_from h_open).antisymm (λ u hu, _), refine (@is_open_iff_nhds α (generate_from s) u).mpr (λ a ha, _), rcases h_nhds a u ha hu with ⟨v, hvs, hav, hvu⟩, rw nhds_generate_from, exact infi₂_le_of_le v ⟨hav, hvs⟩ (le_principal_iff.2 hvu) } end /-- A set `s` is in the neighbourhood of `a` iff there is some basis set `t`, which contains `a` and is itself contained in `s`. -/ lemma is_topological_basis.mem_nhds_iff {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃ t ∈ b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃ t ∈ b, a ∈ t ∧ t ⊆ s, rw [hb.eq_generate_from, nhds_generate_from, binfi_sets_eq], { simp [and_assoc, and.left_comm] }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.sUnion_eq a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_topological_basis.is_open_iff {s : set α} {b : set (set α)} (hb : is_topological_basis b) : is_open s ↔ ∀ a ∈ s, ∃ t ∈ b, a ∈ t ∧ t ⊆ s := by simp [is_open_iff_mem_nhds, hb.mem_nhds_iff] lemma is_topological_basis.nhds_has_basis {b : set (set α)} (hb : is_topological_basis b) {a : α} : (𝓝 a).has_basis (λ t : set α, t ∈ b ∧ a ∈ t) (λ t, t) := ⟨λ s, hb.mem_nhds_iff.trans $ by simp only [exists_prop, and_assoc]⟩ protected lemma is_topological_basis.is_open {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : is_open s := by { rw hb.eq_generate_from, exact generate_open.basic s hs } protected lemma is_topological_basis.mem_nhds {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) (ha : a ∈ s) : s ∈ 𝓝 a := (hb.is_open hs).mem_nhds ha lemma is_topological_basis.exists_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := hb.mem_nhds_iff.1 $ is_open.mem_nhds ou au /-- Any open set is the union of the basis sets contained in it. -/ lemma is_topological_basis.open_eq_sUnion' {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : u = ⋃₀ {s ∈ B | s ⊆ u} := ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := hB.exists_subset_of_mem_open ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩ lemma is_topological_basis.open_eq_sUnion {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, hB.open_eq_sUnion' ou⟩ lemma is_topological_basis.open_eq_Union {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := ⟨↥{s ∈ B | s ⊆ u}, coe, by { rw ← sUnion_eq_Union, apply hB.open_eq_sUnion' ou }, λ s, and.left s.2⟩ /-- A point `a` is in the closure of `s` iff all basis sets containing `a` intersect `s`. -/ lemma is_topological_basis.mem_closure_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} {a : α} : a ∈ closure s ↔ ∀ o ∈ b, a ∈ o → (o ∩ s).nonempty := (mem_closure_iff_nhds_basis' hb.nhds_has_basis).trans $ by simp only [and_imp] /-- A set is dense iff it has non-trivial intersection with all basis sets. -/ lemma is_topological_basis.dense_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} : dense s ↔ ∀ o ∈ b, set.nonempty o → (o ∩ s).nonempty := begin simp only [dense, hb.mem_closure_iff], exact ⟨λ h o hb ⟨a, ha⟩, h a o hb ha, λ h a o hb ha, h o hb ⟨a, ha⟩⟩ end lemma is_topological_basis.is_open_map_iff {β} [topological_space β] {B : set (set α)} (hB : is_topological_basis B) {f : α → β} : is_open_map f ↔ ∀ s ∈ B, is_open (f '' s) := begin refine ⟨λ H o ho, H _ (hB.is_open ho), λ hf o ho, _⟩, rw [hB.open_eq_sUnion' ho, sUnion_eq_Union, image_Union], exact is_open_Union (λ s, hf s s.2.1) end lemma is_topological_basis.exists_nonempty_subset {B : set (set α)} (hb : is_topological_basis B) {u : set α} (hu : u.nonempty) (ou : is_open u) : ∃ v ∈ B, set.nonempty v ∧ v ⊆ u := begin cases hu with x hx, rw [hb.open_eq_sUnion' ou, mem_sUnion] at hx, rcases hx with ⟨v, hv, hxv⟩, exact ⟨v, hv.1, ⟨x, hxv⟩, hv.2⟩ end lemma is_topological_basis_opens : is_topological_basis { U : set α | is_open U } := is_topological_basis_of_open_of_nhds (by tauto) (by tauto) protected lemma is_topological_basis.prod {β} [topological_space β] {B₁ : set (set α)} {B₂ : set (set β)} (h₁ : is_topological_basis B₁) (h₂ : is_topological_basis B₂) : is_topological_basis (image2 (×ˢ) B₁ B₂) := begin refine is_topological_basis_of_open_of_nhds _ _, { rintro _ ⟨u₁, u₂, hu₁, hu₂, rfl⟩, exact (h₁.is_open hu₁).prod (h₂.is_open hu₂) }, { rintro ⟨a, b⟩ u hu uo, rcases (h₁.nhds_has_basis.prod_nhds h₂.nhds_has_basis).mem_iff.1 (is_open.mem_nhds uo hu) with ⟨⟨s, t⟩, ⟨⟨hs, ha⟩, ht, hb⟩, hu⟩, exact ⟨s ×ˢ t, mem_image2_of_mem hs ht, ⟨ha, hb⟩, hu⟩ } end protected lemma is_topological_basis.inducing {β} [topological_space β] {f : α → β} {T : set (set β)} (hf : inducing f) (h : is_topological_basis T) : is_topological_basis (image (preimage f) T) := begin refine is_topological_basis_of_open_of_nhds _ _, { rintros _ ⟨V, hV, rfl⟩, rwa hf.is_open_iff, refine ⟨V, h.is_open hV, rfl⟩ }, { intros a U ha hU, rw hf.is_open_iff at hU, obtain ⟨V, hV, rfl⟩ := hU, obtain ⟨S, hS, rfl⟩ := h.open_eq_sUnion hV, obtain ⟨W, hW, ha⟩ := ha, refine ⟨f ⁻¹' W, ⟨_, hS hW, rfl⟩, ha, set.preimage_mono $ set.subset_sUnion_of_mem hW⟩ } end lemma is_topological_basis_of_cover {ι} {U : ι → set α} (Uo : ∀ i, is_open (U i)) (Uc : (⋃ i, U i) = univ) {b : Π i, set (set (U i))} (hb : ∀ i, is_topological_basis (b i)) : is_topological_basis (⋃ i : ι, image (coe : U i → α) '' (b i)) := begin refine is_topological_basis_of_open_of_nhds (λ u hu, _) _, { simp only [mem_Union, mem_image] at hu, rcases hu with ⟨i, s, sb, rfl⟩, exact (Uo i).is_open_map_subtype_coe _ ((hb i).is_open sb) }, { intros a u ha uo, rcases Union_eq_univ_iff.1 Uc a with ⟨i, hi⟩, lift a to ↥(U i) using hi, rcases (hb i).exists_subset_of_mem_open (by exact ha) (uo.preimage continuous_subtype_coe) with ⟨v, hvb, hav, hvu⟩, exact ⟨coe '' v, mem_Union.2 ⟨i, mem_image_of_mem _ hvb⟩, mem_image_of_mem _ hav, image_subset_iff.2 hvu⟩ } end protected lemma is_topological_basis.continuous {β : Type*} [topological_space β] {B : set (set β)} (hB : is_topological_basis B) (f : α → β) (hf : ∀ s ∈ B, is_open (f ⁻¹' s)) : continuous f := begin rw hB.eq_generate_from, exact continuous_generated_from hf end variables (α) /-- A separable space is one with a countable dense subset, available through `topological_space.exists_countable_dense`. If `α` is also known to be nonempty, then `topological_space.dense_seq` provides a sequence `ℕ → α` with dense range, see `topological_space.dense_range_dense_seq`. If `α` is a uniform space with countably generated uniformity filter (e.g., an `emetric_space`), then this condition is equivalent to `topological_space.second_countable_topology α`. In this case the latter should be used as a typeclass argument in theorems because Lean can automatically deduce `separable_space` from `second_countable_topology` but it can't deduce `second_countable_topology` and `emetric_space`. -/ class separable_space : Prop := (exists_countable_dense : ∃s:set α, s.countable ∧ dense s) lemma exists_countable_dense [separable_space α] : ∃ s : set α, s.countable ∧ dense s := separable_space.exists_countable_dense /-- A nonempty separable space admits a sequence with dense range. Instead of running `cases` on the conclusion of this lemma, you might want to use `topological_space.dense_seq` and `topological_space.dense_range_dense_seq`. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ lemma exists_dense_seq [separable_space α] [nonempty α] : ∃ u : ℕ → α, dense_range u := begin obtain ⟨s : set α, hs, s_dense⟩ := exists_countable_dense α, cases set.countable_iff_exists_subset_range.mp hs with u hu, exact ⟨u, s_dense.mono hu⟩, end /-- A dense sequence in a non-empty separable topological space. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ def dense_seq [separable_space α] [nonempty α] : ℕ → α := classical.some (exists_dense_seq α) /-- The sequence `dense_seq α` has dense range. -/ @[simp] lemma dense_range_dense_seq [separable_space α] [nonempty α] : dense_range (dense_seq α) := classical.some_spec (exists_dense_seq α) variable {α} @[priority 100] instance encodable.to_separable_space [encodable α] : separable_space α := { exists_countable_dense := ⟨set.univ, set.countable_univ, dense_univ⟩ } lemma separable_space_of_dense_range {ι : Type*} [encodable ι] (u : ι → α) (hu : dense_range u) : separable_space α := ⟨⟨range u, countable_range u, hu⟩⟩ /-- In a separable space, a family of nonempty disjoint open sets is countable. -/ lemma _root_.set.pairwise_disjoint.countable_of_is_open [separable_space α] {ι : Type*} {s : ι → set α} {a : set ι} (h : a.pairwise_disjoint s) (ha : ∀ i ∈ a, is_open (s i)) (h'a : ∀ i ∈ a, (s i).nonempty) : a.countable := begin rcases exists_countable_dense α with ⟨u, ⟨u_encodable⟩, u_dense⟩, have : ∀ i : a, ∃ y, y ∈ s i ∩ u := λ i, dense_iff_inter_open.1 u_dense (s i) (ha i i.2) (h'a i i.2), choose f hfs hfu using this, lift f to a → u using hfu, have f_inj : injective f, { refine injective_iff_pairwise_ne.mpr ((h.subtype _ _).mono $ λ i j hij hfij, hij ⟨hfs i, _⟩), simp only [congr_arg coe hfij, hfs j] }, exact ⟨@encodable.of_inj _ _ u_encodable f f_inj⟩ end /-- In a separable space, a family of disjoint sets with nonempty interiors is countable. -/ lemma _root_.set.pairwise_disjoint.countable_of_nonempty_interior [separable_space α] {ι : Type*} {s : ι → set α} {a : set ι} (h : a.pairwise_disjoint s) (ha : ∀ i ∈ a, (interior (s i)).nonempty) : a.countable := (h.mono $ λ i, interior_subset).countable_of_is_open (λ i hi, is_open_interior) ha /-- A set `s` in a topological space is separable if it is contained in the closure of a countable set `c`. Beware that this definition does not require that `c` is contained in `s` (to express the latter, use `separable_space s` or `is_separable (univ : set s))`. In metric spaces, the two definitions are equivalent, see `topological_space.is_separable.separable_space`. -/ def is_separable (s : set α) := ∃ c : set α, c.countable ∧ s ⊆ closure c lemma is_separable.mono {s u : set α} (hs : is_separable s) (hu : u ⊆ s) : is_separable u := begin rcases hs with ⟨c, c_count, hs⟩, exact ⟨c, c_count, hu.trans hs⟩ end lemma is_separable.union {s u : set α} (hs : is_separable s) (hu : is_separable u) : is_separable (s ∪ u) := begin rcases hs with ⟨cs, cs_count, hcs⟩, rcases hu with ⟨cu, cu_count, hcu⟩, refine ⟨cs ∪ cu, cs_count.union cu_count, _⟩, exact union_subset (hcs.trans (closure_mono (subset_union_left _ _))) (hcu.trans (closure_mono (subset_union_right _ _))) end lemma is_separable.closure {s : set α} (hs : is_separable s) : is_separable (closure s) := begin rcases hs with ⟨c, c_count, hs⟩, exact ⟨c, c_count, by simpa using closure_mono hs⟩, end lemma is_separable_Union {ι : Type*} [encodable ι] {s : ι → set α} (hs : ∀ i, is_separable (s i)) : is_separable (⋃ i, s i) := begin choose c hc h'c using hs, refine ⟨⋃ i, c i, countable_Union hc, Union_subset_iff.2 (λ i, _)⟩, exact (h'c i).trans (closure_mono (subset_Union _ i)) end lemma _root_.set.countable.is_separable {s : set α} (hs : s.countable) : is_separable s := ⟨s, hs, subset_closure⟩ lemma _root_.set.finite.is_separable {s : set α} (hs : s.finite) : is_separable s := hs.countable.is_separable lemma is_separable_univ_iff : is_separable (univ : set α) ↔ separable_space α := begin split, { rintros ⟨c, c_count, hc⟩, refine ⟨⟨c, c_count, by rwa [dense_iff_closure_eq, ← univ_subset_iff]⟩⟩ }, { introsI h, rcases exists_countable_dense α with ⟨c, c_count, hc⟩, exact ⟨c, c_count, by rwa [univ_subset_iff, ← dense_iff_closure_eq]⟩ } end lemma is_separable_of_separable_space [h : separable_space α] (s : set α) : is_separable s := is_separable.mono (is_separable_univ_iff.2 h) (subset_univ _) lemma is_separable.image {β : Type*} [topological_space β] {s : set α} (hs : is_separable s) {f : α → β} (hf : continuous f) : is_separable (f '' s) := begin rcases hs with ⟨c, c_count, hc⟩, refine ⟨f '' c, c_count.image _, _⟩, rw image_subset_iff, exact hc.trans (closure_subset_preimage_closure_image hf) end lemma is_separable_of_separable_space_subtype (s : set α) [separable_space s] : is_separable s := begin have : is_separable ((coe : s → α) '' (univ : set s)) := (is_separable_of_separable_space _).image continuous_subtype_coe, simpa only [image_univ, subtype.range_coe_subtype], end end topological_space open topological_space lemma is_topological_basis_pi {ι : Type*} {X : ι → Type*} [∀ i, topological_space (X i)] {T : Π i, set (set (X i))} (cond : ∀ i, is_topological_basis (T i)) : is_topological_basis {S : set (Π i, X i) | ∃ (U : Π i, set (X i)) (F : finset ι), (∀ i, i ∈ F → (U i) ∈ T i) ∧ S = (F : set ι).pi U } := begin refine is_topological_basis_of_open_of_nhds _ _, { rintro _ ⟨U, F, h1, rfl⟩, apply is_open_set_pi F.finite_to_set, intros i hi, exact (cond i).is_open (h1 i hi) }, { intros a U ha hU, obtain ⟨I, t, hta, htU⟩ : ∃ (I : finset ι) (t : Π (i : ι), set (X i)), (∀ i, t i ∈ 𝓝 (a i)) ∧ set.pi ↑I t ⊆ U, { rw [← filter.mem_pi', ← nhds_pi], exact hU.mem_nhds ha }, have : ∀ i, ∃ V ∈ T i, a i ∈ V ∧ V ⊆ t i := λ i, (cond i).mem_nhds_iff.1 (hta i), choose V hVT haV hVt, exact ⟨_, ⟨V, I, λ i hi, hVT i, rfl⟩, λ i hi, haV i, (pi_mono $ λ i hi, hVt i).trans htU⟩ }, end lemma is_topological_basis_infi {β : Type*} {ι : Type*} {X : ι → Type*} [t : ∀ i, topological_space (X i)] {T : Π i, set (set (X i))} (cond : ∀ i, is_topological_basis (T i)) (f : Π i, β → X i) : @is_topological_basis β (⨅ i, induced (f i) (t i)) { S | ∃ (U : Π i, set (X i)) (F : finset ι), (∀ i, i ∈ F → U i ∈ T i) ∧ S = ⋂ i (hi : i ∈ F), (f i) ⁻¹' (U i) } := begin convert (is_topological_basis_pi cond).inducing (inducing_infi_to_pi _), ext V, split, { rintros ⟨U, F, h1, h2⟩, have : (F : set ι).pi U = (⋂ (i : ι) (hi : i ∈ F), (λ (z : Π j, X j), z i) ⁻¹' (U i)), by { ext, simp }, refine ⟨(F : set ι).pi U, ⟨U, F, h1, rfl⟩, _⟩, rw [this, h2, set.preimage_Inter], congr' 1, ext1, rw set.preimage_Inter, refl }, { rintros ⟨U, ⟨U, F, h1, rfl⟩, h⟩, refine ⟨U, F, h1, _⟩, have : (F : set ι).pi U = (⋂ (i : ι) (hi : i ∈ F), (λ (z : Π j, X j), z i) ⁻¹' (U i)), by { ext, simp }, rw [← h, this, set.preimage_Inter], congr' 1, ext1, rw set.preimage_Inter, refl } end lemma is_topological_basis_singletons (α : Type*) [topological_space α] [discrete_topology α] : is_topological_basis {s | ∃ (x : α), (s : set α) = {x}} := is_topological_basis_of_open_of_nhds (λ u hu, is_open_discrete _) $ λ x u hx u_open, ⟨{x}, ⟨x, rfl⟩, mem_singleton x, singleton_subset_iff.2 hx⟩ /-- If `α` is a separable space and `f : α → β` is a continuous map with dense range, then `β` is a separable space as well. E.g., the completion of a separable uniform space is separable. -/ protected lemma dense_range.separable_space {α β : Type*} [topological_space α] [separable_space α] [topological_space β] {f : α → β} (h : dense_range f) (h' : continuous f) : separable_space β := let ⟨s, s_cnt, s_dense⟩ := exists_countable_dense α in ⟨⟨f '' s, countable.image s_cnt f, h.dense_image h' s_dense⟩⟩ lemma dense.exists_countable_dense_subset {α : Type*} [topological_space α] {s : set α} [separable_space s] (hs : dense s) : ∃ t ⊆ s, t.countable ∧ dense t := let ⟨t, htc, htd⟩ := exists_countable_dense s in ⟨coe '' t, image_subset_iff.2 $ λ x _, mem_preimage.2 $ subtype.coe_prop _, htc.image coe, hs.dense_range_coe.dense_image continuous_subtype_val htd⟩ /-- Let `s` be a dense set in a topological space `α` with partial order structure. If `s` is a separable space (e.g., if `α` has a second countable topology), then there exists a countable dense subset `t ⊆ s` such that `t` contains bottom/top element of `α` when they exist and belong to `s`. For a dense subset containing neither bot nor top elements, see `dense.exists_countable_dense_subset_no_bot_top`. -/ lemma dense.exists_countable_dense_subset_bot_top {α : Type*} [topological_space α] [partial_order α] {s : set α} [separable_space s] (hs : dense s) : ∃ t ⊆ s, t.countable ∧ dense t ∧ (∀ x, is_bot x → x ∈ s → x ∈ t) ∧ (∀ x, is_top x → x ∈ s → x ∈ t) := begin rcases hs.exists_countable_dense_subset with ⟨t, hts, htc, htd⟩, refine ⟨(t ∪ ({x | is_bot x} ∪ {x | is_top x})) ∩ s, _, _, _, _, _⟩, exacts [inter_subset_right _ _, (htc.union ((countable_is_bot α).union (countable_is_top α))).mono (inter_subset_left _ _), htd.mono (subset_inter (subset_union_left _ _) hts), λ x hx hxs, ⟨or.inr $ or.inl hx, hxs⟩, λ x hx hxs, ⟨or.inr $ or.inr hx, hxs⟩] end instance separable_space_univ {α : Type*} [topological_space α] [separable_space α] : separable_space (univ : set α) := (equiv.set.univ α).symm.surjective.dense_range.separable_space (continuous_subtype_mk _ continuous_id) /-- If `α` is a separable topological space with a partial order, then there exists a countable dense set `s : set α` that contains those of both bottom and top elements of `α` that actually exist. For a dense set containing neither bot nor top elements, see `exists_countable_dense_no_bot_top`. -/ lemma exists_countable_dense_bot_top (α : Type*) [topological_space α] [separable_space α] [partial_order α] : ∃ s : set α, s.countable ∧ dense s ∧ (∀ x, is_bot x → x ∈ s) ∧ (∀ x, is_top x → x ∈ s) := by simpa using dense_univ.exists_countable_dense_subset_bot_top namespace topological_space universe u variables (α : Type u) [t : topological_space α] include t /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated) attribute [instance] first_countable_topology.nhds_generated_countable namespace first_countable_topology variable {α} /-- In a first-countable space, a cluster point `x` of a sequence is the limit of some subsequence. -/ lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α} (hx : map_cluster_pt x at_top u) : ∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) := subseq_tendsto_of_ne_bot hx end first_countable_topology variables {α} instance {β} [topological_space β] [first_countable_topology α] [first_countable_topology β] : first_countable_topology (α × β) := ⟨λ ⟨x, y⟩, by { rw nhds_prod_eq, apply_instance }⟩ section pi omit t instance {ι : Type*} {π : ι → Type*} [countable ι] [Π i, topological_space (π i)] [∀ i, first_countable_topology (π i)] : first_countable_topology (Π i, π i) := ⟨λ f, by { rw nhds_pi, apply_instance }⟩ end pi instance is_countably_generated_nhds_within (x : α) [is_countably_generated (𝓝 x)] (s : set α) : is_countably_generated (𝓝[s] x) := inf.is_countably_generated _ _ variable (α) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable [] : ∃ b : set (set α), b.countable ∧ t = topological_space.generate_from b) variable {α} protected lemma is_topological_basis.second_countable_topology {b : set (set α)} (hb : is_topological_basis b) (hc : b.countable) : second_countable_topology α := ⟨⟨b, hc, hb.eq_generate_from⟩⟩ variable (α) lemma exists_countable_basis [second_countable_topology α] : ∃b:set (set α), b.countable ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | s.finite ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in ⟨b', ((countable_set_of_finite_subset hb₁).mono (by { simp only [← and_assoc], apply inter_subset_left })).image _, assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp), is_topological_basis_of_subbasis hb₂⟩ /-- A countable topological basis of `α`. -/ def countable_basis [second_countable_topology α] : set (set α) := (exists_countable_basis α).some lemma countable_countable_basis [second_countable_topology α] : (countable_basis α).countable := (exists_countable_basis α).some_spec.1 instance encodable_countable_basis [second_countable_topology α] : encodable (countable_basis α) := (countable_countable_basis α).to_encodable lemma empty_nmem_countable_basis [second_countable_topology α] : ∅ ∉ countable_basis α := (exists_countable_basis α).some_spec.2.1 lemma is_basis_countable_basis [second_countable_topology α] : is_topological_basis (countable_basis α) := (exists_countable_basis α).some_spec.2.2 lemma eq_generate_from_countable_basis [second_countable_topology α] : ‹topological_space α› = generate_from (countable_basis α) := (is_basis_countable_basis α).eq_generate_from variable {α} lemma is_open_of_mem_countable_basis [second_countable_topology α] {s : set α} (hs : s ∈ countable_basis α) : is_open s := (is_basis_countable_basis α).is_open hs lemma nonempty_of_mem_countable_basis [second_countable_topology α] {s : set α} (hs : s ∈ countable_basis α) : s.nonempty := ne_empty_iff_nonempty.1 $ ne_of_mem_of_not_mem hs $ empty_nmem_countable_basis α variable (α) @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := ⟨λ x, has_countable_basis.is_countably_generated $ ⟨(is_basis_countable_basis α).nhds_has_basis, (countable_countable_basis α).mono $ inter_subset_left _ _⟩⟩ /-- If `β` is a second-countable space, then its induced topology via `f` on `α` is also second-countable. -/ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ((is_basis_countable_basis α).prod (is_basis_countable_basis β)).second_countable_topology $ (countable_countable_basis α).image2 (countable_countable_basis β) _ instance {ι : Type*} {π : ι → Type*} [countable ι] [t : ∀a, topological_space (π a)] [∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := begin haveI := encodable.of_countable ι, have : t = (λa, generate_from (countable_basis (π a))), from funext (assume a, (is_basis_countable_basis (π a)).eq_generate_from), rw [this, pi_generate_from_eq], constructor, refine ⟨_, _, rfl⟩, have : set.countable {T : set (Π i, π i) | ∃ (I : finset ι) (s : Π i : I, set (π i)), (∀ i, s i ∈ countable_basis (π i)) ∧ T = {f | ∀ i : I, f i ∈ s i}}, { simp only [set_of_exists, ← exists_prop], refine countable_Union (λ I, countable.bUnion _ (λ _ _, countable_singleton _)), change set.countable {s : Π i : I, set (π i) | ∀ i, s i ∈ countable_basis (π i)}, exact countable_pi (λ i, countable_countable_basis _) }, convert this using 1, ext1 T, split, { rintro ⟨s, I, hs, rfl⟩, refine ⟨I, λ i, s i, λ i, hs i i.2, _⟩, simp only [set.pi, set_coe.forall'], refl }, { rintro ⟨I, s, hs, rfl⟩, rcases @subtype.surjective_restrict ι (λ i, set (π i)) _ (λ i, i ∈ I) s with ⟨s, rfl⟩, exact ⟨s, I, λ i hi, hs ⟨i, hi⟩, set.ext $ λ f, subtype.forall⟩ } end @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := begin choose p hp using λ s : countable_basis α, nonempty_of_mem_countable_basis s.2, exact ⟨⟨range p, countable_range _, (is_basis_countable_basis α).dense_iff.2 $ λ o ho _, ⟨p ⟨o, ho⟩, hp _, mem_range_self _⟩⟩⟩ end variables {α} /-- A countable open cover induces a second-countable topology if all open covers are themselves second countable. -/ lemma second_countable_topology_of_countable_cover {ι} [encodable ι] {U : ι → set α} [∀ i, second_countable_topology (U i)] (Uo : ∀ i, is_open (U i)) (hc : (⋃ i, U i) = univ) : second_countable_topology α := begin have : is_topological_basis (⋃ i, image (coe : U i → α) '' (countable_basis (U i))), from is_topological_basis_of_cover Uo hc (λ i, is_basis_countable_basis (U i)), exact this.second_countable_topology (countable_Union $ λ i, (countable_countable_basis _).image _) end /-- In a second-countable space, an open set, given as a union of open sets, is equal to the union of countably many of those sets. -/ lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, is_open (s i)) : ∃ T : set ι, T.countable ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := begin let B := {b ∈ countable_basis α | ∃ i, b ⊆ s i}, choose f hf using λ b : B, b.2.2, haveI : encodable B := ((countable_countable_basis α).mono (sep_subset _ _)).to_encodable, refine ⟨_, countable_range f, (Union₂_subset_Union _ _).antisymm (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases (is_basis_countable_basis α).exists_subset_of_mem_open xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, is_open s) : ∃ T : set (set α), T.countable ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, cT.image _, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ /-- In a topological space with second countable topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds [second_countable_topology α] {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, s.countable ∧ (⋃ x ∈ s, f x) = univ := begin rcases is_open_Union_countable (λ x, interior (f x)) (λ x, is_open_interior) with ⟨s, hsc, hsU⟩, suffices : (⋃ x ∈ s, interior (f x)) = univ, from ⟨s, hsc, flip eq_univ_of_subset this $ Union₂_mono $ λ _ _, interior_subset⟩, simp only [hsU, eq_univ_iff_forall, mem_Union], exact λ x, ⟨x, mem_interior_iff_mem_nhds.2 (hf x)⟩ end lemma countable_cover_nhds_within [second_countable_topology α] {f : α → set α} {s : set α} (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, t.countable ∧ s ⊆ (⋃ x ∈ t, f x) := begin have : ∀ x : s, coe ⁻¹' (f x) ∈ 𝓝 x, from λ x, preimage_coe_mem_nhds_subtype.2 (hf x x.2), rcases countable_cover_nhds this with ⟨t, htc, htU⟩, refine ⟨coe '' t, subtype.coe_image_subset _ _, htc.image _, λ x hx, _⟩, simp only [bUnion_image, eq_univ_iff_forall, ← preimage_Union, mem_preimage] at htU ⊢, exact htU ⟨x, hx⟩ end section sigma variables {ι : Type*} {E : ι → Type*} [∀ i, topological_space (E i)] omit t /-- In a disjoint union space `Σ i, E i`, one can form a topological basis by taking the union of topological bases on each of the parts of the space. -/ lemma is_topological_basis.sigma {s : Π (i : ι), set (set (E i))} (hs : ∀ i, is_topological_basis (s i)) : is_topological_basis (⋃ (i : ι), (λ u, ((sigma.mk i) '' u : set (Σ i, E i))) '' (s i)) := begin apply is_topological_basis_of_open_of_nhds, { assume u hu, obtain ⟨i, t, ts, rfl⟩ : ∃ (i : ι) (t : set (E i)), t ∈ s i ∧ sigma.mk i '' t = u, by simpa only [mem_Union, mem_image] using hu, exact is_open_map_sigma_mk _ ((hs i).is_open ts) }, { rintros ⟨i, x⟩ u hxu u_open, have hx : x ∈ sigma.mk i ⁻¹' u := hxu, obtain ⟨v, vs, xv, hv⟩ : ∃ (v : set (E i)) (H : v ∈ s i), x ∈ v ∧ v ⊆ sigma.mk i ⁻¹' u := (hs i).exists_subset_of_mem_open hx (is_open_sigma_iff.1 u_open i), exact ⟨(sigma.mk i) '' v, mem_Union.2 ⟨i, mem_image_of_mem _ vs⟩, mem_image_of_mem _ xv, image_subset_iff.2 hv⟩ } end /-- A countable disjoint union of second countable spaces is second countable. -/ instance [encodable ι] [∀ i, second_countable_topology (E i)] : second_countable_topology (Σ i, E i) := begin let b := (⋃ (i : ι), (λ u, ((sigma.mk i) '' u : set (Σ i, E i))) '' (countable_basis (E i))), have A : is_topological_basis b := is_topological_basis.sigma (λ i, is_basis_countable_basis _), have B : b.countable := countable_Union (λ i, countable.image (countable_countable_basis _) _), exact A.second_countable_topology B, end end sigma section sum omit t variables {β : Type*} [topological_space α] [topological_space β] /-- In a sum space `α ⊕ β`, one can form a topological basis by taking the union of topological bases on each of the two components. -/ lemma is_topological_basis.sum {s : set (set α)} (hs : is_topological_basis s) {t : set (set β)} (ht : is_topological_basis t) : is_topological_basis (((λ u, sum.inl '' u) '' s) ∪ ((λ u, sum.inr '' u) '' t)) := begin apply is_topological_basis_of_open_of_nhds, { assume u hu, cases hu, { rcases hu with ⟨w, hw, rfl⟩, exact open_embedding_inl.is_open_map w (hs.is_open hw) }, { rcases hu with ⟨w, hw, rfl⟩, exact open_embedding_inr.is_open_map w (ht.is_open hw) } }, { rintros x u hxu u_open, cases x, { have h'x : x ∈ sum.inl ⁻¹' u := hxu, obtain ⟨v, vs, xv, vu⟩ : ∃ (v : set α) (H : v ∈ s), x ∈ v ∧ v ⊆ sum.inl ⁻¹' u := hs.exists_subset_of_mem_open h'x (is_open_sum_iff.1 u_open).1, exact ⟨sum.inl '' v, mem_union_left _ (mem_image_of_mem _ vs), mem_image_of_mem _ xv, image_subset_iff.2 vu⟩ }, { have h'x : x ∈ sum.inr ⁻¹' u := hxu, obtain ⟨v, vs, xv, vu⟩ : ∃ (v : set β) (H : v ∈ t), x ∈ v ∧ v ⊆ sum.inr ⁻¹' u := ht.exists_subset_of_mem_open h'x (is_open_sum_iff.1 u_open).2, exact ⟨sum.inr '' v, mem_union_right _ (mem_image_of_mem _ vs), mem_image_of_mem _ xv, image_subset_iff.2 vu⟩ } } end /-- A sum type of two second countable spaces is second countable. -/ instance [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α ⊕ β) := begin let b := (λ u, sum.inl '' u) '' (countable_basis α) ∪ (λ u, sum.inr '' u) '' (countable_basis β), have A : is_topological_basis b := (is_basis_countable_basis α).sum (is_basis_countable_basis β), have B : b.countable := (countable.image (countable_countable_basis _) _).union (countable.image (countable_countable_basis _) _), exact A.second_countable_topology B, end end sum end topological_space open topological_space variables {α β : Type*} [topological_space α] [topological_space β] {f : α → β} protected lemma inducing.second_countable_topology [second_countable_topology β] (hf : inducing f) : second_countable_topology α := by { rw hf.1, exact second_countable_topology_induced α β f } protected lemma embedding.second_countable_topology [second_countable_topology β] (hf : embedding f) : second_countable_topology α := hf.1.second_countable_topology
0a6e0437fc6134f48bdb1be46ef3a2930328866a
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/data/to_string.lean
580383c2d72025610a65f21192ef5e49c64128a0
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
2,843
lean
/- Copyright (c) 2016 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.string.basic init.data.bool.basic init.data.subtype.basic import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div import init.data.repr open sum subtype nat universes u v /-- Convert the object into a string for tracing/display purposes. Similar to Haskell's `show`. See also `has_repr`, which is used to output a string which is a valid lean code. See also `has_to_format` and `has_to_tactic_format`, `format` has additional support for colours and pretty printing multilines. -/ class has_to_string (α : Type u) := (to_string : α → string) def to_string {α : Type u} [has_to_string α] : α → string := has_to_string.to_string instance : has_to_string string := ⟨λ s, s⟩ instance : has_to_string bool := ⟨λ b, cond b "tt" "ff"⟩ instance {p : Prop} : has_to_string (decidable p) := -- Remark: type class inference will not consider local instance `b` in the new elaborator ⟨λ b : decidable p, @ite p b _ "tt" "ff"⟩ protected def list.to_string_aux {α : Type u} [has_to_string α] : bool → list α → string | b [] := "" | tt (x::xs) := to_string x ++ list.to_string_aux ff xs | ff (x::xs) := ", " ++ to_string x ++ list.to_string_aux ff xs protected def list.to_string {α : Type u} [has_to_string α] : list α → string | [] := "[]" | (x::xs) := "[" ++ list.to_string_aux tt (x::xs) ++ "]" instance {α : Type u} [has_to_string α] : has_to_string (list α) := ⟨list.to_string⟩ instance : has_to_string unit := ⟨λ u, "star"⟩ instance : has_to_string nat := ⟨λ n, repr n⟩ instance : has_to_string char := ⟨λ c, c.to_string⟩ instance (n : nat) : has_to_string (fin n) := ⟨λ f, to_string f.val⟩ instance : has_to_string unsigned := ⟨λ n, to_string n.val⟩ instance {α : Type u} [has_to_string α] : has_to_string (option α) := ⟨λ o, match o with | none := "none" | (some a) := "(some " ++ to_string a ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_to_string α] [has_to_string β] : has_to_string (α ⊕ β) := ⟨λ s, match s with | (inl a) := "(inl " ++ to_string a ++ ")" | (inr b) := "(inr " ++ to_string b ++ ")" end⟩ instance {α : Type u} {β : Type v} [has_to_string α] [has_to_string β] : has_to_string (α × β) := ⟨λ ⟨a, b⟩, "(" ++ to_string a ++ ", " ++ to_string b ++ ")"⟩ instance {α : Type u} {β : α → Type v} [has_to_string α] [s : ∀ x, has_to_string (β x)] : has_to_string (sigma β) := ⟨λ ⟨a, b⟩, "⟨" ++ to_string a ++ ", " ++ to_string b ++ "⟩"⟩ instance {α : Type u} {p : α → Prop} [has_to_string α] : has_to_string (subtype p) := ⟨λ s, to_string (val s)⟩
538ad5bdc312be33b9e82c266b0e5a5e7bc57a16
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/polynomial/basic.lean
75af008301507b86a0b8d8906b6cb2279ba0df0f
[ "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
33,746
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`. * Notation to refer to `polynomial R`, as `R[X]` or `R[t]`. ## Implementation Polynomials are defined using `add_monoid_algebra R ℕ`, where `R` is a semiring. The variable `X` commutes with every polynomial `p`: lemma `X_mul` proves the identity `X * p = p * X`. The relationship to `add_monoid_algebra R ℕ` is through a structure to make polynomials 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 `R[X]` 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 ℕ) localized "notation (name := polynomial) R`[X]`:9000 := polynomial R" in polynomial open add_monoid_algebra finsupp function open_locale big_operators polynomial namespace polynomial universes u variables {R : Type u} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q : R[X]} lemma forall_iff_forall_finsupp (P : R[X] → 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 : R[X] → Prop) : (∃ p, P p) ↔ ∃ (q : add_monoid_algebra R ℕ), P ⟨q⟩ := ⟨λ ⟨⟨p⟩, hp⟩, ⟨p, hp⟩, λ ⟨q, hq⟩, ⟨⟨q⟩, hq⟩ ⟩ @[simp] lemma eta (f : R[X]) : polynomial.of_finsupp f.to_finsupp = f := by cases f; refl /-! ### Conversions to and from `add_monoid_algebra` Since `R[X]` is not defeq to `add_monoid_algebra R ℕ`, but instead is a structure wrapping it, we have to copy across all the arithmetic operators manually, along with the lemmas about how they unfold around `polynomial.of_finsupp` and `polynomial.to_finsupp`. -/ section add_monoid_algebra @[irreducible] private def add : R[X] → R[X] → R[X] | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg {R : Type u} [ring R] : R[X] → R[X] | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : R[X] → R[X] → R[X] | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero R[X] := ⟨⟨0⟩⟩ instance : has_one R[X] := ⟨⟨1⟩⟩ instance : has_add R[X] := ⟨add⟩ instance {R : Type u} [ring R] : has_neg R[X] := ⟨neg⟩ instance {R : Type u} [ring R] : has_sub R[X] := ⟨λ a b, a + -b⟩ instance : has_mul R[X] := ⟨mul⟩ instance {S : Type*} [smul_zero_class S R] : smul_zero_class S R[X] := { smul := λ r p, ⟨r • p.to_finsupp⟩, smul_zero := λ a, congr_arg of_finsupp (smul_zero a) } @[priority 1] -- to avoid a bug in the `ring` tactic instance has_pow : has_pow R[X] ℕ := { pow := λ p n, npow_rec n p } @[simp] lemma of_finsupp_zero : (⟨0⟩ : R[X]) = 0 := rfl @[simp] lemma of_finsupp_one : (⟨1⟩ : R[X]) = 1 := rfl @[simp] lemma of_finsupp_add {a b} : (⟨a + b⟩ : R[X]) = ⟨a⟩ + ⟨b⟩ := show _ = add _ _, by rw add @[simp] lemma of_finsupp_neg {R : Type u} [ring R] {a} : (⟨-a⟩ : R[X]) = -⟨a⟩ := show _ = neg _, by rw neg @[simp] lemma of_finsupp_sub {R : Type u} [ring R] {a b} : (⟨a - b⟩ : R[X]) = ⟨a⟩ - ⟨b⟩ := by { rw [sub_eq_add_neg, of_finsupp_add, of_finsupp_neg], refl } @[simp] lemma of_finsupp_mul (a b) : (⟨a * b⟩ : R[X]) = ⟨a⟩ * ⟨b⟩ := show _ = mul _ _, by rw mul @[simp] lemma of_finsupp_smul {S : Type*} [smul_zero_class S R] (a : S) (b) : (⟨a • b⟩ : R[X]) = (a • ⟨b⟩ : R[X]) := rfl @[simp] lemma of_finsupp_pow (a) (n : ℕ) : (⟨a ^ n⟩ : R[X]) = ⟨a⟩ ^ n := begin change _ = npow_rec n _, induction n, { simp [npow_rec], } , { simp [npow_rec, n_ih, pow_succ] } end @[simp] lemma to_finsupp_zero : (0 : R[X]).to_finsupp = 0 := rfl @[simp] lemma to_finsupp_one : (1 : R[X]).to_finsupp = 1 := rfl @[simp] lemma to_finsupp_add (a b : R[X]) : (a + b).to_finsupp = a.to_finsupp + b.to_finsupp := by { cases a, cases b, rw ←of_finsupp_add } @[simp] lemma to_finsupp_neg {R : Type u} [ring R] (a : R[X]) : (-a).to_finsupp = -a.to_finsupp := by { cases a, rw ←of_finsupp_neg } @[simp] lemma to_finsupp_sub {R : Type u} [ring R] (a b : R[X]) : (a - b).to_finsupp = a.to_finsupp - b.to_finsupp := by { rw [sub_eq_add_neg, ←to_finsupp_neg, ←to_finsupp_add], refl } @[simp] lemma to_finsupp_mul (a b : R[X]) : (a * b).to_finsupp = a.to_finsupp * b.to_finsupp := by { cases a, cases b, rw ←of_finsupp_mul } @[simp] lemma to_finsupp_smul {S : Type*} [smul_zero_class S R] (a : S) (b : R[X]) : (a • b).to_finsupp = a • b.to_finsupp := rfl @[simp] lemma to_finsupp_pow (a : R[X]) (n : ℕ) : (a ^ n).to_finsupp = a.to_finsupp ^ n := by { cases a, rw ←of_finsupp_pow } 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 R[X] a | ⟨x⟩ ⟨y⟩ h := congr_arg _ $ ha.finsupp (polynomial.of_finsupp.inj h) lemma to_finsupp_injective : function.injective (to_finsupp : R[X] → add_monoid_algebra _ _) := λ ⟨x⟩ ⟨y⟩, congr_arg _ @[simp] lemma to_finsupp_inj {a b : R[X]} : a.to_finsupp = b.to_finsupp ↔ a = b := to_finsupp_injective.eq_iff @[simp] lemma to_finsupp_eq_zero {a : R[X]} : a.to_finsupp = 0 ↔ a = 0 := by rw [←to_finsupp_zero, to_finsupp_inj] @[simp] lemma to_finsupp_eq_one {a : R[X]} : a.to_finsupp = 1 ↔ a = 1 := by rw [←to_finsupp_one, to_finsupp_inj] /-- A more convenient spelling of `polynomial.of_finsupp.inj_eq` in terms of `iff`. -/ lemma of_finsupp_inj {a b} : (⟨a⟩ : R[X]) = ⟨b⟩ ↔ a = b := iff_of_eq of_finsupp.inj_eq @[simp] lemma of_finsupp_eq_zero {a} : (⟨a⟩ : R[X]) = 0 ↔ a = 0 := by rw [←of_finsupp_zero, of_finsupp_inj] @[simp] lemma of_finsupp_eq_one {a} : (⟨a⟩ : R[X]) = 1 ↔ a = 1 := by rw [←of_finsupp_one, of_finsupp_inj] instance : inhabited R[X] := ⟨0⟩ instance : has_nat_cast R[X] := ⟨λ n, polynomial.of_finsupp n⟩ instance : semiring R[X] := function.injective.semiring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul (λ _ _, to_finsupp_smul _ _) to_finsupp_pow (λ _, rfl) instance {S} [monoid S] [distrib_mul_action S R] : distrib_mul_action S R[X] := function.injective.distrib_mul_action ⟨to_finsupp, to_finsupp_zero, to_finsupp_add⟩ to_finsupp_injective to_finsupp_smul instance {S} [monoid S] [distrib_mul_action S R] [has_faithful_smul S R] : has_faithful_smul S R[X] := { 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 R[X] := function.injective.module _ ⟨to_finsupp, to_finsupp_zero, to_finsupp_add⟩ to_finsupp_injective to_finsupp_smul 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₂ R[X] := ⟨by { rintros _ _ ⟨⟩, simp_rw [←of_finsupp_smul, smul_comm] }⟩ instance {S₁ S₂} [has_smul 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₂ R[X] := ⟨by { rintros _ _ ⟨⟩, simp_rw [←of_finsupp_smul, smul_assoc] }⟩ instance is_scalar_tower_right {α K : Type*} [semiring K] [distrib_smul α K] [is_scalar_tower α K K] : is_scalar_tower α K[X] K[X] := ⟨by rintros _ ⟨⟩ ⟨⟩; simp_rw [smul_eq_mul, ← of_finsupp_smul, ← of_finsupp_mul, ← of_finsupp_smul, smul_mul_assoc]⟩ instance {S} [monoid S] [distrib_mul_action S R] [distrib_mul_action Sᵐᵒᵖ R] [is_central_scalar S R] : is_central_scalar S R[X] := ⟨by { rintros _ ⟨⟩, simp_rw [←of_finsupp_smul, op_smul_eq_smul] }⟩ instance [subsingleton R] : unique R[X] := { uniq := by { rintros ⟨x⟩, refine congr_arg of_finsupp _, simp }, .. polynomial.inhabited } variable (R) /-- Ring isomorphism between `R[X]` and `add_monoid_algebra R ℕ`. This is just an implementation detail, but it can be useful to transfer results from `finsupp` to polynomials. -/ @[simps apply symm_apply] def to_finsupp_iso : R[X] ≃+* add_monoid_algebra R ℕ := { to_fun := to_finsupp, inv_fun := of_finsupp, left_inv := λ ⟨p⟩, rfl, right_inv := λ p, rfl, map_mul' := to_finsupp_mul, map_add' := to_finsupp_add } end add_monoid_algebra variable {R} lemma of_finsupp_sum {ι : Type*} (s : finset ι) (f : ι → add_monoid_algebra R ℕ) : (⟨∑ i in s, f i⟩ : R[X]) = ∑ i in s, ⟨f i⟩ := map_sum (to_finsupp_iso R).symm f s lemma to_finsupp_sum {ι : Type*} (s : finset ι) (f : ι → R[X]) : (∑ i in s, f i : R[X]).to_finsupp = ∑ i in s, (f i).to_finsupp := map_sum (to_finsupp_iso R) f s /-- The set of all `n` such that `X^n` has a non-zero coefficient. -/ @[simp] def support : R[X] → finset ℕ | ⟨p⟩ := p.support @[simp] lemma support_of_finsupp (p) : support (⟨p⟩ : R[X]) = p.support := by rw support @[simp] lemma support_zero : (0 : R[X]).support = ∅ := rfl @[simp] lemma support_eq_empty : p.support = ∅ ↔ p = 0 := by { rcases p, simp [support] } 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] R[X] := { to_fun := λ t, ⟨finsupp.single n t⟩, map_add' := by simp, map_smul' := by simp [←of_finsupp_smul] } @[simp] lemma to_finsupp_monomial (n : ℕ) (r : R) : (monomial n r).to_finsupp = finsupp.single n r := by simp [monomial] @[simp] lemma of_finsupp_single (n : ℕ) (r : R) : (⟨finsupp.single n r⟩ : R[X]) = monomial n r := by simp [monomial] @[simp] lemma monomial_zero_right (n : ℕ) : monomial n (0 : R) = 0 := (monomial n).map_zero -- This is not a `simp` lemma as `monomial_zero_left` is more general. lemma monomial_zero_one : monomial 0 (1 : R) = 1 := rfl -- TODO: can't we just delete this one? lemma monomial_add (n : ℕ) (r s : R) : monomial n (r + s) = monomial n r + monomial n s := (monomial n).map_add _ _ lemma monomial_mul_monomial (n m : ℕ) (r s : R) : monomial n r * monomial m s = monomial (n + m) (r * s) := to_finsupp_injective $ by simp only [to_finsupp_monomial, to_finsupp_mul, 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) := to_finsupp_injective $ by simp lemma monomial_injective (n : ℕ) : function.injective (monomial n : R → R[X]) := (to_finsupp_iso R).symm.injective.comp (single_injective n) @[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 [←of_finsupp_add, support], exact support_add end /-- `C a` is the constant polynomial `a`. `C` is provided as a ring homomorphism. -/ def C : R →+* R[X] := { 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 @[simp] lemma to_finsupp_C (a : R) : (C a).to_finsupp = single 0 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 : R[X]) := map_nat_cast C 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 : R[X] := 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 @[simp] lemma to_finsupp_X : X.to_finsupp = finsupp.single 1 (1 : R) := rfl /-- `X` commutes with everything, even when the coefficients are noncommutative. -/ lemma X_mul : X * p = p * X := begin rcases p, simp only [X, ←of_finsupp_single, ←of_finsupp_mul, 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 /-- Prefer putting constants to the left of `X`. This lemma is the loop-avoiding `simp` version of `polynomial.X_mul`. -/ @[simp] lemma X_mul_C (r : R) : X * C r = C r * X := X_mul /-- Prefer putting constants to the left of `X ^ n`. This lemma is the loop-avoiding `simp` version of `X_pow_mul`. -/ @[simp] lemma X_pow_mul_C (r : R) (n : ℕ) : X^n * C r = C r * X^n := X_pow_mul lemma X_pow_mul_assoc {n : ℕ} : (p * X^n) * q = (p * q) * X^n := by rw [mul_assoc, X_pow_mul, ←mul_assoc] /-- Prefer putting constants to the left of `X ^ n`. This lemma is the loop-avoiding `simp` version of `X_pow_mul_assoc`. -/ @[simp] lemma X_pow_mul_assoc_C {n : ℕ} (r : R) : (p * X^n) * C r = p * C r * X^n := X_pow_mul_assoc lemma commute_X (p : R[X]) : commute X p := X_mul lemma commute_X_pow (p : R[X]) (n : ℕ) : commute (X ^ n) p := X_pow_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`. -/ @[simp] def coeff : R[X] → ℕ → R | ⟨p⟩ := p lemma coeff_injective : injective (coeff : R[X] → ℕ → R) := by { rintro ⟨p⟩ ⟨q⟩, simp only [coeff, fun_like.coe_fn_eq, imp_self] } @[simp] lemma coeff_inj : p.coeff = q.coeff ↔ p = q := coeff_injective.eq_iff lemma to_finsupp_apply (f : R[X]) (i) : f.to_finsupp i = f.coeff i := by cases f; refl lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 := by { simp only [←of_finsupp_single, coeff, linear_map.coe_mk], rw finsupp.single_apply } @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : R[X]) n = 0 := rfl @[simp] lemma coeff_one_zero : coeff (1 : R[X]) 0 = 1 := by { rw [← monomial_zero_one, coeff_monomial], simp } @[simp] lemma coeff_X_one : coeff (X : R[X]) 1 = 1 := coeff_monomial @[simp] lemma coeff_X_zero : coeff (X : R[X]) 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 : R[X]) n = if 1 = n then 1 else 0 := coeff_monomial lemma coeff_X_of_ne_one {n : ℕ} (hn : n ≠ 1) : coeff (X : R[X]) 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 } 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] lemma C_mul_X_pow_eq_monomial : ∀ {n : ℕ}, C a * X ^ n = monomial n a | 0 := mul_one _ | (n+1) := by rw [pow_succ', ←mul_assoc, C_mul_X_pow_eq_monomial, X, monomial_mul_monomial, mul_one] @[simp] lemma to_finsupp_C_mul_X_pow (a : R) (n : ℕ) : (C a * X ^ n).to_finsupp = finsupp.single n a := by rw [C_mul_X_pow_eq_monomial, to_finsupp_monomial] lemma C_mul_X_eq_monomial : C a * X = monomial 1 a := by rw [← C_mul_X_pow_eq_monomial, pow_one] @[simp] lemma to_finsupp_C_mul_X (a : R) : (C a * X).to_finsupp = finsupp.single 1 a := by rw [C_mul_X_eq_monomial, to_finsupp_monomial] lemma C_injective : injective (C : R → R[X]) := monomial_injective 0 @[simp] lemma C_inj : C a = C b ↔ a = b := C_injective.eq_iff @[simp] lemma C_eq_zero : C a = 0 ↔ a = 0 := C_injective.eq_iff' (map_zero C) lemma subsingleton_iff_subsingleton : subsingleton R[X] ↔ subsingleton R := ⟨@injective.subsingleton _ _ _ C_injective, by { introI, apply_instance } ⟩ theorem nontrivial.of_polynomial_ne (h : p ≠ q) : nontrivial R := (subsingleton_or_nontrivial R).resolve_left $ λ hI, h $ by exactI subsingleton.elim _ _ lemma forall_eq_iff_forall_eq : (∀ f g : R[X], f = g) ↔ (∀ a b : R, a = b) := by simpa only [← subsingleton_iff] using subsingleton_iff_subsingleton theorem ext_iff {p q : R[X]} : p = q ↔ ∀ n, coeff p n = coeff q n := by { rcases p, rcases q, simp [coeff, finsupp.ext_iff] } @[ext] lemma ext {p q : R[X]} : (∀ n, coeff p n = coeff q n) → p = q := ext_iff.2 /-- Monomials generate the additive monoid of polynomials. -/ lemma add_submonoid_closure_set_of_eq_monomial : add_submonoid.closure {p : R[X] | ∃ n a, p = monomial n a} = ⊤ := begin apply top_unique, rw [← add_submonoid.map_equiv_top (to_finsupp_iso R).symm.to_add_equiv, ← finsupp.add_closure_set_of_eq_single, add_monoid_hom.map_mclosure], refine add_submonoid.closure_mono (set.image_subset_iff.2 _), rintro _ ⟨n, a, rfl⟩, exact ⟨n, a, polynomial.of_finsupp_single _ _⟩, end lemma add_hom_ext {M : Type*} [add_monoid M] {f g : R[X] →+ M} (h : ∀ n a, f (monomial n a) = g (monomial n a)) : f = g := add_monoid_hom.eq_of_eq_on_mdense add_submonoid_closure_set_of_eq_monomial $ by { rintro p ⟨n, a, rfl⟩, exact h n a } @[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : R[X] →+ 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 : R[X] →ₗ[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 : R[X]) : p = 0 := by rw [←one_smul R p, ←h, zero_smul] section fewnomials lemma support_monomial (n) {a : R} (H : a ≠ 0) : (monomial n a).support = singleton n := by rw [←of_finsupp_single, support, finsupp.support_single_ne_zero _ H] lemma support_monomial' (n) (a : R) : (monomial n a).support ⊆ singleton n := by { rw [←of_finsupp_single, support], exact finsupp.support_single_subset } lemma support_C_mul_X {c : R} (h : c ≠ 0) : (C c * X).support = singleton 1 := by rw [C_mul_X_eq_monomial, support_monomial 1 h] lemma support_C_mul_X' (c : R) : (C c * X).support ⊆ singleton 1 := by simpa only [C_mul_X_eq_monomial] using support_monomial' 1 c lemma support_C_mul_X_pow (n : ℕ) {c : R} (h : c ≠ 0) : (C c * X ^ n).support = singleton n := by rw [C_mul_X_pow_eq_monomial, support_monomial n h] lemma support_C_mul_X_pow' (n : ℕ) (c : R) : (C c * X ^ n).support ⊆ singleton n := by simpa only [C_mul_X_pow_eq_monomial] using support_monomial' n c open finset lemma support_binomial' (k m : ℕ) (x y : R) : (C x * X ^ k + C y * X ^ m).support ⊆ {k, m} := support_add.trans (union_subset ((support_C_mul_X_pow' k x).trans (singleton_subset_iff.mpr (mem_insert_self k {m}))) ((support_C_mul_X_pow' m y).trans (singleton_subset_iff.mpr (mem_insert_of_mem (mem_singleton_self m))))) lemma support_trinomial' (k m n : ℕ) (x y z : R) : (C x * X ^ k + C y * X ^ m + C z * X ^ n).support ⊆ {k, m, n} := support_add.trans (union_subset (support_add.trans (union_subset ((support_C_mul_X_pow' k x).trans (singleton_subset_iff.mpr (mem_insert_self k {m, n}))) ((support_C_mul_X_pow' m y).trans (singleton_subset_iff.mpr (mem_insert_of_mem (mem_insert_self m {n})))))) ((support_C_mul_X_pow' n z).trans (singleton_subset_iff.mpr (mem_insert_of_mem (mem_insert_of_mem (mem_singleton_self n)))))) end fewnomials 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 @[simp] lemma to_finsupp_X_pow (n : ℕ) : (X ^ n).to_finsupp = finsupp.single n (1 : R) := by rw [X_pow_eq_monomial, to_finsupp_monomial] lemma smul_X_eq_monomial {n} : a • X ^ n = monomial n (a : R) := by rw [X_pow_eq_monomial, smul_monomial, smul_eq_mul, mul_one] lemma support_X_pow (H : ¬(1 : R) = 0) (n : ℕ) : (X ^ n : R[X]).support = singleton n := begin convert support_monomial n H, exact X_pow_eq_monomial n, end lemma support_X_empty (H : (1 : R) = 0) : (X : R[X]).support = ∅ := by rw [X, H, monomial_zero_right, support_zero] lemma support_X (H : ¬(1 : R) = 0) : (X : R[X]).support = singleton 1 := by rw [← pow_one X, support_X_pow H 1] lemma monomial_left_inj {a : R} (ha : a ≠ 0) {i j : ℕ} : (monomial i a) = (monomial j a) ↔ i = j := by simp_rw [←of_finsupp_single, finsupp.single_left_inj ha] lemma binomial_eq_binomial {k l m n : ℕ} {u v : R} (hu : u ≠ 0) (hv : v ≠ 0) : C u * X ^ k + C v * X ^ l = C u * X ^ m + C v * X ^ n ↔ (k = m ∧ l = n) ∨ (u = v ∧ k = n ∧ l = m) ∨ (u + v = 0 ∧ k = l ∧ m = n) := begin simp_rw [C_mul_X_pow_eq_monomial, ←to_finsupp_inj, to_finsupp_add, to_finsupp_monomial], exact finsupp.single_add_single_eq_single_add_single hu hv, end lemma nat_cast_mul (n : ℕ) (p : R[X]) : (n : R[X]) * 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 : R[X]) (f : ℕ → R → S) : S := ∑ n in p.support, f n (p.coeff n) lemma sum_def {S : Type*} [add_comm_monoid S] (p : R[X]) (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 : R[X]) (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 apply to_finsupp_injective, rcases p, rcases q, simp [support, sum, coeff, to_finsupp_sum], refl end @[simp] lemma sum_zero_index {S : Type*} [add_comm_monoid S] (f : ℕ → R → S) : (0 : R[X]).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 : R[X]).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 : R[X]).sum f = f 1 1 := sum_monomial_index 1 1 f hf lemma sum_add_index {S : Type*} [add_comm_monoid S] (p q : R[X]) (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 [←of_finsupp_add, 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 : R[X]) (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 : R[X]) (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 : R[X]) (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, simpa [sum, support, coeff] using finsupp.sum_smul_index hf, end lemma sum_monomial_eq : ∀ p : R[X], p.sum (λ n a, monomial n a) = p | ⟨p⟩ := (of_finsupp_sum _ _).symm.trans (congr_arg _ $ finsupp.sum_single _) lemma sum_C_mul_X_pow_eq (p : R[X]) : p.sum (λ n a, C a * X ^ n) = p := by simp_rw [C_mul_X_pow_eq_monomial, sum_monomial_eq] /-- `erase p n` is the polynomial `p` in which the `X^n` term has been erased. -/ @[irreducible] definition erase (n : ℕ) : R[X] → R[X] | ⟨p⟩ := ⟨p.erase n⟩ @[simp] lemma to_finsupp_erase (p : R[X]) (n : ℕ) : to_finsupp (p.erase n) = (p.to_finsupp).erase n := by { rcases p, simp only [erase] } @[simp] lemma of_finsupp_erase (p : add_monoid_algebra R ℕ) (n : ℕ) : (⟨p.erase n⟩ : R[X]) = (⟨p⟩ : R[X]).erase n := by { rcases p, simp only [erase] } @[simp] lemma support_erase (p : R[X]) (n : ℕ) : support (p.erase n) = (support p).erase n := by { rcases p, simp only [support, erase, support_erase] } lemma monomial_add_erase (p : R[X]) (n : ℕ) : monomial n (coeff p n) + p.erase n = p := to_finsupp_injective $ begin rcases p, rw [to_finsupp_add, to_finsupp_monomial, to_finsupp_erase, coeff], exact finsupp.single_add_erase _ _, end lemma coeff_erase (p : R[X]) (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 : R[X]).erase n = 0 := to_finsupp_injective $ by simp @[simp] lemma erase_monomial {n : ℕ} {a : R} : erase n (monomial n a) = 0 := to_finsupp_injective $ by simp @[simp] lemma erase_same (p : R[X]) (n : ℕ) : coeff (p.erase n) n = 0 := by simp [coeff_erase] @[simp] lemma erase_ne (p : R[X]) (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 : R[X]` 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 : R[X]) (n : ℕ) (a : R) : R[X] := polynomial.of_finsupp (p.to_finsupp.update n a) lemma coeff_update (p : R[X]) (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], end lemma coeff_update_apply (p : R[X]) (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 : R[X]) (n : ℕ) (a : R) : (p.update n a).coeff n = a := by rw [p.coeff_update_apply, if_pos rfl] lemma coeff_update_ne (p : R[X]) {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 : R[X]) (n : ℕ) : p.update n 0 = p.erase n := by { ext, rw [coeff_update_apply, coeff_erase] } lemma support_update (p : R[X]) (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 : R[X]) (n : ℕ) : support (p.update n 0) = p.support.erase n := by rw [update_zero_eq_erase, support_erase] lemma support_update_ne_zero (p : R[X]) (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 R[X] := function.injective.comm_semiring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul (λ _ _, to_finsupp_smul _ _) to_finsupp_pow (λ _, rfl) end comm_semiring section ring variables [ring R] instance : has_int_cast R[X] := ⟨λ n, of_finsupp n⟩ instance : ring R[X] := function.injective.ring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul to_finsupp_neg to_finsupp_sub (λ _ _, to_finsupp_smul _ _) (λ _ _, to_finsupp_smul _ _) to_finsupp_pow (λ _, rfl) (λ _, rfl) @[simp] lemma coeff_neg (p : R[X]) (n : ℕ) : coeff (-p) n = -coeff p n := by { rcases p, rw [←of_finsupp_neg, coeff, coeff, finsupp.neg_apply] } @[simp] lemma coeff_sub (p q : R[X]) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := by { rcases p, rcases q, rw [←of_finsupp_sub, coeff, coeff, coeff, finsupp.sub_apply] } @[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 : R[X]} : (-p).support = p.support := by { rcases p, rw [←of_finsupp_neg, support, support, finsupp.support_neg] } @[simp] lemma C_eq_int_cast (n : ℤ) : C (n : R) = n := map_int_cast C n end ring instance [comm_ring R] : comm_ring R[X] := function.injective.comm_ring to_finsupp to_finsupp_injective to_finsupp_zero to_finsupp_one to_finsupp_add to_finsupp_mul to_finsupp_neg to_finsupp_sub (λ _ _, to_finsupp_smul _ _) (λ _ _, to_finsupp_smul _ _) to_finsupp_pow (λ _, rfl) (λ _, rfl) section nonzero_semiring variables [semiring R] [nontrivial R] instance : nontrivial R[X] := 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 : R[X]) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) end nonzero_semiring @[simp] lemma nontrivial_iff [semiring R] : nontrivial R[X] ↔ nontrivial R := ⟨λ h, let ⟨r, s, hrs⟩ := @exists_pair_ne _ h in nontrivial.of_polynomial_ne hrs, λ h, @polynomial.nontrivial _ _ h⟩ section repr variables [semiring R] open_locale classical instance [has_repr R] : has_repr R[X] := ⟨λ 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
75fa62042d64263314ae0032050559cfa1508476
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/topology/algebra/nonarchimedean/adic_topology.lean
f06b9d450bba2f3147d67773c8dd996a382df4c5
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,158
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.nonarchimedean.bases import ring_theory.ideal.operations import topology.algebra.uniform_ring /-! # Adic topology Given a commutative ring `R` and an ideal `I` in `R`, this file constructs the unique topology on `R` which is compatible with the ring structure and such that a set is a neighborhood of zero if and only if it contains a power of `I`. This topology is non-archimedean: every neighborhood of zero contains an open subgroup, namely a power of `I`. It also studies the predicate `is_adic` which states that a given topological ring structure is adic, proving a characterization and showing that raising an ideal to a positive power does not change the associated topology. Finally, it defines `with_ideal`, a class registering an ideal in a ring and providing the corresponding adic topology to the type class inference system. ## Main definitions and results * `ideal.adic_basis`: the basis of submodules given by powers of an ideal. * `ideal.adic_topology`: the adic topology associated to an ideal. It has the above basis for neighborhoods of zero. * `ideal.nonarchimedean`: the adic topology is non-archimedean * `is_ideal_adic_iff`: A topological ring is `J`-adic if and only if it admits the powers of `J` as a basis of open neighborhoods of zero. * `with_ideal`: a class registering an ideal in a ring. ## Implementation notes The `I`-adic topology on a ring `R` has a contrived definition using `I^n • ⊤` instead of `I` to make sure it is definitionally equal to the `I`-topology on `R` seen as a `R`-module. -/ variables {R : Type*} [comm_ring R] open set topological_add_group submodule filter open_locale topological_space pointwise namespace ideal lemma adic_basis (I : ideal R) : submodules_ring_basis (λ n : ℕ, (I^n • ⊤ : ideal R)) := { inter := begin suffices : ∀ i j : ℕ, ∃ k, I ^ k ≤ I ^ i ∧ I ^ k ≤ I ^ j, by simpa, intros i j, exact ⟨max i j, pow_le_pow (le_max_left i j), pow_le_pow (le_max_right i j)⟩ end, left_mul := begin suffices : ∀ (a : R) (i : ℕ), ∃ j : ℕ, a • I ^ j ≤ I ^ i, by simpa, intros r n, use n, rintro a ⟨x, hx, rfl⟩, exact (I ^ n).smul_mem r hx end, mul := begin suffices : ∀ (i : ℕ), ∃ (j : ℕ), ↑(I ^ j) * ↑(I ^ j) ⊆ ↑(I ^ i), by simpa, intro n, use n, rintro a ⟨x, b, hx, hb, rfl⟩, exact (I^n).smul_mem x hb end } /-- The adic ring filter basis associated to an ideal `I` is made of powers of `I`. -/ def ring_filter_basis (I : ideal R) := I.adic_basis.to_ring_subgroups_basis.to_ring_filter_basis /-- The adic topology associated to an ideal `I`. This topology admits powers of `I` as a basis of neighborhoods of zero. It is compatible with the ring structure and is non-archimedean. -/ def adic_topology (I : ideal R) : topological_space R := (adic_basis I).topology lemma nonarchimedean (I : ideal R) : @nonarchimedean_ring R _ I.adic_topology := I.adic_basis.to_ring_subgroups_basis.nonarchimedean /-- For the `I`-adic topology, the neighborhoods of zero has basis given by the powers of `I`. -/ lemma has_basis_nhds_zero_adic (I : ideal R) : has_basis (@nhds R I.adic_topology (0 : R)) (λ n : ℕ, true) (λ n, ((I^n : ideal R) : set R)) := ⟨begin intros U, rw I.ring_filter_basis.to_add_group_filter_basis.nhds_zero_has_basis.mem_iff, split, { rintros ⟨-, ⟨i, rfl⟩, h⟩, replace h : ↑(I ^ i) ⊆ U := by simpa using h, use [i, trivial, h] }, { rintros ⟨i, -, h⟩, exact ⟨(I^i : ideal R), ⟨i, by simp⟩, h⟩ } end⟩ lemma has_basis_nhds_adic (I : ideal R) (x : R) : has_basis (@nhds R I.adic_topology x) (λ n : ℕ, true) (λ n, (λ y, x + y) '' (I^n : ideal R)) := begin letI := I.adic_topology, have := I.has_basis_nhds_zero_adic.map (λ y, x + y), rwa map_add_left_nhds_zero x at this end variables (I : ideal R) (M : Type*) [add_comm_group M] [module R M] lemma adic_module_basis : I.ring_filter_basis.submodules_basis (λ n : ℕ, (I^n) • (⊤ : submodule R M)) := { inter := λ i j, ⟨max i j, le_inf_iff.mpr ⟨smul_mono_left $ pow_le_pow (le_max_left i j), smul_mono_left $ pow_le_pow (le_max_right i j)⟩⟩, smul := λ m i, ⟨(I^i • ⊤ : ideal R), ⟨i, rfl⟩, λ a a_in, by { replace a_in : a ∈ I^i := by simpa [(I^i).mul_top] using a_in, exact smul_mem_smul a_in mem_top }⟩ } /-- The topology on a `R`-module `M` associated to an ideal `M`. Submodules $I^n M$, written `I^n • ⊤` form a basis of neighborhoods of zero. -/ def adic_module_topology : topological_space M := @module_filter_basis.topology R M _ I.adic_basis.topology _ _ (I.ring_filter_basis.module_filter_basis (I.adic_module_basis M)) /-- The elements of the basis of neighborhoods of zero for the `I`-adic topology on a `R`-module `M`, seen as open additive subgroups of `M`. -/ def open_add_subgroup (n : ℕ) : @open_add_subgroup R _ I.adic_topology := { is_open' := begin letI := I.adic_topology, convert (I.adic_basis.to_ring_subgroups_basis.open_add_subgroup n).is_open, simp end, ..(I^n).to_add_subgroup} end ideal section is_adic /-- Given a topology on a ring `R` and an ideal `J`, `is_adic J` means the topology is the `J`-adic one. -/ def is_adic [H : topological_space R] (J : ideal R) : Prop := H = J.adic_topology /-- A topological ring is `J`-adic if and only if it admits the powers of `J` as a basis of open neighborhoods of zero. -/ lemma is_adic_iff [top : topological_space R] [topological_ring R] {J : ideal R} : is_adic J ↔ (∀ n : ℕ, is_open ((J^n : ideal R) : set R)) ∧ (∀ s ∈ 𝓝 (0 : R), ∃ n : ℕ, ((J^n : ideal R) : set R) ⊆ s) := begin split, { intro H, change _ = _ at H, rw H, letI := J.adic_topology, split, { intro n, exact (J.open_add_subgroup n).is_open' }, { intros s hs, simpa using J.has_basis_nhds_zero_adic.mem_iff.mp hs } }, { rintro ⟨H₁, H₂⟩, apply topological_add_group.ext, { apply @topological_ring.to_topological_add_group }, { apply (ring_subgroups_basis.to_ring_filter_basis _).to_add_group_filter_basis .is_topological_add_group }, { ext s, letI := ideal.adic_basis J, rw J.has_basis_nhds_zero_adic.mem_iff, split; intro H, { rcases H₂ s H with ⟨n, h⟩, use [n, trivial, h] }, { rcases H with ⟨n, -, hn⟩, rw mem_nhds_iff, refine ⟨_, hn, H₁ n, (J^n).zero_mem⟩ } } } end variables [topological_space R] [topological_ring R] lemma is_ideal_adic_pow {J : ideal R} (h : is_adic J) {n : ℕ} (hn : 0 < n) : is_adic (J^n) := begin rw is_adic_iff at h ⊢, split, { intro m, rw ← pow_mul, apply h.left }, { intros V hV, cases h.right V hV with m hm, use m, refine set.subset.trans _ hm, cases n, { exfalso, exact nat.not_succ_le_zero 0 hn }, rw [← pow_mul, nat.succ_mul], apply ideal.pow_le_pow, apply nat.le_add_left } end lemma is_bot_adic_iff {A : Type*} [comm_ring A] [topological_space A] [topological_ring A] : is_adic (⊥ : ideal A) ↔ discrete_topology A := begin rw is_adic_iff, split, { rintro ⟨h, h'⟩, rw discrete_topology_iff_open_singleton_zero, simpa using h 1 }, { introsI, split, { simp, }, { intros U U_nhds, use 1, simp [mem_of_mem_nhds U_nhds] } }, end end is_adic /-- The ring `R` is equipped with a preferred ideal. -/ class with_ideal (R : Type*) [comm_ring R] := (I : ideal R) namespace with_ideal variables (R) [with_ideal R] @[priority 100] instance : topological_space R := I.adic_topology @[priority 100] instance : nonarchimedean_ring R := ring_subgroups_basis.nonarchimedean _ @[priority 100] instance : uniform_space R := topological_add_group.to_uniform_space R @[priority 100] instance : uniform_add_group R := topological_add_group_is_uniform /-- The adic topology on a `R` module coming from the ideal `with_ideal.I`. This cannot be an instance because `R` cannot be inferred from `M`. -/ def topological_space_module (M : Type*) [add_comm_group M] [module R M] : topological_space M := (I : ideal R).adic_module_topology M /- The next examples are kept to make sure potential future refactors won't break the instance chaining. -/ example : nonarchimedean_ring R := by apply_instance example : topological_ring (uniform_space.completion R) := by apply_instance example (M : Type*) [add_comm_group M] [module R M] : @topological_add_group M (with_ideal.topological_space_module R M) _:= by apply_instance example (M : Type*) [add_comm_group M] [module R M] : @has_continuous_smul R M _ _ (with_ideal.topological_space_module R M) := by apply_instance example (M : Type*) [add_comm_group M] [module R M] : @nonarchimedean_add_group M _ (with_ideal.topological_space_module R M) := submodules_basis.nonarchimedean _ end with_ideal
a1b23d1b4d44b5692c8ccb29a142fc8f49942097
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Parser/Do.lean
d674790317fd1a7da77ae9cb3c2b82cb0d860d3f
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
7,283
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.Parser.Term namespace Lean namespace Parser builtin_initialize registerBuiltinParserAttribute `builtinDoElemParser `doElem builtin_initialize registerBuiltinDynamicParserAttribute `doElemParser `doElem @[inline] def doElemParser (rbp : Nat := 0) : Parser := categoryParser `doElem rbp namespace Term def leftArrow : Parser := unicodeSymbol " ← " " <- " @[builtinTermParser] def liftMethod := leading_parser:minPrec leftArrow >> termParser def doSeqItem := leading_parser ppLine >> doElemParser >> optional "; " def doSeqIndent := leading_parser many1Indent doSeqItem def doSeqBracketed := leading_parser "{" >> withoutPosition (many1 doSeqItem) >> ppLine >> "}" def doSeq := doSeqBracketed <|> doSeqIndent def termBeforeDo := withForbidden "do" termParser attribute [runBuiltinParserAttributeHooks] doSeq termBeforeDo builtin_initialize register_parser_alias "doSeq" doSeq register_parser_alias "termBeforeDo" termBeforeDo def notFollowedByRedefinedTermToken := -- Remark: we don't currently support `open` and `set_option` in `do`-blocks, but we include them in the following list to fix the ambiguity -- "open" command following `do`-block. If we don't add `do`, then users would have to indent `do` blocks or use `{ ... }`. notFollowedBy ("set_option" <|> "open" <|> "if" <|> "match" <|> "let" <|> "have" <|> "do" <|> "dbg_trace" <|> "assert!" <|> "for" <|> "unless" <|> "return" <|> symbol "try") "token at 'do' element" @[builtinDoElemParser] def doLet := leading_parser "let " >> optional "mut " >> letDecl @[builtinDoElemParser] def doLetRec := leading_parser group ("let " >> nonReservedSymbol "rec ") >> letRecDecls def doIdDecl := leading_parser atomic (ident >> optType >> leftArrow) >> doElemParser def doPatDecl := leading_parser atomic (termParser >> leftArrow) >> doElemParser >> optional (checkColGt >> " | " >> doElemParser) @[builtinDoElemParser] def doLetArrow := leading_parser withPosition ("let " >> optional "mut " >> (doIdDecl <|> doPatDecl)) -- We use `letIdDeclNoBinders` to define `doReassign`. -- Motivation: we do not reassign functions, and avoid parser conflict def letIdDeclNoBinders := node `Lean.Parser.Term.letIdDecl $ atomic (ident >> pushNone >> optType >> " := ") >> termParser @[builtinDoElemParser] def doReassign := leading_parser notFollowedByRedefinedTermToken >> (letIdDeclNoBinders <|> letPatDecl) @[builtinDoElemParser] def doReassignArrow := leading_parser notFollowedByRedefinedTermToken >> withPosition (doIdDecl <|> doPatDecl) @[builtinDoElemParser] def doHave := leading_parser "have " >> Term.haveDecl /- In `do` blocks, we support `if` without an `else`. Thus, we use indentation to prevent examples such as ``` if c_1 then if c_2 then action_1 else action_2 ``` from being parsed as ``` if c_1 then { if c_2 then { action_1 } else { action_2 } } ``` We also have special support for `else if` because we don't want to write ``` if c_1 then action_1 else if c_2 then action_2 else action_3 ``` -/ def elseIf := atomic (group (withPosition (" else " >> checkLineEq >> " if "))) -- ensure `if $e then ...` still binds to `e:term` def doIfLetPure := leading_parser " := " >> termParser def doIfLetBind := leading_parser " ← " >> termParser def doIfLet := nodeWithAntiquot "doIfLet" `Lean.Parser.Term.doIfLet <| "let " >> termParser >> (doIfLetPure <|> doIfLetBind) def doIfProp := nodeWithAntiquot "doIfProp" `Lean.Parser.Term.doIfProp <| optIdent >> termParser def doIfCond := withAntiquot (mkAntiquot "doIfCond" none (anonymous := false)) <| doIfLet <|> doIfProp @[builtinDoElemParser] def doIf := leading_parser withPosition $ "if " >> doIfCond >> " then " >> doSeq >> many (checkColGe "'else if' in 'do' must be indented" >> group (elseIf >> doIfCond >> " then " >> doSeq)) >> optional (checkColGe "'else' in 'do' must be indented" >> " else " >> doSeq) @[builtinDoElemParser] def doUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq def doForDecl := leading_parser termParser >> " in " >> withForbidden "do" termParser @[builtinDoElemParser] def doFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq def doMatchAlts := matchAlts (rhsParser := doSeq) @[builtinDoElemParser] def doMatch := leading_parser:leadPrec "match " >> optional Term.generalizingParam >> sepBy1 matchDiscr ", " >> optType >> " with " >> doMatchAlts def doCatch := leading_parser atomic ("catch " >> binderIdent) >> optional (" : " >> termParser) >> darrow >> doSeq def doCatchMatch := leading_parser "catch " >> doMatchAlts def doFinally := leading_parser "finally " >> doSeq @[builtinDoElemParser] def doTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally @[builtinDoElemParser] def doBreak := leading_parser "break" @[builtinDoElemParser] def doContinue := leading_parser "continue" @[builtinDoElemParser] def doReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) @[builtinDoElemParser] def doDbgTrace := leading_parser:leadPrec "dbg_trace " >> ((interpolatedStr termParser) <|> termParser) @[builtinDoElemParser] def doAssert := leading_parser:leadPrec "assert! " >> termParser /- We use `notFollowedBy` to avoid counterintuitive behavior. For example, the `if`-term parser doesn't enforce indentation restrictions, but we don't want it to be used when `doIf` fails. Note that parser priorities would not solve this problem since the `doIf` parser is failing while the `if` parser is succeeding. The first `notFollowedBy` prevents this problem. Consider the `doElem` `x := (a, b⟩` it contains an error since we are using `⟩` instead of `)`. Thus, `doReassign` parser fails. However, `doExpr` would succeed consuming just `x`, and cryptic error message is generated after that. The second `notFollowedBy` prevents this problem. -/ @[builtinDoElemParser] def doExpr := leading_parser notFollowedByRedefinedTermToken >> termParser >> notFollowedBy (symbol ":=" <|> symbol "←" <|> symbol "<-") "unexpected token after 'expr' in 'do' block" @[builtinDoElemParser] def doNested := leading_parser "do " >> doSeq @[builtinTermParser] def «do» := leading_parser:argPrec "do " >> doSeq @[builtinTermParser] def doElem.quot : Parser := leading_parser "`(doElem|" >> incQuotDepth doElemParser >> ")" /- macros for using `unless`, `for`, `try`, `return` as terms. They expand into `do unless ...`, `do for ...`, `do try ...`, and `do return ...` -/ @[builtinTermParser] def termUnless := leading_parser "unless " >> withForbidden "do" termParser >> "do " >> doSeq @[builtinTermParser] def termFor := leading_parser "for " >> sepBy1 doForDecl ", " >> "do " >> doSeq @[builtinTermParser] def termTry := leading_parser "try " >> doSeq >> many (doCatch <|> doCatchMatch) >> optional doFinally @[builtinTermParser] def termReturn := leading_parser:leadPrec withPosition ("return " >> optional (checkLineEq >> termParser)) end Term end Parser end Lean
5d7031ef4bc5b1123ac179de1b9c53854918c5da
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.51.lean
2b67b99eb571b8c791b9841eb05d3c55a39c9ba1
[]
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
418
lean
/- page 95 -/ import standard namespace hide -- BEGIN open nat print definition nat.induction_on print definition nat.cases_on definition induction_on {C : nat → Prop} (n : nat) (fz : C zero) (fs : Π a, C a → C (succ a)) : C n := nat.rec_on n fz fs definition cases_on {C : nat → Prop} (n : nat) (fz : C zero) (fs : Π a, C (succ a)) : C n := nat.rec_on n fz (fun (a : nat) (r : C a), fs a) -- END end hide
2b3e626a9190d24e0406a24c59939d65eec07ab5
1437b3495ef9020d5413178aa33c0a625f15f15f
/analysis/topology/topological_structures.lean
04ccc0947464bfafd9cec210cdf1807dbce08a7f
[ "Apache-2.0" ]
permissive
jean002/mathlib
c66bbb2d9fdc9c03ae07f869acac7ddbfce67a30
dc6c38a765799c99c4d9c8d5207d9e6c9e0e2cfd
refs/heads/master
1,587,027,806,375
1,547,306,358,000
1,547,306,358,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,053
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 Theory of topological monoids, groups and rings. TODO: generalize `topological_monoid` and `topological_add_monoid` to semigroups, or add a type class `topological_operator α (*)`. -/ import order.liminf_limsup import algebra.big_operators algebra.group algebra.pi_instances import data.set.intervals data.equiv.algebra import analysis.topology.topological_space analysis.topology.continuity analysis.topology.uniform_space import ring_theory.ideals open classical set lattice filter topological_space local attribute [instance] classical.prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_monoid /-- A topological monoid is a monoid in which the multiplication is continuous as a function `α × α → α`. -/ class topological_monoid (α : Type u) [topological_space α] [monoid α] : Prop := (continuous_mul : continuous (λp:α×α, p.1 * p.2)) /-- A topological (additive) monoid is a monoid in which the addition is continuous as a function `α × α → α`. -/ class topological_add_monoid (α : Type u) [topological_space α] [add_monoid α] : Prop := (continuous_add : continuous (λp:α×α, p.1 + p.2)) attribute [to_additive topological_add_monoid] topological_monoid attribute [to_additive topological_add_monoid.mk] topological_monoid.mk attribute [to_additive topological_add_monoid.continuous_add] topological_monoid.continuous_mul section variables [topological_space α] [monoid α] [topological_monoid α] @[to_additive continuous_add'] lemma continuous_mul' : continuous (λp:α×α, p.1 * p.2) := topological_monoid.continuous_mul α @[to_additive continuous_add] lemma continuous_mul [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x * g x) := (hf.prod_mk hg).comp continuous_mul' -- @[to_additive continuous_smul] lemma continuous_pow : ∀ n : ℕ, continuous (λ a : α, a ^ n) | 0 := by simpa using continuous_const | (k+1) := show continuous (λ (a : α), a * a ^ k), from continuous_mul continuous_id (continuous_pow _) @[to_additive tendsto_add'] lemma tendsto_mul' {a b : α} : tendsto (λp:α×α, p.fst * p.snd) (nhds (a, b)) (nhds (a * b)) := continuous_iff_tendsto.mp (topological_monoid.continuous_mul α) (a, b) @[to_additive tendsto_add] lemma tendsto_mul {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, f x * g x) x (nhds (a * b)) := (hf.prod_mk hg).comp (by rw [←nhds_prod_eq]; exact tendsto_mul') @[to_additive tendsto_list_sum] lemma tendsto_list_prod {f : γ → β → α} {x : filter β} {a : γ → α} : ∀l:list γ, (∀c∈l, tendsto (f c) x (nhds (a c))) → tendsto (λb, (l.map (λc, f c b)).prod) x (nhds ((l.map a).prod)) | [] _ := by simp [tendsto_const_nhds] | (f :: l) h := begin simp, exact tendsto_mul (h f (list.mem_cons_self _ _)) (tendsto_list_prod l (assume c hc, h c (list.mem_cons_of_mem _ hc))) end @[to_additive continuous_list_sum] lemma continuous_list_prod [topological_space β] {f : γ → β → α} (l : list γ) (h : ∀c∈l, continuous (f c)) : continuous (λa, (l.map (λc, f c a)).prod) := continuous_iff_tendsto.2 $ assume x, tendsto_list_prod l $ assume c hc, continuous_iff_tendsto.1 (h c hc) x @[to_additive prod.topological_add_monoid] instance [topological_space β] [monoid β] [topological_monoid β] : topological_monoid (α × β) := ⟨continuous.prod_mk (continuous_mul (continuous_fst.comp continuous_fst) (continuous_snd.comp continuous_fst)) (continuous_mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)) ⟩ attribute [instance] prod.topological_add_monoid end section variables [topological_space α] [comm_monoid α] [topological_monoid α] @[to_additive tendsto_multiset_sum] lemma tendsto_multiset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : multiset γ) : (∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, (s.map (λc, f c b)).prod) x (nhds ((s.map a).prod)) := by { rcases s with ⟨l⟩, simp, exact tendsto_list_prod l } @[to_additive tendsto_finset_sum] lemma tendsto_finset_prod {f : γ → β → α} {x : filter β} {a : γ → α} (s : finset γ) : (∀c∈s, tendsto (f c) x (nhds (a c))) → tendsto (λb, s.prod (λc, f c b)) x (nhds (s.prod a)) := tendsto_multiset_prod _ @[to_additive continuous_multiset_sum] lemma continuous_multiset_prod [topological_space β] {f : γ → β → α} (s : multiset γ) : (∀c∈s, continuous (f c)) → continuous (λa, (s.map (λc, f c a)).prod) := by { rcases s with ⟨l⟩, simp, exact continuous_list_prod l } @[to_additive continuous_finset_sum] lemma continuous_finset_prod [topological_space β] {f : γ → β → α} (s : finset γ) : (∀c∈s, continuous (f c)) → continuous (λa, s.prod (λc, f c a)) := continuous_multiset_prod _ end end topological_monoid section topological_group /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ class topological_group (α : Type*) [topological_space α] [group α] extends topological_monoid α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends topological_add_monoid α : Prop := (continuous_neg : continuous (λa:α, -a)) attribute [to_additive topological_add_group] topological_group attribute [to_additive topological_add_group.mk] topological_group.mk attribute [to_additive topological_add_group.continuous_neg] topological_group.continuous_inv attribute [to_additive topological_add_group.to_topological_add_monoid] topological_group.to_topological_monoid variables [topological_space α] [group α] @[to_additive continuous_neg'] lemma continuous_inv' [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv α @[to_additive continuous_neg] lemma continuous_inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := hf.comp continuous_inv' @[to_additive tendsto_neg] lemma tendsto_inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (nhds a)) : tendsto (λx, (f x)⁻¹) x (nhds a⁻¹) := hf.comp (continuous_iff_tendsto.mp (topological_group.continuous_inv α) a) @[to_additive prod.topological_add_group] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous.prod_mk (continuous_inv continuous_fst) (continuous_inv continuous_snd) } attribute [instance] prod.topological_add_group protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_mul continuous_const continuous_id, continuous_inv_fun := continuous_mul continuous_const continuous_id, .. equiv.mul_left a } attribute [to_additive homeomorph.add_left._proof_1] homeomorph.mul_left._proof_1 attribute [to_additive homeomorph.add_left._proof_2] homeomorph.mul_left._proof_2 attribute [to_additive homeomorph.add_left._proof_3] homeomorph.mul_left._proof_3 attribute [to_additive homeomorph.add_left._proof_4] homeomorph.mul_left._proof_4 attribute [to_additive homeomorph.add_left] homeomorph.mul_left @[to_additive is_open_map_add_left] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_mul continuous_id continuous_const, continuous_inv_fun := continuous_mul continuous_id continuous_const, .. equiv.mul_right a } attribute [to_additive homeomorph.add_right._proof_1] homeomorph.mul_right._proof_1 attribute [to_additive homeomorph.add_right._proof_2] homeomorph.mul_right._proof_2 attribute [to_additive homeomorph.add_right._proof_3] homeomorph.mul_right._proof_3 attribute [to_additive homeomorph.add_right._proof_4] homeomorph.mul_right._proof_4 attribute [to_additive homeomorph.add_right] homeomorph.mul_right @[to_additive is_open_map_add_right] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv', continuous_inv_fun := continuous_inv', .. equiv.inv α } attribute [to_additive homeomorph.inv._proof_1] homeomorph.inv._proof_1 attribute [to_additive homeomorph.inv._proof_2] homeomorph.inv._proof_2 attribute [to_additive homeomorph.inv] homeomorph.inv @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ (nhds (1 : α)).sets) : ∃ V ∈ (nhds (1 : α)).sets, ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ (nhds ((1, 1) : α × α)).sets := tendsto_mul' (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ (nhds (1 : α)).sets) : ∃ V ∈ (nhds (1 : α)).sets, ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive nhds_zero_symm] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (nhds (1 : α)) = nhds (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (nhds 1) (nhds 1), { simpa using tendsto_inv (@tendsto_id α (nhds 1)) }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive nhds_translation_add_neg] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (nhds 1) = nhds x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (nhds x) (nhds (x * x⁻¹)), { simpa }, exact tendsto_mul tendsto_id tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (nhds 1) (nhds (1 * x)), { simpa }, exact tendsto_mul tendsto_id tendsto_const_nhds } end end topological_group section topological_add_group variables [topological_space α] [add_group α] lemma continuous_sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp; exact continuous_add hf (continuous_neg hg) lemma continuous_sub' [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_sub continuous_fst continuous_snd lemma tendsto_sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, f x - g x) x (nhds (a - b)) := by simp; exact tendsto_add hf (tendsto_neg hg) lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (nhds 0) = nhds x := nhds_translation_add_neg x end topological_add_group section uniform_add_group /-- A uniform (additive) group is a group in which the addition and negation are uniformly continuous. -/ class uniform_add_group (α : Type u) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) theorem uniform_add_group.mk' {α} [uniform_space α] [add_group α] (h₁ : uniform_continuous (λp:α×α, p.1 + p.2)) (h₂ : uniform_continuous (λp:α, -p)) : uniform_add_group α := ⟨(uniform_continuous_fst.prod_mk (uniform_continuous_snd.comp h₂)).comp h₁⟩ variables [uniform_space α] [add_group α] [uniform_add_group α] lemma uniform_continuous_sub' : uniform_continuous (λp:α×α, p.1 - p.2) := uniform_add_group.uniform_continuous_sub α lemma uniform_continuous_sub [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x - g x) := (hf.prod_mk hg).comp uniform_continuous_sub' lemma uniform_continuous_neg [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, - f x) := have uniform_continuous (λx, 0 - f x), from uniform_continuous_sub uniform_continuous_const hf, by simp * at * lemma uniform_continuous_neg' : uniform_continuous (λx:α, - x) := uniform_continuous_neg uniform_continuous_id lemma uniform_continuous_add [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x + g x) := have uniform_continuous (λx, f x - - g x), from uniform_continuous_sub hf $ uniform_continuous_neg hg, by simp * at * lemma uniform_continuous_add' : uniform_continuous (λp:α×α, p.1 + p.2) := uniform_continuous_add uniform_continuous_fst uniform_continuous_snd instance uniform_add_group.to_topological_add_group : topological_add_group α := { continuous_add := uniform_continuous_add'.continuous, continuous_neg := uniform_continuous_neg'.continuous } instance [uniform_space β] [add_group β] [uniform_add_group β] : uniform_add_group (α × β) := ⟨uniform_continuous.prod_mk (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_fst) (uniform_continuous_snd.comp uniform_continuous_fst)) (uniform_continuous_sub (uniform_continuous_fst.comp uniform_continuous_snd) (uniform_continuous_snd.comp uniform_continuous_snd)) ⟩ lemma uniformity_translate (a : α) : uniformity.map (λx:α×α, (x.1 + a, x.2 + a)) = uniformity := le_antisymm (uniform_continuous_add uniform_continuous_id uniform_continuous_const) (calc uniformity = (uniformity.map (λx:α×α, (x.1 + -a, x.2 + -a))).map (λx:α×α, (x.1 + a, x.2 + a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ uniformity.map (λx:α×α, (x.1 + a, x.2 + a)) : filter.map_mono (uniform_continuous_add uniform_continuous_id uniform_continuous_const)) lemma uniform_embedding_translate (a : α) : uniform_embedding (λx:α, x + a) := begin refine ⟨assume x y, eq_of_add_eq_add_right, _⟩, rw [← uniformity_translate a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end section variables (α) lemma uniformity_eq_comap_nhds_zero : uniformity = comap (λx:α×α, x.2 - x.1) (nhds (0:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap_comp], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_sub' hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_sets_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invarant uniform_continuous_add' hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 0 (b - a) a } end end lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x - y ∈ closure ({0} : set α) := have embedding (λa, a + (y - x)), from (uniform_embedding_translate (y - x)).embedding, show (x, y) ∈ ⋂₀ uniformity.sets ↔ x - y ∈ closure ({0} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_zero α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_eq_empty] end lemma uniform_continuous_of_tendsto_zero [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : tendsto f (nhds 0) (nhds 0)) : uniform_continuous f := begin have : ((λx:β×β, x.2 - x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 - x.1)), { simp only [is_add_group_hom.sub f] }, rw [uniform_continuous, uniformity_eq_comap_nhds_zero α, uniformity_eq_comap_nhds_zero β, tendsto_comap_iff, this], exact tendsto.comp tendsto_comap h end lemma uniform_continuous_of_continuous [uniform_space β] [add_group β] [uniform_add_group β] {f : α → β} [is_add_group_hom f] (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_zero $ suffices tendsto f (nhds 0) (nhds (f 0)), by rwa [is_add_group_hom.zero f] at this, h.tendsto 0 end uniform_add_group section topological_ring universe u' variables (α) [topological_space α] /-- A topological semiring is a semiring where addition and multiplication are continuous. -/ class topological_semiring [semiring α] extends topological_add_monoid α, topological_monoid α : Prop variables [ring α] /-- A topological ring is a ring where the ring operations are continuous. -/ class topological_ring extends topological_add_monoid α, topological_monoid α : Prop := (continuous_neg : continuous (λa:α, -a)) variables [t : topological_ring α] instance topological_ring.to_topological_semiring : topological_semiring α := {..t} instance topological_ring.to_topological_add_group : topological_add_group α := {..t} end topological_ring section topological_comm_ring universe u' variables [topological_space α] [comm_ring α] [topological_ring α] def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, zero := subset_closure S.zero_mem, add := assume x y hx hy, mem_closure2 continuous_add' hx hy $ assume a b, S.add_mem, smul := assume c x hx, have continuous (λx:α, c * x) := continuous_mul continuous_const continuous_id, mem_closure this hx $ assume a, S.mul_mem_left } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl end topological_comm_ring /-- (Partially) ordered topology Also called: partially ordered spaces (pospaces). Usually ordered topology is used for a topology on linear ordered spaces, where the open intervals are open sets. This is a generalization as for each linear order where open interals are open sets, the order relation is closed. -/ class ordered_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed (λp:α×α, p.1 ≤ p.2)) section ordered_topology section preorder variables [topological_space α] [preorder α] [t : ordered_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter (is_closed_ge' a) (is_closed_le' b) lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) (h : {b | f b ≤ g b} ∈ b.sets) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (nhds (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from mem_of_closed_of_tendsto hb this t.is_closed_le' h lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | c ≤ b} ∈ x.sets) : a ≤ b := le_of_tendsto_of_tendsto nt lim tendsto_const_nhds h lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | b ≤ c} ∈ x.sets) : b ≤ a := le_of_tendsto_of_tendsto nt tendsto_const_nhds lim h @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := closure_eq_iff_is_closed.mpr $ is_closed_le hf hg end preorder section partial_order variables [topological_space α] [partial_order α] [t : ordered_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) instance ordered_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [t : ordered_topology α] include t lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf lemma is_open_Ioo {a b : α} : is_open (Ioo a b) := is_open_and (is_open_lt continuous_const continuous_id) (is_open_lt continuous_id continuous_const) lemma is_open_Iio {a : α} : is_open (Iio a) := is_open_lt continuous_id continuous_const end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [t : ordered_topology α] [topological_space β] {f g : β → α} include t section variables (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := assume b ⟨hb₁, hb₂⟩, le_antisymm (by simpa [closure_le_eq hf hg] using hb₁) (not_lt.1 $ assume hb : f b < g b, have {b | f b < g b} ⊆ interior {b | f b ≤ g b}, from (subset_interior_iff_subset_of_open $ is_open_lt hf hg).mpr $ assume x, le_of_lt, have b ∈ interior {b | f b ≤ g b}, from this hb, by exact hb₂ this) lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous_max : continuous (λb, max (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, g b = f b, from assume b hb, (frontier_le_subset_eq hf hg hb).symm, continuous_if this hg hf lemma continuous_min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg end lemma tendsto_max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, max (f b) (g b)) b (nhds (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (max a₁ a₂)), from (hf.prod_mk hg).comp begin rw [←nhds_prod_eq], from continuous_iff_tendsto.mp (continuous_max continuous_fst continuous_snd) _ end lemma tendsto_min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, min (f b) (g b)) b (nhds (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (min a₁ a₂)), from (hf.prod_mk hg).comp begin rw [←nhds_prod_eq], from continuous_iff_tendsto.mp (continuous_min continuous_fst continuous_snd) _ end end decidable_linear_order end ordered_topology /-- Topologies generated by the open intervals. This is restricted to linear orders. Only then it is guaranteed that they are also a ordered topology. -/ class orderable_topology (α : Type*) [t : topological_space α] [partial_order α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}}) section orderable_topology section partial_order variables [topological_space α] [partial_order α] [t : orderable_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : {b | a < b} ∈ (nhds b).sets := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : {b | a ≤ b} ∈ (nhds b).sets := (nhds b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : {a | a < b} ∈ (nhds a).sets := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : {a | a ≤ b} ∈ (nhds a).sets := (nhds a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_orderable {a : α} : nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_orderable {f : β → α} {a : α} {x : filter β} : tendsto f x (nhds a) ↔ (∀a'<a, {b | a' < f b} ∈ x.sets) ∧ (∀a'>a, {b | a' > f b} ∈ x.sets) := by simp [@nhds_eq_orderable α _ _, tendsto_inf, tendsto_infi, tendsto_principal] /-- Also known as squeeze or sandwich theorem. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (nhds a)) (hh : tendsto h b (nhds a)) (hgf : {b | g b ≤ f b} ∈ b.sets) (hfh : {b | f b ≤ h b} ∈ b.sets) : tendsto f b (nhds a) := tendsto_orderable.2 ⟨assume a' h', have {b : β | a' < g b} ∈ b.sets, from (tendsto_orderable.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have {b : β | h b < a'} ∈ b.sets, from (tendsto_orderable.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ lemma nhds_orderable_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : nhds a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal {x | l < x ∧ x < u }) := let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in calc nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) : nhds_eq_orderable ... = (⨅b<a, principal {c | b < c} ⊓ (⨅b>a, principal {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, principal {c | c < u} ⊓ principal {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_orderable_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → {b | l < f b ∧ f b < u } ∈ x.sets) : tendsto f x (nhds a) := by rw [nhds_orderable_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_orderable_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @orderable_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced_eq_comap, nhds_generate_from, @nhds_eq_orderable β _ _], apply le_antisymm, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } end theorem induced_orderable_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @orderable_topology _ (induced f ta) _ := induced_orderable_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) lemma nhds_top_orderable [topological_space α] [order_top α] [orderable_topology α] : nhds (⊤:α) = (⨅l (h₂ : l < ⊤), principal {x | l < x}) := by rw [@nhds_eq_orderable α _ _]; simp [(>)] lemma nhds_bot_orderable [topological_space α] [order_bot α] [orderable_topology α] : nhds (⊥:α) = (⨅l (h₂ : ⊥ < l), principal {x | x < l}) := by rw [@nhds_eq_orderable α _ _]; simp section linear_order variables [topological_space α] [linear_order α] [t : orderable_topology α] include t lemma mem_nhds_orderable_dest {a : α} {s : set α} (hs : s ∈ (nhds a).sets) : ((∃u, u>a) → ∃u, a < u ∧ ∀b, a ≤ b → b < u → b ∈ s) ∧ ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ≤ a → b ∈ s) := let ⟨t₁, ht₁, t₂, ht₂, hts⟩ := mem_inf_sets.mp $ by rw [@nhds_eq_orderable α _ _ _] at hs; exact hs in have ht₁ : ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ∈ t₁) ∧ (∀b, a ≤ b → b ∈ t₁), from infi_sets_induct ht₁ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' < a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨max u a', max_lt hu₁ h, assume b hb, ⟨hs₁ $ lt_of_le_of_lt (le_max_right _ _) hb, hu₂ _ $ lt_of_le_of_lt (le_max_left _ _) hb⟩⟩, assume b hb, ⟨hs₁ $ lt_of_lt_of_le h hb, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), have ht₂ : ((∃u, u>a) → ∃u, a < u ∧ ∀b, b < u → b ∈ t₂) ∧ (∀b, b ≤ a → b ∈ t₂), from infi_sets_induct ht₂ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' > a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨min u a', lt_min hu₁ h, assume b hb, ⟨hs₁ $ lt_of_lt_of_le hb (min_le_right _ _), hu₂ _ $ lt_of_lt_of_le hb (min_le_left _ _)⟩⟩, assume b hb, ⟨hs₁ $ lt_of_le_of_lt hb h, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), and.intro (assume hx, let ⟨u, hu, h⟩ := ht₂.left hx in ⟨u, hu, assume b hb hbu, hts ⟨ht₁.right b hb, h _ hbu⟩⟩) (assume hx, let ⟨l, hl, h⟩ := ht₁.left hx in ⟨l, hl, assume b hbl hb, hts ⟨h _ hbl, ht₂.right b hb⟩⟩) lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ (nhds a).sets ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have nhds a = (⨅p : {l // l < a} × {u // a < u}, principal {x | p.1.val < x ∧ x < p.2.val }), by simp [nhds_orderable_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete h with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end instance orderable_topology.to_ordered_topology : ordered_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } instance orderable_topology.t2_space : t2_space α := by apply_instance instance orderable_topology.regular_space : regular_space α := { regular := assume s a hs ha, have -s ∈ (nhds a).sets, from mem_nhds_sets hs ha, let ⟨h₁, h₂⟩ := mem_nhds_orderable_dest this in have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := h₂ h in match dense_or_discrete hl with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h c (lt_of_lt_of_le hb₁ hbc) (le_of_lt hca) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := h₁ h in match dense_or_discrete hu with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h c (le_of_lt hca) (lt_of_le_of_lt hbc hb₂) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [←sup_principal, inf_sup_left, ht₁a, ht₂a, bot_sup_eq]⟩, ..orderable_topology.t2_space } end linear_order lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_comm_group α] [orderable_topology α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg') $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : mono_image $ image_closure_subset_closure_image continuous_neg' ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [orderable_topology α] [orderable_topology β] lemma nhds_principal_ne_bot_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : nhds a ⊓ principal s ≠ ⊥ := let ⟨a', ha'⟩ := exists_mem_of_ne_empty hs in forall_sets_neq_empty_iff_neq_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in let ⟨hu, hl⟩ := mem_nhds_orderable_dest ht₁ in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ne_empty_iff_exists_mem.mpr ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := hl ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right _ this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ _ ‹l < a'› $ ha.left _ ha', ne_empty_iff_exists_mem.mpr ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma nhds_principal_ne_bot_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) : nhds a ⊓ principal s ≠ ⊥ := let ⟨a', ha'⟩ := exists_mem_of_ne_empty hs in forall_sets_neq_empty_iff_neq_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in let ⟨hu, hl⟩ := mem_nhds_orderable_dest ht₁ in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ne_empty_iff_exists_mem.mpr ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a < a', from lt_of_le_of_ne (ha.left _ ‹a' ∈ s›) this, let ⟨u, hu, hut₁⟩ := hu ⟨a', this⟩ in have ∃a'∈s, a' < u, from classical.by_contradiction $ assume : ¬ ∃a'∈s, a' < u, have ∀a'∈s, u ≤ a', from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ a < u, from not_lt.2 $ ha.right _ this, this ‹a < u›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hut₁ _ (ha.left _ ha') ‹a' < u›, ne_empty_iff_exists_mem.mpr ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f.sets) (hfa : f ⊓ nhds a ≠ ⊥) : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ (f ⊓ nhds a).sets, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := inhabited_of_mem_sets hfa this in have b < b, from lt_of_lt_of_le hxb $ hb _ hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ lower_bounds s) (hsf : s ∈ f.sets) (hfa : f ⊓ nhds a ≠ ⊥) : is_glb s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | a < b} ∈ (f ⊓ nhds a).sets, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_gt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := inhabited_of_mem_sets hfa this in have b < b, from lt_of_le_of_lt (hb _ hxs) hxb, lt_irrefl b this⟩ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s ≠ ∅) (hb : tendsto f (nhds a ⊓ principal s) (nhds b)) : is_lub (f '' s) b := have hnbot : (nhds a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have {x | x < f a'} ∈ (nhds b).sets, from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ha') h.symm, have {x | a' < x} ∈ (nhds a).sets, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ (nhds a).sets, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ (nhds a ⊓ principal s).sets, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', le_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' _ $ mem_image_of_mem _ hx) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_glb s a) (hs : s ≠ ∅) (hb : tendsto f (nhds a ⊓ principal s) (nhds b)) : is_glb (f '' s) b := have hnbot : (nhds a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_glb ha hs, have ∀a'∈s, ¬ b > f a', from assume a' ha' h, have {x | x > f a'} ∈ (nhds b).sets, from mem_nhds_sets (is_open_lt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a > f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' > a, from lt_of_le_of_ne (ha.left _ ha') h, have {x | a' > x} ∈ (nhds a).sets, from mem_nhds_sets (is_open_gt' _) this, have {x | a' > x} ∩ t₁ ∈ (nhds a).sets, from inter_mem_sets this ht₁, have ({x | a' > x} ∩ t₁) ∩ s ∈ (nhds a ⊓ principal s).sets, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x > f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≥ f x, from hf _ hx₃ _ ha' $ le_of_lt hx₁, lt_irrefl _ (lt_of_lt_of_le hxa' ha'x)), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', ge_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' _ $ mem_image_of_mem _ hx) lemma is_glb_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) (ha : is_lub s a) (hs : s ≠ ∅) (hb : tendsto f (nhds a ⊓ principal s) (nhds b)) : is_glb (f '' s) b := have hnbot : (nhds a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs, have ∀a'∈s, ¬ b > f a', from assume a' ha' h, have {x | x > f a'} ∈ (nhds b).sets, from mem_nhds_sets (is_open_lt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a > f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ha') h.symm, have {x | a' < x} ∈ (nhds a).sets, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ (nhds a).sets, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ (nhds a ⊓ principal s).sets, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x > f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≥ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_lt_of_le hxa' ha'x)), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', ge_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' _ $ mem_image_of_mem _ hx) lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_lub ha hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) (sc : is_closed s): a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_glb ha hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) (sc : is_closed s): a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma bdd_below_of_compact {α : Type u} [topological_space α] [linear_order α] [ordered_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases @compact_elim_finite_subcover_image α _ _ _ s (λ x, {b | x < b}) hs (λ x _, is_open_lt continuous_const continuous_id) _ with ⟨t, st, ft, ht⟩, { refine H ((bdd_below_finite ft).imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC _ hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma bdd_above_of_compact {α : Type u} [topological_space α] [linear_order α] [orderable_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_above s := begin by_contra H, letI := classical.DLO α, rcases @compact_elim_finite_subcover_image α _ _ _ s (λ x, {b | b < x}) hs (λ x _, is_open_Iio) _ with ⟨t, st, ft, ht⟩, { refine H ((bdd_above_finite ft).imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (le_of_lt xy) (hC _ hx) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end end order_topology section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] [complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Sup s ∈ closure s := mem_closure_of_is_lub is_lub_Sup hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Inf s ∈ closure s := mem_closure_of_is_glb is_glb_Inf hs lemma Sup_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed is_lub_Sup hs hc lemma Inf_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed is_glb_Inf hs hc /-- A continuous monotone function sends supremum to supremum for nonempty sets. -/ lemma Sup_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_iff_Sup_eq.1 (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Cf xy) is_lub_Sup hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending bot to bot sends supremum to supremum. -/ lemma Sup_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (fbot : f ⊥ = ⊥) {s : set α} : f (Sup s) = Sup (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Sup_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed supremum to indexed supremum. -/ lemma supr_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (supr g) = supr (f ∘ g) := by rw [supr, Sup_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum for nonempty sets. -/ lemma Inf_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Inf s) = Inf (f '' s) := (is_glb_iff_Inf_eq.1 (is_glb_of_is_glb_of_tendsto (λ x hx y hy xy, Cf xy) is_glb_Inf hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending top to top sends infimum to infimum. -/ lemma Inf_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (ftop : f ⊤ = ⊤) {s : set α} : f (Inf s) = Inf (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Inf_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed infimum to indexed infimum. -/ lemma infi_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (infi g) = infi (f ∘ g) := by rw [infi, Inf_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] [conditionally_complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma cSup_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma cSup_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma cInf_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- A continuous monotone function sends supremum to supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma cSup_of_cSup_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine (is_lub_iff_eq_of_is_lub _).1 (is_lub_cSup (mt image_eq_empty.1 ne) (bdd_above_of_bdd_above_of_monotone Cf H)), refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Cf xy) (is_lub_cSup ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed supremum to indexed supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma csupr_of_csupr_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_above (range g)) : f (supr g) = supr (f ∘ g) := by rw [supr, cSup_of_cSup_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cInf_of_cInf_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := begin refine (is_glb_iff_eq_of_is_glb _).1 (is_glb_cInf (mt image_eq_empty.1 ne) (bdd_below_of_bdd_below_of_monotone Cf H)), refine is_glb_of_is_glb_of_tendsto (λx hx y hy xy, Cf xy) (is_glb_cInf ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cinfi_of_cinfi_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_below (range g)): f (infi g) = infi (f ∘ g) := by rw [infi, cInf_of_cInf_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma exists_forall_le_of_compact_of_continuous {α : Type u} [topological_space α] (f : α → β) (hf : continuous f) (s : set α) (hs : compact s) (ne_s : s ≠ ∅) : ∃x∈s, ∀y∈s, f x ≤ f y := begin have C : compact (f '' s) := compact_image hs hf, haveI := has_Inf_to_nonempty β, have B : bdd_below (f '' s) := bdd_below_of_compact C, have : Inf (f '' s) ∈ f '' s := cInf_mem_of_is_closed (mt image_eq_empty.1 ne_s) (closed_of_compact _ C) B, rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩, exact ⟨x, xs, λ y hy, hx.symm ▸ cInf_le B ⟨_, hy, rfl⟩⟩ end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma exists_forall_ge_of_compact_of_continuous {α : Type u} [topological_space α] (f : α → β) (hf : continuous f) (s : set α) (hs : compact s) (ne_s : s ≠ ∅) : ∃x∈s, ∀y∈s, f y ≤ f x := begin have C : compact (f '' s) := compact_image hs hf, haveI := has_Inf_to_nonempty β, have B : bdd_above (f '' s) := bdd_above_of_compact C, have : Sup (f '' s) ∈ f '' s := cSup_mem_of_is_closed (mt image_eq_empty.1 ne_s) (closed_of_compact _ C) B, rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩, exact ⟨x, xs, λ y hy, hx.symm ▸ le_cSup B ⟨_, hy, rfl⟩⟩ end end conditionally_complete_linear_order section liminf_limsup section ordered_topology variables [semilattice_sup α] [topological_space α] [orderable_topology α] lemma is_bounded_le_nhds (a : α) : (nhds a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma is_bounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≤) u := is_bounded_of_le h (is_bounded_le_nhds a) lemma is_cobounded_ge_nhds (a : α) : (nhds a).is_cobounded (≥) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_le_nhds a) lemma is_cobounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≥) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_le_of_tendsto h) end ordered_topology section ordered_topology variables [semilattice_inf α] [topological_space α] [orderable_topology α] lemma is_bounded_ge_nhds (a : α) : (nhds a).is_bounded (≥) := match forall_le_or_exists_lt_inf a with | or.inl h := ⟨a, univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, le_mem_nhds hb⟩ end lemma is_bounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≥) u := is_bounded_of_le h (is_bounded_ge_nhds a) lemma is_cobounded_le_nhds (a : α) : (nhds a).is_cobounded (≤) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_ge_nhds a) lemma is_cobounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≤) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_ge_of_tendsto h) end ordered_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : {a | a < b} ∈ f.sets := let ⟨c, (h : {a : α | a ≤ c} ∈ f.sets), hcb⟩ := exists_lt_of_cInf_lt (ne_empty_iff_exists_mem.2 h) l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt {f : filter α} {b} (h : f.is_bounded (≥)) (l : f.Liminf > b) : {a | a > b} ∈ f.sets := let ⟨c, (h : {a : α | c ≤ a} ∈ f.sets), hbc⟩ := exists_lt_of_lt_cSup (ne_empty_iff_exists_mem.2 h) l in mem_sets_of_superset h $ assume a hca, lt_of_lt_of_le hbc hca /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ nhds a := tendsto_orderable.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (nhds a) = a := cInf_intro (ne_empty_iff_exists_mem.2 $ is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ (nhds a).sets), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ (nhds a).sets), c < b, from match dense_or_discrete hba with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (nhds a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds (a : α) : Liminf (nhds a) = a := cSup_intro (ne_empty_iff_exists_mem.2 $ is_bounded_ge_nhds a) (assume a' (h : {n : α | a' ≤ n} ∈ (nhds a).sets), show a' ≤ a, from mem_of_nhds h) (assume b (hba : b < a), show ∃c (h : {n : α | c ≤ n} ∈ (nhds a).sets), b < c, from match dense_or_discrete hba with | or.inl ⟨c, hbc, hca⟩ := ⟨c, le_mem_nhds hca, hbc⟩ | or.inr ⟨h, _⟩ := ⟨a, (nhds a).sets_of_superset (lt_mem_nhds hba) h, hba⟩ end) /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a), have hb_le : is_bounded (≤) f, from is_bounded_of_le h (is_bounded_le_nhds a), le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hf hb_le hb_ge ... ≤ (nhds a).Limsup : Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (nhds a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) (is_cobounded_of_is_bounded hf hb_le)) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : f.Limsup = a := have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a), le_antisymm (calc f.Limsup ≤ (nhds a).Limsup : Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = f.Liminf : (Liminf_eq_of_le_nhds hf h).symm ... ≤ f.Limsup : Liminf_le_Limsup hf (is_bounded_of_le h (is_bounded_le_nhds a)) hb_ge) end conditionally_complete_linear_order end liminf_limsup end orderable_topology lemma orderable_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_comm_group α] [topological_space α] (h_nhds : ∀a:α, nhds a = (⨅r>0, principal {b | abs (a - b) < r})) : orderable_topology α := orderable_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a + -b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, -sub_eq_add_neg, (sub_eq_add_neg _ _).symm, sub_lt, lt_sub_iff_add_lt, and_comm, sub_lt_iff_lt_add']), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end
ac8c474af045de94e79a60216e3ac2daca9865a4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/unfold_cases_auto.lean
8f370d315a09a05eb5b5b329d44cd96755678d93
[]
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
5,239
lean
/- Copyright (c) 2020 Dany Fabian. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dany Fabian -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.split_ifs import Mathlib.PostPort namespace Mathlib /-! # Unfold cases tactic In Lean, pattern matching expressions are not atomic parts of the syntax, but rather they are compiled down into simpler terms that are later checked by the kernel. This allows Lean to have a minimalistic kernel but can occasionally lead an explosion of cases that need to be considered. What looks like one case in the `match` expression can in fact be compiled into many different cases that all need to proved by case analysis. This tactic automates the process by allowing us to write down an equation `f x = y` where we know that `f x = y` is provably true, but does not hold definitionally. In that case the `unfold_cases` tactic will continue unfolding `f` and introducing `cases` where necessary until the left hand side becomes definitionally equal to the right hand side. Consider a definition as follows: ```lean def myand : bool → bool → bool | ff _ := ff | _ ff := ff | _ _ := tt ``` The equation compiler generates 4 equation lemmas for us: ```lean myand ff ff = ff myand ff tt = ff myand tt ff = ff myand tt tt = tt ``` This is not in line with what one might expect looking at the definition. Whilst it is provably true, that `∀ x, myand ff x = ff` and `∀ x, myand x ff = ff`, we do not get these stronger lemmas from the compiler for free but must in fact prove them using `cases` or some other local reasoning. In other words, the following does not constitute a proof that lean accepts. ```lean example : ∀ x, myand ff x = ff := begin intros, refl end ``` However, you can use `unfold_cases { refl }` to prove `∀ x, myand ff x = ff` and `∀ x, myand x ff = ff`. For definitions with many cases, the savings can be very significant. The term that gets generated for the above definition looks like this: ```lean λ (a a_1 : bool), a.cases_on (a_1.cases_on (id_rhs bool ff) (id_rhs bool ff)) (a_1.cases_on (id_rhs bool ff) (id_rhs bool tt)) ``` When the tactic tries to prove the goal `∀ x, myand ff x = ff`, it starts by `intros`, followed by unfolding the definition: ```lean ⊢ ff.cases_on (x.cases_on (id_rhs bool ff) (id_rhs bool ff)) (x.cases_on (id_rhs bool ff) (id_rhs bool tt)) = ff ``` At this point, it can make progress using `dsimp`. But then it gets stuck: ```lean ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) x = ff ``` Next, it can introduce a case split on `x`. At this point, it has to prove two goals: ```lean ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) ff = ff ⊢ bool.rec (id_rhs bool ff) (id_rhs bool ff) tt = ff ``` Now, however, both goals can be discharged using `refl`. -/ namespace tactic namespace unfold_cases /-- Given an equation `f x = y`, this tactic tries to infer an expression that can be used to do distinction by cases on to make progress. Pre-condition: assumes that the outer-most application cannot be beta-reduced (e.g. `whnf` or `dsimp`). -/ /-- Tries to finish the current goal using the `inner` tactic. If the tactic fails, it tries to find an expression on which to do a distinction by cases and calls itself recursively. The order of operations is significant. Because the unfolding can potentially be infinite, it is important to apply the `inner` tactic at every step. Notice, that if the `inner` tactic succeeds, the recursive unfolding is stopped. -/ /-- Given a target of the form `⊢ f x₁ ... xₙ = y`, unfolds `f` using a delta reduction. -/ end unfold_cases namespace interactive /-- This tactic unfolds the definition of a function or `match` expression. Then it recursively introduces a distinction by cases. The decision what expression to do the distinction on is driven by the pattern matching expression. A typical use case is using `unfold_cases { refl }` to collapse cases that need to be considered in a pattern matching. ```lean have h : foo x = y, by unfold_cases { refl }, rw h, ``` The tactic expects a goal in the form of an equation, possibly universally quantified. We can prove a theorem, even if the various case do not directly correspond to the function definition. Here is an example application of the tactic: ```lean def foo : ℕ → ℕ → ℕ | 0 0 := 17 | (n+2) 17 := 17 | 1 0 := 23 | 0 (n+18) := 15 | 0 17 := 17 | 1 17 := 17 | _ (n+18) := 27 | _ _ := 15 example : ∀ x, foo x 17 = 17 := begin unfold_cases { refl }, end ``` The compiler generates 57 cases for `foo`. However, when we look at the definition, we see that whenever the function is applied to `17` in the second argument, it returns `17`. Proving this property consists of merely considering all the cases, eliminating invalid ones and applying `refl` on the ones which remain. Further examples can be found in `test/unfold_cases.lean`. -/ end Mathlib
023da5259bd7391300fcffe23f771734bc9cdce8
d450724ba99f5b50b57d244eb41fef9f6789db81
/src/instructor/lectures/lecture_23a.lean
9b9b23f06ae78ab89a6ec07af6e8448fd30567e1
[]
no_license
jakekauff/CS2120F21
4f009adeb4ce4a148442b562196d66cc6c04530c
e69529ec6f5d47a554291c4241a3d8ec4fe8f5ad
refs/heads/main
1,693,841,880,030
1,637,604,848,000
1,637,604,848,000
399,946,698
0
0
null
null
null
null
UTF-8
Lean
false
false
5,281
lean
import .lecture_22 import data.set /- ADDITIONAL PROPERTIES OF RELATIONS -/ namespace relations section relation /- Define relation, r, as two-place predicate on a type, β, with notation, x ≺ y, for (r x y). -/ variables {α β : Type} (r : β → β → Prop) local infix `≺`:50 := r -- special relations on an arbitrary type, α def empty_relation := λ a₁ a₂ : α, false def full_relation := λ a₁ a₂ : α, true def id_relation := λ a₁ a₂ : α, a₁ = a₂ -- Analog of the subset relation but now on binary relations -- Note: subrelation is a binary relation on binary relations def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y /- Additional properties of relations -/ def strongly_connected := ∀ x y, x ≺ y ∨ y ≺ x def total := @strongly_connected β /- Note: we will use "total" later to refer to a different property of relations that also satisfy the constraints needed to be "functions." To avoid ambiguity we will prefer the term, "strongly_connected," over "total." -/ def anti_reflexive := ∀ x, ¬ x ≺ x def irreflexive := anti_reflexive r -- sometimes used def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def asymmetric := ∀ ⦃x y⦄, x ≺ y → ¬ y ≺ x /- CLOSURE operations on relations. Given a relation, r, the reflexive, symmetric, or transitive closure of r is the smallest relation that (1) contains r, and (2) contains any additional pairs needed to make the resulting relation reflexive, or symmetric, or transitive, respectively. The reflexive, symmetric, transitive closure of r is the smallest relation (which means *no* unnecessary added pairs) that contains r and has all three properties. Note that the resulting relation will be an equivalence relation. The meaning of this is basically that if anything is connecting to somethiing else, they will end up in the same "equivalence class." We'll see a picture. -/ def reflexive_closure := λ (a b : β), (r a b) ∨ (a = b) def symmetric_closure := λ (a b : β), (r a b) ∨ (r b a) /- Let's look examples. What's in the reflexive closure of { (0,1), (1,2), (2, 3), (3, 4), (4, 5) }? It is often easier to think about these things with the aid of a picture, so let's draw this relation and see in graphical terms what it means to compute its reflexive closure. -/ /- The definitions of the reflexive and symmetric closures of a relation are pretty easy to state. It's a little harder to say what set of pairs is in the transitive closure of a given relation, r. Clearly it's a relation, r', where r' is the smallest relation that contains r and that is transitive. In other words, (tc r) is r with any additional pairs needed to make the result transitive. What set of pairs is this? Well, (1) it contains every pair in r, and (2) if (a,b) is in (tc r) and if (b, c) is in (tc r), then (a, c) must also be in r. The way we will say this formally uses what we call an inductive definition. Inductive definitions allow for "bigger" things to be built whenever there are smaller things of the right kind. Consider this relation, r = { (0,1), (1,2), (2, 3) }. It's transitive closure clearly contains all three of these pairs. What else must it include at a minimum to be transitive? Consider r = { (0,1), (1,2), (2, 3), (3, 4), (4, 5) }. What is its transitive closure? In plain English, if there's a "path" of pairs between two values, a and c, e.g., by way of b where (a,b) and (b,c) are in the relation, then (a,c) will also be in the relation, i.e., the direct connection, (a,c), will also be in the relation. The following formal definition is not one that I expect you to understand immediately, as we have not yet introduced iductive definitions, of which this is an example. But you can just read it as definining the introduction rules, base and trans, for proving one relation is the transitive closure of another, r. The first rule says that if any two objects, a and b, are related in r, then they are also related in tc r (the transitive closure of r). The second rule says that if objects a and b are related in (tc r) and b and c are related in (tc r) then a and c must also be related in r. For any length-2 "path" from a to c (via b), then there's a direct connection: (a,c) ∈ r. -/ inductive tc {α : Type} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c /- Here's a possibly surprising fact: the transitive closure concept *cannot be expressed, defined, nor the concept used, in first-order predicate logic*. The reason is that you can't quantify over relations, and so cannot write "for any relation, r, it's transitive closure is ..." Quantifying over relations just isn't allowed: it's not even part of the syntax of first- order predicate logic. Yet what we've written, formally and understandably, is a concept essential in all kinds of logical reasoning in computer science. That suggests something about teaching first-order logic as a first logic for computer science: there's real reason to doubt that it's the best choice. The higher-order predicate logic of Lean and similar modern proof assistants is strictly more expressive. -/ end relation end relations
762f98e994a16c3c52ebec3f660a893fd201417e
1a61aba1b67cddccce19532a9596efe44be4285f
/library/data/int/power.lean
3dcb7748ecbc75f1d4385b930c3a273c1276afc8
[ "Apache-2.0" ]
permissive
eigengrau/lean
07986a0f2548688c13ba36231f6cdbee82abf4c6
f8a773be1112015e2d232661ce616d23f12874d0
refs/heads/master
1,610,939,198,566
1,441,352,386,000
1,441,352,494,000
41,903,576
0
0
null
1,441,352,210,000
1,441,352,210,000
null
UTF-8
Lean
false
false
1,559
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The power function on the integers. -/ import data.int.basic data.int.order data.int.div algebra.group_power data.nat.power namespace int section migrate_algebra open [classes] algebra local attribute int.integral_domain [instance] local attribute int.linear_ordered_comm_ring [instance] local attribute int.decidable_linear_ordered_comm_ring [instance] definition pow (a : ℤ) (n : ℕ) : ℤ := algebra.pow a n infix [priority int.prio] ^ := pow definition nmul (n : ℕ) (a : ℤ) : ℤ := algebra.nmul n a infix [priority int.prio] `⬝` := nmul definition imul (i : ℤ) (a : ℤ) : ℤ := algebra.imul i a migrate from algebra with int replacing dvd → dvd, sub → sub, has_le.ge → ge, has_lt.gt → gt, min → min, max → max, abs → abs, sign → sign, pow → pow, nmul → nmul, imul → imul hiding add_pos_of_pos_of_nonneg, add_pos_of_nonneg_of_pos, add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg, le_add_of_nonneg_of_le, le_add_of_le_of_nonneg, lt_add_of_nonneg_of_lt, lt_add_of_lt_of_nonneg, lt_of_mul_lt_mul_left, lt_of_mul_lt_mul_right, pos_of_mul_pos_left, pos_of_mul_pos_right end migrate_algebra section open nat theorem of_nat_pow (a n : ℕ) : of_nat (a^n) = (of_nat a)^n := begin induction n with n ih, apply eq.refl, rewrite [pow_succ, nat.pow_succ, of_nat_mul, ih] end end end int
cc033f24d642b702677aa7dff01c7a69c0f3dd41
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/hints/category_theory/exercise3/hint5.lean
6cb7a3cf32dbd5bcd7e87f1c5f615dc9315b7884
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
474
lean
import category_theory.equivalence open category_theory variables {C : Type*} [category C] variables {D : Type*} [category D] lemma equiv_reflects_mono {X Y : C} (f : X ⟶ Y) (e : C ≌ D) (hef : mono (e.functor.map f)) : mono f := begin split, intros Z g h w, apply e.functor.map_injective, rw ← cancel_mono (e.functor.map f), apply e.inverse.map_injective, -- That's ugly! In fact, so ugly that surely `simp` can clean things up from here. sorry end
df9cdf1fc92a515b1601a7a4909395aa19c5ec90
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/593.lean
96e1a14dbeff27b02664e5d5a3cbb6863df1f961
[ "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
406
lean
namespace Foo def Bar.bar : Nat := 1 export Bar (bar) def boo := 2 end Foo namespace Baz #check Foo.bar open Foo in #check bar section Ex1 open Foo (bar) #check bar #check boo -- should fail end Ex1 section Ex2 open Foo hiding bar #check bar -- should fail #check boo end Ex2 section Ex2 open Foo renaming bar → bah #check bah end Ex2 export Foo (bar) export Foo.Bar (bar) #check bar end Baz
85bf3b7bdbc6da5eecc3aed45fadae98071e605a
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/affine_space/combination.lean
c0895a446f6bc9a06e83c6bdcaafbd9aaaf7e898
[ "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
42,894
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 algebra.invertible import algebra.indicator_function import linear_algebra.affine_space.affine_map import linear_algebra.affine_space.affine_subspace import linear_algebra.finsupp import tactic.fin_cases /-! # Affine combinations of points This file defines affine combinations of points. ## Main definitions * `weighted_vsub_of_point` is a general weighted combination of subtractions with an explicit base point, yielding a vector. * `weighted_vsub` uses an arbitrary choice of base point and is intended to be used when the sum of weights is 0, in which case the result is independent of the choice of base point. * `affine_combination` adds the weighted combination to the arbitrary base point, yielding a point rather than a vector, and is intended to be used when the sum of weights is 1, in which case the result is independent of the choice of base point. These definitions are for sums over a `finset`; versions for a `fintype` may be obtained using `finset.univ`, while versions for a `finsupp` may be obtained using `finsupp.support`. ## References * https://en.wikipedia.org/wiki/Affine_space -/ noncomputable theory open_locale big_operators classical affine namespace finset lemma univ_fin2 : (univ : finset (fin 2)) = {0, 1} := by { ext x, fin_cases x; simp } variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [S : affine_space V P] include S variables {ι : Type*} (s : finset ι) variables {ι₂ : Type*} (s₂ : finset ι₂) /-- A weighted sum of the results of subtracting a base point from the given points, as a linear map on the weights. The main cases of interest are where the sum of the weights is 0, in which case the sum is independent of the choice of base point, and where the sum of the weights is 1, in which case the sum added to the base point is independent of the choice of base point. -/ def weighted_vsub_of_point (p : ι → P) (b : P) : (ι → k) →ₗ[k] V := ∑ i in s, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b) @[simp] lemma weighted_vsub_of_point_apply (w : ι → k) (p : ι → P) (b : P) : s.weighted_vsub_of_point p b w = ∑ i in s, w i • (p i -ᵥ b) := by simp [weighted_vsub_of_point, linear_map.sum_apply] /-- The value of `weighted_vsub_of_point`, where the given points are equal. -/ @[simp] lemma weighted_vsub_of_point_apply_const (w : ι → k) (p : P) (b : P) : s.weighted_vsub_of_point (λ _, p) b w = (∑ i in s, w i) • (p -ᵥ b) := by rw [weighted_vsub_of_point_apply, sum_smul] /-- Given a family of points, if we use a member of the family as a base point, the `weighted_vsub_of_point` does not depend on the value of the weights at this point. -/ lemma weighted_vsub_of_point_eq_of_weights_eq (p : ι → P) (j : ι) (w₁ w₂ : ι → k) (hw : ∀ i, i ≠ j → w₁ i = w₂ i) : s.weighted_vsub_of_point p (p j) w₁ = s.weighted_vsub_of_point p (p j) w₂ := begin simp only [finset.weighted_vsub_of_point_apply], congr, ext i, cases eq_or_ne i j with h h, { simp [h], }, { simp [hw i h], }, end /-- The weighted sum is independent of the base point when the sum of the weights is 0. -/ lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w = s.weighted_vsub_of_point p b₂ w := begin apply eq_of_sub_eq_zero, rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←sum_sub_distrib], conv_lhs { congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←sum_smul, h, zero_smul] end /-- The weighted sum, added to the base point, is independent of the base point when the sum of the weights is 1. -/ lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w +ᵥ b₁ = s.weighted_vsub_of_point p b₂ w +ᵥ b₂ := begin erw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc, ←sum_sub_distrib], conv_lhs { congr, skip, congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self] end /-- The weighted sum is unaffected by removing the base point, if present, from the set of points. -/ @[simp] lemma weighted_vsub_of_point_erase (w : ι → k) (p : ι → P) (i : ι) : (s.erase i).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply sum_erase, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by adding the base point, whether or not present, to the set of points. -/ @[simp] lemma weighted_vsub_of_point_insert [decidable_eq ι] (w : ι → k) (p : ι → P) (i : ι) : (insert i s).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply sum_insert_zero, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_of_point_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point p b (set.indicator ↑s₁ w) := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], exact set.sum_indicator_subset_of_eq_zero w (λ i wi, wi • (p i -ᵥ b : V)) h (λ i, zero_smul k _) end /-- A weighted sum, over the image of an embedding, equals a weighted sum with the same points and weights over the original `finset`. -/ lemma weighted_vsub_of_point_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) (b : P) : (s₂.map e).weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point (p ∘ e) b (w ∘ e) := begin simp_rw [weighted_vsub_of_point_apply], exact finset.sum_map _ _ _ end /-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `weighted_vsub_of_point` expressions. -/ lemma sum_smul_vsub_eq_weighted_vsub_of_point_sub (w : ι → k) (p₁ p₂ : ι → P) (b : P) : ∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.weighted_vsub_of_point p₁ b w - s.weighted_vsub_of_point p₂ b w := by simp_rw [weighted_vsub_of_point_apply, ←sum_sub_distrib, ←smul_sub, vsub_sub_vsub_cancel_right] /-- A weighted sum of pairwise subtractions, where the point on the right is constant, expressed as a subtraction involving a `weighted_vsub_of_point` expression. -/ lemma sum_smul_vsub_const_eq_weighted_vsub_of_point_sub (w : ι → k) (p₁ : ι → P) (p₂ b : P) : ∑ i in s, w i • (p₁ i -ᵥ p₂) = s.weighted_vsub_of_point p₁ b w - (∑ i in s, w i) • (p₂ -ᵥ b) := by rw [sum_smul_vsub_eq_weighted_vsub_of_point_sub, weighted_vsub_of_point_apply_const] /-- A weighted sum of pairwise subtractions, where the point on the left is constant, expressed as a subtraction involving a `weighted_vsub_of_point` expression. -/ lemma sum_smul_const_vsub_eq_sub_weighted_vsub_of_point (w : ι → k) (p₂ : ι → P) (p₁ b : P) : ∑ i in s, w i • (p₁ -ᵥ p₂ i) = (∑ i in s, w i) • (p₁ -ᵥ b) - s.weighted_vsub_of_point p₂ b w := by rw [sum_smul_vsub_eq_weighted_vsub_of_point_sub, weighted_vsub_of_point_apply_const] /-- A weighted sum of the results of subtracting a default base point from the given points, as a linear map on the weights. This is intended to be used when the sum of the weights is 0; that condition is specified as a hypothesis on those lemmas that require it. -/ def weighted_vsub (p : ι → P) : (ι → k) →ₗ[k] V := s.weighted_vsub_of_point p (classical.choice S.nonempty) /-- Applying `weighted_vsub` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `weighted_vsub` would involve selecting a preferred base point with `weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero` and then using `weighted_vsub_of_point_apply`. -/ lemma weighted_vsub_apply (w : ι → k) (p : ι → P) : s.weighted_vsub p w = ∑ i in s, w i • (p i -ᵥ (classical.choice S.nonempty)) := by simp [weighted_vsub, linear_map.sum_apply] /-- `weighted_vsub` gives the sum of the results of subtracting any base point, when the sum of the weights is 0. -/ lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b : P) : s.weighted_vsub p w = s.weighted_vsub_of_point p b w := s.weighted_vsub_of_point_eq_of_sum_eq_zero w p h _ _ /-- The value of `weighted_vsub`, where the given points are equal and the sum of the weights is 0. -/ @[simp] lemma weighted_vsub_apply_const (w : ι → k) (p : P) (h : ∑ i in s, w i = 0) : s.weighted_vsub (λ _, p) w = 0 := by rw [weighted_vsub, weighted_vsub_of_point_apply_const, h, zero_smul] /-- The `weighted_vsub` for an empty set is 0. -/ @[simp] lemma weighted_vsub_empty (w : ι → k) (p : ι → P) : (∅ : finset ι).weighted_vsub p w = (0:V) := by simp [weighted_vsub_apply] /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub p w = s₂.weighted_vsub p (set.indicator ↑s₁ w) := weighted_vsub_of_point_indicator_subset _ _ _ h /-- A weighted subtraction, over the image of an embedding, equals a weighted subtraction with the same points and weights over the original `finset`. -/ lemma weighted_vsub_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) : (s₂.map e).weighted_vsub p w = s₂.weighted_vsub (p ∘ e) (w ∘ e) := s₂.weighted_vsub_of_point_map _ _ _ _ /-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `weighted_vsub` expressions. -/ lemma sum_smul_vsub_eq_weighted_vsub_sub (w : ι → k) (p₁ p₂ : ι → P) : ∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.weighted_vsub p₁ w - s.weighted_vsub p₂ w := s.sum_smul_vsub_eq_weighted_vsub_of_point_sub _ _ _ _ /-- A weighted sum of pairwise subtractions, where the point on the right is constant and the sum of the weights is 0. -/ lemma sum_smul_vsub_const_eq_weighted_vsub (w : ι → k) (p₁ : ι → P) (p₂ : P) (h : ∑ i in s, w i = 0) : ∑ i in s, w i • (p₁ i -ᵥ p₂) = s.weighted_vsub p₁ w := by rw [sum_smul_vsub_eq_weighted_vsub_sub, s.weighted_vsub_apply_const _ _ h, sub_zero] /-- A weighted sum of pairwise subtractions, where the point on the left is constant and the sum of the weights is 0. -/ lemma sum_smul_const_vsub_eq_neg_weighted_vsub (w : ι → k) (p₂ : ι → P) (p₁ : P) (h : ∑ i in s, w i = 0) : ∑ i in s, w i • (p₁ -ᵥ p₂ i) = -s.weighted_vsub p₂ w := by rw [sum_smul_vsub_eq_weighted_vsub_sub, s.weighted_vsub_apply_const _ _ h, zero_sub] /-- A weighted sum of the results of subtracting a default base point from the given points, added to that base point, as an affine map on the weights. This is intended to be used when the sum of the weights is 1, in which case it is an affine combination (barycenter) of the points with the given weights; that condition is specified as a hypothesis on those lemmas that require it. -/ def affine_combination (p : ι → P) : (ι → k) →ᵃ[k] P := { to_fun := λ w, s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty), linear := s.weighted_vsub p, map_vadd' := λ w₁ w₂, by simp_rw [vadd_vadd, weighted_vsub, vadd_eq_add, linear_map.map_add] } /-- The linear map corresponding to `affine_combination` is `weighted_vsub`. -/ @[simp] lemma affine_combination_linear (p : ι → P) : (s.affine_combination p : (ι → k) →ᵃ[k] P).linear = s.weighted_vsub p := rfl /-- Applying `affine_combination` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `affine_combination` would involve selecting a preferred base point with `affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one` and then using `weighted_vsub_of_point_apply`. -/ lemma affine_combination_apply (w : ι → k) (p : ι → P) : s.affine_combination p w = s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) := rfl /-- The value of `affine_combination`, where the given points are equal. -/ @[simp] lemma affine_combination_apply_const (w : ι → k) (p : P) (h : ∑ i in s, w i = 1) : s.affine_combination (λ _, p) w = p := by rw [affine_combination_apply, s.weighted_vsub_of_point_apply_const, h, one_smul, vsub_vadd] /-- `affine_combination` gives the sum with any base point, when the sum of the weights is 1. -/ lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b : P) : s.affine_combination p w = s.weighted_vsub_of_point p b w +ᵥ b := s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w p h _ _ /-- Adding a `weighted_vsub` to an `affine_combination`. -/ lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) : s.weighted_vsub p w₁ +ᵥ s.affine_combination p w₂ = s.affine_combination p (w₁ + w₂) := by rw [←vadd_eq_add, affine_map.map_vadd, affine_combination_linear] /-- Subtracting two `affine_combination`s. -/ lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) : s.affine_combination p w₁ -ᵥ s.affine_combination p w₂ = s.weighted_vsub p (w₁ - w₂) := by rw [←affine_map.linear_map_vsub, affine_combination_linear, vsub_eq_sub] lemma attach_affine_combination_of_injective (s : finset P) (w : P → k) (f : s → P) (hf : function.injective f) : s.attach.affine_combination f (w ∘ f) = (image f univ).affine_combination id w := begin simp only [affine_combination, weighted_vsub_of_point_apply, id.def, vadd_right_cancel_iff, function.comp_app, affine_map.coe_mk], let g₁ : s → V := λ i, w (f i) • (f i -ᵥ classical.choice S.nonempty), let g₂ : P → V := λ i, w i • (i -ᵥ classical.choice S.nonempty), change univ.sum g₁ = (image f univ).sum g₂, have hgf : g₁ = g₂ ∘ f, { ext, simp, }, rw [hgf, sum_image], exact λ _ _ _ _ hxy, hf hxy, end lemma attach_affine_combination_coe (s : finset P) (w : P → k) : s.attach.affine_combination (coe : s → P) (w ∘ coe) = s.affine_combination id w := by rw [attach_affine_combination_of_injective s w (coe : s → P) subtype.coe_injective, univ_eq_attach, attach_image_coe] omit S /-- Viewing a module as an affine space modelled on itself, a `weighted_vsub` is just a linear combination. -/ @[simp] lemma weighted_vsub_eq_linear_combination {ι} (s : finset ι) {w : ι → k} {p : ι → V} (hw : s.sum w = 0) : s.weighted_vsub p w = ∑ i in s, w i • p i := by simp [s.weighted_vsub_apply, vsub_eq_sub, smul_sub, ← finset.sum_smul, hw] /-- Viewing a module as an affine space modelled on itself, affine combinations are just linear combinations. -/ @[simp] lemma affine_combination_eq_linear_combination (s : finset ι) (p : ι → V) (w : ι → k) (hw : ∑ i in s, w i = 1) : s.affine_combination p w = ∑ i in s, w i • p i := by simp [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw 0] include S /-- An `affine_combination` equals a point if that point is in the set and has weight 1 and the other points in the set have weight 0. -/ @[simp] lemma affine_combination_of_eq_one_of_eq_zero (w : ι → k) (p : ι → P) {i : ι} (his : i ∈ s) (hwi : w i = 1) (hw0 : ∀ i2 ∈ s, i2 ≠ i → w i2 = 0) : s.affine_combination p w = p i := begin have h1 : ∑ i in s, w i = 1 := hwi ▸ sum_eq_single i hw0 (λ h, false.elim (h his)), rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p h1 (p i), weighted_vsub_of_point_apply], convert zero_vadd V (p i), convert sum_eq_zero _, intros i2 hi2, by_cases h : i2 = i, { simp [h] }, { simp [hw0 i2 hi2 h] } end /-- An affine combination is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma affine_combination_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.affine_combination p w = s₂.affine_combination p (set.indicator ↑s₁ w) := by rw [affine_combination_apply, affine_combination_apply, weighted_vsub_of_point_indicator_subset _ _ _ h] /-- An affine combination, over the image of an embedding, equals an affine combination with the same points and weights over the original `finset`. -/ lemma affine_combination_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) : (s₂.map e).affine_combination p w = s₂.affine_combination (p ∘ e) (w ∘ e) := by simp_rw [affine_combination_apply, weighted_vsub_of_point_map] /-- A weighted sum of pairwise subtractions, expressed as a subtraction of two `affine_combination` expressions. -/ lemma sum_smul_vsub_eq_affine_combination_vsub (w : ι → k) (p₁ p₂ : ι → P) : ∑ i in s, w i • (p₁ i -ᵥ p₂ i) = s.affine_combination p₁ w -ᵥ s.affine_combination p₂ w := begin simp_rw [affine_combination_apply, vadd_vsub_vadd_cancel_right], exact s.sum_smul_vsub_eq_weighted_vsub_of_point_sub _ _ _ _ end /-- A weighted sum of pairwise subtractions, where the point on the right is constant and the sum of the weights is 1. -/ lemma sum_smul_vsub_const_eq_affine_combination_vsub (w : ι → k) (p₁ : ι → P) (p₂ : P) (h : ∑ i in s, w i = 1) : ∑ i in s, w i • (p₁ i -ᵥ p₂) = s.affine_combination p₁ w -ᵥ p₂ := by rw [sum_smul_vsub_eq_affine_combination_vsub, affine_combination_apply_const _ _ _ h] /-- A weighted sum of pairwise subtractions, where the point on the left is constant and the sum of the weights is 1. -/ lemma sum_smul_const_vsub_eq_vsub_affine_combination (w : ι → k) (p₂ : ι → P) (p₁ : P) (h : ∑ i in s, w i = 1) : ∑ i in s, w i • (p₁ -ᵥ p₂ i) = p₁ -ᵥ s.affine_combination p₂ w := by rw [sum_smul_vsub_eq_affine_combination_vsub, affine_combination_apply_const _ _ _ h] variables {V} /-- Suppose an indexed family of points is given, along with a subset of the index type. A vector can be expressed as `weighted_vsub_of_point` using a `finset` lying within that subset and with a given sum of weights if and only if it can be expressed as `weighted_vsub_of_point` with that sum of weights for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype {v : V} {x : k} {s : set ι} {p : ι → P} {b : P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = x), v = fs.weighted_vsub_of_point p b w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = x), v = fs.weighted_vsub_of_point (λ (i : s), p i) b w := begin simp_rw weighted_vsub_of_point_apply, split, { rintros ⟨fs, hfs, w, rfl, rfl⟩, use [fs.subtype s, λ i, w i, sum_subtype_of_mem _ hfs, (sum_subtype_of_mem _ hfs).symm] }, { rintros ⟨fs, w, rfl, rfl⟩, refine ⟨fs.map (function.embedding.subtype _), map_subtype_subset _, λ i, if h : i ∈ s then w ⟨i, h⟩ else 0, _, _⟩; simp } end variables (k) /-- Suppose an indexed family of points is given, along with a subset of the index type. A vector can be expressed as `weighted_vsub` using a `finset` lying within that subset and with sum of weights 0 if and only if it can be expressed as `weighted_vsub` with sum of weights 0 for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_weighted_vsub_subset_iff_eq_weighted_vsub_subtype {v : V} {s : set ι} {p : ι → P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 0), v = fs.weighted_vsub p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 0), v = fs.weighted_vsub (λ (i : s), p i) w := eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype variables (V) /-- Suppose an indexed family of points is given, along with a subset of the index type. A point can be expressed as an `affine_combination` using a `finset` lying within that subset and with sum of weights 1 if and only if it can be expressed an `affine_combination` with sum of weights 1 for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_affine_combination_subset_iff_eq_affine_combination_subtype {p0 : P} {s : set ι} {p : ι → P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination (λ (i : s), p i) w := begin simp_rw [affine_combination_apply, eq_vadd_iff_vsub_eq], exact eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype end variables {k V} /-- Affine maps commute with affine combinations. -/ lemma map_affine_combination {V₂ P₂ : Type*} [add_comm_group V₂] [module k V₂] [affine_space V₂ P₂] (p : ι → P) (w : ι → k) (hw : s.sum w = 1) (f : P →ᵃ[k] P₂) : f (s.affine_combination p w) = s.affine_combination (f ∘ p) w := begin have b := classical.choice (infer_instance : affine_space V P).nonempty, have b₂ := classical.choice (infer_instance : affine_space V₂ P₂).nonempty, rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw b, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w (f ∘ p) hw b₂, ← s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w (f ∘ p) hw (f b) b₂], simp only [weighted_vsub_of_point_apply, ring_hom.id_apply, affine_map.map_vadd, linear_map.map_smulₛₗ, affine_map.linear_map_vsub, linear_map.map_sum], end end finset namespace finset variables (k : Type*) {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} (s : finset ι) {ι₂ : Type*} (s₂ : finset ι₂) /-- The weights for the centroid of some points. -/ def centroid_weights : ι → k := function.const ι (card s : k) ⁻¹ /-- `centroid_weights` at any point. -/ @[simp] lemma centroid_weights_apply (i : ι) : s.centroid_weights k i = (card s : k) ⁻¹ := rfl /-- `centroid_weights` equals a constant function. -/ lemma centroid_weights_eq_const : s.centroid_weights k = function.const ι ((card s : k) ⁻¹) := rfl variables {k} /-- The weights in the centroid sum to 1, if the number of points, converted to `k`, is not zero. -/ lemma sum_centroid_weights_eq_one_of_cast_card_ne_zero (h : (card s : k) ≠ 0) : ∑ i in s, s.centroid_weights k i = 1 := by simp [h] variables (k) /-- In the characteristic zero case, the weights in the centroid sum to 1 if the number of points is not zero. -/ lemma sum_centroid_weights_eq_one_of_card_ne_zero [char_zero k] (h : card s ≠ 0) : ∑ i in s, s.centroid_weights k i = 1 := by simp [h] /-- In the characteristic zero case, the weights in the centroid sum to 1 if the set is nonempty. -/ lemma sum_centroid_weights_eq_one_of_nonempty [char_zero k] (h : s.nonempty) : ∑ i in s, s.centroid_weights k i = 1 := s.sum_centroid_weights_eq_one_of_card_ne_zero k (ne_of_gt (card_pos.2 h)) /-- In the characteristic zero case, the weights in the centroid sum to 1 if the number of points is `n + 1`. -/ lemma sum_centroid_weights_eq_one_of_card_eq_add_one [char_zero k] {n : ℕ} (h : card s = n + 1) : ∑ i in s, s.centroid_weights k i = 1 := s.sum_centroid_weights_eq_one_of_card_ne_zero k (h.symm ▸ nat.succ_ne_zero n) include V /-- The centroid of some points. Although defined for any `s`, this is intended to be used in the case where the number of points, converted to `k`, is not zero. -/ def centroid (p : ι → P) : P := s.affine_combination p (s.centroid_weights k) /-- The definition of the centroid. -/ lemma centroid_def (p : ι → P) : s.centroid k p = s.affine_combination p (s.centroid_weights k) := rfl lemma centroid_univ (s : finset P) : univ.centroid k (coe : s → P) = s.centroid k id := by { rw [centroid, centroid, ← s.attach_affine_combination_coe], congr, ext, simp, } /-- The centroid of a single point. -/ @[simp] lemma centroid_singleton (p : ι → P) (i : ι) : ({i} : finset ι).centroid k p = p i := by simp [centroid_def, affine_combination_apply] /-- The centroid of two points, expressed directly as adding a vector to a point. -/ lemma centroid_insert_singleton [invertible (2 : k)] (p : ι → P) (i₁ i₂ : ι) : ({i₁, i₂} : finset ι).centroid k p = (2 ⁻¹ : k) • (p i₂ -ᵥ p i₁) +ᵥ p i₁ := begin by_cases h : i₁ = i₂, { simp [h] }, { have hc : (card ({i₁, i₂} : finset ι) : k) ≠ 0, { rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton], norm_num, exact nonzero_of_invertible _ }, rw [centroid_def, affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ _ _ (sum_centroid_weights_eq_one_of_cast_card_ne_zero _ hc) (p i₁)], simp [h] } end /-- The centroid of two points indexed by `fin 2`, expressed directly as adding a vector to the first point. -/ lemma centroid_insert_singleton_fin [invertible (2 : k)] (p : fin 2 → P) : univ.centroid k p = (2 ⁻¹ : k) • (p 1 -ᵥ p 0) +ᵥ p 0 := begin rw univ_fin2, convert centroid_insert_singleton k p 0 1 end /-- A centroid, over the image of an embedding, equals a centroid with the same points and weights over the original `finset`. -/ lemma centroid_map (e : ι₂ ↪ ι) (p : ι → P) : (s₂.map e).centroid k p = s₂.centroid k (p ∘ e) := by simp [centroid_def, affine_combination_map, centroid_weights] omit V /-- `centroid_weights` gives the weights for the centroid as a constant function, which is suitable when summing over the points whose centroid is being taken. This function gives the weights in a form suitable for summing over a larger set of points, as an indicator function that is zero outside the set whose centroid is being taken. In the case of a `fintype`, the sum may be over `univ`. -/ def centroid_weights_indicator : ι → k := set.indicator ↑s (s.centroid_weights k) /-- The definition of `centroid_weights_indicator`. -/ lemma centroid_weights_indicator_def : s.centroid_weights_indicator k = set.indicator ↑s (s.centroid_weights k) := rfl /-- The sum of the weights for the centroid indexed by a `fintype`. -/ lemma sum_centroid_weights_indicator [fintype ι] : ∑ i, s.centroid_weights_indicator k i = ∑ i in s, s.centroid_weights k i := (set.sum_indicator_subset _ (subset_univ _)).symm /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the number of points is not zero. -/ lemma sum_centroid_weights_indicator_eq_one_of_card_ne_zero [char_zero k] [fintype ι] (h : card s ≠ 0) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_card_ne_zero k h end /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the set is nonempty. -/ lemma sum_centroid_weights_indicator_eq_one_of_nonempty [char_zero k] [fintype ι] (h : s.nonempty) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_nonempty k h end /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the number of points is `n + 1`. -/ lemma sum_centroid_weights_indicator_eq_one_of_card_eq_add_one [char_zero k] [fintype ι] {n : ℕ} (h : card s = n + 1) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_card_eq_add_one k h end include V /-- The centroid as an affine combination over a `fintype`. -/ lemma centroid_eq_affine_combination_fintype [fintype ι] (p : ι → P) : s.centroid k p = univ.affine_combination p (s.centroid_weights_indicator k) := affine_combination_indicator_subset _ _ (subset_univ _) /-- An indexed family of points that is injective on the given `finset` has the same centroid as the image of that `finset`. This is stated in terms of a set equal to the image to provide control of definitional equality for the index type used for the centroid of the image. -/ lemma centroid_eq_centroid_image_of_inj_on {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j) {ps : set P} [fintype ps] (hps : ps = p '' ↑s) : s.centroid k p = (univ : finset ps).centroid k (λ x, x) := begin let f : p '' ↑s → ι := λ x, x.property.some, have hf : ∀ x, f x ∈ s ∧ p (f x) = x := λ x, x.property.some_spec, let f' : ps → ι := λ x, f ⟨x, hps ▸ x.property⟩, have hf' : ∀ x, f' x ∈ s ∧ p (f' x) = x := λ x, hf ⟨x, hps ▸ x.property⟩, have hf'i : function.injective f', { intros x y h, rw [subtype.ext_iff, ←(hf' x).2, ←(hf' y).2, h] }, let f'e : ps ↪ ι := ⟨f', hf'i⟩, have hu : finset.univ.map f'e = s, { ext x, rw mem_map, split, { rintros ⟨i, _, rfl⟩, exact (hf' i).1 }, { intro hx, use [⟨p x, hps.symm ▸ set.mem_image_of_mem _ hx⟩, mem_univ _], refine hi _ (hf' _).1 _ hx _, rw (hf' _).2, refl } }, rw [←hu, centroid_map], congr' with x, change p (f' x) = ↑x, rw (hf' x).2 end /-- Two indexed families of points that are injective on the given `finset`s and with the same points in the image of those `finset`s have the same centroid. -/ lemma centroid_eq_of_inj_on_of_image_eq {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j) {p₂ : ι₂ → P} (hi₂ : ∀ i j ∈ s₂, p₂ i = p₂ j → i = j) (he : p '' ↑s = p₂ '' ↑s₂) : s.centroid k p = s₂.centroid k p₂ := by rw [s.centroid_eq_centroid_image_of_inj_on k hi rfl, s₂.centroid_eq_centroid_image_of_inj_on k hi₂ he] end finset section affine_space' variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V /-- A `weighted_vsub` with sum of weights 0 is in the `vector_span` of an indexed family. -/ lemma weighted_vsub_mem_vector_span {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 0) (p : ι → P) : s.weighted_vsub p w ∈ vector_span k (set.range p) := begin rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, { resetI, simp [finset.eq_empty_of_is_empty s] }, { rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_image_iff_total, finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p h (p i0), finset.weighted_vsub_of_point_apply], let w' := set.indicator ↑s w, have hwx : ∀ i, w' i ≠ 0 → i ∈ s := λ i, set.mem_of_indicator_ne_zero, use [finsupp.on_finset s w' hwx, set.subset_univ _], rw [finsupp.total_apply, finsupp.on_finset_sum hwx], { apply finset.sum_congr rfl, intros i hi, simp [w', set.indicator_apply, if_pos hi] }, { exact λ _, zero_smul k _ } }, end /-- An `affine_combination` with sum of weights 1 is in the `affine_span` of an indexed family, if the underlying ring is nontrivial. -/ lemma affine_combination_mem_affine_span [nontrivial k] {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 1) (p : ι → P) : s.affine_combination p w ∈ affine_span k (set.range p) := begin have hnz : ∑ i in s, w i ≠ 0 := h.symm ▸ one_ne_zero, have hn : s.nonempty := finset.nonempty_of_sum_ne_zero hnz, cases hn with i1 hi1, let w1 : ι → k := function.update (function.const ι 0) i1 1, have hw1 : ∑ i in s, w1 i = 1, { rw [finset.sum_update_of_mem hi1, finset.sum_const_zero, add_zero] }, have hw1s : s.affine_combination p w1 = p i1 := s.affine_combination_of_eq_one_of_eq_zero w1 p hi1 (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), have hv : s.affine_combination p w -ᵥ p i1 ∈ (affine_span k (set.range p)).direction, { rw [direction_affine_span, ←hw1s, finset.affine_combination_vsub], apply weighted_vsub_mem_vector_span, simp [pi.sub_apply, h, hw1] }, rw ←vsub_vadd (s.affine_combination p w) (p i1), exact affine_subspace.vadd_mem_of_mem_direction hv (mem_affine_span k (set.mem_range_self _)) end variables (k) {V} /-- A vector is in the `vector_span` of an indexed family if and only if it is a `weighted_vsub` with sum of weights 0. -/ lemma mem_vector_span_iff_eq_weighted_vsub {v : V} {p : ι → P} : v ∈ vector_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (h : ∑ i in s, w i = 0), v = s.weighted_vsub p w := begin split, { rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, swap, { rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_image_iff_total], rintros ⟨l, hl, hv⟩, use insert i0 l.support, set w := (l : ι → k) - function.update (function.const ι 0 : ι → k) i0 (∑ i in l.support, l i) with hwdef, use w, have hw : ∑ i in insert i0 l.support, w i = 0, { rw hwdef, simp_rw [pi.sub_apply, finset.sum_sub_distrib, finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, finset.sum_insert_of_eq_zero_if_not_mem finsupp.not_mem_support_iff.1, add_zero, sub_self] }, use hw, have hz : w i0 • (p i0 -ᵥ p i0 : V) = 0 := (vsub_self (p i0)).symm ▸ smul_zero _, change (λ i, w i • (p i -ᵥ p i0 : V)) i0 = 0 at hz, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w p hw (p i0), finset.weighted_vsub_of_point_apply, ←hv, finsupp.total_apply, finset.sum_insert_zero hz], change ∑ i in l.support, l i • _ = _, congr' with i, by_cases h : i = i0, { simp [h] }, { simp [hwdef, h] } }, { resetI, rw [set.range_eq_empty, vector_span_empty, submodule.mem_bot], rintro rfl, use [∅], simp } }, { rintros ⟨s, w, hw, rfl⟩, exact weighted_vsub_mem_vector_span hw p } end variables {k} /-- A point in the `affine_span` of an indexed family is an `affine_combination` with sum of weights 1. See also `eq_affine_combination_of_mem_affine_span_of_fintype`. -/ lemma eq_affine_combination_of_mem_affine_span {p1 : P} {p : ι → P} (h : p1 ∈ affine_span k (set.range p)) : ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w := begin have hn : ((affine_span k (set.range p)) : set P).nonempty := ⟨p1, h⟩, rw [affine_span_nonempty, set.range_nonempty_iff_nonempty] at hn, cases hn with i0, have h0 : p i0 ∈ affine_span k (set.range p) := mem_affine_span k (set.mem_range_self i0), have hd : p1 -ᵥ p i0 ∈ (affine_span k (set.range p)).direction := affine_subspace.vsub_mem_direction h h0, rw [direction_affine_span, mem_vector_span_iff_eq_weighted_vsub] at hd, rcases hd with ⟨s, w, h, hs⟩, let s' := insert i0 s, let w' := set.indicator ↑s w, have h' : ∑ i in s', w' i = 0, { rw [←h, set.sum_indicator_subset _ (finset.subset_insert i0 s)] }, have hs' : s'.weighted_vsub p w' = p1 -ᵥ p i0, { rw hs, exact (finset.weighted_vsub_indicator_subset _ _ (finset.subset_insert i0 s)).symm }, let w0 : ι → k := function.update (function.const ι 0) i0 1, have hw0 : ∑ i in s', w0 i = 1, { rw [finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, add_zero] }, have hw0s : s'.affine_combination p w0 = p i0 := s'.affine_combination_of_eq_one_of_eq_zero w0 p (finset.mem_insert_self _ _) (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), use [s', w0 + w'], split, { simp [pi.add_apply, finset.sum_add_distrib, hw0, h'] }, { rw [add_comm, ←finset.weighted_vsub_vadd_affine_combination, hw0s, hs', vsub_vadd] } end lemma eq_affine_combination_of_mem_affine_span_of_fintype [fintype ι] {p1 : P} {p : ι → P} (h : p1 ∈ affine_span k (set.range p)) : ∃ (w : ι → k) (hw : ∑ i, w i = 1), p1 = finset.univ.affine_combination p w := begin obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span h, refine ⟨(s : set ι).indicator w, _, finset.affine_combination_indicator_subset w p s.subset_univ⟩, simp only [finset.mem_coe, set.indicator_apply, ← hw], rw fintype.sum_extend_by_zero s w, end variables (k V) /-- A point is in the `affine_span` of an indexed family if and only if it is an `affine_combination` with sum of weights 1, provided the underlying ring is nontrivial. -/ lemma mem_affine_span_iff_eq_affine_combination [nontrivial k] {p1 : P} {p : ι → P} : p1 ∈ affine_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w := begin split, { exact eq_affine_combination_of_mem_affine_span }, { rintros ⟨s, w, hw, rfl⟩, exact affine_combination_mem_affine_span hw p } end /-- Given a family of points together with a chosen base point in that family, membership of the affine span of this family corresponds to an identity in terms of `weighted_vsub_of_point`, with weights that are not required to sum to 1. -/ lemma mem_affine_span_iff_eq_weighted_vsub_of_point_vadd [nontrivial k] (p : ι → P) (j : ι) (q : P) : q ∈ affine_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k), q = s.weighted_vsub_of_point p (p j) w +ᵥ (p j) := begin split, { intros hq, obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span hq, exact ⟨s, w, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw (p j)⟩, }, { rintros ⟨s, w, rfl⟩, classical, let w' : ι → k := function.update w j (1 - (s \ {j}).sum w), have h₁ : (insert j s).sum w' = 1, { by_cases hj : j ∈ s, { simp [finset.sum_update_of_mem hj, finset.insert_eq_of_mem hj], }, { simp [w', finset.sum_insert hj, finset.sum_update_of_not_mem hj, hj], }, }, have hww : ∀ i, i ≠ j → w i = w' i, { intros i hij, simp [w', hij], }, rw [s.weighted_vsub_of_point_eq_of_weights_eq p j w w' hww, ← s.weighted_vsub_of_point_insert w' p j, ← (insert j s).affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w' p h₁ (p j)], exact affine_combination_mem_affine_span h₁ p, }, end variables {k V} /-- Given a set of points, together with a chosen base point in this set, if we affinely transport all other members of the set along the line joining them to this base point, the affine span is unchanged. -/ lemma affine_span_eq_affine_span_line_map_units [nontrivial k] {s : set P} {p : P} (hp : p ∈ s) (w : s → units k) : affine_span k (set.range (λ (q : s), affine_map.line_map p ↑q (w q : k))) = affine_span k s := begin have : s = set.range (coe : s → P), { simp, }, conv_rhs { rw this, }, apply le_antisymm; intros q hq; erw mem_affine_span_iff_eq_weighted_vsub_of_point_vadd k V _ (⟨p, hp⟩ : s) q at hq ⊢; obtain ⟨t, μ, rfl⟩ := hq; use t; [use λ x, (μ x) * ↑(w x), use λ x, (μ x) * ↑(w x)⁻¹]; simp [smul_smul], end end affine_space' section division_ring variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V open set finset /-- The centroid lies in the affine span if the number of points, converted to `k`, is not zero. -/ lemma centroid_mem_affine_span_of_cast_card_ne_zero {s : finset ι} (p : ι → P) (h : (card s : k) ≠ 0) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_cast_card_ne_zero h) p variables (k) /-- In the characteristic zero case, the centroid lies in the affine span if the number of points is not zero. -/ lemma centroid_mem_affine_span_of_card_ne_zero [char_zero k] {s : finset ι} (p : ι → P) (h : card s ≠ 0) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_ne_zero k h) p /-- In the characteristic zero case, the centroid lies in the affine span if the set is nonempty. -/ lemma centroid_mem_affine_span_of_nonempty [char_zero k] {s : finset ι} (p : ι → P) (h : s.nonempty) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_nonempty k h) p /-- In the characteristic zero case, the centroid lies in the affine span if the number of points is `n + 1`. -/ lemma centroid_mem_affine_span_of_card_eq_add_one [char_zero k] {s : finset ι} (p : ι → P) {n : ℕ} (h : card s = n + 1) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_eq_add_one k h) p end division_ring namespace affine_map variables {k : Type*} {V : Type*} (P : Type*) [comm_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} (s : finset ι) include V -- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd` /-- A weighted sum, as an affine map on the points involved. -/ def weighted_vsub_of_point (w : ι → k) : ((ι → P) × P) →ᵃ[k] V := { to_fun := λ p, s.weighted_vsub_of_point p.fst p.snd w, linear := ∑ i in s, w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _), map_vadd' := begin rintros ⟨p, b⟩ ⟨v, b'⟩, simp [linear_map.sum_apply, finset.weighted_vsub_of_point, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib] end } end affine_map
7471c35dc56fb83110f7d5f1d01e896e003b3dec
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/data/list/basic.lean
7ea47be813922ec3adec05520bfdaf67d2ee1d8e
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
153,130
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 Basic properties of lists. -/ import tactic.interactive tactic.mk_iff_of_inductive_prop tactic.split_ifs logic.basic logic.function logic.relation algebra.group order.basic data.nat.basic data.option data.bool data.prod data.sigma data.fin open function nat namespace list universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} @[simp] theorem cons_ne_nil (a : α) (l : list α) : a::l ≠ []. 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) theorem cons_inj {a : α} : injective (cons a) := assume l₁ l₂, assume Pe, tail_eq_of_cons_eq Pe @[simp] theorem cons_inj' (a : α) {l l' : list α} : a::l = a::l' ↔ l = l' := ⟨λ e, cons_inj e, congr_arg _⟩ /- mem -/ theorem eq_nil_of_forall_not_mem : ∀ {l : list α}, (∀ a, a ∉ l) → l = nil | [] := assume h, rfl | (b :: l') := assume h, absurd (mem_cons_self b l') (h b) 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, by intro h; simp [h]⟩ 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 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 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 mem_split {a : α} {l : list α} (h : a ∈ l) : ∃ s t : list α, l = s ++ a :: t := begin induction l with b l ih; simp at h; cases h with h h, { subst h, exact ⟨[], l, rfl⟩ }, { rcases ih h with ⟨s, t, e⟩, subst l, 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, {simp at h, contradiction }, {simp, simp at h, cases h with h h, {simp *}, {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, {simp at h, contradiction}, {cases (eq_or_mem_of_mem_cons h) with h h, {existsi c, simp [h]}, {rcases ih h with ⟨a, ha₁, ha₂⟩, existsi a, simp * }} 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⟩ @[simp] theorem mem_map_of_inj {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 _⟩ @[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 [join, @mem_join L, or_and_distrib_right, exists_or_distrib] 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 [bind_map l] /- list subset -/ theorem subset_def {l₁ l₂ : list α} : l₁ ⊆ l₂ ↔ ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂ := iff.rfl theorem subset_app_of_subset_left (l l₁ l₂ : list α) : l ⊆ l₁ → l ⊆ l₁++l₂ := λ s, subset.trans s $ subset_append_left _ _ theorem subset_app_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 [subset_def, or_imp_distrib, forall_and_distrib] 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 app_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 _) 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 [mem_map]; exact λ a h e, ⟨a, H h, e⟩ /- append -/ lemma append_eq_has_append {L₁ L₂ : list α} : list.append L₁ L₂ = L₁ ++ 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 theorem append_foldl (f : α → β → α) (a : α) (s t : list β) : foldl f a (s ++ t) = foldl f (foldl f a s) t := by {induction s with b s H generalizing a, refl, simp [foldl], rw H _} theorem append_foldr (f : α → β → β) (a : β) (s t : list α) : foldr f a (s ++ t) = foldr f (foldr f a t) s := by {induction s with b s H generalizing a, refl, simp [foldr], rw H _} @[simp] lemma append_eq_nil {p q : list α} : (p ++ q) = [] ↔ p = [] ∧ q = [] := by cases p; simp @[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 [and_assoc, @eq_comm _ c] 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 { simp [nil_eq_append_iff, iff_def, or_imp_distrib] {contextual := tt} }, case cons : a as ih { cases c, { simp, exact eq_comm }, { simp [ih, @eq_comm _ a, and_assoc, and_or_distrib_left] } } end /-- Split a list at an index. `split 2 [a, b, c] = ([a, b], [c])` -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) @[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 [split_at, split_at_eq_take_drop n xs] @[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) := by simp [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_left {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_right {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 at hap; rwa [← hl] at hap theorem append_inj_left' {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_right' {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_left h rfl theorem append_right_cancel {s₁ s₂ t : list α} (h : s₁ ++ t = s₂ ++ t) : s₁ = s₂ := append_inj_right' h rfl theorem append_left_inj {t₁ t₂ : list α} (s) : s ++ t₁ = s ++ t₂ ↔ t₁ = t₂ := ⟨append_left_cancel, congr_arg _⟩ theorem append_right_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 le_add_right end /- join -/ attribute [simp] join @[simp] theorem join_append (L₁ L₂ : list (list α)) : join (L₁ ++ L₂) = join L₁ ++ join L₂ := by induction L₁; simp * /- 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 := have b = a ∧ ∀ (x : α), x ∈ l → x = a, by simpa [or_imp_distrib, forall_and_distrib] using H, by dsimp; congr; [exact this.1, exact eq_repeat_of_mem this.2] 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 [*, repeat, nat.succ_add, -add_comm] 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; simp [repeat, -add_comm, *] 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; simp * @[simp] theorem tail_repeat (a : α) (n) : tail (repeat a n) = repeat a n.pred := by cases n; refl /- 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 := by simp [bind] /- concat -/ /-- Concatenate an element at the end of a list. `concat [a, b] c = [a, b, c]` -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a @[simp] theorem concat_nil (a : α) : concat [] a = [a] := rfl @[simp] theorem concat_cons (a b : α) (l : list α) : concat (a :: l) b = a :: concat l b := rfl @[simp] theorem concat_ne_nil (a : α) (l : list α) : concat l a ≠ [] := by induction l; intro h; contradiction @[simp] theorem concat_append (a : α) (l₁ l₂ : list α) : concat l₁ a ++ l₂ = l₁ ++ a :: l₂ := by induction l₁ with b l₁ ih; [simp, simp [ih]] @[simp] theorem concat_eq_append (a : α) (l : list α) : concat l a = l ++ [a] := by induction l; simp [*, concat] @[simp] theorem length_concat (a : α) (l : list α) : length (concat l a) = succ (length l) := by simp [succ_eq_add_one] theorem append_concat (a : α) (l₁ l₂ : list α) : l₁ ++ concat l₂ a = concat (l₁ ++ l₂) a := by induction l₂ with b l₂ ih; 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₁; simp *, (aux l nil).symm theorem reverse_core_eq (l₁ l₂ : list α) : reverse_core l₁ l₂ = reverse l₁ ++ l₂ := by induction l₁ generalizing l₂; simp * theorem reverse_cons' (a : α) (l : list α) : reverse (a::l) = concat (reverse l) a := by simp @[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; simp * @[simp] theorem reverse_reverse (l : list α) : reverse (reverse l) = l := by induction l; simp * theorem reverse_injective : injective (@reverse α) := injective_of_left_inverse 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 @[simp] theorem length_reverse (l : list α) : length (reverse l) = length l := by induction l; simp * @[simp] theorem map_reverse (f : α → β) (l : list α) : map f (reverse l) = reverse (map f l) := by induction l; simp * theorem map_reverse_core (f : α → β) (l₁ l₂ : list α) : map f (reverse_core l₁ l₂) = reverse_core (map f l₁) (map f l₂) := by simp [reverse_core_eq] @[simp] theorem mem_reverse {a : α} {l : list α} : a ∈ reverse l ↔ a ∈ l := by induction l; simp [*, or_comm] @[simp] theorem reverse_repeat (a : α) (n) : reverse (repeat a n) = repeat a n := eq_repeat.2 ⟨by simp, λ b h, eq_of_mem_repeat (mem_reverse.1 h)⟩ @[elab_as_eliminator] theorem 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 }, { simp, exact H1 _ _ ih } 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, simp *, reflexivity} @[simp] theorem last_append {a : α} (l : list α) (h : l ++ [a] ≠ []) : last (l ++ [a]) h = a := by induction l; [refl, simp *] theorem last_concat {a : α} (l : list α) (h : concat l a ≠ []) : last (concat l a) h = a := by simp * @[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 last_congr {l₁ l₂ : list α} (h₁ : l₁ ≠ []) (h₂ : l₂ ≠ []) (h₃ : l₁ = l₂) : last l₁ h₁ = last l₂ h₂ := by subst l₁ /- head and tail -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a theorem head_eq_head' [inhabited α] (l : list α) : head l = (head' l).iget := by cases l; refl @[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, simp} theorem cons_head_tail [inhabited α] {l : list α} (h : l ≠ []) : (head l)::(tail l) = l := by {induction l, contradiction, simp} /- map -/ lemma map_congr {f g : α → β} : ∀ {l : list α}, (∀ x ∈ l, f x = g x) → map f l = map g l | [] _ := rfl | (a::l) h := have f a = g a, from h _ (mem_cons_self _ _), have map f l = map g l, from map_congr $ assume a', h _ ∘ mem_cons_of_mem _, show f a :: map f l = g a :: map g l, by simp [*] theorem map_concat (f : α → β) (a : α) (l : list α) : map f (concat l a) = concat (map f l) (f a) := by induction l; simp * theorem map_id' {f : α → α} (h : ∀ x, f x = x) (l : list α) : map f l = l := by induction l; 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; simp * @[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; simp * theorem foldl_hom (f : α → β) (g : α → γ → α) (g' : β → γ → β) (a : α) (h : ∀a x, f (g a x) = g' (f a) x) (l : list γ) : f (foldl g a l) = foldl g' (f a) l := by revert a; induction l; intros; simp * theorem foldr_hom (f : α → β) (g : γ → α → α) (g' : γ → β → β) (a : α) (h : ∀x a, f (g x a) = g' x (f a)) (l : list γ) : f (foldr g a l) = foldr g' (f a) l := by revert a; induction l; intros; simp * theorem eq_nil_of_map_eq_nil {f : α → β} {l : list α} (h : map f l = nil) : l = nil := eq_nil_of_length_eq_zero (begin rw [← length_map f l], simp [h] end) @[simp] theorem map_join (f : α → β) (L : list (list α)) : map f (join L) = join (map (map f) L) := by induction L; simp * theorem bind_ret_eq_map {α β} (f : α → β) (l : list α) : l.bind (list.ret ∘ f) = map f l := by simp [list.bind]; induction l; simp [list.ret, join, *] @[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 /- 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 /- 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_app_of_sublist_left {l l₁ l₂ : list α} (s : l <+ l₁) : l <+ l₁++l₂ := s.trans $ sublist_append_left _ _ theorem sublist_app_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 append_sublist_append_of_sublist_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; simp * }, { 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 reverse_sublist {l₁ l₂ : list α} (h : l₁ <+ l₂) : l₁.reverse <+ l₂.reverse := begin induction h with _ _ _ _ ih _ _ a _ ih; simp, { exact sublist_app_of_sublist_left ih }, { exact append_sublist_append_of_sublist_right ih [a] } end @[simp] theorem reverse_sublist_iff {l₁ l₂ : list α} : l₁.reverse <+ l₂.reverse ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp at this; assumption, reverse_sublist⟩ @[simp] theorem append_sublist_append_right {l₁ l₂ : list α} (l) : l₁++l <+ l₂++l ↔ l₁ <+ l₂ := ⟨λ h, by have := reverse_sublist h; simp at this; assumption, λ h, append_sublist_append_of_sublist_right h l⟩ theorem subset_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → l₁ ⊆ l₂ | ._ ._ sublist.slnil b h := h | ._ ._ (sublist.cons l₁ l₂ a s) b h := mem_cons_of_mem _ (subset_of_sublist 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 _ (subset_of_sublist s h) end theorem singleton_sublist {a : α} {l} : [a] <+ l ↔ a ∈ l := ⟨λ h, subset_of_sublist h (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 $ subset_of_sublist s theorem repeat_sublist_repeat (a : α) {m n} : repeat a m <+ repeat a n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by induction h; [apply sublist.refl, simp [*, 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] 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; simp [-add_comm], by_cases h : a = b; simp [h, -add_comm], { intro, contradiction }, { rw ← ih, exact ⟨succ_inj, congr_arg _⟩ } end @[simp] 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; simp [-add_comm, index_of_cons], by_cases h : a = b; simp [h, -add_comm, zero_le], 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_ge_len : ∀ {l : list α} {n}, n ≥ length l → nth l n = none | [] n h := rfl | (a :: l) (n+1) h := nth_ge_len (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_ge_len 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 _⟩ 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 @[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 @[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 _ _ @[extensionality] 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 [*, ext (λn, h (n+1))] 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_ge_len h₁, nth_ge_len (by 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 * @[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, by simp); exact λh1 h2, nth_le_reverse_aux1 l (a :: r) (i+1) h1 (succ_lt_succ h2) 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 _ _ _ _ _ /-- Convert a list into an array (whose length is the length of `l`) -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /- nth tail operation -/ /-- Apply a function to the nth tail of `l`. `modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c]`. Returns the input without using `f` if the index is larger than the length of the list. -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) 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 [h, mt succ_inj] 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 [update_nth_eq_modify_nth] @[simp] theorem nth_modify_nth_eq (f : α → α) (n) (l : list α) : nth (modify_nth f n l) n = f <$> nth l n := by simp [nth_modify_nth] @[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 [nth_modify_nth, h]; cases nth l n; refl theorem nth_update_nth_eq (a : α) (n) (l : list α) : nth (update_nth l n a) n = (λ _, a) <$> nth l n := by simp [update_nth_eq_modify_nth] 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 [update_nth_eq_modify_nth, h] /- take, drop -/ @[simp] theorem take_zero : ∀ (l : list α), take 0 l = [] := begin intros, reflexivity end @[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 theorem take_all : ∀ (l : list α), take (length l) l = l | [] := rfl | (a::l) := begin change a :: (take (length l) l) = a :: l, rw take_all end theorem take_all_of_ge : ∀ {n} {l : list α}, n ≥ length l → 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_ge (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 simp | (succ n) (succ m) nil := by simp | (succ n) (succ m) (a::l) := by simp [min_succ_succ, take_take] @[simp] theorem drop_nil : ∀ n, drop n [] = ([] : list α) | 0 := rfl | (n+1) := rfl @[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 _ _ 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] @[simp] lemma update_nth_eq_nil (l : list α) (n : ℕ) (a : α) : l.update_nth n a = [] ↔ l = [] := by cases l; cases n; simp [update_nth] section take' variable [inhabited α] def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail @[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 [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' /- take_while -/ /-- Get the longest initial segment of the list whose members all satisfy `p`. `take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2]` -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /- foldl, foldr, scanl, scanr -/ 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 := by induction l generalizing a; simp * {contextual := tt} 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 := by induction l; simp * {contextual := tt} @[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 [foldl_append] @[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 [foldr_append] @[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 [foldl_join] @[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 [foldr_join] theorem foldl_reverse (f : α → β → α) (a : α) (l : list β) : foldl f a (reverse l) = foldr (λx y, f y x) a l := by induction l; simp [*, 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 [foldr_eta l] /-- Fold a function `f` over the list from the left, returning the list of partial results. `scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6]` -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. `scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0]` -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' @[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 [scanr, scanr_aux] at t; simp [scanr, scanr_aux, t] @[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 [scanr] 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 [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; rw [← foldl_eq_of_comm_of_assoc, right_comm _ hcomm hassoc]; simp theorem foldl_eq_foldr : ∀ a l, foldl f a l = foldr f a l | a nil := rfl | a (b :: l) := by simp [foldl_eq_of_comm_of_assoc hcomm hassoc]; rw (foldl_eq_foldr a l) end foldl_eq_foldr 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₂ := by simp | (a :: l) a₁ a₂ := calc a::l <*> (a₁ * a₂) = l <*> (a₁ * (a₂ * a)) : by simp [ha.assoc] ... = a₁ * (a::l <*> a₂) : by rw [foldl_assoc]; simp lemma foldl_op_eq_op_foldr_assoc : ∀{l : list α} {a₁ a₂}, (l <*> a₁) * a₂ = a₁ * l.foldr (*) a₂ | [] a₁ a₂ := by simp | (a :: l) a₁ a₂ := by simp [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 /- sum -/ /-- Product of a list. `prod [a, b, c] = ((1 * a) * b) * c` -/ @[to_additive list.sum] def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 attribute [to_additive list.sum.equations._eqn_1] list.prod.equations._eqn_1 section monoid variables [monoid α] {l l₁ l₂ : list α} {a : α} @[simp, to_additive list.sum_nil] theorem prod_nil : ([] : list α).prod = 1 := rfl @[simp, to_additive list.sum_cons] theorem prod_cons : (a::l).prod = a * l.prod := calc (a::l).prod = foldl (*) (a * 1) l : by simp [list.prod] ... = _ : foldl_assoc @[simp, to_additive list.sum_append] 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 list.sum_join] theorem prod_join {l : list (list α)} : l.join.prod = (l.map list.prod).prod := by induction l; simp [list.join, *] at * end monoid @[simp] theorem sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; simp [*, nat.mul_succ] @[simp] theorem length_join (L : list (list α)) : length (join L) = sum (map length L) := by induction L; simp * @[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] /- lexicographic ordering -/ 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⟩ 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, bounded quantifiers over lists -/ theorem forall_mem_nil (p : α → Prop) : ∀ x ∈ @nil α, p x := by simp @[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 [or_imp_distrib, forall_and_distrib] theorem forall_mem_cons {p : α → Prop} {a : α} {l : list α} : (∀ x ∈ a :: l, p x) ↔ p a ∧ ∀ x ∈ l, p x := by simp 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 theorem forall_mem_append {p : α → Prop} {l₁ l₂ : list α} : (∀ x ∈ l₁ ++ l₂, p x) ↔ (∀ x ∈ l₁, p x) ∧ (∀ x ∈ l₂, p x) := by simp [or_imp_distrib, forall_and_distrib] theorem not_exists_mem_nil (p : α → Prop) : ¬ ∃ x ∈ @nil α, p x := by simp theorem exists_mem_cons_of {p : α → Prop} {a : α} (l : list α) (h : p a) : ∃ x ∈ a :: l, p x := bex.intro a (by simp) 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 (by simp [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, simp [px] end) (assume : x ∈ l, or.inr (bex.intro x this px))) @[simp] 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) @[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 := by induction l with a l; simp [forall_and_distrib, *] theorem all_iff_forall_prop {p : α → Prop} [decidable_pred p] {l : list α} : all l (λ a, p a) ↔ ∀ a ∈ l, p a := by simp [all_iff_forall] @[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 := by induction l with a l; simp [or_and_distrib_right, exists_or_distrib, *] 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₂⟩ 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 pmap_eq_map (p : α → Prop) (f : α → β) (l : list α) (H) : @pmap _ _ p (λ a _, f a) l H = map f l := by induction l; simp * 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; simp *; apply 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; simp * 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 [pmap_eq_map_attach] @[simp] theorem length_pmap {p : α → Prop} {f : Π a, p a → β} {l H} : length (pmap f l H) = length l := by induction l; simp * /- find -/ section find variables {p : α → Prop} [decidable_pred p] {l : list α} {a : α} /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l def find_indexes_aux (p : α → Prop) [decidable_pred p] : list α → nat → list nat | [] n := [] | (a::l) n := let t := find_indexes_aux l (succ n) in if p a then n :: t else t /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := find_indexes_aux p l 0 @[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, {simp}, by_cases p a; simp [h, IH] end @[simp] theorem find_some (H : find p l = some a) : p a := begin induction l with b l IH, {contradiction}, by_cases p b; simp [h] at H, { subst b, assumption }, { 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 p b; simp [h] at H, { subst b, apply mem_cons_self }, { exact mem_cons_of_mem _ (IH H) } end end find /-- `indexes_of a l` is the list of all indexes of `a` in `l`. `indexes_of a [a, b, a, a] = [0, 2, 3]` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) /- 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 [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 [filter_map, h] theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := begin funext l, induction l with a l IH, {simp}, simp [filter_map_cons_some (some ∘ f) _ _ rfl, IH] 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, {simp}, by_cases pa : p a; simp [filter_map, option.guard, pa, IH] 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 [h, option.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 [h, h', option.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 p x; simp [h, option.guard, option.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, {simp}, cases h : f a with b', { have : f a ≠ some b, {rw h, intro, contradiction}, simp [filter_map_cons_none _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] }, { have : f a = some b ↔ b = b', { split; intro t, {rw t at h; injection h}, {exact t.symm ▸ h} }, simp [filter_map_cons_some _ _ _ h, IH, or_and_distrib_right, exists_or_distrib, this] } 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 [map_filter_map, H] theorem filter_map_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 [filter_map]; cases f a with b; simp [filter_map, IH, sublist.cons, sublist.cons2] theorem map_sublist_map (f : α → β) {l₁ l₂ : list α} (s : l₁ <+ l₂) : map f l₁ <+ map f l₂ := by rw ← filter_map_eq_map; exact filter_map_sublist_filter_map _ s /- filter -/ section filter variables {p : α → Prop} [decidable_pred p] 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 simp at h; by_cases pa : p a; [simp [pa, h.1.1 pa, filter_congr h.2], simp [pa, mt h.1.2 pa, filter_congr h.2]] @[simp] theorem filter_subset (l : list α) : filter p l ⊆ l := subset_of_sublist $ filter_sublist l theorem of_mem_filter {a : α} : ∀ {l}, a ∈ filter p l → p a | [] ain := absurd ain (not_mem_nil a) | (b::l) ain := if pb : p b then have a ∈ b :: filter p l, begin simp [pb] at ain, assumption end, 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 [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 | [] ain pa := absurd ain (not_mem_nil a) | (b::l) ain pa := if pb : p b then or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, by simp [pb, this]) (assume : a ∈ l, begin simp [pb], exact (mem_cons_of_mem _ (mem_filter_of_mem this pa)) end) else or.elim (eq_or_mem_of_mem_cons ain) (assume : a = b, begin simp [this] at pa, contradiction end) --absurd (this ▸ pa) pb) (assume : a ∈ l, by simp [pa, pb, mem_filter_of_mem this]) @[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, {simp}, by_cases p a; simp [filter, *], show filter p l ≠ a :: l, 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 [-and.comm, eq_nil_iff_forall_not_mem, mem_filter] theorem filter_sublist_filter {l₁ l₂} (s : l₁ <+ l₂) : filter p l₁ <+ filter p l₂ := by rw ← filter_map_eq_filter; exact filter_map_sublist_filter_map _ s @[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) := by by_cases pa : p a; simp [span, take_while, drop_while, pa, span_eq_take_drop l] @[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) := by by_cases pa : p a; simp [take_while, drop_while, pa, take_while_append_drop l] /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs @[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; [refl, by_cases (p x)]; simp [*, -add_comm] 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 theorem countp_pos {l} : 0 < countp p l ↔ ∃ a ∈ l, p a := by simp [countp_eq_length_filter, length_pos_iff_exists_mem] theorem countp_le_of_sublist {l₁ l₂} (s : l₁ <+ l₂) : countp p l₁ ≤ countp p l₂ := by simpa using length_le_of_sublist (filter_sublist_filter s) end filter /- count -/ section count variable [decidable_eq α] /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count (a : α) : list α → nat := countp (eq a) @[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] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (l : list α) : count a (b::l) = count a l := if_neg h 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 := by simp @[simp] theorem count_append (a : α) : ∀ l₁ l₂, count a (l₁ ++ l₂) = count a l₁ + count a l₂ := countp_append @[simp] theorem count_concat (a : α) (l : list α) : count a (concat l a) = succ (count a l) := by rw [concat_eq_append, count_append, count_singleton] theorem count_pos {a : α} {l : list α} : 0 < count a l ↔ a ∈ l := by simp [count, countp_pos] @[simp] 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 [count, countp_eq_length_filter], λ b m, (of_mem_filter m).symm⟩, by rw ← this; apply filter_sublist, λ h, by simpa using count_le_of_sublist a h⟩ end count /- prefix, suffix, infix -/ /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_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⟩ @[simp] theorem infix_append (l₁ l₂ l₃ : list α) : l₂ <:+: l₁ ++ l₂ ++ l₃ := ⟨l₁, l₃, rfl⟩ 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] @[simp] 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 [h]⟩ @[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₂, by simp⟩ @[trans] theorem is_suffix.trans : ∀ {l₁ l₂ l₃ : list α}, l₁ <:+ l₂ → l₂ <:+ l₃ → l₁ <:+ l₃ | l ._ ._ ⟨l₁, rfl⟩ ⟨l₂, rfl⟩ := ⟨l₂ ++ l₁, by simp⟩ @[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⟩ 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 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_left_inj {l₁ l₂ : list α} (l) : l ++ l₁ <+: l ++ l₂ ↔ l₁ <+: l₂ := exists_congr $ λ r, by rw [append_assoc, append_left_inj] theorem prefix_cons_inj {l₁ l₂ : list α} (a) : a :: l₁ <+: a :: l₂ ↔ l₁ <+: l₂ := prefix_append_left_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 prefix_iff_eq_append {l₁ l₂ : list α} : l₁ <+: l₂ ↔ l₁ ++ drop (length l₁) l₂ = l₂ := ⟨λ h, let ⟨r, e⟩ := h in begin rwa append_inj_left ((take_append_drop (length l₁) l₂).trans e.symm) _, simp [min_eq_left, length_le_of_sublist (sublist_of_prefix h)], end, λ e, ⟨_, e⟩⟩ theorem suffix_iff_eq_append {l₁ l₂ : list α} : l₁ <:+ l₂ ↔ take (length l₂ - length l₁) l₂ ++ l₁ = l₂ := ⟨λ ⟨r, e⟩, begin rwa append_inj_right ((take_append_drop (length l₂ - length l₁) l₂).trans e.symm) _, simp [min_eq_left, nat.sub_le, e.symm], apply nat.add_sub_cancel_left end, λ 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 /-- `inits l` is the list of initial segments of `l`. `inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]]` -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) @[simp] theorem mem_inits : ∀ (s t : list α), s ∈ inits t ↔ s <+: t | s [] := suffices s = nil ↔ s <+: nil, by simpa, ⟨λ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⟩ /-- `tails l` is the list of terminal segments of `l`. `tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []]` -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l @[simp] theorem mem_tails : ∀ (s t : list α), s ∈ tails t ↔ s <:+ t | s [] := by simp; exact ⟨λh, by rw h; exact suffix_refl [], eq_nil_of_suffix_nil⟩ | s (a::t) := by simp [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 -/ def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. `sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]` -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] @[simp] theorem sublists'_nil : sublists' (@nil α) = [[]] := rfl @[simp] 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; simp! * 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; simp! * 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 [sublists'_aux_eq_sublists'] @[simp] theorem mem_sublists' {s t : list α} : s ∈ sublists' t ↔ s <+ t := begin induction t with a t IH generalizing s; simp, { exact ⟨λ h, by rw h, eq_nil_of_sublist_nil⟩ }, split; intro h, rcases h with h | ⟨s, h, rfl⟩, { exact sublist_cons_of_sublist _ (IH.1 h) }, { exact cons_sublist_cons _ (IH.1 h) }, { cases h with _ _ _ h s _ _ h, { exact or.inl (IH.2 h) }, { exact or.inr ⟨s, IH.2 h, rfl⟩ } } end @[simp] theorem length_sublists' : ∀ l : list α, length (sublists' l) = 2 ^ length l | [] := rfl | (a::l) := by simp [-add_comm, *]; rw [← two_mul, mul_comm]; refl def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`. `sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]` -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons @[simp] theorem sublists_nil : sublists (@nil α) = [[]] := rfl @[simp] theorem sublists_singleton (a : α) : sublists [a] = [[], [a]] := rfl def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) 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 * 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 [sublists_aux], rw [IH₂, IH₁], congr' 1, induction sublists_aux l cons with _ _ ih; simp * 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 [sublists_aux₁] | (a::l₁) l₂ f := by simp [sublists_aux₁]; rw [sublists_aux₁_append]; simp 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 [sublists_aux₁_append, sublists_aux₁] 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 := by simp [sublists_aux₁] | (a::l) f g := by simp [sublists_aux₁]; rw [sublists_aux₁_bind]; simp 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 [sublists, sublists_aux_cons_eq_sublists_aux₁], rw [sublists_aux₁_append, sublists_aux₁_bind], congr, funext x, simp, rw [← bind_ret_eq_map, sublists_aux₁_bind], simp [list.ret] end theorem sublists_append (l₁ l₂ : list α) : sublists (l₁ ++ l₂) = (do x ← sublists l₂, (++ x) <$> sublists l₁) := by simp [sublists_aux_cons_append, sublists, map_id'] @[simp] theorem sublists_concat (l : list α) (a : α) : sublists (l ++ [a]) = sublists l ++ map (λ x, x ++ [a]) (sublists l) := by simp [sublists_append]; rw [sublists, sublists_aux_cons_eq_sublists_aux₁]; simp [map_id', sublists_aux₁] theorem sublists_reverse (l : list α) : sublists (reverse l) = map reverse (sublists' l) := by induction l; simp [(∘), *] 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 [sublists_eq_sublists', map_id'] 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; simp [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_inj reverse_injective] @[simp] theorem length_sublists (l : list α) : length (sublists l) = 2 ^ length l := by simp [sublists_eq_sublists', length_sublists'] theorem map_ret_sublist_sublists (l : list α) : map list.ret l <+ sublists l := reverse_rec_on l (nil_sublist _) $ λ l a IH, by simp; exact ((append_sublist_append_left _).2 (singleton_sublist.2 $ mem_map.2 ⟨[], by simp [list.ret]⟩)).trans ((append_sublist_append_right _).2 IH) /- transpose -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. `transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]]` -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /- forall₂ -/ section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} open relator relation inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil {} : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) run_cmd tactic.mk_iff_of_inductive_prop `list.forall₂ `list.forall₂_iff attribute [simp] forall₂.nil @[simp] theorem forall₂_cons {R : α → β → Prop} {a b l₁ l₂} : forall₂ R (a::l₁) (b::l₂) ↔ R a b ∧ forall₂ R l₁ l₂ := ⟨λ h, by cases h with h₁ h₂; simp *, λ ⟨h₁, h₂⟩, forall₂.cons h₁ h₂⟩ lemma forall₂_flip : ∀{a b}, forall₂ (flip r) b a → forall₂ r a b | _ _ forall₂.nil := forall₂.nil | (a :: as) (b :: bs) (forall₂.cons h₁ h₂) := forall₂.cons h₁ (forall₂_flip h₂) lemma forall₂_same {r : α → α → Prop} : ∀{l}, (∀x∈l, r x x) → forall₂ r l l | [] _ := forall₂.nil | (a::as) h := forall₂.cons (h _ (mem_cons_self _ _)) (forall₂_same $ assume a ha, h a $ mem_cons_of_mem _ ha) lemma forall₂_refl {r} [is_refl α r] (l : list α) : forall₂ r l l := forall₂_same $ assume a h, is_refl.refl _ _ lemma forall₂_eq_eq_eq : forall₂ ((=) : α → α → Prop) = (=) := begin funext a b, apply propext, split, { assume h, induction h; simp * }, { assume h, subst h, exact forall₂_refl _ } end @[simp] lemma forall₂_nil_left_iff {l} : forall₂ r nil l ↔ l = nil := by rw [forall₂_iff]; simp @[simp] lemma forall₂_nil_right_iff {l} : forall₂ r l nil ↔ l = nil := by rw [forall₂_iff]; simp lemma forall₂_cons_left_iff {a l u} : forall₂ r (a::l) u ↔ (∃b u', r a b ∧ forall₂ r l u' ∧ u = b :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) lemma forall₂_cons_right_iff {b l u} : forall₂ r u (b::l) ↔ (∃a u', r a b ∧ forall₂ r u' l ∧ u = a :: u') := iff.intro (assume h, match u, h with (b :: u'), forall₂.cons h₁ h₂ := ⟨b, u', h₁, h₂, rfl⟩ end) (assume h, match u, h with _, ⟨b, u', h₁, h₂, rfl⟩ := forall₂.cons h₁ h₂ end) @[simp] lemma forall₂_map_left_iff {f : γ → α} : ∀{l u}, forall₂ r (map f l) u ↔ forall₂ (λc b, r (f c) b) l u | [] _ := by simp | (a::l) _ := by simp [forall₂_cons_left_iff, forall₂_map_left_iff] @[simp] lemma forall₂_map_right_iff {f : γ → β} : ∀{l u}, forall₂ r l (map f u) ↔ forall₂ (λa c, r a (f c)) l u | _ [] := by simp | _ (b::u) := by simp [forall₂_cons_right_iff, forall₂_map_right_iff] lemma left_unique_forall₂ (hr : left_unique r) : left_unique (forall₂ r) | a₀ nil a₁ forall₂.nil forall₂.nil := rfl | (a₀::l₀) (b::l) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ left_unique_forall₂ h₀ h₁ ▸ rfl lemma right_unique_forall₂ (hr : right_unique r) : right_unique (forall₂ r) | nil a₀ a₁ forall₂.nil forall₂.nil := rfl | (b::l) (a₀::l₀) (a₁::l₁) (forall₂.cons ha₀ h₀) (forall₂.cons ha₁ h₁) := hr ha₀ ha₁ ▸ right_unique_forall₂ h₀ h₁ ▸ rfl lemma bi_unique_forall₂ (hr : bi_unique r) : bi_unique (forall₂ r) := ⟨assume a b c, left_unique_forall₂ hr.1, assume a b c, right_unique_forall₂ hr.2⟩ theorem forall₂_length_eq {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → length l₁ = length l₂ | _ _ forall₂.nil := rfl | _ _ (forall₂.cons h₁ h₂) := congr_arg succ (forall₂_length_eq h₂) theorem forall₂_zip {R : α → β → Prop} : ∀ {l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b | _ _ (forall₂.cons h₁ h₂) x y (or.inl rfl) := h₁ | _ _ (forall₂.cons h₁ h₂) x y (or.inr h₃) := forall₂_zip h₂ h₃ theorem forall₂_iff_zip {R : α → β → Prop} {l₁ l₂} : forall₂ R l₁ l₂ ↔ length l₁ = length l₂ ∧ ∀ {a b}, (a, b) ∈ zip l₁ l₂ → R a b := ⟨λ h, ⟨forall₂_length_eq h, @forall₂_zip _ _ _ _ _ h⟩, λ h, begin cases h with h₁ h₂, induction l₁ with a l₁ IH generalizing l₂, { simp [length_eq_zero.1 h₁.symm] }, { cases l₂ with b l₂; injection h₁ with h₁, exact forall₂.cons (h₂ $ or.inl rfl) (IH h₁ $ λ a b h, h₂ $ or.inr h) } end⟩ lemma rel_mem (hr : bi_unique r) : (r ⇒ forall₂ r ⇒ iff) (∈) (∈) | a b h [] [] forall₂.nil := by simp | a b h (a'::as) (b'::bs) (forall₂.cons h₁ h₂) := rel_or (rel_eq hr h h₁) (rel_mem h h₂) lemma rel_map : ((r ⇒ p) ⇒ forall₂ r ⇒ forall₂ p) map map | f g h [] [] forall₂.nil := by simp [forall₂.nil] | f g h (a::as) (b::bs) (forall₂.cons h₁ h₂) := forall₂.cons (h h₁) (rel_map @h h₂) lemma rel_append : (forall₂ r ⇒ forall₂ r ⇒ forall₂ r) append append | [] [] h l₁ l₂ hl := hl | (a::as) (b::bs) (forall₂.cons h₁ h₂) l₁ l₂ hl := forall₂.cons h₁ (rel_append h₂ hl) lemma rel_join : (forall₂ (forall₂ r) ⇒ forall₂ r) join join | [] [] forall₂.nil := by simp [forall₂.nil] | (a::as) (b::bs) (forall₂.cons h₁ h₂) := rel_append h₁ (rel_join h₂) lemma rel_bind : (forall₂ r ⇒ (r ⇒ forall₂ p) ⇒ forall₂ p) list.bind list.bind := assume a b h₁ f g h₂, rel_join (rel_map @h₂ h₁) lemma rel_foldl : ((p ⇒ r ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldl foldl | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := rel_foldl @hfg (hfg hxy hab) hs lemma rel_foldr : ((r ⇒ p ⇒ p) ⇒ p ⇒ forall₂ r ⇒ p) foldr foldr | f g hfg _ _ h _ _ forall₂.nil := h | f g hfg x y hxy _ _ (forall₂.cons hab hs) := hfg hab (rel_foldr @hfg hxy hs) lemma rel_filter {p : α → Prop} {q : β → Prop} [decidable_pred p] [decidable_pred q] (hpq : (r ⇒ (↔)) p q) : (forall₂ r ⇒ forall₂ r) (filter p) (filter q) | _ _ forall₂.nil := forall₂.nil | (a::as) (b::bs) (forall₂.cons h₁ h₂) := begin by_cases p a, { have : q b, { rwa [← hpq h₁] }, simp [h, this, h₁, rel_filter h₂], }, { have : ¬ q b, { rwa [← hpq h₁] }, simp [h, this, h₁, rel_filter h₂], }, end theorem filter_map_cons (f : α → option β) (a : α) (l : list α) : filter_map f (a :: l) = option.cases_on (f a) (filter_map f l) (λb, b :: filter_map f l) := begin generalize eq : f a = b, cases b, { simp [filter_map_cons_none _ _ eq]}, { simp [filter_map_cons_some _ _ _ eq]}, end lemma rel_filter_map {f : α → option γ} {q : β → option δ} : ((r ⇒ option.rel p) ⇒ forall₂ r ⇒ forall₂ p) filter_map filter_map | f g hfg _ _ forall₂.nil := forall₂.nil | f g hfg (a::as) (b::bs) (forall₂.cons h₁ h₂) := by rw [filter_map_cons, filter_map_cons]; from match f a, g b, hfg h₁ with | _, _, option.rel.none := rel_filter_map @hfg h₂ | _, _, option.rel.some h := forall₂.cons h (rel_filter_map @hfg h₂) end @[to_additive list.rel_sum] lemma rel_prod [monoid α] [monoid β] (h : r 1 1) (hf : (r ⇒ r ⇒ r) (*) (*)) : (forall₂ r ⇒ r) prod prod := assume a b, rel_foldl (assume a b, hf) h end forall₂ /- sections -/ /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l theorem mem_sections {L : list (list α)} {f} : f ∈ sections L ↔ forall₂ (∈) f L := begin refine ⟨λ h, _, λ h, _⟩, { induction L generalizing f; simp [sections] at h; casesm* [Exists _, _ ∧ _, _ = _]; simp * }, { induction h with a l f L al fL fs; simp [sections], exact ⟨_, fs, _, al, rfl, rfl⟩ } end theorem mem_sections_length {L : list (list α)} {f} (h : f ∈ sections L) : length f = length L := forall₂_length_eq (mem_sections.1 h) lemma rel_sections {r : α → β → Prop} : (forall₂ (forall₂ r) ⇒ forall₂ (forall₂ r)) sections sections | _ _ forall₂.nil := forall₂.cons forall₂.nil forall₂.nil | _ _ (forall₂.cons h₀ h₁) := rel_bind (rel_sections h₁) (assume _ _ hl, rel_map (assume _ _ ha, forall₂.cons ha hl) h₀) /- permutations -/ section permutations def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ _ (lt_add_of_pos_left _ (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] @[simp] theorem permutations_aux_nil (is : list α) : permutations_aux [] is = [] := by simp [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 simp [permutations_aux, permutations_aux.rec, permutations] 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] theorem insert_of_mem {a : α} {l : list α} (h : a ∈ l) : insert a l = l := by simp [insert.def, h] @[simp] theorem insert_of_not_mem {a : α} {l : list α} (h : a ∉ l) : insert a l = a :: l := by simp [insert.def, h] @[simp] theorem mem_insert_iff {a b : α} {l : list α} : a ∈ insert b l ↔ a = b ∨ a ∈ l := begin by_cases h' : b ∈ l; simp [h'], apply (or_iff_right_of_imp _).symm, exact λ e, e.symm ▸ h' end @[simp] theorem suffix_insert (a : α) (l : list α) : l <:+ insert a l := by by_cases a ∈ l; simp * @[simp] theorem mem_insert_self (a : α) (l : list α) : a ∈ insert a l := mem_insert_iff.2 (or.inl rfl) @[simp] 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 : α} [decidable_eq α] {l : list α} (h : a ∈ l) : length (insert a l) = length l := by simp [h] @[simp] theorem length_insert_of_not_mem {a : α} [decidable_eq α] {l : list α} (h : a ∉ l) : length (insert a l) = length l + 1 := by simp [h] end insert /- 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 [erase_cons] @[simp] theorem erase_cons_tail {a b : α} (l : list α) (h : b ≠ a) : (b::l).erase a = b :: l.erase a := by simp [erase_cons, h] @[simp] theorem erase_of_not_mem {a : α} {l : list α} (h : a ∉ l) : l.erase a = l := by induction l with _ _ ih; [refl, simp [(ne_of_not_mem_cons h).symm, ih (not_mem_of_not_mem_cons 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 induction l with b l ih; [cases h, { simp at h, by_cases e : b = a, { subst b, exact ⟨[], l, not_mem_nil _, rfl, by simp⟩ }, { exact let ⟨l₁, l₂, h₁, h₂, h₃⟩ := ih (h.resolve_left (ne.symm e)) in ⟨b::l₁, l₂, not_mem_cons_of_ne_of_not_mem (ne.symm e) h₁, by rw h₂; refl, by simp [e, h₃]⟩ } }] @[simp] theorem length_erase_of_mem {a : α} {l : list α} (h : a ∈ l) : length (l.erase a) = pred (length l) := match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp [-add_comm]; refl end theorem erase_append_left {a : α} : ∀ {l₁ : list α} (l₂), a ∈ l₁ → (l₁++l₂).erase a = l₁.erase a ++ l₂ | (x::xs) l₂ h := begin by_cases h' : x = a; simp [h'], rw erase_append_left l₂ (mem_of_ne_of_mem (ne.symm h') h) end theorem erase_append_right {a : α} : ∀ {l₁ : list α} (l₂), a ∉ l₁ → (l₁++l₂).erase a = l₁ ++ l₂.erase a | [] l₂ h := rfl | (x::xs) l₂ h := by simp [*, (ne_of_not_mem_cons h).symm, (not_mem_of_not_mem_cons h)] theorem erase_sublist (a : α) (l : list α) : l.erase a <+ l := if h : a ∈ l then match l, l.erase a, exists_erase_eq h with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩ := by simp end else by simp [h] theorem erase_subset (a : α) (l : list α) : l.erase a ⊆ l := subset_of_sublist (erase_sublist a l) theorem erase_sublist_erase (a : α) : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → l₁.erase a <+ l₂.erase a | ._ ._ sublist.slnil := sublist.slnil | ._ ._ (sublist.cons l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head]; exact (erase_sublist _ _).trans s else by rw erase_cons_tail _ h; exact (erase_sublist_erase s).cons _ _ _ | ._ ._ (sublist.cons2 l₁ l₂ b s) := if h : b = a then by rw [h, erase_cons_head, erase_cons_head]; exact s else by rw [erase_cons_tail _ h, erase_cons_tail _ h]; exact (erase_sublist_erase s).cons2 _ _ _ 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 := ⟨mem_of_mem_erase, λ al, if h : b ∈ l then match l, l.erase b, exists_erase_eq h, al with | ._, ._, ⟨l₁, l₂, _, rfl, rfl⟩, al := by simpa [ab] using al end else by simp [h, al]⟩ theorem erase_comm (a b : α) (l : list α) : (l.erase a).erase b = (l.erase b).erase a := if ab : a = b then by simp [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 [hb, mt mem_of_mem_erase hb] else by simp [ha, 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 simp [list.erase] | (b::l) := if h : f b = f a then by simp [h, finj h] else by simp [h, mt (congr_arg f) h, map_erase l] 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₁; simp [map_erase finj, *] 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₂ := by by_cases a ∈ l₁; simp [list.diff, h] 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 [diff_eq_foldl] @[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 [diff_eq_foldl, map_foldl_erase finj] end diff /- zip & unzip -/ @[simp] theorem zip_cons_cons (a : α) (b : β) (l₁ : list α) (l₂ : list β) : zip (a :: l₁) (b :: l₂) = (a, b) :: zip l₁ l₂ := rfl @[simp] theorem zip_nil_left (l : list α) : zip ([] : list β) l = [] := rfl @[simp] theorem zip_nil_right (l : list α) : zip l ([] : list β) = [] := by cases l; refl @[simp] theorem unzip_nil : unzip (@nil (α × β)) = ([], []) := rfl @[simp] theorem unzip_cons (a : α) (b : β) (l : list (α × β)) : unzip ((a, b) :: l) = (a :: (unzip l).1, b :: (unzip l).2) := by rw unzip; cases unzip l; refl theorem zip_unzip : ∀ (l : list (α × β)), zip (unzip l).1 (unzip l).2 = l | [] := rfl | ((a, b) :: l) := by simp [zip_unzip l] /- 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 [enum] @[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 _ /- product -/ /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a @[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 [product, and.left_comm] theorem length_product (l₁ : list α) (l₂ : list β) : length (product l₁ l₂) = length l₁ * length l₂ := by induction l₁ with x l₁ IH; simp [*, right_distrib] /- sigma -/ section variable {σ : α → Type*} /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [5, 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a @[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 [list.sigma, and.left_comm] 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; simp * end /- of_fn -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] theorem length_of_fn_aux {n} (f : fin n → α) : ∀ m h l, length (of_fn_aux f m h l) = length l + m | 0 h l := rfl | (succ m) h l := (length_of_fn_aux m _ _).trans (succ_add _ _) theorem length_of_fn {n} (f : fin n → α) : length (of_fn f) = n := (length_of_fn_aux f _ _ _).trans (zero_add _) def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : _ then some (f ⟨i, h⟩) else none theorem nth_of_fn_aux {n} (f : fin n → α) (i) : ∀ m h l, (∀ i, nth l i = of_fn_nth_val f (i + m)) → nth (of_fn_aux f m h l) i = of_fn_nth_val f i | 0 h l H := H i | (succ m) h l H := nth_of_fn_aux m _ _ begin intro j, cases j with j, { simp [of_fn_nth_val, show m < n, from h], refl }, { simp [H, succ_add, -add_comm] } end @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = of_fn_nth_val f i := nth_of_fn_aux f _ _ _ _ $ λ i, by simp [of_fn_nth_val, not_lt.2 (le_add_right n i)] theorem nth_le_of_fn {n} (f : fin n → α) (i : fin n) : nth_le (of_fn f) i.1 ((length_of_fn f).symm ▸ i.2) = f i := option.some.inj $ by rw [← nth_le_nth]; simp [of_fn_nth_val, i.2]; cases i; refl theorem array_eq_of_fn {n} (a : array n α) : a.to_list = of_fn a.read := suffices ∀ {m h l}, d_array.rev_iterate_aux a (λ i, cons) m h l = of_fn_aux (d_array.read a) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, simp [d_array.rev_iterate_aux, of_fn_aux, IH] end theorem of_fn_zero (f : fin 0 → α) : of_fn f = [] := rfl theorem of_fn_succ {n} (f : fin (succ n) → α) : of_fn f = f 0 :: of_fn (λ i, f i.succ) := suffices ∀ {m h l}, of_fn_aux f (succ m) (succ_le_succ h) l = f 0 :: of_fn_aux (λ i, f i.succ) m h l, from this, begin intros, induction m with m IH generalizing l, {refl}, rw [of_fn_aux, IH], refl end theorem of_fn_nth_le : ∀ l : list α, of_fn (λ i, nth_le l i.1 i.2) = l | [] := rfl | (a::l) := by rw of_fn_succ; congr; simp; exact of_fn_nth_le l /- disjoint -/ section disjoint /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false theorem disjoint.symm {l₁ l₂ : list α} (d : disjoint l₁ l₂) : disjoint l₂ l₁ | a i₂ i₁ := d i₁ i₂ @[simp] 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 [disjoint_left, imp_not_comm] 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 singleton_disjoint {l : list α} {a : α} : disjoint [a] l ↔ a ∉ l := by simp [disjoint]; refl @[simp] theorem disjoint_singleton {l : list α} {a : α} : disjoint l [a] ↔ a ∉ l := by rw disjoint_comm; simp @[simp] theorem disjoint_append_left {l₁ l₂ l : list α} : disjoint (l₁++l₂) l ↔ disjoint l₁ l ∧ disjoint l₂ l := by simp [disjoint, 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 [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 @[simp] theorem disjoint_cons_right {a : α} {l₁ l₂ : list α} : disjoint l₁ (a::l₂) ↔ a ∉ l₁ ∧ disjoint l₁ l₂ := disjoint_comm.trans $ by simp [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 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 [*, 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 by simp [e.symm]; by_cases h : a ∈ t ++ l₂; [existsi t, existsi a::t]; simp [h]; [apply sublist_cons_of_sublist _ s, apply cons_sublist_cons _ s] 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 [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 [eq_nil_iff_forall_not_mem]; 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 end inter /- bag_inter -/ section bag_inter variable [decidable_eq α] @[simp] theorem nil_bag_inter (l : list α) : [].bag_inter l = [] := by cases l; refl @[simp] theorem bag_inter_nil (l : list α) : l.bag_inter [] = [] := by cases l; refl @[simp] theorem cons_bag_inter_of_pos {a} (l₁ : list α) {l₂} (h : a ∈ l₂) : (a :: l₁).bag_inter l₂ = a :: l₁.bag_inter (l₂.erase a) := by cases l₂; exact if_pos h @[simp] theorem cons_bag_inter_of_neg {a} (l₁ : list α) {l₂} (h : a ∉ l₂) : (a :: l₁).bag_inter l₂ = l₁.bag_inter l₂ := by cases l₂; simp [h, list.bag_inter] theorem mem_bag_inter {a : α} : ∀ {l₁ l₂ : list α}, a ∈ l₁.bag_inter l₂ ↔ a ∈ l₁ ∧ a ∈ l₂ | [] l₂ := by simp | (b::l₁) l₂ := by by_cases b ∈ l₂; simp [*, and_or_distrib_left]; by_cases ba : a = b; simp * theorem bag_inter_sublist_left : ∀ l₁ l₂ : list α, l₁.bag_inter l₂ <+ l₁ | [] l₂ := by simp [nil_sublist] | (b::l₁) l₂ := begin by_cases b ∈ l₂; simp [h], { apply cons_sublist_cons, apply bag_inter_sublist_left }, { apply sublist_cons_of_sublist, apply bag_inter_sublist_left } end end bag_inter /- pairwise relation (generalized no duplicate) -/ section pairwise variable (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) attribute [simp] pairwise.nil run_cmd tactic.mk_iff_of_inductive_prop `list.pairwise `list.pariwise_iff variable {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ theorem rel_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : ∀ {a'}, a' ∈ l → R a a' := (pairwise_cons.1 p).1 theorem pairwise_of_pairwise_cons {a : α} {l : list α} (p : pairwise R (a::l)) : pairwise R l := (pairwise_cons.1 p).2 theorem pairwise.imp_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → R a b → S a b) (p : pairwise R l) : pairwise S l := begin induction p with a l r p IH generalizing H; constructor, { exact ball.imp_right (λ x h, H (mem_cons_self _ _) (mem_cons_of_mem _ h)) r }, { exact IH (λ a b m m', H (mem_cons_of_mem _ m) (mem_cons_of_mem _ m')) } end theorem pairwise.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {l : list α} : pairwise R l → pairwise S l := pairwise.imp_of_mem (λ a b _ _, H a b) theorem pairwise.and {S : α → α → Prop} {l : list α} : pairwise (λ a b, R a b ∧ S a b) l ↔ pairwise R l ∧ pairwise S l := ⟨λ h, ⟨h.imp (λ a b h, h.1), h.imp (λ a b h, h.2)⟩, λ ⟨hR, hS⟩, begin clear_, induction hR with a l R1 R2 IH; simp at *, exact ⟨λ b bl, ⟨R1 b bl, hS.1 b bl⟩, IH hS.2⟩ end⟩ theorem pairwise.imp₂ {S : α → α → Prop} {T : α → α → Prop} (H : ∀ a b, R a b → S a b → T a b) {l : list α} (hR : pairwise R l) (hS : pairwise S l) : pairwise T l := (pairwise.and.2 ⟨hR, hS⟩).imp $ λ a b, and.rec (H a b) theorem pairwise.iff_of_mem {S : α → α → Prop} {l : list α} (H : ∀ {a b}, a ∈ l → b ∈ l → (R a b ↔ S a b)) : pairwise R l ↔ pairwise S l := ⟨pairwise.imp_of_mem (λ a b m m', (H m m').1), pairwise.imp_of_mem (λ a b m m', (H m m').2)⟩ theorem pairwise.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {l : list α} : pairwise R l ↔ pairwise S l := pairwise.iff_of_mem (λ a b _ _, H a b) theorem pairwise_of_forall {l : list α} (H : ∀ x y, R x y) : pairwise R l := by induction l; simp * theorem pairwise.and_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l ∧ y ∈ l ∧ R x y) l := pairwise.iff_of_mem (by simp {contextual := tt}) theorem pairwise.imp_mem {l : list α} : pairwise R l ↔ pairwise (λ x y, x ∈ l → y ∈ l → R x y) l := pairwise.iff_of_mem (by simp {contextual := tt}) theorem pairwise_of_sublist : Π {l₁ l₂ : list α}, l₁ <+ l₂ → pairwise R l₂ → pairwise R l₁ | ._ ._ sublist.slnil h := h | ._ ._ (sublist.cons l₁ l₂ a s) (pairwise.cons i n) := pairwise_of_sublist s n | ._ ._ (sublist.cons2 l₁ l₂ a s) (pairwise.cons i n) := (pairwise_of_sublist s n).cons (ball.imp_left (subset_of_sublist s) i) theorem pairwise_singleton (R) (a : α) : pairwise R [a] := by simp theorem pairwise_pair {a b : α} : pairwise R [a, b] ↔ R a b := by simp theorem pairwise_append {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R l₁ ∧ pairwise R l₂ ∧ ∀ x ∈ l₁, ∀ y ∈ l₂, R x y := by induction l₁ with x l₁ IH; simp [*, or_imp_distrib, forall_and_distrib, and_assoc, and.left_comm] theorem pairwise_app_comm (s : symmetric R) {l₁ l₂ : list α} : pairwise R (l₁++l₂) ↔ pairwise R (l₂++l₁) := have ∀ l₁ l₂ : list α, (∀ (x : α), x ∈ l₁ → ∀ (y : α), y ∈ l₂ → R x y) → (∀ (x : α), x ∈ l₂ → ∀ (y : α), y ∈ l₁ → R x y), from λ l₁ l₂ a x xm y ym, s (a y ym x xm), by simp [pairwise_append, and.left_comm]; rw iff.intro (this l₁ l₂) (this l₂ l₁) theorem pairwise_middle (s : symmetric R) {a : α} {l₁ l₂ : list α} : pairwise R (l₁ ++ a::l₂) ↔ pairwise R (a::(l₁++l₂)) := show pairwise R (l₁ ++ ([a] ++ l₂)) ↔ pairwise R ([a] ++ l₁ ++ l₂), by rw [← append_assoc, pairwise_append, @pairwise_append _ _ ([a] ++ l₁), pairwise_app_comm s]; simp only [mem_append, or_comm] theorem pairwise_map (f : β → α) : ∀ {l : list β}, pairwise R (map f l) ↔ pairwise (λ a b : β, R (f a) (f b)) l | [] := by simp | (b::l) := have (∀ a b', b' ∈ l → f b' = a → R (f b) a) ↔ ∀ (b' : β), b' ∈ l → R (f b) (f b'), from forall_swap.trans $ forall_congr $ λ a, forall_swap.trans $ by simp, by simp *; rw this theorem pairwise_of_pairwise_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {l : list α} (p : pairwise S (map f l)) : pairwise R l := ((pairwise_map f).1 p).imp H theorem pairwise_map_of_pairwise {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {l : list α} (p : pairwise R l) : pairwise S (map f l) := (pairwise_map f).2 $ p.imp H theorem pairwise_filter_map (f : β → option α) {l : list β} : pairwise R (filter_map f l) ↔ pairwise (λ a a' : β, ∀ (b ∈ f a) (b' ∈ f a'), R b b') l := let S (a a' : β) := ∀ (b ∈ f a) (b' ∈ f a'), R b b' in begin simp, induction l with a l IH; simp, cases e : f a with b; simp [e, IH], rw [filter_map_cons_some _ _ _ e], simp [IH], show (∀ (a' : α) (x : β), x ∈ l → f x = some a' → R b a') ∧ pairwise S l ↔ (∀ (a' : β), a' ∈ l → ∀ (b' : α), f a' = some b' → R b b') ∧ pairwise S l, from and_congr ⟨λ h b mb a ma, h a b mb ma, λ h a b mb ma, h b mb a ma⟩ iff.rfl end theorem pairwise_filter_map_of_pairwise {S : β → β → Prop} (f : α → option β) (H : ∀ (a a' : α), R a a' → ∀ (b ∈ f a) (b' ∈ f a'), S b b') {l : list α} (p : pairwise R l) : pairwise S (filter_map f l) := (pairwise_filter_map _).2 $ p.imp H theorem pairwise_filter (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R (filter p l) ↔ pairwise (λ x y, p x → p y → R x y) l := begin rw [← filter_map_eq_filter, pairwise_filter_map], apply pairwise.iff, simp end theorem pairwise_filter_of_pairwise (p : α → Prop) [decidable_pred p] {l : list α} : pairwise R l → pairwise R (filter p l) := pairwise_of_sublist (filter_sublist _) theorem pairwise_join {L : list (list α)} : pairwise R (join L) ↔ (∀ l ∈ L, pairwise R l) ∧ pairwise (λ l₁ l₂, ∀ (x ∈ l₁) (y ∈ l₂), R x y) L := begin induction L with l L IH, {simp}, have : (∀ (x : α), x ∈ l → ∀ (y : α) (x_1 : list α), x_1 ∈ L → y ∈ x_1 → R x y) ↔ ∀ (a' : list α), a' ∈ L → ∀ (x : α), x ∈ l → ∀ (y : α), y ∈ a' → R x y := ⟨λ h a b c d e, h c d e a b, λ h c d e a b, h a b c d e⟩, simp [pairwise_append, IH, this], simp [and_assoc, and_comm, and.left_comm], end @[simp] theorem pairwise_reverse : ∀ {R} {l : list α}, pairwise R (reverse l) ↔ pairwise (λ x y, R y x) l := suffices ∀ {R l}, @pairwise α R l → pairwise (λ x y, R y x) (reverse l), from λ R l, ⟨λ p, reverse_reverse l ▸ this p, this⟩, λ R l p, by induction p with a l h p IH; [simp, simpa [pairwise_append, IH] using h] theorem pairwise_iff_nth_le {R} : ∀ {l : list α}, pairwise R l ↔ ∀ i j (h₁ : j < length l) (h₂ : i < j), R (nth_le l i (lt_trans h₂ h₁)) (nth_le l j h₁) | [] := by simp; exact λ i j h, (not_lt_zero j).elim h | (a::l) := begin rw [pairwise_cons, pairwise_iff_nth_le], refine ⟨λ H i j h₁ h₂, _, λ H, ⟨λ a' m, _, λ i j h₁ h₂, H _ _ (succ_lt_succ h₁) (succ_lt_succ h₂)⟩⟩, { cases j with j, {exact (not_lt_zero _).elim h₂}, cases i with i, { apply H.1, simp [nth_le_mem] }, { exact H.2 _ _ (lt_of_succ_lt_succ h₁) (lt_of_succ_lt_succ h₂) } }, { rcases nth_le_of_mem m with ⟨n, h, rfl⟩, exact H _ _ (succ_lt_succ h) (succ_pos _) } end theorem pairwise_sublists' {R} : ∀ {l : list α}, pairwise R l → pairwise (lex (swap R)) (sublists' l) | _ (pairwise.nil _) := pairwise_singleton _ _ | _ (@pairwise.cons _ _ a l H₁ H₂) := begin simp [pairwise_append, pairwise_map], have IH := pairwise_sublists' H₂, refine ⟨IH, IH.imp (λ l₁ l₂, lex.cons), _⟩, intros l₁ sl₁ x l₂ sl₂ e, subst e, cases l₁ with b l₁, {constructor}, exact lex.rel (H₁ _ $ subset_of_sublist sl₁ $ mem_cons_self _ _) end theorem pairwise_sublists {R} {l : list α} (H : pairwise R l) : pairwise (λ l₁ l₂, lex R (reverse l₁) (reverse l₂)) (sublists l) := by have := pairwise_sublists' (pairwise_reverse.2 H); rwa [sublists'_reverse, pairwise_map] at this variable [decidable_rel R] instance decidable_pairwise (l : list α) : decidable (pairwise R l) := by induction l; simp; resetI; apply_instance /- pairwise reduct -/ /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function, and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 5, 6] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH @[simp] theorem pw_filter_nil : pw_filter R [] = [] := rfl @[simp] theorem pw_filter_cons_of_pos {a : α} {l : list α} (h : ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = a :: pw_filter R l := if_pos h @[simp] theorem pw_filter_cons_of_neg {a : α} {l : list α} (h : ¬ ∀ b ∈ pw_filter R l, R a b) : pw_filter R (a::l) = pw_filter R l := if_neg h theorem pw_filter_sublist : ∀ (l : list α), pw_filter R l <+ l | [] := nil_sublist _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { rw [pw_filter_cons_of_pos h], exact cons_sublist_cons _ (pw_filter_sublist l) }, { rw [pw_filter_cons_of_neg h], exact sublist_cons_of_sublist _ (pw_filter_sublist l) }, end theorem pw_filter_subset (l : list α) : pw_filter R l ⊆ l := subset_of_sublist (pw_filter_sublist _) theorem pairwise_pw_filter : ∀ (l : list α), pairwise R (pw_filter R l) | [] := pairwise.nil _ | (x::l) := begin by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { rw [pw_filter_cons_of_pos h], exact pairwise_cons.2 ⟨h, pairwise_pw_filter l⟩ }, { rw [pw_filter_cons_of_neg h], exact pairwise_pw_filter l }, end theorem pw_filter_eq_self {l : list α} : pw_filter R l = l ↔ pairwise R l := ⟨λ e, e ▸ pairwise_pw_filter l, λ p, begin induction l with x l IH, {simp}, cases pairwise_cons.1 p with al p, rw [pw_filter_cons_of_pos (ball.imp_left (pw_filter_subset l) al), IH p], end⟩ @[simp] theorem pw_filter_idempotent {l : list α} : pw_filter R (pw_filter R l) = pw_filter R l := pw_filter_eq_self.mpr (pairwise_pw_filter l) theorem forall_mem_pw_filter (neg_trans : ∀ {x y z}, R x z → R x y ∨ R y z) (a : α) (l : list α) : (∀ b ∈ pw_filter R l, R a b) ↔ (∀ b ∈ l, R a b) := ⟨begin induction l with x l IH; simp *, by_cases (∀ y ∈ pw_filter R l, R x y); dsimp at h, { simp [pw_filter_cons_of_pos h], exact λ r H, ⟨r, IH H⟩ }, { rw [pw_filter_cons_of_neg h], refine λ H, ⟨_, IH H⟩, cases e : find (λ y, ¬ R x y) (pw_filter R l) with k, { refine h.elim (ball.imp_right _ (find_eq_none.1 e)), exact λ y _, not_not.1 }, { have := find_some e, exact (neg_trans (H k (find_mem e))).resolve_right this } } end, ball.imp_left (pw_filter_subset l)⟩ end pairwise /- chain relation (conjunction of R a b ∧ R b c ∧ R c d ...) -/ section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. `chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d` -/ inductive chain : α → list α → Prop | nil (a : α) : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) attribute [simp] chain.nil run_cmd tactic.mk_iff_of_inductive_prop `list.chain `list.chain_iff variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ theorem rel_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : R a b := (chain_cons.1 p).1 theorem chain_of_chain_cons {a b : α} {l : list α} (p : chain R a (b::l)) : chain R b l := (chain_cons.1 p).2 theorem chain.imp {S : α → α → Prop} (H : ∀ a b, R a b → S a b) {a : α} {l : list α} (p : chain R a l) : chain S a l := by induction p with _ a b l r p IH; constructor; [exact H _ _ r, exact IH] theorem chain.iff {S : α → α → Prop} (H : ∀ a b, R a b ↔ S a b) {a : α} {l : list α} : chain R a l ↔ chain S a l := ⟨chain.imp (λ a b, (H a b).1), chain.imp (λ a b, (H a b).2)⟩ theorem chain.iff_mem {S : α → α → Prop} {a : α} {l : list α} : chain R a l ↔ chain (λ x y, x ∈ a :: l ∧ y ∈ l ∧ R x y) a l := ⟨λ p, by induction p with _ a b l r p IH; constructor; [exact ⟨mem_cons_self _ _, mem_cons_self _ _, r⟩, exact IH.imp (λ a b ⟨am, bm, h⟩, ⟨mem_cons_of_mem _ am, mem_cons_of_mem _ bm, h⟩)], chain.imp (λ a b h, h.2.2)⟩ theorem chain_singleton {a b : α} : chain R a [b] ↔ R a b := by simp theorem chain_split {a b : α} {l₁ l₂ : list α} : chain R a (l₁++b::l₂) ↔ chain R a (l₁++[b]) ∧ chain R b l₂ := by induction l₁ with x l₁ IH generalizing a; simp [*, and_assoc] theorem chain_map (f : β → α) {b : β} {l : list β} : chain R (f b) (map f l) ↔ chain (λ a b : β, R (f a) (f b)) b l := by induction l generalizing b; simp * theorem chain_of_chain_map {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, S (f a) (f b) → R a b) {a : α} {l : list α} (p : chain S (f a) (map f l)) : chain R a l := ((chain_map f).1 p).imp H theorem chain_map_of_chain {S : β → β → Prop} (f : α → β) (H : ∀ a b : α, R a b → S (f a) (f b)) {a : α} {l : list α} (p : chain R a l) : chain S (f a) (map f l) := (chain_map f).2 $ p.imp H theorem chain_of_pairwise {a : α} {l : list α} (p : pairwise R (a::l)) : chain R a l := begin cases pairwise_cons.1 p with r p', clear p, induction p' with b l r' p IH generalizing a; simp, simp at r, simp [r], show chain R b l, from IH r' end theorem chain_iff_pairwise (tr : transitive R) {a : α} {l : list α} : chain R a l ↔ pairwise R (a::l) := ⟨λ c, begin induction c with b b c l r p IH, {simp}, apply IH.cons _, simp [r], show ∀ x ∈ l, R b x, from λ x m, (tr r (rel_of_pairwise_cons IH m)), end, chain_of_pairwise⟩ instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp; resetI; apply_instance end chain /- no duplicates predicate -/ /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) section nodup @[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_nil : @nodup α [] := pairwise.nil _ @[simp] theorem nodup_cons {a : α} {l : list α} : nodup (a::l) ↔ a ∉ l ∧ nodup l := by simp [nodup] lemma rel_nodup {r : α → β → Prop} (hr : relator.bi_unique r) : (forall₂ r ⇒ (↔)) nodup nodup | _ _ forall₂.nil := by simp | _ _ (forall₂.cons hab h) := by simpa using relator.rel_and (relator.rel_not (rel_mem hr hab h)) (rel_nodup h) theorem nodup_cons_of_nodup {a : α} {l : list α} (m : a ∉ l) (n : nodup l) : nodup (a::l) := nodup_cons.2 ⟨m, n⟩ theorem nodup_singleton (a : α) : nodup [a] := nodup_cons_of_nodup (not_mem_nil a) nodup_nil theorem nodup_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : nodup l := (nodup_cons.1 h).2 theorem not_mem_of_nodup_cons {a : α} {l : list α} (h : nodup (a::l)) : a ∉ l := (nodup_cons.1 h).1 theorem not_nodup_cons_of_mem {a : α} {l : list α} : a ∈ l → ¬ nodup (a :: l) := imp_not_comm.1 not_mem_of_nodup_cons theorem nodup_of_sublist {l₁ l₂ : list α} : l₁ <+ l₂ → nodup l₂ → nodup l₁ := pairwise_of_sublist theorem not_nodup_pair (a : α) : ¬ nodup [a, a] := not_nodup_cons_of_mem $ mem_singleton_self _ theorem nodup_iff_sublist {l : list α} : nodup l ↔ ∀ a, ¬ [a, a] <+ l := ⟨λ d a h, not_nodup_pair a (nodup_of_sublist h d), begin induction l with a l IH; intro h, {simp}, exact nodup_cons_of_nodup (λ al, h a $ cons_sublist_cons _ $ singleton_sublist.2 al) (IH $ λ a s, h a $ sublist_cons_of_sublist _ s) end⟩ theorem nodup_iff_nth_le_inj {l : list α} : nodup l ↔ ∀ i j h₁ h₂, nth_le l i h₁ = nth_le l j h₂ → i = j := pairwise_iff_nth_le.trans ⟨λ H i j h₁ h₂ h, ((lt_trichotomy _ _) .resolve_left (λ h', H _ _ h₂ h' h)) .resolve_right (λ h', H _ _ h₁ h' h.symm), λ H i j h₁ h₂ h, ne_of_lt h₂ (H _ _ _ _ h)⟩ @[simp] theorem nth_le_index_of [decidable_eq α] {l : list α} (H : nodup l) (n h) : index_of (nth_le l n h) l = n := nodup_iff_nth_le_inj.1 H _ _ _ h $ index_of_nth_le $ index_of_lt_length.2 $ nth_le_mem _ _ _ theorem nodup_iff_count_le_one [decidable_eq α] {l : list α} : nodup l ↔ ∀ a, count a l ≤ 1 := nodup_iff_sublist.trans $ forall_congr $ λ a, have [a, a] <+ l ↔ 1 < count a l, from (@le_count_iff_repeat_sublist _ _ a l 2).symm, (not_congr this).trans not_lt @[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {l : list α} (d : nodup l) (h : a ∈ l) : count a l = 1 := le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h) theorem nodup_of_nodup_append_left {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₁ := nodup_of_sublist (sublist_append_left l₁ l₂) theorem nodup_of_nodup_append_right {l₁ l₂ : list α} : nodup (l₁++l₂) → nodup l₂ := nodup_of_sublist (sublist_append_right l₁ l₂) theorem nodup_append {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup l₁ ∧ nodup l₂ ∧ disjoint l₁ l₂ := by simp [nodup, pairwise_append, disjoint_iff_ne] theorem disjoint_of_nodup_append {l₁ l₂ : list α} (d : nodup (l₁++l₂)) : disjoint l₁ l₂ := (nodup_append.1 d).2.2 theorem nodup_append_of_nodup {l₁ l₂ : list α} (d₁ : nodup l₁) (d₂ : nodup l₂) (dj : disjoint l₁ l₂) : nodup (l₁++l₂) := nodup_append.2 ⟨d₁, d₂, dj⟩ theorem nodup_app_comm {l₁ l₂ : list α} : nodup (l₁++l₂) ↔ nodup (l₂++l₁) := by simp [nodup_append, and.left_comm] theorem nodup_middle {a : α} {l₁ l₂ : list α} : nodup (l₁ ++ a::l₂) ↔ nodup (a::(l₁++l₂)) := by simp [nodup_append, not_or_distrib, and.left_comm, and_assoc] theorem nodup_of_nodup_map (f : α → β) {l : list α} : nodup (map f l) → nodup l := pairwise_of_pairwise_map f $ λ a b, mt $ congr_arg f theorem nodup_map_on {f : α → β} {l : list α} (H : ∀x∈l, ∀y∈l, f x = f y → x = y) (d : nodup l) : nodup (map f l) := pairwise_map_of_pairwise _ (by exact λ a b ⟨ma, mb, n⟩ e, n (H a ma b mb e)) (pairwise.and_mem.1 d) theorem nodup_map {f : α → β} {l : list α} (hf : injective f) : nodup l → nodup (map f l) := nodup_map_on (assume x _ y _ h, hf h) theorem nodup_map_iff {f : α → β} {l : list α} (hf : injective f) : nodup (map f l) ↔ nodup l := ⟨nodup_of_nodup_map _, nodup_map hf⟩ @[simp] theorem nodup_attach {l : list α} : nodup (attach l) ↔ nodup l := ⟨λ h, attach_map_val l ▸ nodup_map (λ a b, subtype.eq) h, λ h, nodup_of_nodup_map subtype.val ((attach_map_val l).symm ▸ h)⟩ theorem nodup_pmap {p : α → Prop} {f : Π a, p a → β} {l : list α} {H} (hf : ∀ a ha b hb, f a ha = f b hb → a = b) (h : nodup l) : nodup (pmap f l H) := by rw [pmap_eq_map_attach]; exact nodup_map (λ ⟨a, ha⟩ ⟨b, hb⟩ h, by congr; exact hf a (H _ ha) b (H _ hb) h) (nodup_attach.2 h) theorem nodup_filter (p : α → Prop) [decidable_pred p] {l} : nodup l → nodup (filter p l) := pairwise_filter_of_pairwise p @[simp] theorem nodup_reverse {l : list α} : nodup (reverse l) ↔ nodup l := pairwise_reverse.trans $ by simp [nodup, eq_comm] instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise theorem nodup_erase_eq_filter [decidable_eq α] (a : α) {l} (d : nodup l) : l.erase a = filter (≠ a) l := begin induction d with b l m d IH; simp [list.erase, list.filter], by_cases b = a; simp *, subst b, show l = filter (λ a', ¬ a' = a) l, rw filter_eq_self.2, simpa only [eq_comm] using m end theorem nodup_erase_of_nodup [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) := nodup_of_sublist (erase_sublist _ _) 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_join {L : list (list α)} : nodup (join L) ↔ (∀ l ∈ L, nodup l) ∧ pairwise disjoint L := by simp [nodup, pairwise_join, disjoint_left.symm] theorem nodup_bind {l₁ : list α} {f : α → list β} : nodup (l₁.bind f) ↔ (∀ x ∈ l₁, nodup (f x)) ∧ pairwise (λ (a b : α), disjoint (f a) (f b)) l₁ := by simp [list.bind, nodup_join, pairwise_map, and_comm, and.left_comm]; rw [show (∀ (l : list β) (x : α), f x = l → x ∈ l₁ → nodup l) ↔ (∀ (x : α), x ∈ l₁ → nodup (f x)), from forall_swap.trans $ forall_congr $ λ_, by simp] theorem nodup_product {l₁ : list α} {l₂ : list β} (d₁ : nodup l₁) (d₂ : nodup l₂) : nodup (product l₁ l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (injective_of_left_inverse (λ b, (rfl : (a,b).2 = b))) d₂, d₁.imp (λ a₁ a₂ n x, suffices ∀ (b₁ : β), b₁ ∈ l₂ → (a₁, b₁) = x → ∀ (b₂ : β), b₂ ∈ l₂ → (a₂, b₂) ≠ x, by simpa, λ b₁ mb₁ e b₂ mb₂ e', by subst e'; injection e; contradiction)⟩ theorem nodup_sigma {σ : α → Type*} {l₁ : list α} {l₂ : Π a, list (σ a)} (d₁ : nodup l₁) (d₂ : ∀ a, nodup (l₂ a)) : nodup (l₁.sigma l₂) := nodup_bind.2 ⟨λ a ma, nodup_map (λ b b' h, by injection h with _ h; exact eq_of_heq h) (d₂ a), d₁.imp (λ a₁ a₂ n x, suffices ∀ (b₁ : σ a₁), sigma.mk a₁ b₁ = x → b₁ ∈ l₂ a₁ → ∀ (b₂ : σ a₂), sigma.mk a₂ b₂ = x → b₂ ∉ l₂ a₂, by simpa [and_comm], λ b₁ e mb₁ b₂ e' mb₂, by subst e'; injection e; contradiction)⟩ theorem nodup_filter_map {f : α → option β} {l : list α} (H : ∀ (a a' : α) (b : β), b ∈ f a → b ∈ f a' → a = a') : nodup l → nodup (filter_map f l) := pairwise_filter_map_of_pairwise f $ λ a a' n b bm b' bm' e, n $ H a a' b' (e ▸ bm) bm' theorem nodup_concat {a : α} {l : list α} (h : a ∉ l) (h' : nodup l) : nodup (concat l a) := by simp; exact nodup_append_of_nodup h' (nodup_singleton _) (disjoint_singleton.2 h) theorem nodup_insert [decidable_eq α] {a : α} {l : list α} (h : nodup l) : nodup (insert a l) := by by_cases h' : a ∈ l; simp [h', h]; apply nodup_cons h' h theorem nodup_union [decidable_eq α] (l₁ : list α) {l₂ : list α} (h : nodup l₂) : nodup (l₁ ∪ l₂) := begin induction l₁ with a l₁ ih generalizing l₂, { exact h }, simp, apply nodup_insert, exact ih h end theorem nodup_inter_of_nodup [decidable_eq α] {l₁ : list α} (l₂) : nodup l₁ → nodup (l₁ ∩ l₂) := nodup_filter _ @[simp] theorem nodup_sublists {l : list α} : nodup (sublists l) ↔ nodup l := ⟨λ h, nodup_of_nodup_map _ (nodup_of_sublist (map_ret_sublist_sublists _) h), λ h, (pairwise_sublists h).imp (λ _ _ h, mt reverse_inj.2 h.to_ne)⟩ @[simp] theorem nodup_sublists' {l : list α} : nodup (sublists' l) ↔ nodup l := by rw [sublists'_eq_sublists, nodup_map_iff reverse_injective, nodup_sublists, nodup_reverse] end nodup /- erase duplicates function -/ section erase_dup variable [decidable_eq α] /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). erase_dup [1, 2, 2, 0, 1] = [1, 2, 0] -/ def erase_dup : list α → list α := pw_filter (≠) @[simp] theorem erase_dup_nil : erase_dup [] = ([] : list α) := rfl theorem erase_dup_cons_of_mem' {a : α} {l : list α} (h : a ∈ erase_dup l) : erase_dup (a::l) = erase_dup l := pw_filter_cons_of_neg $ by simpa using h theorem erase_dup_cons_of_not_mem' {a : α} {l : list α} (h : a ∉ erase_dup l) : erase_dup (a::l) = a :: erase_dup l := pw_filter_cons_of_pos $ by simpa using h @[simp] theorem mem_erase_dup {a : α} {l : list α} : a ∈ erase_dup l ↔ a ∈ l := by simpa using not_congr (@forall_mem_pw_filter α (≠) _ (λ x y z xz, not_and_distrib.1 $ mt (and.rec eq.trans) xz) a l) @[simp] theorem erase_dup_cons_of_mem {a : α} {l : list α} (h : a ∈ l) : erase_dup (a::l) = erase_dup l := erase_dup_cons_of_mem' $ mem_erase_dup.2 h @[simp] theorem erase_dup_cons_of_not_mem {a : α} {l : list α} (h : a ∉ l) : erase_dup (a::l) = a :: erase_dup l := erase_dup_cons_of_not_mem' $ mt mem_erase_dup.1 h theorem erase_dup_sublist : ∀ (l : list α), erase_dup l <+ l := pw_filter_sublist theorem erase_dup_subset : ∀ (l : list α), erase_dup l ⊆ l := pw_filter_subset theorem subset_erase_dup (l : list α) : l ⊆ erase_dup l := λ a, mem_erase_dup.2 theorem nodup_erase_dup : ∀ l : list α, nodup (erase_dup l) := pairwise_pw_filter theorem erase_dup_eq_self {l : list α} : erase_dup l = l ↔ nodup l := pw_filter_eq_self @[simp] theorem erase_dup_idempotent {l : list α} : erase_dup (erase_dup l) = erase_dup l := pw_filter_idempotent theorem erase_dup_append (l₁ l₂ : list α) : erase_dup (l₁ ++ l₂) = l₁ ∪ erase_dup l₂ := begin induction l₁ with a l₁ IH; simp, rw ← IH, show erase_dup (a :: (l₁ ++ l₂)) = insert a (erase_dup (l₁ ++ l₂)), by_cases a ∈ erase_dup (l₁ ++ l₂); [ rw [erase_dup_cons_of_mem' h, insert_of_mem h], rw [erase_dup_cons_of_not_mem' h, insert_of_not_mem h]] end end erase_dup /- iota and range -/ /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n @[simp] theorem length_range' : ∀ (s n : ℕ), length (range' s n) = n | s 0 := rfl | s (n+1) := congr_arg succ (length_range' _ _) @[simp] theorem mem_range' {m : ℕ} : ∀ {s n : ℕ}, m ∈ range' s n ↔ s ≤ m ∧ m < s + n | s 0 := by simp | s (n+1) := have m = s → m < s + (n + 1), from λ e, e ▸ lt_succ_of_le (le_add_right _ _), have l : m = s ∨ s + 1 ≤ m ↔ s ≤ m, by simpa [eq_comm] using (@le_iff_eq_or_lt _ _ s m).symm, by simp [@mem_range' (s+1) n, or_and_distrib_left, or_iff_right_of_imp this, l] theorem map_add_range' (a) : ∀ s n : ℕ, map ((+) a) (range' s n) = range' (a + s) n | s 0 := rfl | s (n+1) := congr_arg (cons _) (map_add_range' (s+1) n) theorem chain_succ_range' : ∀ s n : ℕ, chain (λ a b, b = succ a) s (range' (s+1) n) | s 0 := chain.nil _ _ | s (n+1) := (chain_succ_range' (s+1) n).cons rfl theorem chain_lt_range' (s n : ℕ) : chain (<) s (range' (s+1) n) := (chain_succ_range' s n).imp (λ a b e, e.symm ▸ lt_succ_self _) theorem pairwise_lt_range' : ∀ s n : ℕ, pairwise (<) (range' s n) | s 0 := pairwise.nil _ | s (n+1) := (chain_iff_pairwise (by exact λ a b c, lt_trans)).1 (chain_lt_range' s n) theorem nodup_range' (s n : ℕ) : nodup (range' s n) := (pairwise_lt_range' s n).imp (λ a b, ne_of_lt) theorem range'_append : ∀ s m n : ℕ, range' s m ++ range' (s+m) n = range' s (n+m) | s 0 n := rfl | s (m+1) n := show s :: (range' (s+1) m ++ range' (s+m+1) n) = s :: range' (s+1) (n+m), by rw [add_right_comm, range'_append] theorem range'_sublist_right {s m n : ℕ} : range' s m <+ range' s n ↔ m ≤ n := ⟨λ h, by simpa using length_le_of_sublist h, λ h, by rw [← nat.sub_add_cancel h, ← range'_append]; apply sublist_append_left⟩ theorem range'_subset_right {s m n : ℕ} : range' s m ⊆ range' s n ↔ m ≤ n := ⟨λ h, le_of_not_lt $ λ hn, lt_irrefl (s+n) $ (mem_range'.1 $ h $ mem_range'.2 ⟨le_add_right _ _, nat.add_lt_add_left hn s⟩).2, λ h, subset_of_sublist (range'_sublist_right.2 h)⟩ theorem nth_range' : ∀ s {m n : ℕ}, m < n → nth (range' s n) m = some (s + m) | s 0 (n+1) _ := by simp | s (m+1) (n+1) h := by simp [nth_range' (s+1) (lt_of_add_lt_add_right h)] theorem range'_concat (s n : ℕ) : range' s (n + 1) = range' s n ++ [s+n] := by rw add_comm n 1; exact (range'_append s n 1).symm theorem range_core_range' : ∀ s n : ℕ, range_core s (range' s n) = range' 0 (n + s) | 0 n := rfl | (s+1) n := by rw [show n+(s+1) = n+1+s, by simp]; exact range_core_range' s (n+1) theorem range_eq_range' (n : ℕ) : range n = range' 0 n := (range_core_range' n 0).trans $ by rw zero_add theorem range_succ_eq_map (n : ℕ) : range (n + 1) = 0 :: map succ (range n) := by rw [range_eq_range', range_eq_range', range', add_comm, ← map_add_range']; congr; exact funext one_add theorem range'_eq_map_range (s n : ℕ) : range' s n = map ((+) s) (range n) := by rw [range_eq_range', map_add_range']; refl @[simp] theorem length_range (n : ℕ) : length (range n) = n := by simp [range_eq_range'] theorem pairwise_lt_range (n : ℕ) : pairwise (<) (range n) := by simp [range_eq_range', pairwise_lt_range'] theorem nodup_range (n : ℕ) : nodup (range n) := by simp [range_eq_range', nodup_range'] theorem range_sublist {m n : ℕ} : range m <+ range n ↔ m ≤ n := by simp [range_eq_range', range'_sublist_right] theorem range_subset {m n : ℕ} : range m ⊆ range n ↔ m ≤ n := by simp [range_eq_range', range'_subset_right] @[simp] theorem mem_range {m n : ℕ} : m ∈ range n ↔ m < n := by simp [range_eq_range', zero_le] @[simp] theorem not_mem_range_self {n : ℕ} : n ∉ range n := mt mem_range.1 $ lt_irrefl _ theorem nth_range {m n : ℕ} (h : m < n) : nth (range n) m = some m := by simp [range_eq_range', nth_range' _ h] theorem range_concat (n : ℕ) : range (n + 1) = range n ++ [n] := by simp [range_eq_range', range'_concat] theorem iota_eq_reverse_range' : ∀ n : ℕ, iota n = reverse (range' 1 n) | 0 := rfl | (n+1) := by simp [iota, range'_concat, iota_eq_reverse_range' n] @[simp] theorem length_iota (n : ℕ) : length (iota n) = n := by simp [iota_eq_reverse_range'] theorem pairwise_gt_iota (n : ℕ) : pairwise (>) (iota n) := by simp [iota_eq_reverse_range', pairwise_lt_range'] theorem nodup_iota (n : ℕ) : nodup (iota n) := by simp [iota_eq_reverse_range', nodup_range'] theorem mem_iota {m n : ℕ} : m ∈ iota n ↔ 1 ≤ m ∧ m ≤ n := by simp [iota_eq_reverse_range', lt_succ_iff] theorem reverse_range' : ∀ s n : ℕ, reverse (range' s n) = map (λ i, s + n - 1 - i) (range n) | s 0 := rfl | s (n+1) := by rw [range'_concat, reverse_append, range_succ_eq_map]; simpa [show s + (n + 1) - 1 = s + n, from rfl, (∘), λ a i, show a - 1 - i = a - succ i, by rw [nat.sub_sub, add_comm]; refl] using reverse_range' s n @[simp] theorem enum_from_map_fst : ∀ n (l : list α), map prod.fst (enum_from n l) = range' n l.length | n [] := rfl | n (a :: l) := congr_arg (cons _) (enum_from_map_fst _ _) @[simp] theorem enum_map_fst (l : list α) : map prod.fst (enum l) = range l.length := by simp [enum, range_eq_range'] end list theorem option.to_list_nodup {α} (o : option α) : o.to_list.nodup := by cases o; simp [option.to_list]
856c788a8f80cd12a0fed405cfc16045d522e3c2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/field_theory/finite/galois_field.lean
30d77ccf408b1889f4d5707bbbc69e3bce8c05bf
[ "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
8,883
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Alex J. Best, Johan Commelin, Eric Rodriguez, Ruben Van de Velde -/ import algebra.char_p.algebra import field_theory.finite.basic import field_theory.separable import linear_algebra.finite_dimensional /-! # Galois fields If `p` is a prime number, and `n` a natural number, then `galois_field p n` is defined as the splitting field of `X^(p^n) - X` over `zmod p`. It is a finite field with `p ^ n` elements. ## Main definition * `galois_field p n` is a field with `p ^ n` elements ## Main Results - `galois_field.alg_equiv_galois_field`: Any finite field is isomorphic to some Galois field - `finite_field.alg_equiv_of_card_eq`: Uniqueness of finite fields : algebra isomorphism - `finite_field.ring_equiv_of_card_eq`: Uniqueness of finite fields : ring isomorphism -/ noncomputable theory open polynomial lemma galois_poly_separable {K : Type*} [field K] (p q : ℕ) [char_p K p] (h : p ∣ q) : separable (X ^ q - X : polynomial K) := begin use [1, (X ^ q - X - 1)], rw [← char_p.cast_eq_zero_iff (polynomial K) p] at h, rw [derivative_sub, derivative_pow, derivative_X, h], ring, end /-- A finite field with `p ^ n` elements. Every field with the same cardinality is (non-canonically) isomorphic to this field. -/ @[derive field] def galois_field (p : ℕ) [fact p.prime] (n : ℕ) := splitting_field (X^(p^n) - X : polynomial (zmod p)) instance : inhabited (@galois_field 2 (fact.mk nat.prime_two) 1) := ⟨37⟩ namespace galois_field variables (p : ℕ) [fact p.prime] (n : ℕ) instance : algebra (zmod p) (galois_field p n) := splitting_field.algebra _ instance : is_splitting_field (zmod p) (galois_field p n) (X^(p^n) - X) := polynomial.is_splitting_field.splitting_field _ instance : char_p (galois_field p n) p := (algebra.char_p_iff (zmod p) (galois_field p n) p).mp (by apply_instance) instance : fintype (galois_field p n) := by {dsimp only [galois_field], exact finite_dimensional.fintype_of_fintype (zmod p) (galois_field p n) } lemma finrank {n} (h : n ≠ 0) : finite_dimensional.finrank (zmod p) (galois_field p n) = n := begin set g_poly := (X^(p^n) - X : polynomial (zmod p)), have hp : 1 < p := (fact.out (nat.prime p)).one_lt, have aux : g_poly ≠ 0 := finite_field.X_pow_card_pow_sub_X_ne_zero _ h hp, have key : fintype.card ((g_poly).root_set (galois_field p n)) = (g_poly).nat_degree := card_root_set_eq_nat_degree (galois_poly_separable p _ (dvd_pow (dvd_refl p) h)) (splitting_field.splits g_poly), have nat_degree_eq : (g_poly).nat_degree = p ^ n := finite_field.X_pow_card_pow_sub_X_nat_degree_eq _ h hp, rw nat_degree_eq at key, suffices : (g_poly).root_set (galois_field p n) = set.univ, { simp_rw [this, ←fintype.of_equiv_card (equiv.set.univ _)] at key, rw [@card_eq_pow_finrank (zmod p), zmod.card] at key, exact nat.pow_right_injective ((nat.prime.one_lt' p).out) key }, rw set.eq_univ_iff_forall, suffices : ∀ x (hx : x ∈ (⊤ : subalgebra (zmod p) (galois_field p n))), x ∈ (X ^ p ^ n - X : polynomial (zmod p)).root_set (galois_field p n), { simpa, }, rw ← splitting_field.adjoin_root_set, simp_rw algebra.mem_adjoin_iff, intros x hx, -- We discharge the `p = 0` separately, to avoid typeclass issues on `zmod p`. unfreezingI { cases p, cases hp, }, apply subring.closure_induction hx; clear_dependent x; simp_rw mem_root_set aux, { rintros x (⟨r, rfl⟩ | hx), { simp only [aeval_X_pow, aeval_X, alg_hom.map_sub], rw [← map_pow, zmod.pow_card_pow, sub_self], }, { dsimp only [galois_field] at hx, rwa mem_root_set aux at hx, }, }, { dsimp only [g_poly], rw [← coeff_zero_eq_aeval_zero'], simp only [coeff_X_pow, coeff_X_zero, sub_zero, ring_hom.map_eq_zero, ite_eq_right_iff, one_ne_zero, coeff_sub], intro hn, exact nat.not_lt_zero 1 (pow_eq_zero hn.symm ▸ hp), }, { simp, }, { simp only [aeval_X_pow, aeval_X, alg_hom.map_sub, add_pow_char_pow, sub_eq_zero], intros x y hx hy, rw [hx, hy], }, { intros x hx, simp only [sub_eq_zero, aeval_X_pow, aeval_X, alg_hom.map_sub, sub_neg_eq_add] at *, rw [neg_pow, hx, char_p.neg_one_pow_char_pow], simp, }, { simp only [aeval_X_pow, aeval_X, alg_hom.map_sub, mul_pow, sub_eq_zero], intros x y hx hy, rw [hx, hy], }, end lemma card (h : n ≠ 0) : fintype.card (galois_field p n) = p ^ n := begin let b := is_noetherian.finset_basis (zmod p) (galois_field p n), rw [module.card_fintype b, ← finite_dimensional.finrank_eq_card_basis b, zmod.card, finrank p h], end theorem splits_zmod_X_pow_sub_X : splits (ring_hom.id (zmod p)) (X ^ p - X) := begin have hp : 1 < p := (fact.out (nat.prime p)).one_lt, have h1 : roots (X ^ p - X : polynomial (zmod p)) = finset.univ.val, { convert finite_field.roots_X_pow_card_sub_X _, exact (zmod.card p).symm }, have h2 := finite_field.X_pow_card_sub_X_nat_degree_eq (zmod p) hp, -- We discharge the `p = 0` separately, to avoid typeclass issues on `zmod p`. unfreezingI { cases p, cases hp, }, rw [splits_iff_card_roots, h1, ←finset.card_def, finset.card_univ, h2, zmod.card], end /-- A Galois field with exponent 1 is equivalent to `zmod` -/ def equiv_zmod_p : galois_field p 1 ≃ₐ[zmod p] (zmod p) := have h : (X ^ p ^ 1 : polynomial (zmod p)) = X ^ (fintype.card (zmod p)), by rw [pow_one, zmod.card p], have inst : is_splitting_field (zmod p) (zmod p) (X ^ p ^ 1 - X), by { rw h, apply_instance }, by exactI (is_splitting_field.alg_equiv (zmod p) (X ^ (p ^ 1) - X : polynomial (zmod p))).symm variables {K : Type*} [field K] [fintype K] [algebra (zmod p) K] theorem splits_X_pow_card_sub_X : splits (algebra_map (zmod p) K) (X ^ fintype.card K - X) := by rw [←splits_id_iff_splits, polynomial.map_sub, polynomial.map_pow, map_X, splits_iff_card_roots, finite_field.roots_X_pow_card_sub_X, ←finset.card_def, finset.card_univ, finite_field.X_pow_card_sub_X_nat_degree_eq]; exact fintype.one_lt_card lemma is_splitting_field_of_card_eq (h : fintype.card K = p ^ n) : is_splitting_field (zmod p) K (X ^ (p ^ n) - X) := { splits := by { rw ← h, exact splits_X_pow_card_sub_X p }, adjoin_roots := begin have hne : n ≠ 0, { rintro rfl, rw [pow_zero, fintype.card_eq_one_iff_nonempty_unique] at h, cases h, resetI, exact false_of_nontrivial_of_subsingleton K }, refine algebra.eq_top_iff.mpr (λ x, algebra.subset_adjoin _), rw [polynomial.map_sub, polynomial.map_pow, map_X, finset.mem_coe, multiset.mem_to_finset, mem_roots, is_root.def, eval_sub, eval_pow, eval_X, ← h, finite_field.pow_card, sub_self], exact finite_field.X_pow_card_pow_sub_X_ne_zero K hne (fact.out _) end } /-- Any finite field is (possibly non canonically) isomorphic to some Galois field. -/ def alg_equiv_galois_field (h : fintype.card K = p ^ n) : K ≃ₐ[zmod p] galois_field p n := by haveI := is_splitting_field_of_card_eq _ _ h; exact is_splitting_field.alg_equiv _ _ end galois_field namespace finite_field variables {K : Type*} [field K] [fintype K] {K' : Type*} [field K'] [fintype K'] /-- Uniqueness of finite fields: Any two finite fields of the same cardinality are (possibly non canonically) isomorphic-/ def alg_equiv_of_card_eq (p : ℕ) [fact p.prime] [algebra (zmod p) K] [algebra (zmod p) K'] (hKK' : fintype.card K = fintype.card K') : K ≃ₐ[zmod p] K' := begin haveI : char_p K p, { rw ← algebra.char_p_iff (zmod p) K p, exact zmod.char_p p, }, haveI : char_p K' p, { rw ← algebra.char_p_iff (zmod p) K' p, exact zmod.char_p p, }, choose n a hK using finite_field.card K p, choose n' a' hK' using finite_field.card K' p, rw [hK,hK'] at hKK', have hGalK := galois_field.alg_equiv_galois_field p n hK, have hK'Gal := (galois_field.alg_equiv_galois_field p n' hK').symm, rw (nat.pow_right_injective (fact.out (nat.prime p)).one_lt hKK') at *, use alg_equiv.trans hGalK hK'Gal, end /-- Uniqueness of finite fields: Any two finite fields of the same cardinality are (possibly non canonically) isomorphic-/ def ring_equiv_of_card_eq (hKK' : fintype.card K = fintype.card K') : K ≃+* K' := begin choose p _char_p_K using char_p.exists K, choose p' _char_p'_K' using char_p.exists K', resetI, choose n hp hK using finite_field.card K p, choose n' hp' hK' using finite_field.card K' p', have hpp' : p = p', -- := eq_prime_of_eq_prime_pow { by_contra hne, have h2 := nat.coprime_pow_primes n n' hp hp' hne, rw [(eq.congr hK hK').mp hKK', nat.coprime_self, pow_eq_one_iff (pnat.ne_zero n')] at h2, exact nat.prime.ne_one hp' h2, all_goals {apply_instance}, }, rw ← hpp' at *, haveI := fact_iff.2 hp, exact alg_equiv_of_card_eq p hKK', end end finite_field
3fd29b99dc6a1e799818ca1f63480b635e8ccecb
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/smt_assert_define.lean
f24446b5745fe5641ed8632ca36717e8101ba80d
[ "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
891
lean
open smt_tactic constant p : nat → nat → Prop constant f : nat → nat axiom pf (a : nat) : p (f a) (f a) → p a a lemma ex1 (a b c : nat) : a = b + 0 → a + c = b + c := by using_smt $ do pr ← tactic.to_expr ```(add_zero b), note `h none pr, trace_state, return () lemma ex2(a b c : nat) : a = b → p (f a) (f b) → p a b := by using_smt $ do intros, t ← tactic.to_expr ```(p (f a) (f a)), assert `h t, -- assert automatically closed the new goal trace_state, tactic.trace "-----", pr ← tactic.to_expr ```(pf _ h), note `h2 none pr, trace_state, return () def foo := 0 lemma fooex : foo = 0 := rfl lemma ex3 (a b c : nat) : a = b + foo → a + c = b + c := begin [smt] intros, add_fact fooex, ematch end lemma ex4 (a b c : nat) : a = b → p (f a) (f b) → p a b := begin [smt] intros, have h : p (f a) (f a), add_fact (pf _ h) end
b512b219bd3513a3dd384c5896bafcdc2ab412e3
9e90bb7eb4d1bde1805f9eb6187c333fdf09588a
/src/stump/stump_pac_theorem.lean
2bffb942870b8913c5cce15d3453e384e40e2fbc
[ "Apache-2.0" ]
permissive
alexjbest/stump-learnable
6311d0c3a1a1a0e65ce83edcbb3b4b7cecabb851
f8fd812fc646d2ece312ff6ffc2a19848ac76032
refs/heads/master
1,659,486,805,691
1,590,454,024,000
1,590,454,024,000
266,173,720
0
0
Apache-2.0
1,590,169,884,000
1,590,169,883,000
null
UTF-8
Lean
false
false
3,228
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import .setup_definition .setup_measurable import .algorithm_definition .algorithm_measurable import .sample_complexity import .stump_pac_lemmas import .to_epsilon open set nat local attribute [instance] classical.prop_decidable namespace stump variables (μ: probability_measure ℍ) (target: ℍ) (n: ℕ) noncomputable def denot: probability_measure ℍ := let η := vec.prob_measure n μ in let ν := map (label_sample target n) η in let γ := map (choose n) ν in γ lemma pullback: ∀ P: nnreal → Prop, is_measurable {h: ℍ | P(@error μ target h)} → is_measurable {S: vec (ℍ × bool) n | P(error μ target (choose n S))} → (denot μ target n) {h: ℍ | P(@error μ target h)} = (vec.prob_measure n μ) {S: vec ℍ n | P(error μ target (choose n (label_sample target n S)))} := begin intros, dunfold denot, rw map_apply, rw map_apply, repeat {simp}, repeat {assumption}, end theorem choose_PAC: ∀ ε: nnreal, ∀ δ: nnreal, ∀ n: ℕ, ε > 0 → ε < 1 → δ > 0 → δ < 1 → (n: ℝ) > (complexity ε δ) → (denot μ target n) {h: ℍ | @error μ target h ≤ ε} ≥ 1 - δ := begin introv eps_0 eps_1 delta_0 delta_1 n_gt, by_cases((μ (Ioc 0 target)) > ε), { rw ← probability_measure.neq_prob_set, rw pullback μ target n (λ x, x > ε) _ _; try {simp}, transitivity ((1 - ε)^(n+1)), { have EPS := extend_to_epsilon_1 μ target ε eps_0 h, cases EPS with θ θ_prop, cases θ_prop, have TZ: θ > 0, { by_contradiction h_contra, simp at h_contra, rw h_contra at *, have CONTRA: ¬ (μ (Ioc 0 target) ≤ ε), simp, assumption, contradiction, }, transitivity ((vec.prob_measure n μ) {S: vec ℍ n | ∀ (i: dfin (nat.succ n)), ∀ p = label target (kth_projn S i), (if p.snd then p.fst else 0) < θ}), { apply probability_measure.prob_mono, refine all_missed _ _ _ _ _ θ_prop_right, }, { have INDEP := @prob_independence ℍ _ n _ (λ x, ∀ p = label target x, (if p.snd then p.fst else 0) < θ) μ (is_meas_one target θ TZ) (is_meas_forall target θ TZ), rw INDEP, clear INDEP, simp, apply pow_preserves_order (n+1), refine miss_prob _ _ _ _ TZ θ_prop_left, }, }, { apply complexity_enough ε δ n; assumption, }, exact le_of_lt delta_1, simp, }, { simp at h, rw pullback μ target n (λ x, x ≤ ε) _ _; try {simp}, have DC: (vec.prob_measure n μ) {S: vec ℍ n | error μ target (choose n (label_sample target n S)) ≤ ε} = 1, { have AS := always_succeed μ target ε eps_0 n h, refine probability_measure.prob_trivial _ _ AS, }, rw DC; try {assumption}, rw ← nnreal.sub_le_iff_le_add, apply super_dumb, assumption, }, end end stump
c78ee680c410a87c9fe3dea42f157013e9cb1897
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/list/defs.lean
f04c4b70fdb4bbec02faaac1683978c906f2f6b7
[ "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
39,542
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 data.option.defs import logic.basic import tactic.cache import data.rbmap.basic import data.rbtree.default_lt /-! ## Definitions on lists This file contains various definitions on lists. It does not contain proofs about these definitions, those are contained in other files in `data/list` -/ namespace list open function nat universes u v w x variables {α β γ δ ε ζ : Type*} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) /-- An auxiliary function for `split_on_p`. -/ def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a /-- `head' xs` returns the first element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) /-- Apply `f` to the last element of `l`, if it exists. -/ @[simp] def modify_last (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: modify_last xs /-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l` `insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/ def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] /-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `default`. -/ def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l /-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')` then `scanr f b l = b' :: l'` -/ def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 /-- Sum of a list. sum [a, b, c] = ((0 + a) + b) + c -/ -- Later this will be tagged with `to_additive`, but this can't be done yet because of import -- dependencies. def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 /-- The alternating sum of a list. -/ def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G | [] := 0 | (g :: []) := g | (g :: h :: t) := g + -h + alternating_sum t /-- The alternating product of a list. -/ def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G | [] := 1 | (g :: []) := g | (g :: h :: t) := g * h⁻¹ * alternating_prod t /-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f` whilst partitioning the result it into a pair of lists, `list β × list γ`, partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list. `partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/ def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l /-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and fails otherwise. -/ def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α := list.mfirst $ λ a, tac a $> a /-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in `l`. This is a monadic version of `list.find`. -/ def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) : list α → m (option α) | [] := pure none | (x :: xs) := do ⟨px⟩ ← p x, if px then pure (some x) else mbfind' xs section variables {m : Type → Type v} [monad m] /-- A variant of `mbfind'` with more restrictive universe levels. -/ def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) := xs.mbfind' (functor.map ulift.up ∘ p) /-- `many p as` returns true iff `p` returns true for any element of `l`. `many` short-circuits, so if `p` returns true for any element of `l`, later elements are not checked. This is a monadic version of `list.any`. -/ -- Implementing this via `mbfind` would give us less universe polymorphism. def many {α : Type u} (p : α → m bool) : list α → m bool | [] := pure false | (x :: xs) := do px ← p x, if px then pure tt else many xs /-- `mall p as` returns true iff `p` returns true for all elements of `l`. `mall` short-circuits, so if `p` returns false for any element of `l`, later elements are not checked. This is a monadic version of `list.all`. -/ def mall {α : Type u} (p : α → m bool) (as : list α) : m bool := bnot <$> many (λ a, bnot <$> p a) as /-- `mbor xs` runs the actions in `xs`, returning true if any of them returns true. `mbor` short-circuits, so if an action returns true, later actions are not run. This is a monadic version of `list.bor`. -/ def mbor : list (m bool) → m bool := many id /-- `mband xs` runs the actions in `xs`, returning true if all of them return true. `mband` short-circuits, so if an action returns false, later actions are not run. This is a monadic version of `list.band`. -/ def mband : list (m bool) → m bool := mall id end /-- Auxiliary definition for `foldl_with_index`. -/ def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α | _ a [] := a | i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l /-- Fold a list from left to right as with `foldl`, but the combining function also receives each element's index. -/ def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α := foldl_with_index_aux f 0 a l /-- Auxiliary definition for `foldr_with_index`. -/ def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β | _ b [] := b | i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l) /-- Fold a list from right to left as with `foldr`, but the combining function also receives each element's index. -/ def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β := foldr_with_index_aux f 0 b l /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := foldr_with_index (λ i a is, if p a then i :: is else is) [] l /-- Returns the elements of `l` that satisfy `p` together with their indexes in `l`. The returned list is ordered by index. -/ def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) := foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l /-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example: ``` indexes_of a [a, b, a, a] = [0, 2, 3] ``` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) section mfold_with_index variables {m : Type v → Type w} [monad m] /-- Monadic variant of `foldl_with_index`. -/ def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β := as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b) /-- Monadic variant of `foldr_with_index`. -/ def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β := as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b) end mfold_with_index section mmap_with_index variables {m : Type v → Type w} [applicative m] /-- Auxiliary definition for `mmap_with_index`. -/ def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β) | _ [] := pure [] | i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as /-- Applicative variant of `map_with_index`. -/ def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) := mmap_with_index_aux f 0 as /-- Auxiliary definition for `mmap_with_index'`. -/ def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit | _ [] := pure ⟨⟩ | i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as /-- A variant of `mmap_with_index` specialised to applicative actions which return `unit`. -/ def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit := mmap_with_index'_aux f 0 as end mmap_with_index /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} /-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ /-- Auxiliary definition used to define `transpose`. `transpose_aux l L` takes each element of `l` and appends it to the start of each element of `L`. `transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations /-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to `(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`. permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id = ([1, 2, 3, 4, 5, 6], [[10, 1, 2, 3, 4, 5, 6], [1, 10, 2, 3, 4, 5, 6], [1, 2, 10, 3, 4, 5, 6]]) -/ def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas /-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for `l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/ @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } /-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all permutations of `is ++ ts` that do not fix `ts`. -/ def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] /-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last. This function is intended for use in specifications, so it is simpler than `permutations_aux2`, which plays roughly the same role in `permutations`. Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last position: permutations'_aux 10 [1, 2, 3] = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]] (permutations_aux2 10 [] [] [1, 2, 3] id).2 = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/ @[simp] def permutations'_aux (t : α) : list α → list (list α) | [] := [[t]] | (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y) /-- List of all permutations of `l`. This version of `permutations` is less efficient but has simpler definitional equations. The permutations are in a different order, but are equal up to permutation, as shown by `list.permutations_perm_permutations'`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]] -/ @[simp] def permutations' : list α → list (list α) | [] := [[]] | (t::ts) := (permutations' ts).bind $ permutations'_aux t end permutations /-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/ def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l /-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') /-- `revzip l` returns a list of pairs of the elements of `l` paired with the elements of `l` in reverse order. `revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]` -/ def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a /-- Auxliary definition used to define `of_fn`. `of_fn_aux f m h l` returns the first `m` elements of `of_fn f` appended to `l` -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) /-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i` `of_fun f = [f 0, f 1, ... , f(n - 1)]` -/ def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] /-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/ def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : i < n then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] pairwise.nil instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] chain.nil instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n /-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/ def reduce_option {α} : list (option α) → list α := list.filter_map id /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns both `a` and proofs of `a ∈ l` and `p a`. -/ def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns `a : α`, and properties are given by `choose_mem` and `choose_property`. -/ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose /-- Filters and maps elements of a list -/ def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := do b ← f h, t' ← t.mmap_filter, return $ match b with none := t' | (some x) := x::t' end /-- `mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list `[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`. -/ def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β) | [] := return [] | (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t /-- `mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order, `f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`. -/ def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit | [] := return () | (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : list α → F (list β) | [] := pure [] | (x :: xs) := list.cons <$> f x <*> traverse xs /-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def get_rest [decidable_eq α] : list α → list α → option (list α) | l [] := some l | [] _ := none | (x::l) (y::l₁) := if x = y then get_rest l l₁ else none /-- `list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`. -/ def slice {α} : ℕ → ℕ → list α → list α | 0 n xs := xs.drop n | (succ n) m [] := [] | (succ n) m (x :: xs) := x :: slice n m xs /-- Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. Returns the results of the `f` applications and the remaining `bs`. ``` map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β) | [] bs := ([], bs) | (a :: as) [] := ((a :: as).map (λ a, f a none), []) | (a :: as) (b :: bs) := let rec := map₂_left' as bs in (f a (some b) :: rec.fst, rec.snd) /-- Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. Returns the results of the `f` applications and the remaining `as`. ``` map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) := map₂_left' (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`. ``` zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b']) zip_left' = map₂_left' prod.mk ``` -/ def zip_left' : list α → list β → list (α × option β) × list β := map₂_left' prod.mk /-- Right-biased version of `list.zip`. `zip_right' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. Also returns the remaining `as`. ``` zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2]) zip_right' = map₂_right' prod.mk ``` -/ def zip_right' : list α → list β → list (option α × β) × list α := map₂_right' prod.mk /-- Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. ``` map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')] map₂_left f as bs = (map₂_left' f as bs).fst ``` -/ @[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ | [] _ := [] | (a :: as) [] := (a :: as).map (λ a, f a none) | (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs /-- Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. ``` map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')] map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] map₂_right f as bs = (map₂_right' f as bs).fst ``` -/ def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) : list γ := map₂_left (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. ``` zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)] zip_left [1] ['a', 'b'] = [(1, some 'a')] zip_left = map₂_left prod.mk ``` -/ def zip_left : list α → list β → list (α × option β) := map₂_left prod.mk /-- Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. ``` zip_right [1, 2] ['a'] = [(some 1, 'a')] zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zip_right = map₂_right prod.mk ``` -/ def zip_right : list α → list β → list (option α × β) := map₂_right prod.mk /-- If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise it returns `none`. ``` all_some [some 1, some 2] = some [1, 2] all_some [some 1, none ] = none ``` -/ def all_some : list (option α) → option (list α) | [] := some [] | (some a :: as) := cons a <$> all_some as | (none :: as) := none /-- `fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there are not enough `ys` to replace all the `none`s, the remaining `none`s are dropped from `xs`. ``` fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3] ``` -/ def fill_nones {α} : list (option α) → list α → list α | [] _ := [] | (some a :: as) as' := a :: fill_nones as as' | (none :: as) [] := as.reduce_option | (none :: as) (a :: as') := a :: fill_nones as as' /-- `take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`, it first takes the `n₁` initial elements from `as`, then the next `n₂` ones, etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining elements of `as`. If `as` does not have at least as many elements as the sum of the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements. ``` take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e']) take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], []) ``` -/ def take_list {α} : list α → list ℕ → list (list α) × list α | xs [] := ([], xs) | xs (n :: ns) := let ⟨xs₁, xs₂⟩ := xs.split_at n in let ⟨xss, rest⟩ := take_list xs₂ ns in (xs₁ :: xss, rest) /-- `to_rbmap as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ def to_rbmap {α : Type*} : list α → rbmap ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α) /-- Auxliary definition used to define `to_chunks`. `to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`, that is, the first `i` elements of `xs`, and the remaining elements chunked into sublists of length `n+1`. -/ def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α) | [] i := ([], []) | (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L) | (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L) /-- `xs.to_chunks n` splits the list into sublists of size at most `n`, such that `(xs.to_chunks n).join = xs`. ``` [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]] ``` -/ def to_chunks {α} : ℕ → list α → list (list α) | _ [] := [] | 0 xs := [xs] | (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L /-- Asynchronous version of `list.map`. -/ meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β := ((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get /-! We add some n-ary versions of `list.zip_with` for functions with more than two arguments. These can also be written in terms of `list.zip` or `list.zip_with`. For example, `zip_with3 f xs ys zs` could also be written as `zip_with id (zip_with f xs ys) zs` or as `(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`. -/ /-- Ternary version of `list.zip_with`. -/ def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ | (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs | _ _ _ := [] /-- Quaternary version of `list.zip_with`. -/ def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε | (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us | _ _ _ _ := [] /-- Quinary version of `list.zip_with`. -/ def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ | (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs | _ _ _ _ _ := [] /-- An auxiliary function for `list.map_with_prefix_suffix`. -/ def map_with_prefix_suffix_aux {α β} (f : list α → α → list α → β) : list α → list α → list β | prev [] := [] | prev (h::t) := f prev h t :: map_with_prefix_suffix_aux (prev.concat h) t /-- `list.map_with_prefix_suffix f l` maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f pref a suff`. Example: if `f : list ℕ → ℕ → list ℕ → β`, `list.map_with_prefix_suffix f [1, 2, 3]` will produce the list `[f [] 1 [2, 3], f [1] 2 [3], f [1, 2] 3 []]`. -/ def map_with_prefix_suffix {α β} (f : list α → α → list α → β) (l : list α) : list β := map_with_prefix_suffix_aux f [] l /-- `list.map_with_complement f l` is a variant of `list.map_with_prefix_suffix` that maps `f` across a list `l`. For each `a ∈ l` with `l = pref ++ [a] ++ suff`, `a` is mapped to `f a (pref ++ suff)`, i.e., the list input to `f` is `l` with `a` removed. Example: if `f : ℕ → list ℕ → β`, `list.map_with_complement f [1, 2, 3]` will produce the list `[f 1 [2, 3], f 2 [1, 3], f 3 [1, 2]]`. -/ def map_with_complement {α β} (f : α → list α → β) : list α → list β := map_with_prefix_suffix $ λ pref a suff, f a (pref ++ suff) end list
5033ac30d9a2d0241fd13e625cdb774228b6115f
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/data/finset.lean
97171686f6d55cb500f4e86be8ba0c1f4f72db2c
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
83,878
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro Finite sets. -/ import logic.embedding order.boolean_algebra algebra.order_functions data.multiset data.sigma.basic data.set.lattice open multiset subtype nat lattice variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := erase_dup_eq_self.2 s.2 instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /- membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /- set coercion -/ /-- Convert a finset to a set in the natural way. -/ def to_set (s : finset α) : set α := {x | x ∈ s} instance : has_lift (finset α) (set α) := ⟨to_set⟩ @[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl /- extensionality -/ theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[extensionality] theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext.2 @[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ := (set.ext_iff _ _).trans ext.symm lemma to_set_injective {α} : function.injective (finset.to_set : finset α → set α) := λ s t, coe_inj.1 /- subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp] theorem coe_subset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff @[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ := show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff /- empty -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ | e := not_mem_empty a $ e ▸ h @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s := exists_mem_of_ne_zero (mt val_eq_zero.1 h) @[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl lemma nonempty_iff_ne_empty (s : finset α) : nonempty (↑s : set α) ↔ s ≠ ∅ := begin rw [set.coe_nonempty_iff_ne_empty, ←coe_empty], apply not_congr, apply function.injective.eq_iff, exact to_set_injective end /-- `singleton a` is the set `{a}` containing `a` and nothing else. -/ def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩ local prefix `ι`:90 := singleton @[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b := ⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩ @[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _) @[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl /- insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ @[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm] @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := ne_empty_of_mem (mem_insert_self a s) theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) := iff.intro (assume ⟨h₁, h₂⟩, have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂, let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩) (assume ⟨a, hat, has⟩, let ⟨h₁, h₂⟩ := insert_subset.mp has in ⟨h₂, assume h, hat $ h h₁⟩) lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [insert_val, ndinsert_of_not_mem m] } end) nd @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s @[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl @[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a := insert_eq_of_mem $ mem_singleton_self _ /- union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ @[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext.2 $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext.2 $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext.2 $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext.2 $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] @[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext.2 $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext.2 $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] /- inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext.2 $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and_assoc] @[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext.2 $ λ _, by simp only [mem_inter, and.left_comm] @[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext.2 $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext.2 $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext.2 $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext.2 $ λ _, mem_inter.trans $ false_and _ @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] /- lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice } instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.lattice.semilattice_inf_bot, ..finset.lattice.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right /- erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 @[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ /- sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩ @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm, or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a) @[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := (union_comm _ _).trans (sdiff_union_of_subset h) @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := (inter_comm _ _).trans (inter_sdiff_self _ _) theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂) @[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] lemma to_set_sdiff (s t : finset α) : (s \ t).to_set = s.to_set \ t.to_set := by apply finset.coe_sdiff end decidable_eq /- attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /- filter -/ section filter variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm] @[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext.2 $ assume a, by simp only [mem_filter, and_false]; refl lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (p q : α → Prop) [decidable_pred p] [decidable_pred q] (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext.2 $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter] theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset s)] theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] @[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} [decidable_pred (∈ t₁)] (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, classical.or_not] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end end filter /- range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n := finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩, ⟨max (a + 1) n, insert_subset.2 ⟨by simpa only [mem_range] using le_max_left (a+1) n, subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩ end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset namespace option /-- Construct an empty or singleton finset from an `option` -/ def to_finset (o : option α) : finset α := match o with | none := ∅ | some a := finset.singleton a end @[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl @[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl @[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o := by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl end option /- erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 (erase_dup_eq_self.2 n).symm @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a :: s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext' $ by simp @[simp] lemma to_finset_smul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (add_monoid.smul n s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, add_monoid.one_smul] }, { rw [add_monoid.add_smul, to_finset_add, add_monoid.one_smul, to_finset_smul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext' $ by simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero end multiset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] end list namespace finset section map open function def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_inj f.2 @[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] theorem map_refl : s.map (embedding.refl _) = s := ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := by simp only [subset.antisymm_iff, map_subset_map] def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩ @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩, by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact ⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩, by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩ @[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) := ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ_inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] @[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] @[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f := multiset.erase_dup_eq_self.2 (nodup_map_on H s.2) theorem image_id [decidable_eq α] : s.image id = s := ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) := ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b := ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm] protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subset_image_iff [decidable_eq α] [decidable_eq β] {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, induction s using finset.induction with a s has ih h, { exact ⟨∅, set.empty_subset _, finset.image_empty _⟩ }, rw [finset.coe_insert, set.insert_subset] at h, rcases ih h.2 with ⟨s', hst, hsi⟩, rcases h.1 with ⟨x, hxt, rfl⟩, refine ⟨insert x s', _, _⟩, { rw [finset.coe_insert, set.insert_subset], exact ⟨hxt, hst⟩ }, rw [finset.image_insert, hsi] end end image /- card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = finset.singleton a := by cases s; simp [multiset.card_eq_one, finset.singleton, finset.card] @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by simpa only [card_cons, card, insert_val] using congr_arg multiset.card (ndinsert_of_not_mem h) theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _ theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : function.injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have card s > 0, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂) @[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s | ⟨s, nd⟩ ih := multiset.strong_induction_on s (λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext.2 $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt}) lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ le_add_right _ _ lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end end card section bind variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bind s t` is the union of `t x` over `x ∈ s` -/ protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bind_val (s : finset α) (t : α → finset β) : (s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl @[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t := ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib] @[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a := show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _ theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bind t = s.bind (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bind_insert, ih]) theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bind t).image f = s.bind (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bind_insert, image_union, ih]) theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) := ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop] lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop] lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f := ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm] lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bind (λa, s.filter $ (λc, g c = a)) = s := begin ext b, simp, split, { rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb }, { rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ } end end bind section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bind (λa, t.image $ λb, (a, b)) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ end prod section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) := ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop, and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right] end sigma section pi variables {δ : α → Type*} [decidable_eq α] def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) := ⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩ @[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) : (s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl @[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} : f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) := mem_pi _ _ _ def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a := multiset.pi.empty β a h def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' := multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h) @[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) : pi.cons s a b f a h = b := multiset.pi.cons_same _ lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') : pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) := multiset.pi.cons_ne _ _ lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume e₁ e₂ eq, @multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $ funext $ assume e, funext $ assume h, have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h), by rw [eq], this @[simp] lemma pi_empty {t : Πa:α, finset (δ a)} : pi (∅ : finset α) t = singleton (pi.empty δ) := rfl @[simp] lemma pi_insert [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) : pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) := begin apply eq_of_veq, rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2, refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) = erase_dup ((t a).1.bind $ λ b, erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $ λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha), subst s', rw pi_cons, congr, funext b, rw multiset.erase_dup_eq_self.2, exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2, end end pi section powerset def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) end powerset section powerset_len def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len 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 f s` folds the commutative associative operation `op` over the `f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/ def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b variables {op} {f : α → β} {b : β} {s : finset α} {a : α} @[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl @[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f := by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left] @[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl @[simp] theorem fold_map [decidable_eq α] {g : γ ↪ α} {s : finset γ} : (s.map g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, map, multiset.map_map] @[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ} (H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) := by simp only [fold, image_val_of_inj_on H, multiset.map_map] @[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g := by rw [fold, fold, map_congr H] theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} : s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g := by simp only [fold, fold_distrib] theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op'] {m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) : s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) := by rw [fold, fold, ← fold_hom op hm, multiset.map_map] theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} : (s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f := by unfold fold; rw [← fold_add op, ← map_add, union_val, inter_val, union_add_inter, map_add, hc.comm, fold_add] @[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] : (insert a s).fold op b f = f a * s.fold op b f := by haveI := classical.prop_decidable; rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq, fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold] end fold section sup variables [semilattice_sup_bot α] /-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/ def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f variables {s s₁ s₂ : finset β} {f : β → α} lemma sup_val : s.sup f = (s.1.map f).sup := rfl @[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ := fold_empty @[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f := fold_insert_idem @[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b := calc _ = f b ⊔ (∅:finset β).sup f : sup_insert ... = f b : sup_bot_eq lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f := finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih, by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc] theorem sup_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.sup f = s₂.sup g := by subst hs; exact finset.fold_congr hfg lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2)) lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f := by letI := classical.dec_eq β; from calc f b ≤ f b ⊔ s.sup f : le_sup_left ... = (insert b s).sup f : sup_insert.symm ... = s.sup f : by rw [insert_eq_of_mem hb] lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a := by letI := classical.dec_eq β; from finset.induction_on s (λ _, bot_le) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [sup_insert]; exact sup_le H.1 (ih H.2)) lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) := iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f := sup_le $ assume b hb, le_sup (h hb) lemma sup_lt [is_total α (≤)] {a : α} : (⊥ < a) → (∀b ∈ s, f b < a) → s.sup f < a := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_sup_eq_sup_comp [is_total α (≤)] {γ : Type} [semilattice_sup_bot γ] (g : α → γ) (mono_g : monotone g) (bot : g ⊥ = ⊥) : g (s.sup f) = s.sup (g ∘ f) := have A : ∀x y, g (x ⊔ y) = g x ⊔ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [sup_of_le_right h, sup_of_le_right (mono_g h)] }, { simp [sup_of_le_left h, sup_of_le_left (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [bot]) (by simp [A] {contextual := tt}) end sup lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) := le_antisymm (finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha) (supr_le $ assume a, supr_le $ assume ha, le_sup ha) section inf variables [semilattice_inf_top α] /-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/ def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f variables {s s₁ s₂ : finset β} {f : β → α} lemma inf_val : s.inf f = (s.1.map f).inf := rfl @[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ := fold_empty @[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f := fold_insert_idem @[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b := calc _ = f b ⊓ (∅:finset β).inf f : inf_insert ... = f b : inf_top_eq lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f := finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih, by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc] theorem inf_congr {f g : β → α} (hs : s₁ = s₂) (hfg : ∀a∈s₂, f a = g a) : s₁.inf f = s₂.inf g := by subst hs; exact finset.fold_congr hfg lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_refl _) (λ a s has ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2)) lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b := by letI := classical.dec_eq β; from calc f b ≥ f b ⊓ s.inf f : inf_le_left ... = (insert b s).inf f : inf_insert.symm ... = s.inf f : by rw [insert_eq_of_mem hb] lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (λ _, le_top) (λ n s hns ih H, by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H; simp only [inf_insert]; exact le_inf H.1 (ih H.2)) lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) := iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f := le_inf $ assume b hb, inf_le (h hb) lemma lt_inf [is_total α (≤)] {a : α} : (a < ⊤) → (∀b ∈ s, a < f b) → a < s.inf f := by letI := classical.dec_eq β; from finset.induction_on s (by simp) (by simp {contextual := tt}) lemma comp_inf_eq_inf_comp [is_total α (≤)] {γ : Type} [semilattice_inf_top γ] (g : α → γ) (mono_g : monotone g) (top : g ⊤ = ⊤) : g (s.inf f) = s.inf (g ∘ f) := have A : ∀x y, g (x ⊓ y) = g x ⊓ g y := begin assume x y, cases (is_total.total (≤) x y) with h, { simp [inf_of_le_left h, inf_of_le_left (mono_g h)] }, { simp [inf_of_le_right h, inf_of_le_right (mono_g h)] } end, by letI := classical.dec_eq β; from finset.induction_on s (by simp [top]) (by simp [A] {contextual := tt}) end inf lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) := le_antisymm (le_infi $ assume a, le_infi $ assume ha, inf_le ha) (finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha) /- max and min of finite sets -/ section max_min variables [decidable_linear_order α] protected def max : finset α → option α := fold (option.lift_or_get max) none some theorem max_eq_sup_with_bot (s : finset α) : s.max = @sup (with_bot α) α _ s some := rfl @[simp] theorem max_empty : (∅ : finset α).max = none := rfl @[simp] theorem max_insert {a : α} {s : finset α} : (insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem @[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert @[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max := (@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ max_empty⟩ theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s := finset.induction_on s (λ _ H, by cases H) (λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice max_choice (some b) s.max with q q; rw [max_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end) theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b := by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption protected def min : finset α → option α := fold (option.lift_or_get min) none some theorem min_eq_inf_with_top (s : finset α) : s.min = @inf (with_top α) α _ s some := rfl @[simp] theorem min_empty : (∅ : finset α).min = none := rfl @[simp] theorem min_insert {a : α} {s : finset α} : (insert a s).min = option.lift_or_get min (some a) s.min := fold_insert_idem @[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min := (@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min := let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ := ⟨λ h, by_contradiction $ λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha, λ h, h.symm ▸ min_empty⟩ theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s := finset.induction_on s (λ _ H, by cases H) $ λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min), begin by_cases p : b = a, { induction p, exact mem_insert_self b s }, { cases option.lift_or_get_choice min_choice (some b) s.min with q q; rw [min_insert, q] at h, { cases h, cases p rfl }, { exact mem_insert_of_mem (ih h) } } end theorem le_min_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b := by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩; cases h₂.symm.trans hb; assumption end max_min 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 unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ end sort section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans singleton_disjoint @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_bind_left {ι : Type*} [decidable_eq ι] (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bind f) t ↔ (∀i∈s, disjoint (f i) t) := begin refine s.induction _ _, { simp only [forall_mem_empty_iff, bind_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bind_insert, his, forall_mem_insert, ih] } end lemma disjoint_bind_right {ι : Type*} [decidable_eq ι] (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bind f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bind_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] end disjoint theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ a.1 ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp 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 theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf section decidable_linear_order variables {α} [decidable_linear_order α] def min' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.min $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb] def max' (S : finset α) (H : S ≠ ∅) : α := @option.get _ S.max $ let ⟨k, hk⟩ := exists_mem_of_ne_empty H in let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb] variables (S : finset α) (H : S ≠ ∅) theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min'] theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := le_min_of_mem H2 $ option.get_mem _ theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _ theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max'] theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _ theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _ theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H := begin rcases lt_trichotomy i j with H4 | H4 | H4, { have H5 := min'_le S H i H1, have H6 := le_max' S H j H2, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 }, { cc }, { have H5 := min'_le S H j H2, have H6 := le_max' S H i H1, apply lt_of_le_of_lt H5, apply lt_of_lt_of_le H4 H6 } end end decidable_linear_order /- Ico (a closed openinterval) -/ variables {n m l : ℕ} /-- `Ico n m` is the set of natural numbers `n ≤ k < m`. -/ def Ico (n m : ℕ) : finset ℕ := ⟨_, Ico.nodup n m⟩ namespace Ico @[simp] theorem val (n m : ℕ) : (Ico n m).1 = multiset.Ico n m := rfl @[simp] theorem to_finset (n m : ℕ) : (multiset.Ico n m).to_finset = Ico n m := (multiset.to_finset_eq _).symm theorem image_add (n m k : ℕ) : (Ico n m).image ((+) k) = Ico (n + k) (m + k) := by simp [image, multiset.Ico.map_add] theorem image_sub (n m k : ℕ) (h : k ≤ n): (Ico n m).image (λ x, x - k) = Ico (n - k) (m - k) := begin dsimp [image], rw [multiset.Ico.map_sub _ _ _ h, ←multiset.to_finset_eq], refl, end theorem zero_bot (n : ℕ) : Ico 0 n = range n := eq_of_veq $ multiset.Ico.zero_bot _ @[simp] theorem card (n m : ℕ) : (Ico n m).card = m - n := multiset.Ico.card _ _ @[simp] theorem mem {n m l : ℕ} : l ∈ Ico n m ↔ n ≤ l ∧ l < m := multiset.Ico.mem theorem eq_empty_of_le {n m : ℕ} (h : m ≤ n) : Ico n m = ∅ := eq_of_veq $ multiset.Ico.eq_zero_of_le h @[simp] theorem self_eq_empty {n : ℕ} : Ico n n = ∅ := eq_empty_of_le $ le_refl n @[simp] theorem eq_empty_iff {n m : ℕ} : Ico n m = ∅ ↔ m ≤ n := iff.trans val_eq_zero.symm multiset.Ico.eq_zero_iff lemma union_consecutive {n m l : ℕ} (hnm : n ≤ m) (hml : m ≤ l) : Ico n m ∪ Ico m l = Ico n l := by rw [← to_finset, ← to_finset, ← multiset.to_finset_add, multiset.Ico.add_consecutive hnm hml, to_finset] @[simp] lemma inter_consecutive {n m l : ℕ} : Ico n m ∩ Ico m l = ∅ := begin rw [← to_finset, ← to_finset, ← multiset.to_finset_inter, multiset.Ico.inter_consecutive], simp, end @[simp] theorem succ_singleton {n : ℕ} : Ico n (n+1) = {n} := eq_of_veq $ multiset.Ico.succ_singleton theorem succ_top {n m : ℕ} (h : n ≤ m) : Ico n (m + 1) = insert m (Ico n m) := by rw [← to_finset, multiset.Ico.succ_top h, multiset.to_finset_cons, to_finset] theorem succ_top' {n m : ℕ} (h : n < m) : Ico n m = insert (m - 1) (Ico n (m - 1)) := begin have w : m = m - 1 + 1 := (nat.sub_add_cancel (nat.one_le_of_lt h)).symm, conv { to_lhs, rw w }, rw succ_top, exact nat.le_pred_of_lt h end theorem eq_cons {n m : ℕ} (h : n < m) : Ico n m = insert n (Ico (n + 1) m) := by rw [← to_finset, multiset.Ico.eq_cons h, multiset.to_finset_cons, to_finset] @[simp] theorem pred_singleton {m : ℕ} (h : m > 0) : Ico (m - 1) m = {m - 1} := eq_of_veq $ multiset.Ico.pred_singleton h @[simp] theorem not_mem_top {n m : ℕ} : m ∉ Ico n m := multiset.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 := eq_of_veq $ multiset.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) = ∅ := eq_of_veq $ multiset.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 := eq_of_veq $ multiset.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) := eq_of_veq $ multiset.Ico.filter_lt n m l lemma filter_ge_of_le_bot {n m l : ℕ} (hln : l ≤ n) : (Ico n m).filter (λ x, x ≥ l) = Ico n m := eq_of_veq $ multiset.Ico.filter_ge_of_le_bot hln lemma filter_ge_of_top_le {n m l : ℕ} (hml : m ≤ l) : (Ico n m).filter (λ x, x ≥ l) = ∅ := eq_of_veq $ multiset.Ico.filter_ge_of_top_le hml lemma filter_ge_of_ge {n m l : ℕ} (hnl : n ≤ l) : (Ico n m).filter (λ x, x ≥ l) = Ico l m := eq_of_veq $ multiset.Ico.filter_ge_of_ge hnl @[simp] lemma filter_ge (n m l : ℕ) : (Ico n m).filter (λ x, x ≥ l) = Ico (max n l) m := eq_of_veq $ multiset.Ico.filter_ge n m l @[simp] lemma diff_left (l n m : ℕ) : (Ico n m) \ (Ico n l) = Ico (max n l) m := by ext k; by_cases n ≤ k; simp [h, and_comm] @[simp] lemma diff_right (l n m : ℕ) : (Ico n m) \ (Ico l m) = Ico n (min m l) := have ∀k, (k < m ∧ (l ≤ k → m ≤ k)) ↔ (k < m ∧ k < l) := assume k, and_congr_right $ assume hk, by rw [← not_imp_not]; simp [hk], by ext k; by_cases n ≤ k; simp [h, this] end Ico end finset namespace multiset lemma count_sup [decidable_eq β] (s : finset α) (f : α → multiset β) (b : β) : count b (s.sup f) = s.sup (λa, count b (f a)) := begin letI := classical.dec_eq α, refine s.induction _ _, { exact count_zero _ }, { assume i s his ih, rw [finset.sup_insert, sup_eq_union, count_union, finset.sup_insert, ih], refl } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h end list namespace lattice variables {ι : Sort*} [complete_lattice α] [decidable_eq ι] lemma supr_eq_supr_finset (s : ι → α) : (⨆i, s i) = (⨆t:finset (plift ι), ⨆i∈t, s (plift.down i)) := le_antisymm (supr_le $ assume b, le_supr_of_le {plift.up b} $ le_supr_of_le (plift.up b) $ le_supr_of_le (by simp) $ le_refl _) (supr_le $ assume t, supr_le $ assume b, supr_le $ assume hb, le_supr _ _) lemma infi_eq_infi_finset (s : ι → α) : (⨅i, s i) = (⨅t:finset (plift ι), ⨅i∈t, s (plift.down i)) := le_antisymm (le_infi $ assume t, le_infi $ assume b, le_infi $ assume hb, infi_le _ _) (le_infi $ assume b, infi_le_of_le {plift.up b} $ infi_le_of_le (plift.up b) $ infi_le_of_le (by simp) $ le_refl _) end lattice namespace set variables {ι : Sort*} [decidable_eq ι] lemma Union_eq_Union_finset (s : ι → set α) : (⋃i, s i) = (⋃t:finset (plift ι), ⋃i∈t, s (plift.down i)) := lattice.supr_eq_supr_finset s lemma Inter_eq_Inter_finset (s : ι → set α) : (⋂i, s i) = (⋂t:finset (plift ι), ⋂i∈t, s (plift.down i)) := lattice.infi_eq_infi_finset s end set
65cc1439f5c905c3cad5328ced08371ed82e9468
6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1
/ExamPractice/final_review.lean
9c2b94b4be186c95460a46431bc7c814edc5a792
[]
no_license
derekjohnsonva/CS2102
8ed45daa6658e6121bac0f6691eac6147d08246d
b3f507d4be824a2511838a1054d04fc9aef3304c
refs/heads/master
1,648,529,162,527
1,578,851,859,000
1,578,851,859,000
233,433,207
0
0
null
null
null
null
UTF-8
Lean
false
false
7,193
lean
/- QUICK NOTE: -/ /- This was made by Charlie and Ben with no consultation with Professor Sullivan. This is just some review that we thought you should have while Professor Sullivan is finishing HW9. While most of these proofs were not written to be difficult, some turned out to be particularly challenging (which I've marked below). This is not necessarily representative of what you will see on your exam, unlike homework 9. As always -- if we've made any mistakes or you have any questions please post on Piazza. :) -/ -- For all proofs, please use provablesystems.com -- for a reference guide on how to start these proofs -- Also, you may see the same proofs written two different ways: example {P : Prop} : P → P := begin assume p, exact p, end -- Prof. Sullivan likes forall more -- so almost all proofs onward will appear with a forall -- like this: example : ∀ P : Prop, P → P := begin assume P, assume p, exact p, end /- START OF REVIEW -/ /- IMPLICATION -/ example : ∀ P, P → P := begin intro t, intro P, exact P, end example : ∀ P Q, P → Q → P := begin intro P, intro Q, intro p, intro q, exact p, end example : (0 = 1) → (0 = 1) := begin intros, exact a, end -- You will use implication extensively throughout -- the remainder of this review /- TRUE -/ -- intro example : true := begin exact true.intro, end example : ∀ P Q R : Prop, true := begin intros, exact true.intro, end example : (0 = 1) → true := begin intros, apply true.intro, end /- FALSE -/ example : false → (0 = 1) := begin intro f, apply false.elim f, end example : ∀ P : Prop, false → P := begin intro P, assume f, apply false.elim f, end example : ∀ P Q, P → Q → false → (P ∧ Q) := begin assume P Q, assume p, assume q, assume f, apply false.elim f, end /- EQUALITY -/ example : 3 = 3 := begin exact eq.refl 3, end example : ∀ n : nat, n = n := begin assume n, exact eq.refl n, end /- AND -/ -- intro (and.intro _ _) example : ∀ P Q : Prop, P → Q → (P ∧ Q) := begin intros P Q, intros p q, apply and.intro p q, end example {P Q : Prop} : P → Q → (Q ∧ P) := begin intros P Q, apply and.intro Q P, end example : (0 = 0) ∧ (1 = 1) := begin have zero := eq.refl 0, have one := eq.refl 1, apply and.intro zero one, end -- elim (and.elim_left _ and and.right _ ) example : ∀ P Q : Prop, P ∧ Q → P := begin intros P Q pandq, apply and.elim_left pandq, end example : ∀ P Q : Prop, P ∧ Q → Q := begin intros P Q pandq, apply and.elim_right pandq, end example : ∀ P Q R : Prop, P ∧ Q ∧ R → Q := begin intros P Q R pnqnr, apply and.elim_left (and.elim_right pnqnr), end -- both example : ∀ P Q R : Prop, P ∧ Q ∧ R → (P ∧ R) := begin intros, have r := and.elim_right (and.elim_right a), have p := and.elim_left a, apply and.intro p r, end example : ∀ P Q R : Prop, Q ∧ R ∧ P → (R ∧ P ∧ Q) := begin intros, apply and.intro, apply and.elim_left (and.elim_right a), apply and.intro, apply and.elim_right (and.elim_right a), apply and.elim_left a, end /- OR -/ -- intro (or.intro_left _ _, shortcut: or.inl _ and the associated right-side variant) example : ∀ P Q, P → (P ∨ Q) := begin intros P Q p, apply or.intro_left, apply p, end example : ∀ P Q R, (P ∧ R) → (P ∨ Q) := begin intros, have p := and.elim_left a, apply or.intro_left, apply p, end example : (0 = 1) ∨ (1 = 1) := begin have one := eq.refl 1, apply or.intro_right, apply one, end -- elim (or.elim _ _ _ ) -- remember you can use the 'cases' keyword example : ∀ P Q R, (P → R) → (Q → R) → (P ∨ Q) → R := begin assume P Q, intro R, assume pimpr, assume qimpr, assume porq, apply or.elim porq, apply pimpr, apply qimpr, end example : ∀ P Q, (P → Q) → (P ∨ Q) → Q := begin intros P Q, intros pimpq porq, cases porq, apply pimpq porq, -- case 1 apply porq, -- case 2 end /- BI-IMPLICATION -/ -- intro example : ∀ P Q, (P → Q) → (Q → P) → (P ↔ Q) := begin intros P Q, intros pimpq qimpp, apply iff.intro pimpq qimpp, end -- elim (iff.elim _ ) example : ∀ P Q : Prop, (P ↔ Q) → (P → Q) := begin assume P Q, assume piffq, have pimpq := iff.elim_left piffq, exact pimpq, end example : ∀ P Q : Prop, (P ↔ Q) → ((P → Q) ∧ (Q → P)) := begin intros P Q, intros piffq, let pimpq := iff.elim_left piffq, let qimpp := iff.elim_right piffq, apply and.intro pimpq, apply qimpp, end -- both -- this is a particularly challenging proof example : ∀ P Q R : Prop, (P ↔ Q) → (Q ↔ R) → (R ↔ P) := begin intros P Q R, intros piffq, intros qiffr, have pimpq := iff.elim_left piffq, have qimpr := iff.elim_left qiffr, have qimpp := iff.elim_right piffq, have rimpq := iff.elim_right qiffr, apply iff.intro, assume r, apply qimpp (rimpq r), assume p, apply qimpr (pimpq p), end /- NEGATION -/ example : ∀ P : Prop, ¬ P → (P → false) := begin intros P np p, contradiction, end example : ∀ P Q : Prop, (P ∧ Q) → ¬ P → false := begin intros P Q pandq np, have p := and.elim_left pandq, contradiction, end /- FORALL -/ -- which we've been using extensively up until this point already example : ∀ P Q : Prop, (∀ p : P, Q) → (P → Q) := begin intros P Q pimpq, apply pimpq, end /- EXISTS -/ -- intro example : ∀ n : nat, ∃ m, n = m := begin intros n, have nrefl := eq.refl n, apply exists.intro n, apply nrefl, end -- Below is the property isEven. -- A natural number is even if there exists -- another natural number k such that 2k = n def isEven : ℕ → Prop := λ n, ∃ k, 2 * k = n -- Define isOdd below. -- A natural number is odd if there exists -- another natural number k such that 2k + 1 = n def isOdd : ℕ → Prop := λ (n : nat), ∃ k, 2 + k =n -- elim/both -- this is a particularly challenging proof example : ∀ n : nat, (isEven n) → (isEven (2*n)) := begin intros n, unfold isEven, -- "desugars" isEven to its definition above intros, apply exists.intro n, refl, end example : 0 ≠ 1 := begin intro, contradiction, end
9f1a7b5229fcc2328b9f99eb1b3426f2c3c79e3b
4727251e0cd73359b15b664c3170e5d754078599
/src/data/rat/order.lean
4c792e06853cc825f2eb0459c6e179d19c5756cf
[ "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
8,182
lean
/- Copyright (c) 2019 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 data.rat.basic /-! # Order for Rational Numbers ## Summary We define the order on `ℚ`, prove that `ℚ` is a discrete, linearly ordered field, and define functions such as `abs` and `sqrt` that depend on this order. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, order, ordering, sqrt, abs -/ namespace rat variables (a b c : ℚ) open_locale rat /-- A rational number is called nonnegative if its numerator is nonnegative. -/ protected def nonneg (r : ℚ) : Prop := 0 ≤ r.num @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : 0 < b) : (a /. b).nonneg ↔ 0 ≤ a := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected lemma nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}, end protected lemma nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : 0 < (d₁:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : 0 < (d₂:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0, mul_nonneg] { contextual := tt } end protected lemma nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : 0 < (d:ℤ) := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm h₂ h₁ end protected lemma nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance /-- Relation `a ≤ b` on `ℚ` defined as `a ≤ b ↔ rat.nonneg (b - a)`. Use `a ≤ b` instead of `rat.le a b`. -/ protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : 0 < b) (d0 : 0 < d) : a /. b ≤ c /. d ↔ a * d ≤ c * b := begin show rat.nonneg _ ↔ _, rw ← sub_nonneg, simp [sub_eq_add_neg, ne_of_gt b0, ne_of_gt d0, mul_pos d0 b0] end protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by { have := eq_neg_of_add_eq_zero_left (rat.nonneg_antisymm hba $ by rwa [← sub_eq_add_neg, neg_sub]), rwa neg_neg at this } protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, by simpa [sub_eq_add_neg, add_comm, add_left_comm] instance : linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : distrib_lattice ℚ := by apply_instance instance : lattice ℚ := by apply_instance instance : semilattice_inf ℚ := by apply_instance instance : semilattice_sup ℚ := by apply_instance instance : has_inf ℚ := by apply_instance instance : has_sup ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance protected lemma le_def' {p q : ℚ} : p ≤ q ↔ p.num * q.denom ≤ q.num * p.denom := begin rw [←(@num_denom q), ←(@num_denom p)], conv_rhs { simp only [num_denom] }, exact rat.le_def (by exact_mod_cast p.pos) (by exact_mod_cast q.pos) end protected lemma lt_def {p q : ℚ} : p < q ↔ p.num * q.denom < q.num * p.denom := begin rw [lt_iff_le_and_ne, rat.le_def'], suffices : p ≠ q ↔ p.num * q.denom ≠ q.num * p.denom, by { split; intro h, { exact lt_iff_le_and_ne.elim_right ⟨h.left, (this.elim_left h.right)⟩ }, { have tmp := lt_iff_le_and_ne.elim_left h, exact ⟨tmp.left, this.elim_right tmp.right⟩ }}, exact (not_iff_not.elim_right eq_iff_mul_eq_mul) end theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : linear_ordered_field ℚ := { zero_le_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.field, ..rat.linear_order, ..rat.semiring } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : linear_ordered_add_comm_group ℚ := by apply_instance instance : ordered_add_comm_group ℚ := by apply_instance instance : ordered_cancel_add_comm_monoid ℚ := by apply_instance instance : ordered_add_comm_monoid ℚ := by apply_instance attribute [irreducible] rat.le theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := lt_iff_lt_of_le_iff_le $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) lemma div_lt_div_iff_mul_lt_mul {a b c d : ℤ} (b_pos : 0 < b) (d_pos : 0 < d) : (a : ℚ) / b < c / d ↔ a * d < c * b := begin simp only [lt_iff_le_not_le], apply and_congr, { simp [div_num_denom, (rat.le_def b_pos d_pos)] }, { apply not_iff_not_of_iff, simp [div_num_denom, (rat.le_def d_pos b_pos)] } end lemma lt_one_iff_num_lt_denom {q : ℚ} : q < 1 ↔ q.num < q.denom := by simp [rat.lt_def] theorem abs_def (q : ℚ) : |q| = q.num.nat_abs /. q.denom := begin cases le_total q 0 with hq hq, { rw [abs_of_nonpos hq], rw [←(@num_denom q), ← mk_zero_one, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one, mul_one, zero_mul] at hq, rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, num_denom] }, { rw [abs_of_nonneg hq], rw [←(@num_denom q), ← mk_zero_one, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos), mul_one, zero_mul] at hq, rw [int.nat_abs_of_nonneg hq, num_denom] } end end rat